hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
sequencelengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
sequencelengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
sequencelengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
7955716e0be7aaf90d77a69165a961ece0ee2438
1,780
php
PHP
streams/controllers/admin_checker.php
eResnova/neofrag-streams
e5423d75de70bf8a9809d723582c3587b65cad18
[ "MIT" ]
1
2018-06-08T11:54:18.000Z
2018-06-08T11:54:18.000Z
streams/controllers/admin_checker.php
eResnova/neofrag-streams
e5423d75de70bf8a9809d723582c3587b65cad18
[ "MIT" ]
null
null
null
streams/controllers/admin_checker.php
eResnova/neofrag-streams
e5423d75de70bf8a9809d723582c3587b65cad18
[ "MIT" ]
null
null
null
<?php if (!defined('NEOFRAG_CMS')) exit; /************************************************************************** Copyright © 2015 Michaël BILCOT & Jérémy VALENTIN This file is part of NeoFrag. NeoFrag is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. NeoFrag is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with NeoFrag. If not, see <http://www.gnu.org/licenses/>. **************************************************************************/ class m_streams_c_admin_checker extends Controller_Module { public function add() { if (!$this->is_authorized('add_streams')) { throw new Exception(NeoFrag::UNAUTHORIZED); } return []; } public function _edit($stream_id, $title) { if (!$this->is_authorized('modify_streams')) { throw new Exception(NeoFrag::UNAUTHORIZED); } if ($stream = $this->model()->check_stream($stream_id, $title)) { return $stream; } } public function delete($stream_id, $title) { if (!$this->is_authorized('delete_streams')) { throw new Exception(NeoFrag::UNAUTHORIZED); } $this->ajax(); if ($stream = $this->model()->check_stream($stream_id, $title)) { return [$stream['stream_id'], $stream['title']]; } } } /* NeoFrag Alpha 0.1.6.1 ./modules/streams/controllers/admin_checker.php */
27.384615
76
0.632022
97c7fe0817169c99455b1428546724b4b1ba2cb1
7,237
swift
Swift
Common/Sources/OutlineType.swift
jessegrosjean/BirchOutline
18e6e79b4fd08f64f4d2c40554371c97045930d8
[ "MIT" ]
60
2016-06-27T13:32:54.000Z
2022-02-20T08:44:52.000Z
Common/Sources/OutlineType.swift
jessegrosjean/BirchOutline
18e6e79b4fd08f64f4d2c40554371c97045930d8
[ "MIT" ]
null
null
null
Common/Sources/OutlineType.swift
jessegrosjean/BirchOutline
18e6e79b4fd08f64f4d2c40554371c97045930d8
[ "MIT" ]
3
2016-09-07T22:01:40.000Z
2019-10-20T10:00:56.000Z
// // OutlineType.swift // Birch // // Created by Jesse Grosjean on 6/14/16. // Copyright © 2016 Jesse Grosjean. All rights reserved. // import Foundation import JavaScriptCore public protocol OutlineType: AnyObject { var jsOutline: JSValue { get } var root: ItemType { get } var items: [ItemType] { get } func itemForID(_ id: String) -> ItemType? func evaluateItemPath(_ path: String) -> [ItemType] func createItem(_ text: String) -> ItemType func cloneItem(_ item: ItemType, deep: Bool) -> ItemType func cloneItems(_ items: [ItemType], deep: Bool) -> [ItemType] func groupUndo(_ callback: @escaping () -> Void) func groupChanges(_ callback: @escaping () -> Void) var changed: Bool { get } func updateChangeCount(_ changeKind: ChangeKind) func onDidUpdateChangeCount(_ callback: @escaping (_ changeKind: ChangeKind) -> Void) -> DisposableType func onDidChange(_ callback: @escaping (_ mutation: MutationType) -> Void) -> DisposableType func onDidEndChanges(_ callback: @escaping (_ mutations: [MutationType]) -> Void) -> DisposableType func undo() func redo() var serializedMetadata: String { get set } func serializeItems(_ items: [ItemType], options: [String : Any]?) -> String func deserializeItems(_ serializedItems: String, options: [String : Any]?) -> [ItemType]? func serialize(_ options: [String: Any]?) -> String func reloadSerialization(_ serialization: String, options: [String: Any]?) var retainCount: Int { get } } public enum ChangeKind { case done case undone case redone case cleared public init?(string: String) { switch string { case "Done": self = .done case "Undone": self = .undone case "Redone": self = .redone case "Cleared": self = .cleared default: return nil } } public func toString() -> String { switch self { case .done: return "Done" case .undone: return "Undone" case .redone: return "Redone" case .cleared: return "Cleared" } } } open class Outline: OutlineType { open var jsOutline: JSValue public init(jsOutline: JSValue) { self.jsOutline = jsOutline } open var root: ItemType { return jsOutline.forProperty("root") } open var items: [ItemType] { return jsOutline.forProperty("items").toItemTypeArray() } open func itemForID(_ id: String) -> ItemType? { return jsOutline.invokeMethod("getItemForID", withArguments: [id]).selfOrNil() } open func evaluateItemPath(_ path: String) -> [ItemType] { return jsOutline.invokeMethod("evaluateItemPath", withArguments: [path]).toItemTypeArray() } open func createItem(_ text: String) -> ItemType { return jsOutline.invokeMethod("createItem", withArguments: [text]) } open func cloneItem(_ item: ItemType, deep: Bool = true) -> ItemType { return jsOutline.invokeMethod("cloneItem", withArguments: [item, deep]) } open func cloneItems(_ items: [ItemType], deep: Bool = true) -> [ItemType] { let jsItems = JSValue.fromItemTypeArray(items, context: jsOutline.context) let jsItemsClone = jsOutline.invokeMethod("cloneItems", withArguments: [jsItems, deep]) return jsItemsClone!.toItemTypeArray() } public func groupUndo(_ callback: @escaping () -> Void) { let callbackWrapper: @convention(block) () -> Void = { callback() } jsOutline.invokeMethod("groupUndo", withArguments: [unsafeBitCast(callbackWrapper, to: AnyObject.self)]) } public func groupChanges(_ callback: @escaping () -> Void) { let callbackWrapper: @convention(block) () -> Void = { callback() } jsOutline.invokeMethod("groupChanges", withArguments: [unsafeBitCast(callbackWrapper, to: AnyObject.self)]) } open var changed: Bool { return jsOutline.forProperty("isChanged").toBool() } open func updateChangeCount(_ changeKind: ChangeKind) { jsOutline.invokeMethod("updateChangeCount", withArguments: [changeKind.toString()]) } open func onDidUpdateChangeCount(_ callback: @escaping (_ changeKind: ChangeKind) -> Void) -> DisposableType { let callbackWrapper: @convention(block) (_ changeKindString: String) -> Void = { changeKindString in callback(ChangeKind(string: changeKindString)!) } return jsOutline.invokeMethod("onDidUpdateChangeCount", withArguments: [unsafeBitCast(callbackWrapper, to: AnyObject.self)]) } open func onDidChange(_ callback: @escaping (_ mutation: MutationType) -> Void) -> DisposableType { let callbackWrapper: @convention(block) (_ mutation: JSValue) -> Void = { mutation in callback(Mutation(jsMutation: mutation)) } return jsOutline.invokeMethod("onDidChange", withArguments: [unsafeBitCast(callbackWrapper, to: AnyObject.self)]) } open func onDidEndChanges(_ callback: @escaping (_ mutations: [MutationType]) -> Void) -> DisposableType { let callbackWrapper: @convention(block) (_ mutation: JSValue) -> Void = { jsMutations in let length = Int((jsMutations.forProperty("length").toInt32())) var mutations = [Mutation]() for i in 0..<length { mutations.append(Mutation(jsMutation: jsMutations.atIndex(i))) } callback(mutations) } return jsOutline.invokeMethod("onDidEndChanges", withArguments: [unsafeBitCast(callbackWrapper, to: AnyObject.self)]) } open func undo() { jsOutline.invokeMethod("undo", withArguments: []) } open func redo() { jsOutline.invokeMethod("redo", withArguments: []) } public var serializedMetadata: String { get { return jsOutline.forProperty("serializedMetadata").toString() } set { jsOutline.setValue(newValue, forProperty: "serializedMetadata") } } open func serializeItems(_ items: [ItemType], options: [String : Any]?) -> String { let mapped: [Any] = items.map { $0 } return jsOutline.invokeMethod("serializeItems", withArguments: [mapped, options ?? [:]]).toString() } open func deserializeItems(_ serializedItems: String, options: [String : Any]?) -> [ItemType]? { return jsOutline.invokeMethod("deserializeItems", withArguments: [serializedItems, options ?? [:]]).toItemTypeArray() } open func serialize(_ options:[String: Any]?) -> String { return jsOutline.invokeMethod("serialize", withArguments: [options ?? [:]]).toString() } open func reloadSerialization(_ serialization: String, options: [String: Any]?) { jsOutline.invokeMethod("reloadSerialization", withArguments: [serialization, options ?? [:]]) } open var retainCount: Int { return Int(jsOutline.forProperty("retainCount").toInt32()) } }
34.461905
132
0.63051
96ed9aa77c0cf1813b0599d66a6dbae3b01e337c
541
cs
C#
Dev/PropertyWriter/ViewModels/Properties/IntViewModel.cs
NumAniCloud/PropertyWriter
3549e5c1fb4724cd05701b88915893dc21501b20
[ "MIT" ]
1
2017-02-17T16:29:52.000Z
2017-02-17T16:29:52.000Z
Dev/PropertyWriter/ViewModels/Properties/IntViewModel.cs
NumAniCloud/PropertyWriter
3549e5c1fb4724cd05701b88915893dc21501b20
[ "MIT" ]
1
2017-01-06T03:38:55.000Z
2017-01-06T03:38:55.000Z
Dev/PropertyWriter/ViewModels/Properties/IntViewModel.cs
NumAniCloud/PropertyWriter
3549e5c1fb4724cd05701b88915893dc21501b20
[ "MIT" ]
null
null
null
using PropertyWriter.Models.Properties; using PropertyWriter.ViewModels.Properties.Common; using Reactive.Bindings; using System; using System.Reactive; using System.Reactive.Linq; namespace PropertyWriter.ViewModels.Properties { public class IntViewModel : PropertyViewModel<IntProperty> { public ReactiveProperty<int> IntValue => Property.IntValue; public override IObservable<Unit> OnChanged => Property.IntValue.Select(x => Unit.Default); public IntViewModel(IntProperty property) : base(property) { } } }
25.761905
93
0.772643
050d0010b43ea952678199d1576dbea0b79bd7e1
3,383
rb
Ruby
spec/satisfy/matcher_spec.rb
jnyman/satisfy
01b57b866ed220a03470e2ba34b0a1926feaee0f
[ "MIT" ]
null
null
null
spec/satisfy/matcher_spec.rb
jnyman/satisfy
01b57b866ed220a03470e2ba34b0a1926feaee0f
[ "MIT" ]
null
null
null
spec/satisfy/matcher_spec.rb
jnyman/satisfy
01b57b866ed220a03470e2ba34b0a1926feaee0f
[ "MIT" ]
null
null
null
RSpec.describe Satisfy::Matcher do describe 'matching' do it 'matches a simple step' do step = Satisfy::Matcher.new('all your base are belong to us') {} expect(step).to match('all your base are belong to us') expect(step).not_to match('all their base are belong to us') expect(step).not_to match('all their base are belong to me') end it 'matches placeholders within a step' do allow(Satisfy::Placeholder).to receive(:resolve).with(:count).and_return(/\d+/) step = Satisfy::Matcher.new('there are :count tests') {} expect(step).to match('there are 10 tests') expect(step).to match('there are 10000 tests') expect(step).not_to match('there are no tests') end it 'extracts arguments from matched steps' do step = Satisfy::Matcher.new("a :age year old tester called :name") {} match = step.match('a 43 year old tester called Jeff') expect(match.params).to eq(['43', 'Jeff']) end it 'can reuse the same placeholder multiple times' do step = Satisfy::Matcher.new('the testers :name and :name') {} match = step.match('the testers Jeff and Kasira') expect(match.params).to eq(['Jeff', 'Kasira']) end it 'can reuse the same custom placeholder multiple times' do allow(Satisfy::Placeholder).to receive(:resolve).with(:count).and_return(/\d+/) allow(Satisfy::Placeholder).to receive(:apply).with(:count, '3').and_return(3) allow(Satisfy::Placeholder).to receive(:apply).with(:count, '2').and_return(2) step = Satisfy::Matcher.new(":count testers and :count developers") {} match = step.match('3 testers and 2 developers') expect(match.params).to eq([3, 2]) end it 'matches quoted placeholders' do step = Satisfy::Matcher.new('there is a tester named :name') {} expect(step).to match("there is a tester named 'Jeff'") expect(step).to match('there is a tester named "Jeff"') end it 'matches alternative words' do step = Satisfy::Matcher.new('there is/are testers') {} expect(step).to match('there are testers') expect(step).to match('there is testers') expect(step).not_to match('there be testers') end it 'matches several alternative words' do step = Satisfy::Matcher.new('testers are cool/nice/scary') {} expect(step).to match('testers are cool') expect(step).to match('testers are nice') expect(step).to match('testers are scary') expect(step).not_to match('testers are strange') end it 'matches optional parts of words' do step = Satisfy::Matcher.new('there is/are tester(s)') {} expect(step).to match('there is tester') expect(step).to match('there are testers') end it 'matches optional words' do step = Satisfy::Matcher.new('there is a (scary) tester') {} expect(step).to match('there is a tester') expect(step).to match('there is a scary tester') expect(step).not_to match('there is a terrifying tester') step = Satisfy::Matcher.new('there is a tester (that is scary)') {} expect(step).to match('there is a tester that is scary') expect(step).to match('there is a tester') step = Satisfy::Matcher.new('(there is) a tester') {} expect(step).to match('there is a tester') expect(step).to match('a tester') end end end
41.256098
85
0.650015
57e49a73de9176ed19fd1b60171f9dd01da9c174
677
php
PHP
locale/Hungarian/admin/robots.php
Tibi02/progvill-site
f12b6a36fa4ef8dcb32b94cf56a6bf141b4f460a
[ "MIT" ]
null
null
null
locale/Hungarian/admin/robots.php
Tibi02/progvill-site
f12b6a36fa4ef8dcb32b94cf56a6bf141b4f460a
[ "MIT" ]
null
null
null
locale/Hungarian/admin/robots.php
Tibi02/progvill-site
f12b6a36fa4ef8dcb32b94cf56a6bf141b4f460a
[ "MIT" ]
null
null
null
<?php // Titles $locale['400'] = "robots.txt"; // Messages $locale['410'] = "Biztos vissza szeretnéd állítani a robots.txt tartalmát az eredeti állapotra?"; $locale['411'] = "A robots.txt fájl nem létezik. Hozd létre ezt a fájlt a PHP-Fusion gyökérk9nyvtárjában, és próbáld meg újra."; $locale['412'] = "robots.txt módosítva."; $locale['413'] = "Hiba történt:"; $locale['414'] = "A robots.txt nem írható."; $locale['415'] = "Nem sikerült módosítani a robots.txt fájlt."; // Edit form $locale['420'] = "robots.txt fájl szerkesztése"; $locale['421'] = "További információ a robots.txt működéséről."; $locale['422'] = "Mentés"; $locale['423'] = "Alapértelmezés visszaállítása"; ?>
42.3125
128
0.689808
be6f1d07431b23b782618c34489d5d271537078a
56
ts
TypeScript
common/reducers/transaction/broadcast/index.ts
cleanunicorn/MyCrypto
d41c326cfe1e869379953a947c6e71866622a8c4
[ "MIT" ]
2
2019-03-06T11:52:53.000Z
2019-03-06T14:29:43.000Z
common/reducers/transaction/broadcast/index.ts
cleanunicorn/MyCrypto
d41c326cfe1e869379953a947c6e71866622a8c4
[ "MIT" ]
1
2022-03-19T19:22:58.000Z
2022-03-19T19:22:58.000Z
common/reducers/transaction/broadcast/index.ts
cleanunicorn/MyCrypto
d41c326cfe1e869379953a947c6e71866622a8c4
[ "MIT" ]
1
2018-01-16T18:40:43.000Z
2018-01-16T18:40:43.000Z
export * from './typings'; export * from './broadcast';
18.666667
28
0.642857
df147e3b4cc778565b94faa9487363c9414cbc00
2,347
cs
C#
BusinessObjects/Resources/BusinessObjectsResourceManager.cs
roberto-taveras/MVPPattern
6c8027e94a3fd38313e31da6b762719fd5c0e946
[ "MIT" ]
null
null
null
BusinessObjects/Resources/BusinessObjectsResourceManager.cs
roberto-taveras/MVPPattern
6c8027e94a3fd38313e31da6b762719fd5c0e946
[ "MIT" ]
null
null
null
BusinessObjects/Resources/BusinessObjectsResourceManager.cs
roberto-taveras/MVPPattern
6c8027e94a3fd38313e31da6b762719fd5c0e946
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) [2020] [Jose Roberto Taveras Galvan] 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. */ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Resources; using System.Text; using System.Threading; using System.Threading.Tasks; namespace BusinessObjects.Resources { public class BusinessObjectsResourceManager { string _cultureName; ResourceManager _resourceManager; public string CultureName{ get { return _cultureName; } } public ResourceManager ResourceManager { get { return _resourceManager; } } public BusinessObjectsResourceManager(string cultureName = "es-DO") { this._cultureName = cultureName; CultureInfo culture = CultureInfo.CreateSpecificCulture(_cultureName); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; _resourceManager = new ResourceManager(typeof(Resources.Resource)); Resource.Culture = culture; } private BusinessObjectsResourceManager() { } public string Translate(string sender) { return (ResourceManager.GetString(sender, Resource.Culture)); } } }
36.671875
83
0.736685
6205c270cbb9489a8fdace547c69333cfd8c7a74
1,962
dart
Dart
lib/main.dart
molokows/molokows
e2180175d31f9ff1e7308852899d0a879a92fb3f
[ "CC0-1.0" ]
null
null
null
lib/main.dart
molokows/molokows
e2180175d31f9ff1e7308852899d0a879a92fb3f
[ "CC0-1.0" ]
null
null
null
lib/main.dart
molokows/molokows
e2180175d31f9ff1e7308852899d0a879a92fb3f
[ "CC0-1.0" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:newnavapp/about_screen.dart'; import 'package:newnavapp/achievments_screen.dart'; import 'package:newnavapp/home_screen.dart'; import 'package:newnavapp/lessons_screen.dart'; import 'package:newnavapp/profile_screen.dart'; import 'package:newnavapp/programms_screen.dart'; import 'package:newnavapp/skills_screen.dart'; import 'package:newnavapp/welcome_screen.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( // initialRoute: WelcomeScreen.id initialRoute: AboutScreen.id, routes: { WelcomeScreen.id: (context) => WelcomeScreen(title: 'Grow aikidoka home'), // WelcomeScreenSliverList.id: (context) => WelcomeScreenSliverList(), AboutScreen.id: (context) => AboutScreen(), AchievmentsScreen.id: (context) => AchievmentsScreen(), HomeScreen.id: (context) => HomeScreen(), LessonsScreen.id: (context) => LessonsScreen(), ProfileScreen.id: (context) => ProfileScreen(), ProgrammsScreen.id: (context) => ProgrammsScreen(), SkillsScreen.id: (context) => SkillsScreen(), }, title: 'Grow aikidoka', theme: ThemeData( // This is the theme of your application. // // Try running your application with "flutter run". You'll see the // application has a blue toolbar. Then, without quitting the app, try // changing the primarySwatch below to Colors.green and then invoke // "hot reload" (press "r" in the console where you ran "flutter run", // or simply save your changes to "hot reload" in a Flutter IDE). // Notice that the counter didn't reset back to zero; the application // is not restarted. primarySwatch: Colors.blue, ), // scrollBehavior: const ConstantScrollBehavior(), ); } }
38.470588
78
0.672783
2fdf88cd8ce4cf1de299648ba00f4b86c4d90efd
21,950
py
Python
keras/layers/rnn/time_distributed_test.py
mcx/keras
3613c3defc39c236fb1592c4f7ba1a9cc887343a
[ "Apache-2.0" ]
null
null
null
keras/layers/rnn/time_distributed_test.py
mcx/keras
3613c3defc39c236fb1592c4f7ba1a9cc887343a
[ "Apache-2.0" ]
null
null
null
keras/layers/rnn/time_distributed_test.py
mcx/keras
3613c3defc39c236fb1592c4f7ba1a9cc887343a
[ "Apache-2.0" ]
null
null
null
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for TimeDistributed wrapper.""" import numpy as np import tensorflow.compat.v2 as tf from absl.testing import parameterized import keras from keras.testing_infra import test_combinations from keras.testing_infra import test_utils # isort: off from tensorflow.python.training.tracking import ( util as trackable_util, ) class TimeDistributedTest(test_combinations.TestCase): @test_combinations.generate( test_combinations.combine(mode=["graph", "eager"]) ) def test_timedistributed_dense(self): model = keras.models.Sequential() model.add( keras.layers.TimeDistributed( keras.layers.Dense(2), input_shape=(3, 4) ) ) model.compile(optimizer="rmsprop", loss="mse") model.fit( np.random.random((10, 3, 4)), np.random.random((10, 3, 2)), epochs=1, batch_size=10, ) # test config model.get_config() # check whether the model variables are present in the # trackable list of objects checkpointed_object_ids = { id(o) for o in trackable_util.list_objects(model) } for v in model.variables: self.assertIn(id(v), checkpointed_object_ids) def test_timedistributed_static_batch_size(self): model = keras.models.Sequential() model.add( keras.layers.TimeDistributed( keras.layers.Dense(2), input_shape=(3, 4), batch_size=10 ) ) model.compile(optimizer="rmsprop", loss="mse") model.fit( np.random.random((10, 3, 4)), np.random.random((10, 3, 2)), epochs=1, batch_size=10, ) def test_timedistributed_invalid_init(self): x = tf.constant(np.zeros((1, 1)).astype("float32")) with self.assertRaisesRegex( ValueError, "Please initialize `TimeDistributed` layer with a " "`tf.keras.layers.Layer` instance.", ): keras.layers.TimeDistributed(x) def test_timedistributed_conv2d(self): with self.cached_session(): model = keras.models.Sequential() model.add( keras.layers.TimeDistributed( keras.layers.Conv2D(5, (2, 2), padding="same"), input_shape=(2, 4, 4, 3), ) ) model.add(keras.layers.Activation("relu")) model.compile(optimizer="rmsprop", loss="mse") model.train_on_batch( np.random.random((1, 2, 4, 4, 3)), np.random.random((1, 2, 4, 4, 5)), ) model = keras.models.model_from_json(model.to_json()) model.summary() def test_timedistributed_stacked(self): with self.cached_session(): model = keras.models.Sequential() model.add( keras.layers.TimeDistributed( keras.layers.Dense(2), input_shape=(3, 4) ) ) model.add(keras.layers.TimeDistributed(keras.layers.Dense(3))) model.add(keras.layers.Activation("relu")) model.compile(optimizer="rmsprop", loss="mse") model.fit( np.random.random((10, 3, 4)), np.random.random((10, 3, 3)), epochs=1, batch_size=10, ) def test_regularizers(self): with self.cached_session(): model = keras.models.Sequential() model.add( keras.layers.TimeDistributed( keras.layers.Dense( 2, kernel_regularizer="l1", activity_regularizer="l1" ), input_shape=(3, 4), ) ) model.add(keras.layers.Activation("relu")) model.compile(optimizer="rmsprop", loss="mse") self.assertEqual(len(model.losses), 2) def test_TimeDistributed_learning_phase(self): with self.cached_session(): # test layers that need learning_phase to be set np.random.seed(1234) x = keras.layers.Input(shape=(3, 2)) y = keras.layers.TimeDistributed(keras.layers.Dropout(0.999))( x, training=True ) model = keras.models.Model(x, y) y = model.predict(np.random.random((10, 3, 2))) self.assertAllClose(np.mean(y), 0.0, atol=1e-1, rtol=1e-1) def test_TimeDistributed_batchnorm(self): with self.cached_session(): # test that wrapped BN updates still work. model = keras.models.Sequential() model.add( keras.layers.TimeDistributed( keras.layers.BatchNormalization(center=True, scale=True), name="bn", input_shape=(10, 2), ) ) model.compile(optimizer="rmsprop", loss="mse") # Assert that mean and variance are 0 and 1. td = model.layers[0] self.assertAllClose(td.get_weights()[2], np.array([0, 0])) assert np.array_equal(td.get_weights()[3], np.array([1, 1])) # Train model.train_on_batch( np.random.normal(loc=2, scale=2, size=(1, 10, 2)), np.broadcast_to(np.array([0, 1]), (1, 10, 2)), ) # Assert that mean and variance changed. assert not np.array_equal(td.get_weights()[2], np.array([0, 0])) assert not np.array_equal(td.get_weights()[3], np.array([1, 1])) def test_TimeDistributed_trainable(self): # test layers that need learning_phase to be set x = keras.layers.Input(shape=(3, 2)) layer = keras.layers.TimeDistributed(keras.layers.BatchNormalization()) _ = layer(x) self.assertEqual(len(layer.trainable_weights), 2) layer.trainable = False assert not layer.trainable_weights layer.trainable = True assert len(layer.trainable_weights) == 2 def test_TimeDistributed_with_masked_embedding_and_unspecified_shape(self): with self.cached_session(): # test with unspecified shape and Embeddings with mask_zero model = keras.models.Sequential() model.add( keras.layers.TimeDistributed( keras.layers.Embedding(5, 6, mask_zero=True), input_shape=(None, None), ) ) # N by t_1 by t_2 by 6 model.add( keras.layers.TimeDistributed( keras.layers.SimpleRNN(7, return_sequences=True) ) ) model.add( keras.layers.TimeDistributed( keras.layers.SimpleRNN(8, return_sequences=False) ) ) model.add(keras.layers.SimpleRNN(1, return_sequences=False)) model.compile(optimizer="rmsprop", loss="mse") model_input = np.random.randint( low=1, high=5, size=(10, 3, 4), dtype="int32" ) for i in range(4): model_input[i, i:, i:] = 0 model.fit( model_input, np.random.random((10, 1)), epochs=1, batch_size=10 ) mask_outputs = [model.layers[0].compute_mask(model.input)] for layer in model.layers[1:]: mask_outputs.append( layer.compute_mask(layer.input, mask_outputs[-1]) ) func = keras.backend.function([model.input], mask_outputs[:-1]) mask_outputs_val = func([model_input]) ref_mask_val_0 = model_input > 0 # embedding layer ref_mask_val_1 = ref_mask_val_0 # first RNN layer ref_mask_val_2 = np.any(ref_mask_val_1, axis=-1) # second RNN layer ref_mask_val = [ref_mask_val_0, ref_mask_val_1, ref_mask_val_2] for i in range(3): self.assertAllEqual(mask_outputs_val[i], ref_mask_val[i]) self.assertIs(mask_outputs[-1], None) # final layer @test_combinations.generate( test_combinations.combine(mode=["graph", "eager"]) ) def test_TimeDistributed_with_masking_layer(self): # test with Masking layer model = keras.models.Sequential() model.add( keras.layers.TimeDistributed( keras.layers.Masking( mask_value=0.0, ), input_shape=(None, 4), ) ) model.add(keras.layers.TimeDistributed(keras.layers.Dense(5))) model.compile(optimizer="rmsprop", loss="mse") model_input = np.random.randint(low=1, high=5, size=(10, 3, 4)) for i in range(4): model_input[i, i:, :] = 0.0 model.compile(optimizer="rmsprop", loss="mse") model.fit( model_input, np.random.random((10, 3, 5)), epochs=1, batch_size=6 ) mask_outputs = [model.layers[0].compute_mask(model.input)] mask_outputs += [ model.layers[1].compute_mask( model.layers[1].input, mask_outputs[-1] ) ] func = keras.backend.function([model.input], mask_outputs) mask_outputs_val = func([model_input]) self.assertEqual((mask_outputs_val[0]).all(), model_input.all()) self.assertEqual((mask_outputs_val[1]).all(), model_input.all()) def test_TimeDistributed_with_different_time_shapes(self): time_dist = keras.layers.TimeDistributed(keras.layers.Dense(5)) ph_1 = keras.backend.placeholder(shape=(None, 10, 13)) out_1 = time_dist(ph_1) self.assertEqual(out_1.shape.as_list(), [None, 10, 5]) ph_2 = keras.backend.placeholder(shape=(None, 1, 13)) out_2 = time_dist(ph_2) self.assertEqual(out_2.shape.as_list(), [None, 1, 5]) ph_3 = keras.backend.placeholder(shape=(None, 1, 18)) with self.assertRaisesRegex(ValueError, "is incompatible with"): time_dist(ph_3) def test_TimeDistributed_with_invalid_dimensions(self): time_dist = keras.layers.TimeDistributed(keras.layers.Dense(5)) ph = keras.backend.placeholder(shape=(None, 10)) with self.assertRaisesRegex( ValueError, "`TimeDistributed` Layer should be passed an `input_shape `", ): time_dist(ph) @test_combinations.generate( test_combinations.combine(mode=["graph", "eager"]) ) def test_TimeDistributed_reshape(self): class NoReshapeLayer(keras.layers.Layer): def call(self, inputs): return inputs # Built-in layers that aren't stateful use the reshape implementation. td1 = keras.layers.TimeDistributed(keras.layers.Dense(5)) self.assertTrue(td1._always_use_reshape) # Built-in layers that are stateful don't use the reshape # implementation. td2 = keras.layers.TimeDistributed( keras.layers.RNN(keras.layers.SimpleRNNCell(10), stateful=True) ) self.assertFalse(td2._always_use_reshape) # Custom layers are not allowlisted for the fast reshape implementation. td3 = keras.layers.TimeDistributed(NoReshapeLayer()) self.assertFalse(td3._always_use_reshape) @test_combinations.generate( test_combinations.combine(mode=["graph", "eager"]) ) def test_TimeDistributed_output_shape_return_types(self): class TestLayer(keras.layers.Layer): def call(self, inputs): return tf.concat([inputs, inputs], axis=-1) def compute_output_shape(self, input_shape): output_shape = tf.TensorShape(input_shape).as_list() output_shape[-1] = output_shape[-1] * 2 output_shape = tf.TensorShape(output_shape) return output_shape class TestListLayer(TestLayer): def compute_output_shape(self, input_shape): shape = super().compute_output_shape(input_shape) return shape.as_list() class TestTupleLayer(TestLayer): def compute_output_shape(self, input_shape): shape = super().compute_output_shape(input_shape) return tuple(shape.as_list()) # Layers can specify output shape as list/tuple/TensorShape test_layers = [TestLayer, TestListLayer, TestTupleLayer] for layer in test_layers: input_layer = keras.layers.TimeDistributed(layer()) inputs = keras.backend.placeholder(shape=(None, 2, 4)) output = input_layer(inputs) self.assertEqual(output.shape.as_list(), [None, 2, 8]) self.assertEqual( input_layer.compute_output_shape([None, 2, 4]).as_list(), [None, 2, 8], ) @test_combinations.run_all_keras_modes(always_skip_v1=True) # TODO(scottzhu): check why v1 session failed. def test_TimeDistributed_with_mask_first_implementation(self): np.random.seed(100) rnn_layer = keras.layers.LSTM(4, return_sequences=True, stateful=True) data = np.array( [ [[[1.0], [1.0]], [[0.0], [1.0]]], [[[1.0], [0.0]], [[1.0], [1.0]]], [[[1.0], [0.0]], [[1.0], [1.0]]], ] ) x = keras.layers.Input(shape=(2, 2, 1), batch_size=3) x_masking = keras.layers.Masking()(x) y = keras.layers.TimeDistributed(rnn_layer)(x_masking) model_1 = keras.models.Model(x, y) model_1.compile( "rmsprop", "mse", run_eagerly=test_utils.should_run_eagerly() ) output_with_mask = model_1.predict(data, steps=1) y = keras.layers.TimeDistributed(rnn_layer)(x) model_2 = keras.models.Model(x, y) model_2.compile( "rmsprop", "mse", run_eagerly=test_utils.should_run_eagerly() ) output = model_2.predict(data, steps=1) self.assertNotAllClose(output_with_mask, output, atol=1e-7) @test_combinations.run_all_keras_modes @parameterized.named_parameters( *test_utils.generate_combinations_with_testcase_name( layer=[keras.layers.LSTM, keras.layers.Dense] ) ) def test_TimeDistributed_with_ragged_input(self, layer): if tf.executing_eagerly(): self.skipTest("b/143103634") np.random.seed(100) layer = layer(4) ragged_data = tf.ragged.constant( [ [[[1.0], [1.0]], [[2.0], [2.0]]], [[[4.0], [4.0]], [[5.0], [5.0]], [[6.0], [6.0]]], [[[7.0], [7.0]], [[8.0], [8.0]], [[9.0], [9.0]]], ], ragged_rank=1, ) x_ragged = keras.Input(shape=(None, 2, 1), dtype="float32", ragged=True) y_ragged = keras.layers.TimeDistributed(layer)(x_ragged) model_1 = keras.models.Model(x_ragged, y_ragged) model_1._run_eagerly = test_utils.should_run_eagerly() output_ragged = model_1.predict(ragged_data, steps=1) x_dense = keras.Input(shape=(None, 2, 1), dtype="float32") masking = keras.layers.Masking()(x_dense) y_dense = keras.layers.TimeDistributed(layer)(masking) model_2 = keras.models.Model(x_dense, y_dense) dense_data = ragged_data.to_tensor() model_2._run_eagerly = test_utils.should_run_eagerly() output_dense = model_2.predict(dense_data, steps=1) output_ragged = convert_ragged_tensor_value(output_ragged) self.assertAllEqual(output_ragged.to_tensor(), output_dense) @test_combinations.run_all_keras_modes def test_TimeDistributed_with_ragged_input_with_batch_size(self): np.random.seed(100) layer = keras.layers.Dense(16) ragged_data = tf.ragged.constant( [ [[[1.0], [1.0]], [[2.0], [2.0]]], [[[4.0], [4.0]], [[5.0], [5.0]], [[6.0], [6.0]]], [[[7.0], [7.0]], [[8.0], [8.0]], [[9.0], [9.0]]], ], ragged_rank=1, ) # Use the first implementation by specifying batch_size x_ragged = keras.Input( shape=(None, 2, 1), batch_size=3, dtype="float32", ragged=True ) y_ragged = keras.layers.TimeDistributed(layer)(x_ragged) model_1 = keras.models.Model(x_ragged, y_ragged) output_ragged = model_1.predict(ragged_data, steps=1) x_dense = keras.Input(shape=(None, 2, 1), batch_size=3, dtype="float32") masking = keras.layers.Masking()(x_dense) y_dense = keras.layers.TimeDistributed(layer)(masking) model_2 = keras.models.Model(x_dense, y_dense) dense_data = ragged_data.to_tensor() output_dense = model_2.predict(dense_data, steps=1) output_ragged = convert_ragged_tensor_value(output_ragged) self.assertAllEqual(output_ragged.to_tensor(), output_dense) def test_TimeDistributed_set_static_shape(self): layer = keras.layers.TimeDistributed(keras.layers.Conv2D(16, (3, 3))) inputs = keras.Input(batch_shape=(1, None, 32, 32, 1)) outputs = layer(inputs) # Make sure the batch dim is not lost after array_ops.reshape. self.assertListEqual(outputs.shape.as_list(), [1, None, 30, 30, 16]) @test_combinations.run_all_keras_modes def test_TimeDistributed_with_mimo(self): dense_1 = keras.layers.Dense(8) dense_2 = keras.layers.Dense(16) class TestLayer(keras.layers.Layer): def __init__(self): super().__init__() self.dense_1 = dense_1 self.dense_2 = dense_2 def call(self, inputs): return self.dense_1(inputs[0]), self.dense_2(inputs[1]) def compute_output_shape(self, input_shape): output_shape_1 = self.dense_1.compute_output_shape( input_shape[0] ) output_shape_2 = self.dense_2.compute_output_shape( input_shape[1] ) return output_shape_1, output_shape_2 np.random.seed(100) layer = TestLayer() data_1 = tf.constant( [ [[[1.0], [1.0]], [[2.0], [2.0]]], [[[4.0], [4.0]], [[5.0], [5.0]]], [[[7.0], [7.0]], [[8.0], [8.0]]], ] ) data_2 = tf.constant( [ [[[1.0], [1.0]], [[2.0], [2.0]]], [[[4.0], [4.0]], [[5.0], [5.0]]], [[[7.0], [7.0]], [[8.0], [8.0]]], ] ) x1 = keras.Input(shape=(None, 2, 1), dtype="float32") x2 = keras.Input(shape=(None, 2, 1), dtype="float32") y1, y2 = keras.layers.TimeDistributed(layer)([x1, x2]) model_1 = keras.models.Model([x1, x2], [y1, y2]) model_1.compile( optimizer="rmsprop", loss="mse", run_eagerly=test_utils.should_run_eagerly(), ) output_1 = model_1.predict((data_1, data_2), steps=1) y1 = dense_1(x1) y2 = dense_2(x2) model_2 = keras.models.Model([x1, x2], [y1, y2]) output_2 = model_2.predict((data_1, data_2), steps=1) self.assertAllClose(output_1, output_2) model_1.fit( x=[ np.random.random((10, 2, 2, 1)), np.random.random((10, 2, 2, 1)), ], y=[ np.random.random((10, 2, 2, 8)), np.random.random((10, 2, 2, 16)), ], epochs=1, batch_size=3, ) def test_TimeDistributed_Attention(self): query_input = keras.layers.Input(shape=(None, 1, 10), dtype="float32") value_input = keras.layers.Input(shape=(None, 4, 10), dtype="float32") # Query-value attention of shape [batch_size, Tq, filters]. query_value_attention_seq = keras.layers.TimeDistributed( keras.layers.Attention() )([query_input, value_input]) model = keras.models.Model( [query_input, value_input], query_value_attention_seq ) model.compile(optimizer="rmsprop", loss="mse") model.fit( [ np.random.random((10, 8, 1, 10)), np.random.random((10, 8, 4, 10)), ], np.random.random((10, 8, 1, 10)), epochs=1, batch_size=10, ) # test config and serialization/deserialization model.get_config() model = keras.models.model_from_json(model.to_json()) model.summary() def convert_ragged_tensor_value(inputs): if isinstance(inputs, tf.compat.v1.ragged.RaggedTensorValue): flat_values = tf.convert_to_tensor( value=inputs.flat_values, name="flat_values" ) return tf.RaggedTensor.from_nested_row_splits( flat_values, inputs.nested_row_splits, validate=False ) return inputs if __name__ == "__main__": tf.test.main()
38.57645
80
0.572392
bb0a3855428ac8575217bf95f496a5b112bc09d2
4,006
cs
C#
Amns.Tessen/Web/UI/WebControls/DojoBulkAttendanceEntryGrid.cs
rahodges/Tessen
bb2198eedf1e04412b7a656dda0b92439e8b6aa5
[ "MIT" ]
null
null
null
Amns.Tessen/Web/UI/WebControls/DojoBulkAttendanceEntryGrid.cs
rahodges/Tessen
bb2198eedf1e04412b7a656dda0b92439e8b6aa5
[ "MIT" ]
null
null
null
Amns.Tessen/Web/UI/WebControls/DojoBulkAttendanceEntryGrid.cs
rahodges/Tessen
bb2198eedf1e04412b7a656dda0b92439e8b6aa5
[ "MIT" ]
null
null
null
using System; using System.Data; using System.Data.OleDb; using System.Web.UI; using System.ComponentModel; using System.Web.UI.WebControls; using System.Web; using Amns.GreyFox.Web.UI.WebControls; using Amns.Tessen; namespace Amns.Tessen.Web.UI.WebControls { /// <summary> /// Summary description for MemberListGrid. /// </summary> [DefaultProperty("Text"), ToolboxData("<{0}:DojoBulkAttendanceEntryGrid runat=server></{0}:DojoBulkAttendanceEntryGrid>")] public class DojoBulkAttendanceEntryGrid : TableGrid { private string connectionString; #region Public Properties [Bindable(true), Category("Data"), DefaultValue("")] public string ConnectionString { get { return connectionString; } set { connectionString = value; } } #endregion public DojoBulkAttendanceEntryGrid() : base() { this.features |= TableWindowFeatures.ClientSideSelector; } protected override void OnInit(EventArgs e) { base.OnInit (e); bool adminMode = Page.User.IsInRole("Tessen/Administrator"); this.deleteButton.Enabled = adminMode; this.editButton.Enabled = adminMode; this.newButton.Enabled = adminMode; } #region Rendering /// <summary> /// Render this control to the output parameter specified. /// </summary> /// <param name="output"> The HTML writer to write out to </param> protected override void RenderContent(HtmlTextWriter output) { EnsureChildControls(); DojoBulkAttendanceEntryManager m = new DojoBulkAttendanceEntryManager(); DojoBulkAttendanceEntryCollection dojoBulkAttendanceEntryCollection = m.GetCollection(string.Empty, "LastName, FirstName, MiddleName", new DojoBulkAttendanceEntryFlags[] { DojoBulkAttendanceEntryFlags.Member, DojoBulkAttendanceEntryFlags.Rank, DojoBulkAttendanceEntryFlags.MemberPrivateContact}); bool rowflag = false; string rowCssClass; // // Render Records // foreach(DojoBulkAttendanceEntry entry in dojoBulkAttendanceEntryCollection) { if(rowflag) rowCssClass = this.defaultRowCssClass; else rowCssClass = this.alternateRowCssClass; rowflag = !rowflag; output.WriteBeginTag("tr"); output.WriteAttribute("i", entry.ID.ToString()); output.WriteLine(HtmlTextWriter.TagRightChar); output.Indent++; // // Render Main Representation of Record // output.WriteBeginTag("td"); output.WriteAttribute("valign", "top"); output.WriteAttribute("class", rowCssClass); output.Write(HtmlTextWriter.TagRightChar); output.Write(entry.Member.PrivateContact.FullName); output.WriteEndTag("td"); output.WriteLine(); // // Render Start and End Dates // output.WriteBeginTag("td"); output.WriteAttribute("class", rowCssClass); output.Write(HtmlTextWriter.TagRightChar); output.Write(entry.StartDate.ToShortDateString()); output.Write(" - "); output.Write(entry.EndDate.ToShortDateString()); output.WriteEndTag("td"); output.WriteLine(); // // Render Time // output.WriteBeginTag("td"); output.WriteAttribute("class", rowCssClass); output.Write(HtmlTextWriter.TagRightChar); output.Write(entry.Duration.TotalHours); output.Write(" hrs. "); output.WriteEndTag("td"); output.WriteLine(); // // Render Rank // output.WriteBeginTag("td"); output.WriteAttribute("class", rowCssClass); output.Write(HtmlTextWriter.TagRightChar); output.Write(entry.Rank.Name); output.WriteEndTag("td"); output.WriteLine(); if(deleteEnabled) { output.WriteBeginTag("a"); output.WriteAttribute("href", "javascript:" + Page.ClientScript.GetPostBackEventReference(this, "delete_" + entry.ID)); output.Write(HtmlTextWriter.TagRightChar); output.Write("delete"); output.WriteEndTag("a"); output.WriteLine(); } output.Indent--; output.WriteEndTag("tr"); output.WriteLine(); } } #endregion } }
26.529801
124
0.694958
af89ecde19b8ea0aa6f7eec4d787b4af1c5c28e9
2,564
py
Python
VMD 3D Pose Baseline Multi-Objects/applications/VmdWriter.py
kyapp69/OpenMMD
795d4dd660cf7e537ceb599fdb038c5388b33390
[ "MIT" ]
717
2018-10-31T16:52:42.000Z
2022-03-31T16:13:47.000Z
VMD 3D Pose Baseline Multi-Objects/applications/VmdWriter.py
Pixis5566/OpenMMD
795d4dd660cf7e537ceb599fdb038c5388b33390
[ "MIT" ]
48
2018-11-08T12:16:43.000Z
2020-08-10T00:24:50.000Z
VMD 3D Pose Baseline Multi-Objects/applications/VmdWriter.py
Pixis5566/OpenMMD
795d4dd660cf7e537ceb599fdb038c5388b33390
[ "MIT" ]
180
2018-10-31T18:41:33.000Z
2022-03-27T23:49:06.000Z
# -*- coding: utf-8 -*- import struct from PyQt5.QtGui import QQuaternion, QVector3D class VmdBoneFrame(): def __init__(self, frame=0): self.name = '' self.frame = frame self.position = QVector3D(0, 0, 0) self.rotation = QQuaternion() def write(self, fout): fout.write(self.name) fout.write(bytearray([0 for i in range(len(self.name), 15)])) # ボーン名15Byteの残りを\0で埋める fout.write(struct.pack('<L', self.frame)) fout.write(struct.pack('<f', self.position.x())) fout.write(struct.pack('<f', self.position.y())) fout.write(struct.pack('<f', self.position.z())) v = self.rotation.toVector4D() fout.write(struct.pack('<f', v.x())) fout.write(struct.pack('<f', v.y())) fout.write(struct.pack('<f', v.z())) fout.write(struct.pack('<f', v.w())) fout.write(bytearray([0 for i in range(0, 64)])) # 補間パラメータ(64Byte) class VmdInfoIk(): def __init__(self, name='', onoff=0): self.name = name self.onoff = onoff class VmdShowIkFrame(): def __init__(self): self.frame = 0 self.show = 0 self.ik = [] def write(self, fout): fout.write(struct.pack('<L', self.frame)) fout.write(struct.pack('b', self.show)) fout.write(struct.pack('<L', len(self.ik))) for k in (self.ik): fout.write(k.name) fout.write(bytearray([0 for i in range(len(k.name), 20)])) # IKボーン名20Byteの残りを\0で埋める fout.write(struct.pack('b', k.onoff)) class VmdWriter(): def __init__(self): pass def write_vmd_file(self, filename, bone_frames, showik_frames): """Write VMD data to a file""" fout = open(filename, "wb") # header fout.write(b'Vocaloid Motion Data 0002\x00\x00\x00\x00\x00') fout.write(b'Dummy Model Name ') # bone frames fout.write(struct.pack('<L', len(bone_frames))) # ボーンフレーム数 for bf in bone_frames: bf.write(fout) fout.write(struct.pack('<L', 0)) # 表情キーフレーム数 fout.write(struct.pack('<L', 0)) # カメラキーフレーム数 fout.write(struct.pack('<L', 0)) # 照明キーフレーム数 fout.write(struct.pack('<L', 0)) # セルフ影キーフレーム数 if showik_frames == None: fout.write(struct.pack('<L', 0)) # モデル表示・IK on/offキーフレーム数 else: fout.write(struct.pack('<L', len(showik_frames))) # モデル表示・IK on/offキーフレーム数 for sf in showik_frames: sf.write(fout) fout.close()
34.648649
95
0.565523
ccf7b8a022781d12d0a991008ebe7fde4ef9e671
340
rb
Ruby
trivia-time-backend/app/services/game_serializer.rb
B0NG0FURY/trivia-time
e1d858588c4afd3e492f4c656443af3395057755
[ "MIT" ]
1
2021-11-01T23:22:49.000Z
2021-11-01T23:22:49.000Z
trivia-time-backend/app/services/game_serializer.rb
B0NG0FURY/trivia-time
e1d858588c4afd3e492f4c656443af3395057755
[ "MIT" ]
null
null
null
trivia-time-backend/app/services/game_serializer.rb
B0NG0FURY/trivia-time
e1d858588c4afd3e492f4c656443af3395057755
[ "MIT" ]
null
null
null
class GameSerializer def initialize(game) @game = game end def to_serialized_json @game.to_json(include: { questions: {methods: [:all_answers], only: [:text, :correct_answer]}, category: {only: [:name]} }, except: [:user_id, :category_id, :created_at, :updated_at]) end end
24.285714
81
0.591176
54967e6729bb6cd141674014cad222c362f63f32
1,158
css
CSS
src/styles/jawbar.css
brettz9/jawbar
ab0c792d1b1af6c2b1aa0c5cc237300e1e98033f
[ "MIT" ]
null
null
null
src/styles/jawbar.css
brettz9/jawbar
ab0c792d1b1af6c2b1aa0c5cc237300e1e98033f
[ "MIT" ]
null
null
null
src/styles/jawbar.css
brettz9/jawbar
ab0c792d1b1af6c2b1aa0c5cc237300e1e98033f
[ "MIT" ]
null
null
null
.jawbar-optionContainer { position: absolute; visibility: visible; z-index: 101; background-color: #ffffff; border: 1px solid #000000; overflow: auto; } .jawbar-hidden { visibility: hidden; } .jawbar-dropdownButton { position: absolute; border: 0px; width: 5px; background: url(../images/down.png) center no-repeat; cursor: pointer; } .jawbar-imageContainer { font-size: 0px; padding: 2px; float: left; width: 16px; } .jawbar-menuitem { color: #000000; background-color: #ffffff; cursor: pointer; border-bottom: 1px solid #e0e0e0; display: block; } .jawbar-menuitem-hover { /* To support keyboard-initiated hover, we need a class instead of :hover because mouseover, as it is not a trusted event, cannot be simulated to activate :hover (see http://stackoverflow.com/a/17226753 )*/ color: #ffffff; background-color: #0099ff; } .jawbar-menuitem-removed { display: none; } .jawbar-menuitem-icon { vertical-align: top; border: 0px; } .jawbar-menuitem-text { font-size: 15pt; } .jawbar-menuitem-subText { font-size: 10pt; font-style: italic; }
21.849057
231
0.664076
b08ed42d8685951ada4f5234dfde4ce55f2d0c04
9,510
py
Python
Clue/S3LoadingSample.py
RijulT/examples
497bba8df9717193fbc89f038bab081c25efd972
[ "Unlicense" ]
null
null
null
Clue/S3LoadingSample.py
RijulT/examples
497bba8df9717193fbc89f038bab081c25efd972
[ "Unlicense" ]
7
2018-07-13T00:36:38.000Z
2021-10-20T03:02:20.000Z
Clue/S3LoadingSample.py
RijulT/examples
497bba8df9717193fbc89f038bab081c25efd972
[ "Unlicense" ]
18
2016-08-05T16:19:01.000Z
2021-07-07T18:30:11.000Z
''' Example of reading a data file and loading it into S3 bucket Files are processed from a "queue" directory and after processing moved to a "processed" directory Version: 1.6 Date: 2021-04-22 Version History: Version Description Author --------------------------------------------------- 1.0 Initial Release MB 1.1 Ready for Task Manager MB 1.3 Sorted files in mod time asc MB 1.4 Added delay between files MB 1.5 Changed put method to set ACL MB Changes to List method (using v2) to enable more than 1000 files 1.6 Adds method of handling various MB time formats see to_falkonry_datetime_str ''' import pandas as pd # used to facilitate reading metadata and file contents import logging import logging.handlers import io import boto3 import os import time as tm import shutil from enum import Enum from datetime import * import pytz import warnings warnings.simplefilter(action='ignore', category=UserWarning) warnings.simplefilter(action='ignore', category=pd.errors.DtypeWarning) def configure_logging(logroot,source=__file__,format='%(asctime)s:%(levelname)s:%(message)s',daystokeep=7,level=logging.INFO): name=os.path.basename(source) logger=logging.getLogger(name) logger.setLevel(level) logfile=name[:-3] formatter=logging.Formatter(format) if(not(os.path.exists(logroot))): os.makedirs(logroot) fileHandler=logging.handlers.TimedRotatingFileHandler("{0}/{1}.log".format(logroot,logfile),when='D',backupCount=10,interval=daystokeep) fileHandler.setFormatter(formatter) logger.addHandler(fileHandler) consoleHandler=logging.StreamHandler() consoleHandler.setFormatter(formatter) logger.addHandler(consoleHandler) return logger # sort files in dir according to modification time def get_time_sorted_files(dir,extension=None): fts_sorted=[] for _,_,files in os.walk(dir): fts={} for file in files: if(extension and not(file.endswith(extension))): continue fts[file]=os.path.getmtime(os.path.join(dir,file)) fts_sorted=sorted(fts,key=lambda key: fts[key]) break # only process this directory return fts_sorted class TimeFormats(Enum): ISO='iso-8601' MICROS='micros' NANOS='nanos' MILLIS='millis' SECS='seconds' def to_falkonry_datetime_str(dt:datetime,format=TimeFormats.ISO): # if not timezone aware raise exception if(dt.tzinfo is None or dt.tzinfo.utcoffset(dt) is None): raise ValueError("dt must be timezone aware") # convert to utc utc_dt=dt.astimezone(timezone.utc) # Falkonry only accepts 6 figures (microsecs) if(format==TimeFormats.SECS): return str(round(utc_dt.timestamp())) elif(format==TimeFormats.MILLIS): return str(round(utc_dt.timestamp()*1000)) elif(format==TimeFormats.MICROS): return str(round(utc_dt.timestamp()*1e6)) elif(format==TimeFormats.NANOS): return str(round(utc_dt.timestamp()*1e9)) else: # Falkonry only accepts 6 figures (microsecs) return datetime.strftime(utc_dt,"%Y-%m-%dT%H:%M:%S.%fZ") def remove_nas(df,inplace=True): df_ret = df if(not(inplace)): df_ret=pd.DataFrame(df) df_ret = df_ret.replace(r'^\s*$', '', regex=True) # eliminate spaces df_ret = df_ret.applymap(lambda s: '' if str(s).lower() in ['na','n/a','nan','none','null'] else s) return df_ret out_bucket="falkonry-customer-uploads" # TODO: Data files are expected to be .csv time in wide format. # The column names are expected to be those in the customer tags defined in the Site Survey # plus a timestamp column (any name is fine) # # Files are placed in a directory and # Example file contents: # timestamp, tag1, tag2, tag3 # 2021-01-01 12:00:01.500 PM, 12.34, STARTING_MODE, 1 # .... # 2021-05-01 09:00:02.0000 AM, 4.5, STOPPING_MODE, 0 # TODO: ADJUST ACCORDING TO NEEDS. IF FILES ARE VERY LARGE INCREASE DELAY IN BETWEEN poll=1 # minutes to check again for arrival of new files to the queue delay=60 # delay between sending each file. Allows S3 events to not overlap. # TODO: SPECIFY LOCATION OF LOGS, FILES TO PROCESS, log_root="<PATH TO WHERE TO STORE LOG FILES>" # location to store log files queue_dir = "<PATH TO QUEUE WERE FILES ARE GOING TO BE PLACED FOR LOADING>" # Location of files to move processed_dir = "<PATH TO STORE PROCESSED FILES>" # Location of files sucessfully processed logger=configure_logging(log_root) # TODO: SPECIFY TIME COLUMN FORMAT IN FILES tscol="<NAME OF COLUMN IN DATA FILES THAT HOLDS TIMESTAMPS>" # Column in the soure file that contains the time stamp tsformat="<FORMAT STRING OF WHAT IS IN THE FILE>" # Format in which the timestamp string is stored in the file # see https://www.cplusplus.com/reference/ctime/strftime/ desired_format=TimeFormats.ISO # desired format to send to Falkonry - MUST match defined in Clue Data Source tzone= "<TIMEZONE STRING FOR THE TIMESTAMPS IN THE FILE>" # Time zone name in which the date was stored please see this for list of supported names # see https://gist.github.com/heyalexej/8bf688fd67d7199be4a1682b3eec7568 pytzone=pytz.timezone(tzone) # TODO: SPECIFY ACCOUNT SPECIFIC INFORMATION account_id= "<YOUR ACCOUNT ID FROM FALKONRY APP>" profile_name="<PROFILE NAME IN credentials file>" # this points to a set of credentials stored in .aws credentials file in the host # see https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials_profiles.html prefix="<ANY PREFIX TO ISOLATE FILES OR DIFFERENT FORMATS AND HANDLING>" # This is used to differentiate files that need different processing (example, different formats, equipment) # TODO: MODIFIY ACCORDING TO YOUR SITE SURVEY CUSTOMER TAGS SHEET site_survey_file= "<PATH TO YOUR SITE SURVEY EXCEL FILE>" tags_df=pd.read_excel(site_survey_file,sheet_name="4.Customer Tags") # Falkonry will not ignore additional columns that may exit in the source data files # This uses the site survey to only process those columns cols_to_send=tags_df['Signal Tag Name'].unique().tolist() # TODO: COMMENT NEXT LINE IF RUNNING WITH TASK MANAGER AND OUTDENT TRY,CATCH BLOCKS # while(True): try: # Open connection to s3 session = boto3.Session(profile_name=profile_name) s3_resource = session.resource('s3') # low level client s3_client = session.client('s3') # high level client logger.info("session opened with profile name {0}".format(profile_name)) files=get_time_sorted_files(queue_dir) if(len(files)==0): logger.info("No files to process at this time in the {0} directory".format(queue_dir)) for in_file in files: logger.info("reading file {0}".format(in_file)) source_file=os.path.join(queue_dir, in_file) df=pd.read_csv(source_file,dtype={tscol:str}) # do not parse timestamp to datetime # exclude tags not needed df=df[cols_to_send] # Correct datetime format before sending df[tscol]=pd.to_datetime(df[tscol]) df[tscol]=df[tscol].apply(lambda c: to_falkonry_datetime_str(c.tz_localize(pytzone), desired_format)) # Correct nans,n/a,none,np.nan with emtpy df=remove_nas(df) # Send file pfx="{0}/{1}".format(account_id,prefix) out_file="{0}/{1}".format(pfx,in_file) s=io.StringIO() logging.info("writing dataframe to text stream") df.to_csv(s,index=False) # write pandas frame to stream logger.info("sending file {0} to bucket {1}".format(out_file,out_bucket)) s3_resource.Object(out_bucket, out_file).put(Body=s.getvalue(),ACL="bucket-owner-full-control") # Check if it worked size = 0 saved = False items = s3_client.list_objects_v2(Bucket=out_bucket, Prefix=pfx) items_list = [] items_list.extend(items['Contents']) while (items['IsTruncated']): next_key = items['NextContinuationToken'] items = s3_client.list_objects_v2(Bucket=out_bucket, Prefix=pfx, ContinuationToken=next_key) items_list.extend(items['Contents']) for item in items_list: if(item['Key']==out_file): saved=True size=item['Size'] break if(saved): if(size>0): logger.info("file {1} saved to bucket {0} with size={2} bytes".format(out_bucket,source_file,size)) shutil.move(source_file,os.path.join(processed_dir,in_file)) else: logger.error("file {1} saved to bucket {0} is empty".format(out_bucket,out_file)) else: logger.error("failed to save file {0} in bucket {1}".format(source_file,out_bucket)) # sleep between sending each file tm.sleep(delay) except Exception as e: logger.exception(e) # TODO: COMMENT NEXT TWO LINES IF RUNNING WITH TASK MANAGER #logger.info("Sleeping for {0} minutes".format(poll)) #tm.sleep(60*poll)
44.027778
182
0.660883
ab37b9b6c1529dfd213077de12a7206ad9506c18
168
swift
Swift
demo/Checkmark/Source/RootViewController.swift
Blackjacx/SignInWithApple
275894d1130268aec832c02dff49d4a353d8146c
[ "MIT" ]
1
2019-12-20T21:59:02.000Z
2019-12-20T21:59:02.000Z
demo/Checkmark/Source/RootViewController.swift
Blackjacx/SignInWithApple
275894d1130268aec832c02dff49d4a353d8146c
[ "MIT" ]
null
null
null
demo/Checkmark/Source/RootViewController.swift
Blackjacx/SignInWithApple
275894d1130268aec832c02dff49d4a353d8146c
[ "MIT" ]
null
null
null
import UIKit final class RootViewController: UITableViewController { @IBAction func didPressSignOut(_ sender: Any) { GlobalState.performSignOut() } }
18.666667
55
0.72619
97ec2f8b0f9d622bf63a14bce251e34be5021473
413
rb
Ruby
app/models/user.rb
muazzamnashat/finAdvisor-backend
612c00c68d0b512546dd7f8516f7ab3a307f44d0
[ "Unlicense" ]
null
null
null
app/models/user.rb
muazzamnashat/finAdvisor-backend
612c00c68d0b512546dd7f8516f7ab3a307f44d0
[ "Unlicense" ]
null
null
null
app/models/user.rb
muazzamnashat/finAdvisor-backend
612c00c68d0b512546dd7f8516f7ab3a307f44d0
[ "Unlicense" ]
null
null
null
class User < ApplicationRecord has_many :transactions has_many :bills has_many :budgets has_secure_password validates :email, uniqueness: { case_sensitive: false } def total_spend Transaction.where(user_id: self.id, deposit: false).group_by_month(:date).sum(:amount) end def total_income Transaction.where(user_id: self.id, deposit: true).group_by_month(:date).sum(:amount) end end
24.294118
90
0.748184
b332fd69b37397305a12fadff2c3f282ba18f273
8,527
py
Python
src/copy.py
swerwath/monitor_mapper
59a1f2977212e68abd6bc4906cd6d10b0430529e
[ "BSD-2-Clause" ]
null
null
null
src/copy.py
swerwath/monitor_mapper
59a1f2977212e68abd6bc4906cd6d10b0430529e
[ "BSD-2-Clause" ]
null
null
null
src/copy.py
swerwath/monitor_mapper
59a1f2977212e68abd6bc4906cd6d10b0430529e
[ "BSD-2-Clause" ]
null
null
null
from flask import Markup CHEM_NAMES = { "PM2.5" : "PM<sub>2.5</sub>", "SO2" : "SO<sub>2</sub>", "NO2" : "NO<sub>2</sub>", "OZONE" : "ozone", } HEALTH_RISKS = { "PM2.5" : "Long-term exposure increases the risk of death from <a href=\"https://www.ncbi.nlm.nih.gov/pubmed/20458016\">heart disease</a> and <a href=\"https://www.ncbi.nlm.nih.gov/pubmed/11879110\">lung cancer</a>. Prolonged exporsure can also lead to <a href=\"https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3637008/\">quicker rate of artery thickening</a>, which increases the lifetime risk of developing cardiovascular disease.", "SO2" : "Acute short-term exposure to SO<sub>2</sub> can cause breathing difficulty, especially for people with asthma or other vulnerable populations.", "NO2" : "Long-term exposure to NO<sub>2</sub> is suspected to contribute to the development of asthma. Acute exposure can cause <a href=\"https://www.epa.gov/no2-pollution/basic-information-about-no2#Effects\" target=\"_blank\">irritation of the lungs and aggravate existing respiratory diseases</a>. NO<sub>2</sub> and other NO<sub>x</sub> compounds also lead to the development of acid rain, which can damage important ecosystems.", "OZONE" : "Long-term exposure to ozone increases the chance of lung infection and can <a href=\"https://www.epa.gov/ozone-pollution/health-effects-ozone-pollution\" target=\"_blank\">lead to the development of asthma</a>, especially in children. Acute short-term exposure can trigger asthma attacks or aggravate chronic bronchitis in people who already have those diseases. It can also cause difficulty of breathing and coughing, even in healthy people.", } EJ_EVIDENCE = { "PM2.5" : "Additionally, PM<sub>2.5</sub> carries environmental justice concerns, since people of color in the US <a href=\"https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3137995/\" target=\"_blank\">are more likely to live in areas with high PM<sub>2.5</sub> levels</a>. ", "SO2" : "", "NO2" : "", "OZONE" : "Additionally, ozone carries environmental justice concerns, since people of color in the US <a href=\"https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3137995/\" target=\"_blank\">are more likely to live in areas with high ozone levels</a>. ", } INFO = { "PM2.5" : CHEM_NAMES["PM2.5"] + " refers to particulate matter that has a diameter of less than 2.5 micrometers. These fine particles can be emitted from a number of sources, including power plants, motor vehicles, and forest/residential fires. Because " + CHEM_NAMES["PM2.5"] + " particles are so small, they stay in the air for longer than their heavier counterparts, increasing the odds that a human breathes them in. Once they enter the body, the fine particles can penetrate into the lungs and circulatory system. " + HEALTH_RISKS["PM2.5"] + " " + EJ_EVIDENCE["PM2.5"], "SO2" : "Sulfur Dioxide (SO<sub>2</sub>) is an air pollutant released primarily from the burning of fossil fuels at power plants and large industrial facilities. In addition to carrying its own health risks, SO<sub>2</sub> can react with other chemicals in the air to form PM<sub>2.5</sub> particulate matter (see above). " + HEALTH_RISKS["SO2"], "NO2" : "Nitrogen Dioxide (NO<sub>2</sub>) is a highly reactive gas emitted primarily from the burning of fuel, both from motor vehicles and power plants. NO<sub>2</sub> is a member of and an indicator for a group of chemicals called nitrogen oxides (NO<sub>x</sub>). " + HEALTH_RISKS["NO2"], "OZONE" : "Ozone (O<sub>3</sub>) is a gas found both in the upper atmosphere and at ground level. Ground level ozone is not released directly into the air; rather, it is created as a product of chemical reactions between other air pollutants. These chemical reactions are accelerated on hot days, leading to increased ozone levels. " + HEALTH_RISKS["OZONE"] + " " + EJ_EVIDENCE["OZONE"], } LINK = { "PM2.5" : "#", "SO2" : "#", "NO2" : "#", "OZONE" : "https://www.epa.gov/ozone-pollution/health-effects-ozone-pollution", } DIST_VAR = { "PM2.5" : "While PM<sub>2.5</sub> levels at various stations within a single city tend to be highly correlated, <a href=\"https://doi.org/10.1080/10473289.2004.10470919\">there is still variation</a> in measurements.", "SO2" : "", "NO2" : "Since one of main sources of NO<sub>2</sub> is motor vehicles, <a href=\"https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5348563/\">proximity to traffic</a> is a highly predictive of pollution levels. Since motor vehicle traffic varies over time (e.g. \"rush hour\") and air monitoring has low temporal resolution, it's important to keep in mind that NO<sub>2</sub> levels may higher than measured at certain times of day.", "OZONE" : "While ozone has <a href=\"https://www.sciencedirect.com/science/article/pii/0004698180900529\">relatively low spatial variation</a> in comparison to other pollutants, its distribution is still heavily dependent on nearby emission sources. If an ozone monitor is upwind of a large emission source, its reading may not be representative of the surrounding area.", } def dist_copy(dist, chem): copy = "The nearest " + CHEM_NAMES[chem] + " monitoring station is " + ("%.1f" % dist) + " miles away from you" if dist < 6.21: copy += ", meaning that this monitor is likely close enough to give you an accurate estimate of the air pollution where you are." elif dist < 9.3: copy += ". While this station is not very close to you, it provides a moderately confident estimate of " + CHEM_NAMES[chem] + " levels near you. However, certain factors like wind and topological features may affect this accuracy." else: copy += ". Given how far away the monitor is, it's unlikely that its measurements are representative of " + CHEM_NAMES[chem] + " levels near you." copy += " " + DIST_VAR[chem] return copy def aqi_copy(aqi, chem_name): copy = "The <b>Air Quality Index</b> (AQI) is a number that tells you how much of a certain " + \ "chemical is in the air, and if that level of pollution carries any potential health concerns. " + \ "Based on the nearest available monitoring station, the estimated AQI for " + chem_name + " near you is " + str(aqi) + ", " if aqi < 51: copy += "which the EPA classifies as <font color=\"green\">good</font>. This means that levels of " + chem_name + " are low, and air pollution poses little to no health risks for long periods of exposure." elif aqi < 101: copy += "which the EPA classifies as <font color=\"orange\">moderate</font>. This means that levels of " + chem_name + " are within regulatory limits, but a very small number of sensitive people may experience health effects." elif aqi < 151: copy += "which the EPA classifies as <font color=\"red\">unhealthy for sensitive groups</font>. This means that levels of " + chem_name + " are at high levels. People with heart or lung disease, children, and older adults may begin to experience greater health risk." else: copy += "which the EPA classifies as <font color=\"maroon\">very unhealthy</font>. This means that levels of " + chem_name + " are at very high levels. All people may begin to experience health effects, and members of sensitive groups may experience very serious health risks." copy += " For more information on the Air Quality Index, click <a href=\"https://airnow.gov/index.cfm?action=aqibasics.aqi\" target=\"_blank\">here</a>." return copy def get_copy(chem, nearest_monitors): info = INFO[chem] + "<br /><br />" if not chem in nearest_monitors.keys(): dist = "It looks like <b>there are no " + CHEM_NAMES[chem] + " monitors in your area!</b> Why does this matter? " + \ " Since you don't live by any " + CHEM_NAMES[chem] + \ " monitoring stations, there is no way for public health officials to estimate the exposure of people in your community. " + \ EJ_EVIDENCE[chem] + "If you're concerned about the lack of " + CHEM_NAMES[chem] + " monitoring in your community, you can " + \ "learn more about " + CHEM_NAMES[chem] + " using the link below, or keep scrolling to get involved with community air monitoring efforts and your local air district." read = "" else: d = nearest_monitors[chem][1] aqi = nearest_monitors[chem][0]['AQI'] dist = dist_copy(d, chem) + " <br /><br />" read = aqi_copy(aqi, CHEM_NAMES[chem]) return (Markup(info), Markup(dist), Markup(read))
92.684783
578
0.705406
c9ea044a70879d4c93febf98625e9e28d5d1c862
2,234
ts
TypeScript
Samples/Widgets/infor.sample.workspace/services/workspace.service.ts
infor-hl-manila/homepage-widgets
1ff1971579ca0a6f3fbab706bbb17fe6f3a33ae4
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
1
2020-01-28T16:08:47.000Z
2020-01-28T16:08:47.000Z
Samples/Widgets/infor.sample.workspace/services/workspace.service.ts
infor-hl-manila/homepage-widgets
1ff1971579ca0a6f3fbab706bbb17fe6f3a33ae4
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
3
2019-01-28T06:44:10.000Z
2020-04-04T17:40:45.000Z
Samples/Widgets/infor.sample.workspace/services/workspace.service.ts
infor-hl-manila/homepages-widget
1ff1971579ca0a6f3fbab706bbb17fe6f3a33ae4
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
null
null
null
import { Injectable, ViewContainerRef } from "@angular/core"; import { PanelComponentType, SohoContextualActionPanelService, SohoMessageService } from "@infor/sohoxi-angular"; import { Observable } from "rxjs"; @Injectable({ providedIn: "root", }) export class WorkspaceService { constructor(private capService: SohoContextualActionPanelService, private messageService: SohoMessageService) { } open<T extends IWorkspaceComponent>(options: IWorkspaceOptions<T>) { const cap = this.capService.contextualactionpanel(options.component, options.viewRef); cap.options({ centerTitle: true, }); const buttons: SohoContextualActionPanelButton[] = [ { click: () => cap.close(), text: "Cancel", align: "left", } as SohoContextualActionPanelButton, { align: "center", cssClass: "btn-icon", icon: "#icon-launch", click: () => { cap.componentPanel.launchClicked(); cap.close(); }, } as SohoContextualActionPanelButton, ]; if (!options.props.readOnly) { buttons.push({ text: "Submit", align: "right", click: () => { cap.componentPanel.submitClicked().subscribe( () => cap.close(), (error: Error) => this.showError(error), ); }, } as SohoContextualActionPanelButton); } cap.buttons(buttons); cap.apply(component => { if (options.props) { for (const propertyKey in options.props) { if (options.props.hasOwnProperty(propertyKey)) { component[propertyKey] = options.props[propertyKey]; } } } }); cap.title(options.title || " "); cap.trigger("immediate"); cap.open(); } private showError(error: Error) { const messageRef = this.messageService.error({ title: "Error when submitting changes", message: error.message, buttons: [ { text: "Close", click: () => messageRef.close() } ], }); messageRef.open(); } } export interface IWorkspaceComponent { submitClicked: () => Observable<unknown>; launchClicked: () => void; readOnly: boolean; } export interface IWorkspaceOptions<T> { component: PanelComponentType<T>; viewRef: ViewContainerRef; title?: string; props?: Partial<T>; }
26.915663
115
0.643688
45379a53e986312abc021ee2996dabeba38d6b50
34
sql
SQL
app/ThirdParty/php-sql-parser/tests/expected/creator/issue86.sql
PedrinskyXV/catastro
edc25d9074ba3cdf4dd76d94c7a6b929abafcc05
[ "MIT" ]
535
2015-01-19T18:12:48.000Z
2022-03-30T18:54:46.000Z
app/ThirdParty/php-sql-parser/tests/expected/creator/issue86.sql
PedrinskyXV/catastro
edc25d9074ba3cdf4dd76d94c7a6b929abafcc05
[ "MIT" ]
287
2015-01-17T21:55:46.000Z
2022-03-04T11:55:31.000Z
app/ThirdParty/php-sql-parser/tests/expected/creator/issue86.sql
PedrinskyXV/catastro
edc25d9074ba3cdf4dd76d94c7a6b929abafcc05
[ "MIT" ]
171
2015-02-17T17:34:55.000Z
2022-03-27T03:52:05.000Z
SELECT * FROM cities GROUP BY 1, 2
34
34
0.735294
df69a0edf52d14dedf1ae1fd77350d8510fa0483
1,606
asm
Assembly
samples/sms/player_cntrl_dog/player_anm.asm
0x8BitDev/MAPeD-SPReD
da1a8a582980ea5963777a46fd3dfddc0d69aa82
[ "MIT" ]
23
2019-05-16T20:23:49.000Z
2022-03-13T21:53:10.000Z
samples/sms/player_cntrl_dog/player_anm.asm
0x8BitDev/MAPeD-SPReD
da1a8a582980ea5963777a46fd3dfddc0d69aa82
[ "MIT" ]
6
2021-03-30T05:51:46.000Z
2022-01-07T13:18:44.000Z
samples/sms/player_cntrl_dog/player_anm.asm
0x8BitDev/MAPeD-SPReD
da1a8a582980ea5963777a46fd3dfddc0d69aa82
[ "MIT" ]
null
null
null
;######################################################################## ; ; Copyright 2019-2020 0x8BitDev ( MIT license ) ; ;######################################################################## .incdir "data" .include "dog_gfx.asm" player_tiles_0: .incbin "dog_gfx_chr0.bin" player_tiles_1: .incbin "dog_gfx_chr1.bin" player_tiles_2: .incbin "dog_gfx_chr2.bin" player_tiles_3: .incbin "dog_gfx_chr3.bin" player_tiles_4: .incbin "dog_gfx_chr4.bin" player_tiles_5: .incbin "dog_gfx_chr5.bin" player_tiles_6: .incbin "dog_gfx_chr6.bin" player_tiles_7: .incbin "dog_gfx_chr7.bin" player_tiles_arr: .word 384, player_tiles_0, .word 384, player_tiles_1, .word 384, player_tiles_2, .word 384, player_tiles_3, .word 384, player_tiles_4, .word 384, player_tiles_5, .word 384, player_tiles_6, .word 384, player_tiles_7 ; *** ANIMATIONS DATA *** player_run_right: .byte 8 ; number of ticks to change a frame .byte $02 ; number of frames .byte $00 ; loop frame .word dog01_RUN01_RIGHT_frame ; frame data pointer player_run_left: .byte 8 .byte $02 .byte $00 .word dog01_RUN01_LEFT_frame player_idle_right: player_duck_right: player_shoot_right: .byte 10 .byte $02 .byte $00 .word dog01_IDLE01_RIGHT_frame player_idle_left: player_duck_left: player_shoot_left: .byte 10 .byte $02 .byte $00 .word dog01_IDLE01_LEFT_frame player_jump_right: .byte 1 .byte $01 .byte $00 .word dog01_JUMP_RIGHT_frame player_jump_left: .byte 1 .byte $01 .byte $00 .word dog01_JUMP_LEFT_frame
19.82716
74
0.644458
f1799bb67831a2ae2c5c8ce584960779d1ac592a
3,339
rb
Ruby
spec/mmdb_spec.rb
trevorrjohn/mmdb
a61b9b25e78d3650f9d505386d44d5163dc216f6
[ "MIT" ]
1
2021-01-23T04:54:25.000Z
2021-01-23T04:54:25.000Z
spec/mmdb_spec.rb
trevorrjohn/mmdb
a61b9b25e78d3650f9d505386d44d5163dc216f6
[ "MIT" ]
1
2020-03-17T14:14:55.000Z
2020-03-17T14:14:55.000Z
spec/mmdb_spec.rb
trevorrjohn/mmdb
a61b9b25e78d3650f9d505386d44d5163dc216f6
[ "MIT" ]
null
null
null
# frozen_string_literal: true require 'json' RSpec.describe Mmdb do it 'has a version number' do expect(Mmdb::VERSION).not_to be nil end describe '.query' do context 'when VPN data' do before do Mmdb.configure do |c| c.file_path = './spec/data/vpn_data.mmdb' end end context 'when IP is in db' do it 'returns the raw data' do ip = '1.2.236.218' result = Mmdb.query(ip) expected = JSON.parse(File.read("./spec/data/fixtures/vpn_#{ip}.json")) expect(result).to eq(expected) end end context 'when IP is not in db' do it 'returns empty hash' do expect(Mmdb.query('192.168.1.1')).to eq({}) end end end context 'when City data' do before do Mmdb.configure do |c| c.file_path = './spec/data/GeoLite2-City.mmdb' end end context 'when IPV6' do context 'when IP is in db' do it 'returns the raw data' do ip = '2001:708:510:8:9a6:442c:f8e0:7133' result = Mmdb.query(ip) expected = JSON.parse(File.read("./spec/data/fixtures/city_#{ip}.json")) expect(result).to eq(expected) end end context 'when IP is not in db' do it 'returns nil' do expect(Mmdb.query('::FFFF:192.168.1.1')).to eq({}) end end end context 'when IPV4' do context 'when IP is in db' do it 'returns the raw data' do ip = '74.125.225.224' result = Mmdb.query(ip) expected = JSON.parse(File.read("./spec/data/fixtures/city_#{ip}.json")) expect(result).to eq(expected) end end context 'when IP is not in db' do it 'returns nil' do expect(Mmdb.query('192.168.1.1')).to eq({}) end end end end context 'when Country data' do before do Mmdb.configure do |c| c.file_path = './spec/data/GeoLite2-Country.mmdb' end end context 'when IP is in db' do it 'returns the raw data' do ip = '74.125.225.224' result = Mmdb.query(ip) expected = JSON.parse(File.read("./spec/data/fixtures/country_#{ip}.json")) expect(result).to eq(expected) end end context 'when IP is not in db' do it 'returns nil' do expect(Mmdb.query('192.168.1.1')).to eq({}) end end end end describe 'multiple database files' do before do Mmdb.configure do |c| c.files = { city: './spec/data/GeoLite2-City.mmdb', 'vpn' => './spec/data/vpn_data.mmdb' } end end it 'allows querying from both databases' do vpn_ip = '1.2.236.218' vpn_result = Mmdb.query(vpn_ip, file_key: 'vpn') vpn_expected = JSON.parse(File.read("./spec/data/fixtures/vpn_#{vpn_ip}.json")) expect(vpn_result).to eq(vpn_expected) city_ip = '2001:708:510:8:9a6:442c:f8e0:7133' city_result = Mmdb.query(city_ip, file_key: :city) city_expected = JSON.parse(File.read("./spec/data/fixtures/city_#{city_ip}.json")) expect(city_result).to eq(city_expected) end end after { Mmdb.reset } end
26.927419
88
0.550764
9c9ba8afed7fe5fc1eb50b40355cbb1285f1b189
3,185
rs
Rust
src/os/macos/mod.rs
ArthurKValladares/gradle-bump
ba40bac89ec2f340bbbd242c4ac58ebeeda7e184
[ "Apache-2.0", "MIT" ]
614
2020-08-07T18:38:54.000Z
2022-03-25T12:34:00.000Z
src/os/macos/mod.rs
ArthurKValladares/gradle-bump
ba40bac89ec2f340bbbd242c4ac58ebeeda7e184
[ "Apache-2.0", "MIT" ]
38
2020-11-25T19:31:16.000Z
2022-03-05T03:10:13.000Z
src/os/macos/mod.rs
ArthurKValladares/gradle-bump
ba40bac89ec2f340bbbd242c4ac58ebeeda7e184
[ "Apache-2.0", "MIT" ]
31
2020-10-29T03:44:38.000Z
2022-03-05T03:42:10.000Z
mod ffi; pub(super) mod info; use core_foundation::{ array::CFArray, base::{OSStatus, TCFType}, error::{CFError, CFErrorRef}, string::{CFString, CFStringRef}, url::CFURL, }; use std::{ ffi::OsStr, fmt::{self, Display}, path::{Path, PathBuf}, ptr, }; // This can hopefully be relied upon... https://stackoverflow.com/q/8003919 static RUST_UTI: &str = "dyn.ah62d4rv4ge81e62"; #[derive(Debug)] pub enum DetectEditorError { LookupFailed(CFError), } impl Display for DetectEditorError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::LookupFailed(err) => write!(f, "{}", err), } } } #[derive(Debug)] pub enum OpenFileError { PathToUrlFailed { path: PathBuf }, LaunchFailed(OSStatus), } impl Display for OpenFileError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PathToUrlFailed { path } => { write!(f, "Failed to convert path {:?} into a `CFURL`.", path) } Self::LaunchFailed(status) => write!(f, "Status code {}", status), } } } #[derive(Debug)] pub struct Application { url: CFURL, } impl Application { pub fn detect_editor() -> Result<Self, DetectEditorError> { unsafe fn inner(uti: CFStringRef) -> Result<CFURL, CFError> { let mut err: CFErrorRef = ptr::null_mut(); let out_url = ffi::LSCopyDefaultApplicationURLForContentType(uti, ffi::kLSRolesEditor, &mut err); if out_url.is_null() { Err(TCFType::wrap_under_create_rule(err)) } else { Ok(TCFType::wrap_under_create_rule(out_url)) } } let uti = CFString::from_static_string(RUST_UTI); let url = unsafe { inner(uti.as_concrete_TypeRef()) }.map_err(DetectEditorError::LookupFailed)?; Ok(Self { url }) } pub fn open_file(&self, path: impl AsRef<Path>) -> Result<(), OpenFileError> { let path = path.as_ref(); let item_url = CFURL::from_path(path, path.is_dir()).ok_or_else(|| { OpenFileError::PathToUrlFailed { path: path.to_owned(), } })?; let items = CFArray::from_CFTypes(&[item_url]); let spec = ffi::LSLaunchURLSpec::new( self.url.as_concrete_TypeRef(), items.as_concrete_TypeRef(), ffi::kLSLaunchDefaults, ); let status = unsafe { ffi::LSOpenFromURLSpec(&spec, ptr::null_mut()) }; if status == 0 { Ok(()) } else { Err(OpenFileError::LaunchFailed(status)) } } } pub fn open_file_with( application: impl AsRef<OsStr>, path: impl AsRef<OsStr>, ) -> bossy::Result<()> { bossy::Command::impure("open") .with_arg("-a") .with_args(&[application.as_ref(), path.as_ref()]) .run_and_wait()?; Ok(()) } #[cfg(target_os = "macos")] pub fn command_path(name: &str) -> bossy::Result<bossy::Output> { bossy::Command::impure("command") .with_args(&["-v", name]) .run_and_wait_for_output() }
28.185841
99
0.571743
f753427834e605d6994fa1ee3af7a7f00f63f2e3
1,957
rb
Ruby
lib/puppet/network/http/rack/xmlrpc.rb
ccaum/puppet
941e7945925f59e33dab2a09be505ea43ae8b3f2
[ "Apache-2.0" ]
8
2015-02-23T22:47:08.000Z
2021-08-10T18:57:43.000Z
lib/puppet/network/http/rack/xmlrpc.rb
ccaum/puppet
941e7945925f59e33dab2a09be505ea43ae8b3f2
[ "Apache-2.0" ]
4
2015-01-03T18:02:09.000Z
2016-05-06T02:18:10.000Z
lib/puppet/network/http/rack/xmlrpc.rb
ccaum/puppet
941e7945925f59e33dab2a09be505ea43ae8b3f2
[ "Apache-2.0" ]
7
2016-08-20T10:11:45.000Z
2020-12-07T10:55:00.000Z
require 'puppet/network/http/rack/httphandler' require 'puppet/network/xmlrpc/server' require 'resolv' class Puppet::Network::HTTP::RackXMLRPC < Puppet::Network::HTTP::RackHttpHandler def initialize(handlers) @xmlrpc_server = Puppet::Network::XMLRPCServer.new handlers.each do |name| Puppet.debug " -> register xmlrpc namespace #{name}" unless handler = Puppet::Network::Handler.handler(name) raise ArgumentError, "Invalid XMLRPC handler #{name}" end @xmlrpc_server.add_handler(handler.interface, handler.new({})) end super() end def process(request, response) # errors are sent as text/plain response['Content-Type'] = 'text/plain' if not request.post? response.status = 405 response.write 'Method Not Allowed' return end if request.media_type != "text/xml" response.status = 400 response.write 'Bad Request' return end # get auth/certificate data client_request = build_client_request(request) response_body = @xmlrpc_server.process(request.body.read, client_request) response.status = 200 response['Content-Type'] = 'text/xml; charset=utf-8' response.write response_body end def build_client_request(request) ip = request.ip # if we find SSL info in the headers, use them to get a hostname. # try this with :ssl_client_header, which defaults should work for # Apache with StdEnvVars. if dn = request.env[Puppet[:ssl_client_header]] and dn_matchdata = dn.match(/^.*?CN\s*=\s*(.*)/) node = dn_matchdata[1].to_str authenticated = (request.env[Puppet[:ssl_client_verify_header]] == 'SUCCESS') else begin node = Resolv.getname(ip) rescue => detail Puppet.err "Could not resolve #{ip}: #{detail}" node = "unknown" end authenticated = false end Puppet::Network::ClientRequest.new(node, ip, authenticated) end end
29.651515
100
0.672969
1417216cc211450bb7b344bda69ce4001c88f230
10,865
ts
TypeScript
app/models/stainer.ts
it7-solutions/accommodation-public-plugin
acd2c83da8f781cd5e2bb7e15be66d227714e667
[ "MIT" ]
null
null
null
app/models/stainer.ts
it7-solutions/accommodation-public-plugin
acd2c83da8f781cd5e2bb7e15be66d227714e667
[ "MIT" ]
null
null
null
app/models/stainer.ts
it7-solutions/accommodation-public-plugin
acd2c83da8f781cd5e2bb7e15be66d227714e667
[ "MIT" ]
null
null
null
import {Collection} from './collection'; import {Day} from './day'; import {Room} from './room'; import {Hotel} from './hotel'; /** * Created by Buzzer on 21.11.2016. */ export interface DataContainer { hotel_id: string room_type_id: string date_input: string date_output: string hotels: Hotel[]; rooms: Room[]; checkIn: Day[]; checkOut: Day[]; } export class Stainer { hotels: Collection<Hotel>; rooms: Collection<Room>; days: Collection<Day>; room: Room; hotel: Hotel; checkIn: Day; checkOut: Day; // constructor(hotels: Hotel[], rooms: Room[], days: Day[]) { // this.hotels = new Collection<Hotel>(hotels); // this.rooms = new Collection<Room>(rooms); // this.days = new Collection<Day>(days); // } constructor(hotels: Collection<Hotel>, rooms: Collection<Room>, days: Collection<Day>) { this.hotels = hotels; this.rooms = rooms; this.days = days; } public setHotel(id: string) { this.hotel = this.hotels.get(id); this.room = undefined; } public setRoom(id: string) { this.room = this.rooms.get(id); } public setCheckInDay(id: string) { this.checkIn = this.days.get(id); } public setCheckOutDay(id: string) { this.checkOut = this.days.items.find(d => d.id_check_out === id); } public getHotels(): Hotel[] { return this.filterHotelsGivenDates(); } public getRooms(): Room[] { let rooms: Room[] = this.hotel ? this.rooms.items.filter(r => r.hotel_id === this.hotel.id) : []; return this.filterRoomsGivenDates(rooms); } public getCheckInDays(): Day[] { let days: Day[] = this.room ? this.getDaysForRoom(this.room) : this.getAllRoomsDays(); let r = this.filterDaysGivenCheckOut(days); return r; } public getCheckOutDays(): Day[] { let days: Day[] = this.room ? this.getDaysForRoom(this.room) : this.getAllRoomsDays(); return this.filterDaysGivenCheckIn(days); } public static actualizeData(dc: DataContainer): boolean { let changed = false; // Room id may be outside the allowable values if(!dc.rooms.map(r => r.id).find(id => id === dc.room_type_id) && dc.room_type_id !== '') { dc.room_type_id = ''; changed = true; } return changed; } private filterHotelsGivenDates() : Hotel[] { let hotels: Hotel[] = this.hotels.items; if (this.checkIn) { if (this.checkOut) { // For cases filled Check-in and/or-not Check-out return hotels.filter(h => { return !!this.getHotelRooms(h.id).filter(r => { return !!this.findPeriod(r, this.checkIn.id, this.checkOut.id).length }).length; }); } else { // For cases filled Check-in only return hotels.filter(h => { return !!this.getHotelRooms(h.id).filter(r => { return !!this.findPeriod(r, this.checkIn.id).length }).length; }); } } else if (this.checkOut) { // For cases filled Check-out only return hotels.filter(h => { return !!this.getHotelRooms(h.id).filter(r => { return !!this.findPeriod(r, undefined, this.checkOut.id).length }).length; }); } return hotels; } private getHotelRooms(id: string): Room[] { return this.rooms.items.filter(r => r.hotel_id === id); } private filterRoomsGivenDates(rooms: Room[]): Room[] { if (this.checkIn) { if (this.checkOut) { // For cases filled Check-in and/or-not Check-out return rooms.filter(r => { return !!this.findPeriod(r, this.checkIn.id, this.checkOut.id).length }); } else { // For cases filled Check-in only return rooms.filter(r => { return !!this.findPeriod(r, this.checkIn.id).length }); } } else if (this.checkOut) { // For cases filled Check-out only return rooms.filter(r => { return !!this.findPeriod(r, undefined, this.checkOut.id).length }); } return rooms; } private filterDaysGivenCheckOut(days: Day[]): Day[] { if (this.checkOut) { if (this.room) { let period = this.findPeriod(this.room, undefined, this.checkOut.id); let ids = this.getDayIdsToForCheckOut(period, this.checkOut.id); return this.days.getByIds(ids); } else if (this.hotel) { let ids: string[] = []; this.rooms.items.forEach( r => { if(this.hotel.id === r.hotel_id) { let period = this.findPeriod(r, undefined, this.checkOut.id); this.getDayIdsToForCheckOut(period, this.checkOut.id).forEach(id => ids.push(id)); } } ); return this.days.getByIds(ids); } else { // If Hotel not selected let ids: string[] = []; this.rooms.items.forEach( r => { let period = this.findPeriod(r, undefined, this.checkOut.id); this.getDayIdsToForCheckOut(period, this.checkOut.id).forEach(id => ids.push(id)); } ); return this.days.getByIds(ids); } } return days; } private filterDaysGivenCheckIn(days: Day[]): Day[] { if (this.checkIn) { if (this.room) { // If select Room let period = this.findPeriod(this.room, this.checkIn.id); let ids = this.getDayIdsFrom(period, this.checkIn.id); return this.days.getByIds(ids); } else if (this.hotel) { // If select Only Hotel let ids: string[] = []; this.rooms.items.forEach( r => { if(this.hotel.id === r.hotel_id){ let period = this.findPeriod(r, this.checkIn.id); this.getDayIdsFrom(period, this.checkIn.id).forEach(id => ids.push(id)); } } ); return this.days.getByIds(ids); } else { // If Hotel not selected let ids: string[] = []; this.rooms.items.forEach( r => { let period = this.findPeriod(r, this.checkIn.id); this.getDayIdsFrom(period, this.checkIn.id).forEach(id => ids.push(id)); } ); return this.days.getByIds(ids); } } return days; } private getDayIdsTo(period: string[], dayId: string): string[] { let found = false; return period.filter( id => { let current = id === dayId; found = (found || current); return !found || current; } ); } private getDayIdsToForCheckOut(period: string[], dayId: string): string[] { let found = false; return period.filter( id => { let current = id === dayId; found = (found || current); return !found || current; } ); } private getDayIdsFrom(period: string[], dayId: string) : string[] { let found = false; return period.filter(id => found = (found || id === dayId)); } /** * Returns identifiers days from the beginning of the period until a specified date. But not including. * * @param period * @param dayId * @returns {string[]} */ private getDayIdsToButExcluding(period: string[], dayId: string): string[] { let found = false; return period.filter( id => { let current = id === dayId; found = (found || current); return !found; } ); } /** * Returns identifiers days from the specified date (but not including) until the end of the period. * * @param period * @param dayId * @returns {string[]} */ private getDayIdsFromButExcluding(period: string[], dayId: string) : string[] { let found = false; return period.filter( id => { let last = found; found = (found || id === dayId); return last; } ); } private findPeriod(room: Room, checkInId: string, checkOutId: string = ''): string[] { let periods: string[][]; if (checkInId && checkOutId) { periods = room.periods.filter(p => !!(p.find(id => id === checkInId) && p.find(id => id === checkOutId))); } else if(checkInId) { periods = room.periods.filter(p => !!p.find(id => id === checkInId)); } else { periods = room.periods.filter(p => !!p.find(id => id === checkOutId)); } return periods.length > 0 ? periods[0] : []; } private getDaysForRoom(room: Room): Day[] { let day_ids: any = {}; // Loop for each day_id in each periods of selected room // and save id in temporary array room.periods.forEach(p => p.forEach(id => day_ids[id] = true)); // Create new array od Days identifiers are present in the array return this.days.items.filter(d => !!day_ids[d.id]); } private getAllRoomsDays(): Day[] { let day_ids: any = {}; if (this.hotel) { // Loop for each day_id in each periods in each hotel rooms // and save id in temporary array this.rooms.items.forEach( r => { if (r.hotel_id === this.hotel.id) { r.periods.forEach(p => p.forEach(id => day_ids[id] = true)) } } ); } else { // Loop for each day_id in each periods in each rooms // and save id in temporary array this.rooms.items.forEach(r => r.periods.forEach(p => p.forEach(id => day_ids[id] = true))); } // Create new array od Days identifiers are present in the array return this.days.items.filter(d => !!day_ids[d.id]); } }
34.492063
118
0.49977
e26993e5b3a56108d6511112466ebdb8c5f6880b
1,330
py
Python
3. Strings/URI1873.py
antuniooh/uri-resolutions
c2844a9a6e2fae350293d6d24b0551691e7c8656
[ "MIT" ]
null
null
null
3. Strings/URI1873.py
antuniooh/uri-resolutions
c2844a9a6e2fae350293d6d24b0551691e7c8656
[ "MIT" ]
null
null
null
3. Strings/URI1873.py
antuniooh/uri-resolutions
c2844a9a6e2fae350293d6d24b0551691e7c8656
[ "MIT" ]
null
null
null
N = int(input("")) for x in range(0, N): if N > 0: s = input("") s = s.split() #separar if s[0] == s[1]: print("empate") else: if s[0] == "tesoura": if s[1] == "papel" or s[1] =="lagarto": print("rajesh") elif s[1] == "pedra" or s[1]=="spock": print("sheldon") elif s[0] == "papel": if s[1] == "pedra" or s[1] =="spock": print("rajesh") elif s[1] == "tesoura" or s[1]=="lagarto": print("sheldon") elif s[0] == "pedra": if s[1] == "lagarto" or s[1] =="tesoura": print("rajesh") elif s[1] == "spock" or s[1]=="papel": print("sheldon") elif s[0] == "lagarto": if s[1] == "spock" or s[1] =="papel": print("rajesh") elif s[1] == "pedra" or s[1]=="tesoura": print("sheldon") elif s[0] == "spock": if s[1] == "tesoura" or s[1] =="pedra": print("rajesh") elif s[1] == "lagarto" or s[1]=="papel": print("sheldon") else: print("invalido")
32.439024
58
0.347368
a3a39dbc04599ce701a281bd3d8c53619f613de1
384
ts
TypeScript
src/core/Callout/components/CalloutTitle/style.ts
codemonkey800/sci-components
29d31effe6e2ad5285db1dd1085151e1b1465133
[ "MIT" ]
10
2021-03-08T20:42:36.000Z
2022-03-29T15:24:19.000Z
src/core/Callout/components/CalloutTitle/style.ts
codemonkey800/sci-components
29d31effe6e2ad5285db1dd1085151e1b1465133
[ "MIT" ]
128
2021-03-09T04:37:38.000Z
2022-03-28T17:56:31.000Z
src/core/Callout/components/CalloutTitle/style.ts
codemonkey800/sci-components
29d31effe6e2ad5285db1dd1085151e1b1465133
[ "MIT" ]
2
2021-12-21T23:19:22.000Z
2022-01-11T22:55:03.000Z
import styled from "@emotion/styled"; import { AlertTitle } from "@material-ui/lab"; import { fontBody, getSpaces } from "src/core/styles"; const fontBodyXs = fontBody("xs"); export const StyledCalloutTitle = styled(AlertTitle)` ${fontBodyXs} ${(props) => { const spacings = getSpaces(props); return ` margin: ${spacings?.xxxs}px 0 ${spacings?.xs}px; `; }} `;
21.333333
54
0.658854
8412be7f6e0a68f511e0668454f7cff75d7f3022
383
swift
Swift
LaunchDarkly/LaunchDarkly/Networking/URLResponse.swift
neklollc/ios-client-sdk
0f99af458701fd943a4ed7c3a70f658c842496f1
[ "Apache-2.0" ]
null
null
null
LaunchDarkly/LaunchDarkly/Networking/URLResponse.swift
neklollc/ios-client-sdk
0f99af458701fd943a4ed7c3a70f658c842496f1
[ "Apache-2.0" ]
null
null
null
LaunchDarkly/LaunchDarkly/Networking/URLResponse.swift
neklollc/ios-client-sdk
0f99af458701fd943a4ed7c3a70f658c842496f1
[ "Apache-2.0" ]
null
null
null
// // URLResponse.swift // LaunchDarkly // // Created by Mark Pokorny on 3/13/19. +JMJ // Copyright © 2019 Catamorphic Co. All rights reserved. // import Foundation extension URLResponse { var httpStatusCode: Int? { return (self as? HTTPURLResponse)?.statusCode } var httpHeaderEtag: String? { return (self as? HTTPURLResponse)?.headerEtag } }
19.15
57
0.663185
95275a7bea2f2ea42281bf60c4b19cfd116c5a0b
10,490
sql
SQL
bem.sql
Jerry2204/bem-project
cec6e882da2340240e56c8768cdab8a9fcea8278
[ "MIT" ]
null
null
null
bem.sql
Jerry2204/bem-project
cec6e882da2340240e56c8768cdab8a9fcea8278
[ "MIT" ]
1
2021-02-02T20:03:36.000Z
2021-02-02T20:03:36.000Z
bem.sql
Jerry2204/bem-project
cec6e882da2340240e56c8768cdab8a9fcea8278
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Jun 26, 2020 at 07:25 PM -- Server version: 10.4.11-MariaDB -- PHP Version: 7.2.31 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `bem` -- -- -------------------------------------------------------- -- -- Table structure for table `anggota` -- CREATE TABLE `anggota` ( `id` bigint(20) UNSIGNED NOT NULL, `nama` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `nim` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `prodi` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `no_hp` bigint(20) NOT NULL, `departemen_id` int(11) NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `departemen` -- CREATE TABLE `departemen` ( `id` bigint(20) UNSIGNED NOT NULL, `nama_departemen` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `program_kerja` text COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `departemen` -- INSERT INTO `departemen` (`id`, `nama_departemen`, `program_kerja`, `created_at`, `updated_at`) VALUES (1, 'Departemen Sarana dan Prasarana', NULL, NULL, '2020-06-22 10:38:25'), (2, 'Departemen Komunikasi dan Informasi', NULL, NULL, NULL), (3, 'Departemen Ilmu Pengetahuan dan Teknologi', NULL, NULL, NULL); -- -------------------------------------------------------- -- -- Table structure for table `failed_jobs` -- CREATE TABLE `failed_jobs` ( `id` bigint(20) UNSIGNED NOT NULL, `connection` text COLLATE utf8mb4_unicode_ci NOT NULL, `queue` text COLLATE utf8mb4_unicode_ci NOT NULL, `payload` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `exception` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `failed_at` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Table structure for table `kadep` -- CREATE TABLE `kadep` ( `id` bigint(20) UNSIGNED NOT NULL, `nama` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `user_id` int(11) NOT NULL, `nim` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `alamat` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `no_hp` bigint(20) NOT NULL, `departemen_id` int(11) NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `kadep` -- INSERT INTO `kadep` (`id`, `nama`, `user_id`, `nim`, `alamat`, `no_hp`, `departemen_id`, `created_at`, `updated_at`) VALUES (5, 'Polia', 8, '11718908', 'Lembang', 81356742399, 3, '2020-06-23 01:44:50', '2020-06-23 01:44:50'); -- -------------------------------------------------------- -- -- Table structure for table `kelas` -- CREATE TABLE `kelas` ( `id` bigint(20) UNSIGNED NOT NULL, `nama_kelas` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `jumlah_mahasiswa` int(11) NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `kelas` -- INSERT INTO `kelas` (`id`, `nama_kelas`, `jumlah_mahasiswa`, `created_at`, `updated_at`) VALUES (1, '41TRPL1', 32, '2020-06-23 09:12:51', '2020-06-23 09:12:51'), (4, '11SI1', 25, '2020-06-24 08:56:31', '2020-06-24 08:56:31'); -- -------------------------------------------------------- -- -- Table structure for table `keuangan` -- CREATE TABLE `keuangan` ( `id` bigint(20) UNSIGNED NOT NULL, `jumlah_bayar` bigint(20) NOT NULL, `tanggal_bayar` date NOT NULL, `kelas_id` int(11) NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `keuangan` -- INSERT INTO `keuangan` (`id`, `jumlah_bayar`, `tanggal_bayar`, `kelas_id`, `created_at`, `updated_at`) VALUES (1, 60000, '2020-08-10', 1, '2020-06-23 03:19:44', '2020-06-23 03:55:53'), (2, 50000, '2020-08-19', 4, '2020-06-24 08:57:06', '2020-06-24 08:57:06'); -- -------------------------------------------------------- -- -- Table structure for table `migrations` -- CREATE TABLE `migrations` ( `id` int(10) UNSIGNED NOT NULL, `migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `batch` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `migrations` -- INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (4, '2014_10_12_000000_create_users_table', 1), (5, '2019_08_19_000000_create_failed_jobs_table', 1), (6, '2020_06_22_081943_create_departemen_table', 1), (7, '2020_06_22_091841_create_kadep_table', 2), (8, '2020_06_22_104538_add_role_to_users_table', 3), (9, '2020_06_22_133738_add_departemen_id_to_kadep_table', 4), (10, '2020_06_22_153754_create_anggota_table', 5), (11, '2020_06_22_155348_add_departemen_id_to_anggota_table', 6), (12, '2020_06_23_085444_create_kelas_table', 7), (13, '2020_06_23_094258_create_keuangan_table', 8), (14, '2020_06_24_161411_create_pengeluaran_table', 9); -- -------------------------------------------------------- -- -- Table structure for table `pengeluaran` -- CREATE TABLE `pengeluaran` ( `id` bigint(20) UNSIGNED NOT NULL, `jumlah_uang` bigint(20) NOT NULL, `keperluan` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `tanggal` date NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `pengeluaran` -- INSERT INTO `pengeluaran` (`id`, `jumlah_uang`, `keperluan`, `tanggal`, `created_at`, `updated_at`) VALUES (1, 80000, 'beli bola kaki', '2020-10-12', '2020-06-24 09:46:05', '2020-06-24 19:19:03'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` bigint(20) UNSIGNED NOT NULL, `role` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email_verified_at` timestamp NULL DEFAULT NULL, `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `role`, `name`, `email`, `email_verified_at`, `password`, `remember_token`, `created_at`, `updated_at`) VALUES (1, 'admin', 'Jerry Andrianto', '[email protected]', NULL, '$2y$10$ty7ouajqkT87kMSAdhkkB.zRWv14FSF9GTPfsoWFprl7GtbiI1Ije', 'Ycpk4VHu7M12c5e4bOaGuyLXLt993jz69dbvAYw2TnRB9I0e9W08jNCdZ19v', '2020-06-22 02:54:07', '2020-06-25 04:36:31'), (8, 'kadep', 'Polia', '[email protected]', NULL, '$2y$10$cafx27usp8XDL32CjyITjuFFoXH1H5idoLQ/IAPuOGnNX9niWqvOK', 'UTNNCVjsMJUhQEHeWPlEPeWn5sZM9ijaLruAcczGbyHqOv5GU8NlsuAPoEQU', '2020-06-23 01:44:49', '2020-06-23 01:44:49'), (12, 'admin', 'Ricky Alfrido Pangaribuan', '[email protected]', NULL, '$2y$10$wta4KdxsYXqJyxYSmyDo7eDJw3GKMC9j66sibmTlN/awLBBE.siMi', 'JF3Ujtb0PX4j8qVPtgLUwLxnAP4aFmPvl6KxuXNonzmF0YWqF8LCjE3uMDTa', '2020-06-25 04:25:09', '2020-06-25 04:25:09'); -- -- Indexes for dumped tables -- -- -- Indexes for table `anggota` -- ALTER TABLE `anggota` ADD PRIMARY KEY (`id`); -- -- Indexes for table `departemen` -- ALTER TABLE `departemen` ADD PRIMARY KEY (`id`); -- -- Indexes for table `failed_jobs` -- ALTER TABLE `failed_jobs` ADD PRIMARY KEY (`id`); -- -- Indexes for table `kadep` -- ALTER TABLE `kadep` ADD PRIMARY KEY (`id`); -- -- Indexes for table `kelas` -- ALTER TABLE `kelas` ADD PRIMARY KEY (`id`); -- -- Indexes for table `keuangan` -- ALTER TABLE `keuangan` ADD PRIMARY KEY (`id`); -- -- Indexes for table `migrations` -- ALTER TABLE `migrations` ADD PRIMARY KEY (`id`); -- -- Indexes for table `pengeluaran` -- ALTER TABLE `pengeluaran` ADD PRIMARY KEY (`id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `users_email_unique` (`email`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `anggota` -- ALTER TABLE `anggota` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `departemen` -- ALTER TABLE `departemen` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `failed_jobs` -- ALTER TABLE `failed_jobs` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `kadep` -- ALTER TABLE `kadep` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; -- -- AUTO_INCREMENT for table `kelas` -- ALTER TABLE `kelas` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `keuangan` -- ALTER TABLE `keuangan` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; -- -- AUTO_INCREMENT for table `migrations` -- ALTER TABLE `migrations` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=15; -- -- AUTO_INCREMENT for table `pengeluaran` -- ALTER TABLE `pengeluaran` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
30.143678
249
0.691325
035c1df2b0914c66348714cf6954a774e217cb5f
300
cpp
C++
Fundamentals/f_STLAssociativeContainers/c_pointIsInside.cpp
KaPrimov/cpp-courses
c114e46cd570d2e987ee65baf26dd85557f929d3
[ "MIT" ]
null
null
null
Fundamentals/f_STLAssociativeContainers/c_pointIsInside.cpp
KaPrimov/cpp-courses
c114e46cd570d2e987ee65baf26dd85557f929d3
[ "MIT" ]
null
null
null
Fundamentals/f_STLAssociativeContainers/c_pointIsInside.cpp
KaPrimov/cpp-courses
c114e46cd570d2e987ee65baf26dd85557f929d3
[ "MIT" ]
null
null
null
#include <iostream> int main() { int x1, y1, x2, y2, x3, y3; std::cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3; bool isInside = x3 >= x1 && x3 <= x2 && y3 >= y1 && y3 <= y2; if (isInside) { std::cout << "Check point is inside"; } else { std::cout << "Check point is outside"; } return 0; }
17.647059
62
0.516667
4596cb527b6a0d794e9825856661f34d54238d4e
4,702
py
Python
HRI/TFVT_HRI/perception/common/visualize.py
WorldEditors/PaddleRobotics
d02efd74662c6f78dfb964e8beb93f1914dcb2f3
[ "Apache-2.0" ]
146
2020-12-08T11:51:38.000Z
2022-03-23T12:58:43.000Z
HRI/TFVT_HRI/perception/common/visualize.py
WorldEditors/PaddleRobotics
d02efd74662c6f78dfb964e8beb93f1914dcb2f3
[ "Apache-2.0" ]
10
2020-12-23T03:00:31.000Z
2022-03-23T09:55:30.000Z
HRI/TFVT_HRI/perception/common/visualize.py
WorldEditors/PaddleRobotics
d02efd74662c6f78dfb964e8beb93f1914dcb2f3
[ "Apache-2.0" ]
43
2020-12-21T09:40:39.000Z
2022-03-31T06:41:32.000Z
import cv2 import numpy as np from PIL import Image from PIL import ImageDraw from subprocess import Popen, PIPE import pycocotools.mask as coco_mask_util def draw_bboxes(image, bboxes, labels=None, output_file=None, fill='red'): """ Draw bounding boxes on image. Return image with drawings as BGR ndarray. Args: image (string | ndarray): input image path or image BGR ndarray. bboxes (np.array): bounding boxes. labels (list of string): the label names of bboxes. output_file (string): output image path. """ if labels: assert len(bboxes) == len(labels) if isinstance(image, str): image = Image.open(image) elif isinstance(image, np.ndarray): image = Image.fromarray(image[:, :, ::-1], mode='RGB') else: raise ValueError('`image` should be image path in string or ' 'image ndarray.') draw = ImageDraw.Draw(image) for i in range(len(bboxes)): xmin, ymin, xmax, ymax = bboxes[i] left, right, top, bottom = xmin, xmax, ymin, ymax lines = [(left, top), (left, bottom), (right, bottom), (right, top), (left, top)] draw.line(lines, width=4, fill=fill) if labels and image.mode == 'RGB': draw.text((left, top), labels[i], (255, 255, 0)) if output_file: print('The image with bbox is saved as {}'.format(output_file)) image.save(output_file) return np.array(image)[:, :, ::-1] def save_as_gif(images, gif_file, fps=5): """ Save numpy images as gif file using ffmpeg. Args: images (list|ndarray): a list of uint8 images or uint8 ndarray with shape [time, height, width, channels]. `channels` can be 1 or 3. gif_file (str): path to saved gif file. fps (int): frames per second of the animation. """ h, w, c = images[0].shape cmd = [ 'ffmpeg', '-y', '-f', 'rawvideo', '-vcodec', 'rawvideo', '-r', '%.02f' % fps, '-s', '%dx%d' % (w, h), '-pix_fmt', {1: 'gray', 3: 'rgb24'}[c], '-i', '-', '-filter_complex', '[0:v]split[x][z];[z]palettegen[y];[x][y]paletteuse', '-r', '%.02f' % fps, '-f', 'gif', '-'] proc = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) for image in images: proc.stdin.write(image.tostring()) out, err = proc.communicate() if proc.returncode: err = '\n'.join([' '.join(cmd), err.decode('utf8')]) raise IOError(err) del proc with open(gif_file, 'wb') as f: f.write(out) def colormap(rgb=False): """ Get colormap """ color_list = np.array([ 0.000, 0.447, 0.741, 0.850, 0.325, 0.098, 0.929, 0.694, 0.125, 0.494, 0.184, 0.556, 0.466, 0.674, 0.188, 0.301, 0.745, 0.933, 0.635, 0.078, 0.184, 0.300, 0.300, 0.300, 0.600, 0.600, 0.600, 1.000, 0.000, 0.000, 1.000, 0.500, 0.000, 0.749, 0.749, 0.000, 0.000, 1.000, 0.000, 0.000, 0.000, 1.000, 0.667, 0.000, 1.000, 0.333, 0.333, 0.000, 0.333, 0.667, 0.000, 0.333, 1.000, 0.000, 0.667, 0.333, 0.000, 0.667, 0.667, 0.000, 0.667, 1.000, 0.000, 1.000, 0.333, 0.000, 1.000, 0.667, 0.000, 1.000, 1.000, 0.000, 0.000, 0.333, 0.500, 0.000, 0.667, 0.500, 0.000, 1.000, 0.500, 0.333, 0.000, 0.500, 0.333, 0.333, 0.500, 0.333, 0.667, 0.500, 0.333, 1.000, 0.500, 0.667, 0.000, 0.500, 0.667, 0.333, 0.500, 0.667, 0.667, 0.500, 0.667, 1.000, 0.500, 1.000, 0.000, 0.500, 1.000, 0.333, 0.500, 1.000, 0.667, 0.500, 1.000, 1.000, 0.500, 0.000, 0.333, 1.000, 0.000, 0.667, 1.000, 0.000, 1.000, 1.000, 0.333, 0.000, 1.000, 0.333, 0.333, 1.000, 0.333, 0.667, 1.000, 0.333, 1.000, 1.000, 0.667, 0.000, 1.000, 0.667, 0.333, 1.000, 0.667, 0.667, 1.000, 0.667, 1.000, 1.000, 1.000, 0.000, 1.000, 1.000, 0.333, 1.000, 1.000, 0.667, 1.000, 0.167, 0.000, 0.000, 0.333, 0.000, 0.000, 0.500, 0.000, 0.000, 0.667, 0.000, 0.000, 0.833, 0.000, 0.000, 1.000, 0.000, 0.000, 0.000, 0.167, 0.000, 0.000, 0.333, 0.000, 0.000, 0.500, 0.000, 0.000, 0.667, 0.000, 0.000, 0.833, 0.000, 0.000, 1.000, 0.000, 0.000, 0.000, 0.167, 0.000, 0.000, 0.333, 0.000, 0.000, 0.500, 0.000, 0.000, 0.667, 0.000, 0.000, 0.833, 0.000, 0.000, 1.000, 0.000, 0.000, 0.000, 0.143, 0.143, 0.143, 0.286, 0.286, 0.286, 0.429, 0.429, 0.429, 0.571, 0.571, 0.571, 0.714, 0.714, 0.714, 0.857, 0.857, 0.857, 1.000, 1.000, 1.000 ]).astype(np.float32) color_list = color_list.reshape((-1, 3)) * 255 if not rgb: color_list = color_list[:, ::-1] return color_list
39.512605
78
0.547639
7b12923e61670c519b8c442a2f643a4f56f4018e
3,258
rb
Ruby
vendor/bundle/ruby/2.3.0/gems/codeclimate-test-reporter-1.0.8/lib/code_climate/test_reporter/formatter.rb
tbkoo53/Spina
37e780ca4f48c298d8acb36590fcf5cf6ff36f95
[ "MIT" ]
null
null
null
vendor/bundle/ruby/2.3.0/gems/codeclimate-test-reporter-1.0.8/lib/code_climate/test_reporter/formatter.rb
tbkoo53/Spina
37e780ca4f48c298d8acb36590fcf5cf6ff36f95
[ "MIT" ]
null
null
null
vendor/bundle/ruby/2.3.0/gems/codeclimate-test-reporter-1.0.8/lib/code_climate/test_reporter/formatter.rb
tbkoo53/Spina
37e780ca4f48c298d8acb36590fcf5cf6ff36f95
[ "MIT" ]
null
null
null
# encoding: utf-8 require "tmpdir" require "securerandom" require "json" require "digest/sha1" require "simplecov" require "code_climate/test_reporter/exception_message" require "code_climate/test_reporter/payload_validator" module CodeClimate module TestReporter class Formatter def format(results) simplecov_results = results.map do |command_name, data| SimpleCov::Result.from_hash(command_name => data) end simplecov_result = if simplecov_results.size == 1 simplecov_results.first else merge_results(simplecov_results) end payload = to_payload(simplecov_result) PayloadValidator.validate(payload) payload end private def partial? CodeClimate::TestReporter.tddium? end def to_payload(result) totals = Hash.new(0) source_files = result.files.map do |file| totals[:total] += file.lines.count totals[:covered] += file.covered_lines.count totals[:missed] += file.missed_lines.count # Set coverage for all skipped lines to nil file.skipped_lines.each do |skipped_line| file.coverage[skipped_line.line_number - 1] = nil end { name: ShortenFilename.new(file.filename).short_filename, blob_id: CalculateBlob.new(file.filename).blob_id, coverage: file.coverage.to_json, covered_percent: round(file.covered_percent, 2), covered_strength: round(file.covered_strength, 2), line_counts: { total: file.lines.count, covered: file.covered_lines.count, missed: file.missed_lines.count, }, } end { repo_token: ENV["CODECLIMATE_REPO_TOKEN"], source_files: source_files, run_at: result.created_at.to_i, covered_percent: result.source_files.covered_percent.round(2), covered_strength: result.source_files.covered_strength.round(2), line_counts: totals, partial: partial?, git: Git.info, environment: { pwd: Dir.pwd, rails_root: (Rails.root.to_s rescue nil), simplecov_root: ::SimpleCov.root, gem_version: VERSION, }, ci_service: CodeClimate::TestReporter.ci_service_data, } end # Convert to Float before rounding. # Fixes [#7] possible segmentation fault when calling #round on a Rational def round(numeric, precision) Float(numeric).round(precision) end # Re-implementation of Simplecov::ResultMerger#merged_result, which is # needed because calling it directly gets you into caching land with files # on disk. def merge_results(results) merged = {} results.each do |result| merged = result.original_result.merge_resultset(merged) end result = SimpleCov::Result.new(merged) result.command_name = results.map(&:command_name).sort.join(", ") result end end end end
31.028571
80
0.60221
efd274fe67f76bf5e23222d2c86b1aa79c36a6c4
657
sql
SQL
01-Class-Content/14-Full-Stack/01-Activities/04-StarWars/Unsolved/schema.sql
sharpzeb/bootcamp
358aa123c946e41afde07822109a4d4614a44614
[ "ADSL" ]
8
2020-12-08T16:56:29.000Z
2021-07-17T18:24:38.000Z
01-Class-Content/14-Full-Stack/01-Activities/04-StarWars/Unsolved/schema.sql
sharpzeb/bootcamp
358aa123c946e41afde07822109a4d4614a44614
[ "ADSL" ]
1
2021-01-16T15:35:51.000Z
2021-01-16T15:35:51.000Z
01-Class-Content/14-Full-Stack/01-Activities/04-StarWars/Unsolved/schema.sql
sharpzeb/bootcamp
358aa123c946e41afde07822109a4d4614a44614
[ "ADSL" ]
6
2020-12-14T17:38:24.000Z
2021-04-13T00:12:17.000Z
/* This file is intended to help developers get their SQL Databases setup correctly. It is important since other developers will be unlikely to have the same database or tables setup already. */ /* Create and use the starwars db */ DROP DATABASE IF EXISTS `starwars`; CREATE DATABASE `starwars`; USE `starwars`; /* Create a table for all your star wars characters */ CREATE TABLE `allcharacters` ( `id` Int( 11 ) AUTO_INCREMENT NOT NULL, `routeName` VARCHAR( 255) NOT NULL, `name` VARCHAR( 255 ) NOT NULL, `role` VARCHAR( 255 ) NOT NULL, `age` Int(11) NOT NULL, `forcePoints` Int(11) NOT NULL, /* Set ID as primary key */ PRIMARY KEY ( `id` ) );
28.565217
106
0.713851
51f8c142354c94b1ff6ce037530ecfd337dc2fb0
7,735
dart
Dart
lib/message/messageRepo.dart
aruntemme/flutchat
2a6f82d5f79bf867b39afdc5f1d3a3836adcc60e
[ "MIT" ]
null
null
null
lib/message/messageRepo.dart
aruntemme/flutchat
2a6f82d5f79bf867b39afdc5f1d3a3836adcc60e
[ "MIT" ]
null
null
null
lib/message/messageRepo.dart
aruntemme/flutchat
2a6f82d5f79bf867b39afdc5f1d3a3836adcc60e
[ "MIT" ]
null
null
null
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'message.dart'; import '../groupModel.dart'; class MessageRepo { CollectionReference reference = Firestore.instance.collection("message"); //? Check if room exists else create it setReference(GroupModel model) async { print(" in set reference "); QuerySnapshot a = await Firestore.instance .collection("message") .where('participants', isEqualTo: model.participants) .getDocuments(); print("First query results = : ${a.documents.length}"); if (a.documents.length <= 0) { print(" in if ----checking another way"); a = await Firestore.instance.collection("message").where('participants', isEqualTo: [ model.participants[1], model.participants[0] ]).getDocuments(); } if (a.documents.length > 0) { print(" in set reference -- if -- \n "); var e = a.documents[0].reference; reference = e.collection("messages").reference(); } else { print(" in set reference --else -- \n"); await Firestore.instance.collection('message').document().setData( {'participants': model.participants, 'date': DateTime.now()}, merge: true); QuerySnapshot a = await Firestore.instance .collection('message') .where('participants', isEqualTo: model.participants) .getDocuments(); var e = a.documents[0].reference; reference = e.collection("messages").reference(); } } Stream<QuerySnapshot> getStream() { return reference.orderBy("date", descending: true).snapshots(); } Future<void> addMessage(Message message, GroupModel model, var docId) { updateTime(docId, message.date, model); return reference .document(message.date.millisecondsSinceEpoch.toString()) .setData(message.toJson()); } updateTime(String docId, DateTime date, GroupModel model) { Firestore.instance .collection('message') .document(docId) .setData({'participants': model.participants, 'date': date}); } Future getGroupDocumentId(GroupModel model) async { var snapshot = await Firestore.instance .collection("message") .where( 'participants', isEqualTo: model.participants, ) .getDocuments(); if (snapshot.documents.length <= 0) return null; return snapshot.documents[0].documentID; } Stream getLastMessage(GroupModel model, var documentId) { return Firestore.instance .collection('message') .document(documentId) .collection('messages') .snapshots(); } deleteMessage(Message message) async { if (message.message != "This message has been deleted") { await reference .document(message.date.millisecondsSinceEpoch.toString()) .updateData( Message( message: "This message has been deleted", date: message.date, idFrom: message.idFrom, idTo: message.idTo, documentId: message.documentId, isSeen: message.isSeen, type: 0) .toJson(), ); } } clearChat(GroupModel model) async { print('-------------in Clear chat--------- '); getGroupDocumentId(model).then((value) async { var querySnapshot = await Firestore.instance .collection('message') .document(value) .collection('messages') .getDocuments(); var inst = Firestore.instance.collection('message').document(value); if (querySnapshot.documents.length > 0) { for (int i = 0; i < querySnapshot.documents.length; i++) { Message message = Message.fromSnapshot(querySnapshot.documents[i]); if (message.type == 1) { deleteImageCompletely(value, message); inst .collection('messages') .document(message.date.millisecondsSinceEpoch.toString()) .delete(); } else { print("\n--- Deleting message(${message.documentId})---\n "); inst .collection('messages') .document(message.date.millisecondsSinceEpoch.toString()) .delete(); } } } }); } deleteGroup(GroupModel model) async { _printer(" in delete group "); getGroupDocumentId(model).then((value) async { var querySnapshot = await Firestore.instance .collection('message') .document(value) .collection('messages') .where('type', isEqualTo: 1) .getDocuments(); if (querySnapshot.documents.length > 0) { for (int i = 0; i < querySnapshot.documents.length; i++) { Message message = Message.fromSnapshot(querySnapshot.documents[i]); deleteImageCompletely(value, message); } } Firestore.instance.collection("message").document(value).delete(); }); } deleteImageCompletely(String documentId, Message message) { FirebaseStorage.instance .ref() .child('chats/$documentId/${message.date.millisecondsSinceEpoch}') .delete() .then((value) { _printer("-Deleted message completely-"); }); } deleteImage(String documentId, Message message) { deleteMessage(message); FirebaseStorage.instance .ref() .child('chats/$documentId/${message.date.millisecondsSinceEpoch}') .delete() .then((value) { _printer("-Deleted message completely-"); }); } updateIsSeen(Message message) async { await reference .document(message.date.millisecondsSinceEpoch.toString()) .updateData( Message( message: message.message, date: message.date, idFrom: message.idFrom, idTo: message.idTo, documentId: message.documentId, isSeen: true, notificationShown: message.notificationShown, imageUrl: message.imageUrl, type: message.type) .toJson(), ); } updateIsNotificationShown(Message message) async { await Firestore.instance .collection('message') .document(message.documentId) .collection("messages") .document(message.date.millisecondsSinceEpoch.toString()) .updateData(Message( message: message.message, date: message.date, idFrom: message.idFrom, idTo: message.idTo, documentId: message.documentId, isSeen: message.isSeen, notificationShown: true, imageUrl: message.imageUrl, type: message.type) .toJson()); } getChatRoom(String uid) async { _printer("getChatRoom [MessageRepo.dart]"); /* Stream<QuerySnapshot> a = Firestore.instance .collection("message") .where('participants', arrayContains: uid) .getDocuments() .asStream(); _printer("-"); return a; */ var a = await Firestore.instance .collection('message') .where( 'participants', arrayContains: uid, ) .getDocuments(); var b = a.documents[0].reference; b.collection("message").add({'kuchbhi': "aur nitpo lue"}); } } _printer(String text) { print( "\n\n--------------------------------$text---------------------------\n\n"); print("\n\n\n"); } MessageRepo messageRepo = MessageRepo();
31.70082
82
0.581513
a1985a97a164c19598e39213e559f614bc72d438
803
ts
TypeScript
packages/trie-codec/src/stream/createBranch.ts
hskang9/common
8fa67cdcf3452205338e37f21f8bdeb9193d2707
[ "Apache-2.0" ]
null
null
null
packages/trie-codec/src/stream/createBranch.ts
hskang9/common
8fa67cdcf3452205338e37f21f8bdeb9193d2707
[ "Apache-2.0" ]
null
null
null
packages/trie-codec/src/stream/createBranch.ts
hskang9/common
8fa67cdcf3452205338e37f21f8bdeb9193d2707
[ "Apache-2.0" ]
null
null
null
// Copyright 2017-2019 @polkadot/trie-codec authors & contributors // This software may be modified and distributed under the terms // of the Apache-2.0 license. See the LICENSE file for details. import { u8aConcat } from '@polkadot/util'; import { BITMAP, BRANCH_NODE_NO_VALUE, BRANCH_NODE_WITH_VALUE } from '../constants'; import createValue from './createValue'; export default function createBranch (value: Uint8Array | null, hasChildren: boolean[]): Uint8Array { let bitmap = 0; for (let i = 0; i < hasChildren.length; i++) { if (hasChildren[i]) { bitmap |= BITMAP[i]; } } return u8aConcat( Uint8Array.from([ value ? BRANCH_NODE_WITH_VALUE : BRANCH_NODE_NO_VALUE, (bitmap & 0xff), (bitmap >> 8) ]), createValue(value) ); }
26.766667
101
0.666252
04261c99db3bf9a9e48d49ccffca3098709f464e
335
hpp
C++
deps/Rack-SDK/include/engine/Param.hpp
pinting/GdRackBridge
346616f1bee0f7a4770c81277a625ae1e5421664
[ "MIT" ]
null
null
null
deps/Rack-SDK/include/engine/Param.hpp
pinting/GdRackBridge
346616f1bee0f7a4770c81277a625ae1e5421664
[ "MIT" ]
null
null
null
deps/Rack-SDK/include/engine/Param.hpp
pinting/GdRackBridge
346616f1bee0f7a4770c81277a625ae1e5421664
[ "MIT" ]
null
null
null
#pragma once #include <common.hpp> #include <math.hpp> namespace rack { namespace engine { struct Param { /** Unstable API. Use setValue() and getValue() instead. */ float value = 0.f; float getValue() { return value; } void setValue(float value) { this->value = value; } }; } // namespace engine } // namespace rack
12.884615
60
0.653731
e80451356e483d633a3ae302259e9288aa5ca00d
12,107
swift
Swift
Sources/Charcoal/CharcoalViewController.swift
bstien/charcoal-ios
66667680a698eb385ce8acf9b4b422af6457574b
[ "MIT" ]
null
null
null
Sources/Charcoal/CharcoalViewController.swift
bstien/charcoal-ios
66667680a698eb385ce8acf9b4b422af6457574b
[ "MIT" ]
null
null
null
Sources/Charcoal/CharcoalViewController.swift
bstien/charcoal-ios
66667680a698eb385ce8acf9b4b422af6457574b
[ "MIT" ]
null
null
null
// // Copyright © FINN.no AS, Inc. All rights reserved. // import UIKit public protocol CharcoalViewControllerTextEditingDelegate: AnyObject { func charcoalViewControllerWillBeginTextEditing(_ viewController: CharcoalViewController) func charcoalViewControllerWillEndTextEditing(_ viewController: CharcoalViewController) } public protocol CharcoalViewControllerSelectionDelegate: AnyObject { func charcoalViewController(_ viewController: CharcoalViewController, didSelect vertical: Vertical) func charcoalViewController(_ viewController: CharcoalViewController, didSelectExternalFilterWithKey key: String, value: String?) func charcoalViewControllerDidPressShowResults(_ viewController: CharcoalViewController) func charcoalViewController(_ viewController: CharcoalViewController, didChangeSelection selection: [URLQueryItem], origin: SelectionChangeOrigin) } public final class CharcoalViewController: UINavigationController { // MARK: - Public properties public var filterContainer: FilterContainer? { didSet { configure(with: filterContainer) } } public weak var textEditingDelegate: CharcoalViewControllerTextEditingDelegate? public weak var selectionDelegate: CharcoalViewControllerSelectionDelegate? public weak var mapDataSource: MapFilterDataSource? public weak var searchLocationDataSource: SearchLocationDataSource? public weak var freeTextFilterDataSource: FreeTextFilterDataSource? { didSet { rootFilterViewController?.freeTextFilterDataSource = freeTextFilterDataSource } } public weak var freeTextFilterDelegate: FreeTextFilterDelegate? { didSet { rootFilterViewController?.freeTextFilterDelegate = freeTextFilterDelegate } } public var isLoading: Bool = false { didSet { rootFilterViewController?.showLoadingIndicator(isLoading) } } // MARK: - Private properties private var selectionHasChanged = false private var bottomBottonClicked = false private lazy var selectionStore: FilterSelectionStore = { let store = FilterSelectionStore() store.delegate = self return store }() private var rootFilterViewController: RootFilterViewController? private lazy var verticalCalloutOverlay: VerticalCalloutOverlay = { let overlay = VerticalCalloutOverlay(withAutoLayout: true) overlay.delegate = self return overlay }() // MARK: - Lifecycle public override func viewDidLoad() { super.viewDidLoad() setupNavigationBar() delegate = self } public override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) let userDefaults = UserDefaults.standard if let text = filterContainer?.verticalsCalloutText, !userDefaults.verticalCalloutShown { showVerticalCallout(withText: text) userDefaults.verticalCalloutShown = true } } public override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) verticalCalloutOverlay.removeFromSuperview() } // MARK: - Public public func set(selection: Set<URLQueryItem>) { selectionStore.set(selection: selection) rootFilterViewController?.reloadFilters() } // MARK: - Private private func configure(with filterContainer: FilterContainer?) { guard let filterContainer = filterContainer else { return } selectionStore.syncSelection(with: filterContainer) if let rootFilterViewController = rootFilterViewController { rootFilterViewController.set(filterContainer: filterContainer) } else { rootFilterViewController = RootFilterViewController( filterContainer: filterContainer, selectionStore: selectionStore ) rootFilterViewController?.rootDelegate = self rootFilterViewController?.freeTextFilterDataSource = freeTextFilterDataSource rootFilterViewController?.freeTextFilterDelegate = freeTextFilterDelegate setViewControllers([rootFilterViewController!], animated: false) } } private func setupNavigationBar() { navigationBar.isTranslucent = false navigationBar.setBackgroundImage(UIImage(), for: .default) navigationBar.shadowImage = UIImage() } } // MARK: - RootFilterViewControllerDelegate extension CharcoalViewController: RootFilterViewControllerDelegate { func rootFilterViewControllerDidResetAllFilters(_ viewController: RootFilterViewController) { handleFilterSelectionChange(from: .resetAllButton) } func rootFilterViewController(_ viewController: RootFilterViewController, didRemoveFilter filter: Filter) { handleFilterSelectionChange(from: .removeFilterButton) } func rootFilterViewController(_ viewController: RootFilterViewController, didSelectInlineFilter filter: Filter) { handleFilterSelectionChange(from: .inlineFilter) } func rootFilterViewController(_ viewController: RootFilterViewController, didSelectFreeTextFilter filter: Filter) { handleFilterSelectionChange(from: .freeTextInput) } func rootFilterViewController(_ viewController: RootFilterViewController, didSelectSuggestionAt index: Int, filter: Filter) { handleFilterSelectionChange(from: .freeTextSuggestion(index: index)) } func rootFilterViewController(_ viewController: RootFilterViewController, didSelectVertical vertical: Vertical) { selectionDelegate?.charcoalViewController(self, didSelect: vertical) } private func handleFilterSelectionChange(from origin: SelectionChangeOrigin) { if let filterContainer = filterContainer { let queryItems = selectionStore.queryItems(for: filterContainer) selectionDelegate?.charcoalViewController(self, didChangeSelection: queryItems, origin: origin) } } } // MARK: - FilterViewControllerDelegate extension CharcoalViewController: FilterViewControllerDelegate { func filterViewControllerWillBeginTextEditing(_ viewController: FilterViewController) { textEditingDelegate?.charcoalViewControllerWillBeginTextEditing(self) } func filterViewControllerWillEndTextEditing(_ viewController: FilterViewController) { textEditingDelegate?.charcoalViewControllerWillEndTextEditing(self) } func filterViewControllerDidPressBottomButton(_ viewController: FilterViewController) { if viewController === rootFilterViewController { selectionDelegate?.charcoalViewControllerDidPressShowResults(self) } else { bottomBottonClicked = true popToRootViewController(animated: true) } } func filterViewController(_ viewController: FilterViewController, didSelectFilter filter: Filter) { switch filter.kind { case .standard: guard !filter.subfilters.isEmpty else { break } let listViewController = ListFilterViewController(filter: filter, selectionStore: selectionStore) let showBottomButton = viewController === rootFilterViewController ? false : viewController.isShowingBottomButton listViewController.showBottomButton(showBottomButton, animated: false) pushViewController(listViewController) case .grid: guard !filter.subfilters.isEmpty else { break } let gridViewController = GridFilterViewController(filter: filter, selectionStore: selectionStore) gridViewController.showBottomButton(viewController.isShowingBottomButton, animated: false) pushViewController(gridViewController) case let .range(lowValueFilter, highValueFilter, filterConfig): let rangeViewController = RangeFilterViewController( title: filter.title, lowValueFilter: lowValueFilter, highValueFilter: highValueFilter, filterConfig: filterConfig, selectionStore: selectionStore ) pushViewController(rangeViewController) case let .stepper(filterConfig): let stepperViewController = StepperFilterViewController( filter: filter, selectionStore: selectionStore, filterConfig: filterConfig ) pushViewController(stepperViewController) case let .map(latitudeFilter, longitudeFilter, radiusFilter, locationNameFilter): let mapViewController = MapFilterViewController( title: filter.title, latitudeFilter: latitudeFilter, longitudeFilter: longitudeFilter, radiusFilter: radiusFilter, locationNameFilter: locationNameFilter, selectionStore: selectionStore ) mapViewController.mapDataSource = mapDataSource mapViewController.searchLocationDataSource = searchLocationDataSource pushViewController(mapViewController) case .external: selectionDelegate?.charcoalViewController(self, didSelectExternalFilterWithKey: filter.key, value: filter.value) } } private func pushViewController(_ viewController: FilterViewController) { viewController.delegate = self pushViewController(viewController, animated: true) } } // MARK: - FilterSelectionStoreDelegate extension CharcoalViewController: FilterSelectionStoreDelegate { func filterSelectionStoreDidChange(_ selectionStore: FilterSelectionStore) { if topViewController !== rootFilterViewController { selectionHasChanged = true } rootFilterViewController?.updateResetButtonAvailability() } } // MARK: - UINavigationControllerDelegate extension CharcoalViewController: UINavigationControllerDelegate { public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) { defer { bottomBottonClicked = false } guard viewController === rootFilterViewController else { showBottomButtonIfNeeded() return } // Will return to root filters if selectionHasChanged, let filterContainer = filterContainer { let queryItems = selectionStore.queryItems(for: filterContainer) let origin: SelectionChangeOrigin = bottomBottonClicked ? .bottomButton : .navigation selectionDelegate?.charcoalViewController(self, didChangeSelection: queryItems, origin: origin) selectionHasChanged = false } } private func showBottomButtonIfNeeded() { for viewController in viewControllers where viewController !== rootFilterViewController { (viewController as? ListFilterViewController)?.showBottomButton(selectionHasChanged, animated: false) } } } // MARK: - VerticalCalloutOverlayDelegate extension CharcoalViewController: VerticalCalloutOverlayDelegate { func verticalCalloutOverlayDidTapInside(_ verticalCalloutOverlay: VerticalCalloutOverlay) { UIView.animate(withDuration: 0.3, animations: { verticalCalloutOverlay.alpha = 0 }, completion: { _ in verticalCalloutOverlay.removeFromSuperview() }) } private func showVerticalCallout(withText text: String) { verticalCalloutOverlay.alpha = 0 view.addSubview(verticalCalloutOverlay) verticalCalloutOverlay.configure(withText: text) verticalCalloutOverlay.fillInSuperview() UIView.animate(withDuration: 0.3, delay: 0.5, options: [], animations: { [weak self] in self?.verticalCalloutOverlay.alpha = 1 }, completion: nil) } } // MARK: - UserDefaults private extension UserDefaults { var verticalCalloutShown: Bool { get { return bool(forKey: #function) } set { set(newValue, forKey: #function) } } }
39.18123
145
0.717601
c8cc632b9a57ce6b721d101a0ec2ce5200212eb4
5,968
css
CSS
src/main/webapp/css/base.css
suguru/cassandra-webconsole
22415f259d825880acc89b8265f16b4c9e426783
[ "Apache-2.0" ]
17
2015-01-05T02:53:29.000Z
2020-08-31T08:38:24.000Z
src/main/webapp/css/base.css
suguru/cassandra-webconsole
22415f259d825880acc89b8265f16b4c9e426783
[ "Apache-2.0" ]
null
null
null
src/main/webapp/css/base.css
suguru/cassandra-webconsole
22415f259d825880acc89b8265f16b4c9e426783
[ "Apache-2.0" ]
12
2015-06-08T01:41:49.000Z
2021-08-31T05:29:55.000Z
body { background: #fff; margin: 0; padding: 0; font-family: Arial; font-size: 0.9em; } h1, h2, h3, h4, h5 { margin: 0; padding: 0; font-size: 1.0em; } h1 { background: #333; background: -webkit-gradient(linear, left top, left bottom, from(#555), to(#333)); background: -moz-linear-gradient(top, #555, #333); padding: 5px 10px; color: #fff; font-size: 1.4em; } footer { display: block; color: #222; text-align: right; text-shadow: 0 -1px 1px #fff; font-size: 0.8em; padding: 1em 2em 1em 2em; border-top: 4px solid #333; } a { text-decoration: none; } a:hover { text-decoration: underline; } ul { padding: 0; margin: 0; } li { list-style: none; margin: 0; padding: 0; } table { border-collapse: collapse; } table.keyspace { margin-bottom: 1em; } table caption { text-align: left; font-weight: bold; padding: 0.3em 0.3em 0.3em 0.6em; border: 1px solid #666; border-bottom: none; background: #cce; -webkit-border-radius: 7px 7px 0 0; -moz-border-radius: 7px 7px 0 0; border-radius: 7px 7px 0 0; } table.section caption a { color: #ffeeee; } table tr { } table th { border: 1px solid #666; margin: 0; padding: 0.3em; background: #eef; text-align: left; } td { border: 1px solid #666; margin: 0; padding: 0.3em; } td.up { color: #3c3; font-weight: bold; } td.down { color: #c33; font-weight: bold; } td.status { text-align: center; } td.bytes, td.number, td.date { text-align: right; } nav.control { display: block; padding-top: 8px; } nav.control a, a.button { color: #fff; -moz-box-shadow: 0 0 2px rgba(0,0,0,0.5); -webkit-box-shadow: 0 0 2px rgba(0,0,0,0.5); text-shadow: 0 -1px 1px rgba(0,0,0,0.25); border-bottom: 1px solid rgba(0,0,0,0.25); display: inline-block; padding: 4px 10px 5px; font-weight: bold; font-size: 0.9em; -moz-border-radius: 5px; -webkit-border-radius: 5px; background: #f78d1d; background: -webkit-gradient(linear, left top, left bottom, from(#faa51a), to(#f47a20)); background: -moz-linear-gradient(top, #faa51a, #f47a20); cursor: pointer; } nav.control a:hover, a.button:hover { background: #f78d1d; background: -webkit-gradient(linear, left top, left bottom, from(#fc4), to(#f83)); background: -moz-linear-gradient(top, #fc4, #f83); text-decoration: none; } form.float { min-width: 480px; min-height: 100px; background: #fff; padding: 0.4em 1em; } form p { padding: 0 0 14px 0; border-bottom: 1px solid #ccc; } form label { display: inline-block; width: 160px; } form label.error { margin-left: 160px; width: 300px; padding: 4px 0; font-size: 0.9em; color: #c33; } input, select { font-family: Arial; } form p.buttons { padding-left: 160px; border-bottom: none; } button { color: #fff; -moz-box-shadow: 0 0 2px rgba(0,0,0,0.5); -webkit-box-shadow: 0 0 2px rgba(0,0,0,0.5); text-shadow: 0 -1px 1px rgba(0,0,0,0.25); border: none; border-bottom: 1px solid rgba(0,0,0,0.25); display: inline-block; padding: 3px 8px 4px; -moz-border-radius: 5px; -webkit-border-radius: 5px; background: #f78d1d; background: -webkit-gradient(linear, left top, left bottom, from(#faa51a), to(#f47a20)); background: -moz-linear-gradient(top, #faa51a, #f47a20); font-family: Arial; font-weight: bold; cursor: pointer; } button.submit { background: -webkit-gradient(linear, left top, left bottom, from(#faa51a), to(#f47a20)); background: -moz-linear-gradient(top, #faa51a, #f47a20); } button.submit:hover { background: -webkit-gradient(linear, left top, left bottom, from(#fc4), to(#f83)); background: -moz-linear-gradient(top, #fc4, #f83); } button.cancel { background: -webkit-gradient(linear, left top, left bottom, from(#999), to(#666)); background: -moz-linear-gradient(top, #999, #666); } button.cancel:hover { background: -webkit-gradient(linear, left top, left bottom, from(#bbb), to(#888)); background: -moz-linear-gradient(top, #bbb, #888); } #container { display: -moz-box; display: -webkit-box; } #content { padding-top: 1.4em; padding-bottom: 5em; } #content h2 { font-size: 1.2em; padding: 0; margin: 0.8em 0; color: #336; border-bottom: 1px solid #999; } #content h3 { font-size: 1.2em; -webkit-border-radius: 7px 7px 0 0; -moz-border-radius: 7px 7px 0 0; border-radius: 7px 7px 0 0; margin: 0 0 0.4em 0; padding: 0.2em 0.5em; color: #fff; background: -webkit-gradient(linear, left top, left bottom, from(#778), to(#667)); background: -moz-linear-gradient(top, #778, #556); } #content nav { margin: 0 0.4em; } #content nav.path { display: block; margin: 0 0 0.4em 0; } #content nav.path a { font-size: 0.8em; } #content table { margin-bottom: 1em; } #content .section { -webkit-border-radius: 8px; -moz-border-radius: 8px; border-radius: 8px; border: 1px solid #666; padding-bottom: .6em; margin-bottom: 1em; } #menu { background: #333; padding: 0 0 5em 0; margin: 0 1.4em 0 0; text-align: right; } #menu h2 { padding: 4px 8px; margin: 4px 0 0 0; color: #fff; font-size: 1em; } #menu li { list-style: none; } #menu li a { color: #000; background: #aaa; text-decoration: none; display: block; padding: 4px 8px; margin: 3px 0 0 20px; -webkit-border-radius: 6px 0 0 6px; -moz-border-radius: 6px 0 0 6px; } #menu li.active a { background: #fff; } #menu li a:hover { background: #ccc; } #menu li.cf a { font-size: 0.8em; margin: 1px 0 0 40px; -webkit-border-radius: 0; -moz-border-radius: 0; } #menu li.last a { margin: 1px 0 3px 40px; -webkit-border-radius: 0 0 0 6px; -moz-border-radius: 0 0 0 6px; } div.nodeCfStore nav { display: block; padding-bottom: 2em; }
17.814925
90
0.620476
b05fb30c052341cafcc7fc10ade5c4fe2a332cf8
3,701
py
Python
python/plotrecording.py
eric-wieser/4m20-coursework2
3b894563eb35336faa7e5f04dccb1a3fd9bfbc65
[ "MIT" ]
null
null
null
python/plotrecording.py
eric-wieser/4m20-coursework2
3b894563eb35336faa7e5f04dccb1a3fd9bfbc65
[ "MIT" ]
null
null
null
python/plotrecording.py
eric-wieser/4m20-coursework2
3b894563eb35336faa7e5f04dccb1a3fd9bfbc65
[ "MIT" ]
null
null
null
#! python3 """ Pass this program a filename as the first argument """ import sys import pickle import numpy as np import matplotlib.pyplot as plt from robot.base import State import config from logger import augment def add_arrow(line, direction='right', size=15, color=None, n=1): """ add an arrow to a line. line: Line2D object position: x-position of the arrow. If None, mean of xdata is taken direction: 'left' or 'right' size: size of the arrow in fontsize points color: if None, line color is taken. """ if color is None: color = line.get_color() xdata = line.get_xdata() ydata = line.get_ydata() # find closest index dists = np.cumsum(np.hypot(np.diff(xdata), np.diff(ydata))) dists = np.concatenate(([0], dists)) total_dist = dists[-1] for i in range(1, n+1): target_dist = total_dist * i / (n+1) end_ind = np.argmax(dists >= target_dist) start_ind = end_ind - 1 frac = (target_dist - dists[start_ind]) / (dists[end_ind] - dists[start_ind]) end_x = xdata[start_ind]*(1-frac) + xdata[end_ind]*frac end_y = ydata[start_ind]*(1-frac) + ydata[end_ind]*frac line.axes.annotate('', xytext=(xdata[start_ind], ydata[start_ind]), xy=(end_x, end_y), arrowprops=dict(arrowstyle="->", color=color), size=size ) if len(sys.argv) > 1: fname = sys.argv[1] else: fname = 'walking.pickle' with open(fname, 'rb') as f: data = pickle.load(f) # add all the extra calculated fields aug = augment(data) error_bounds = config.error_active_lim fig, axs = plt.subplots(3, sharex=True) fig.patch.set(alpha=0) fig.suptitle('Time-angle plots: {}'.format(fname)) for i, ax in enumerate(axs): ax.plot(aug.t, np.degrees(aug.target[:,i]), label='target') l, = ax.plot(aug.t, np.degrees(aug.actual[:,i]), label='actual') ax.plot(aug.t, np.degrees(aug.actual_oob[:,i]), color=l.get_color(), alpha=0.5) l, = ax.plot(aug.t, np.degrees(aug.servo[:,i]), label='servo') ax.plot(aug.t, np.degrees(aug.servo_oob[:,i]), color=l.get_color(), alpha=0.5) l, = ax.plot(aug.t, np.degrees(aug.error[:,i]), label='displacement') ax.axhline(y=np.degrees(error_bounds[i,0]), color=l.get_color(), alpha=0.5) ax.axhline(y=np.degrees(error_bounds[i,1]), color=l.get_color(), alpha=0.5) ax.grid() ax.set(xlabel='time / s', ylabel='$q_{}$ / degrees'.format(i+1)) ax.legend() target_states = np.stack([State(target).joint_positions for target in aug.target], axis=1) actual_states = np.stack([State(actual).joint_positions for actual in aug.actual], axis=1) fig, ax = plt.subplots() fig.patch.set(alpha=0) fig.suptitle('Space-plots: {}'.format(fname)) for targets, actuals in zip(target_states, actual_states): l, = ax.plot(targets[:,0],targets[:,1], alpha=0.5, linewidth=3, label='target') ax.plot(actuals[:,0],actuals[:,1], color=l.get_color(), label='actual') ax.legend() ax.axis('equal') ax.grid() # this data is super noisy, so filter it N = 11 filt = np.ones(N) / N fig, axs = plt.subplots(3) fig.patch.set(alpha=0) fig.suptitle('Angle-force plots: {}'.format(fname)) for i, ax in enumerate(axs): # extract aug, and smooth it actual_i = aug.actual[:,i] error_i = aug.error[:,i] sm_actual_i = np.convolve(actual_i, filt)[N//2:][:len(actual_i)] sm_error_i = np.convolve(error_i, filt)[N//2:][:len(error_i)] # plot both l, = ax.plot(np.degrees(actual_i), np.degrees(error_i), alpha=0.25) l, = ax.plot(np.degrees(sm_actual_i), np.degrees(sm_error_i), color=l.get_color()) add_arrow(l, n=5) ax.grid() ax.set(xlabel=r'$\phi_{}$ / degrees', ylabel='spring angle / degrees'.format(i+1)) plt.show()
30.841667
90
0.656039
6b81f7da587c68f08243fdccf89dc05b0f6d1e7a
1,473
js
JavaScript
lib/v2/disinformationindex/research.js
magicLaLa/RSSHub
76cc2e37af112f29d8b659fa528c8e439b1457dc
[ "MIT" ]
16
2018-04-02T14:57:10.000Z
2018-04-06T13:02:50.000Z
lib/v2/disinformationindex/research.js
magicLaLa/RSSHub
76cc2e37af112f29d8b659fa528c8e439b1457dc
[ "MIT" ]
274
2021-11-26T08:27:02.000Z
2022-03-31T21:34:27.000Z
lib/v2/disinformationindex/research.js
magicLaLa/RSSHub
76cc2e37af112f29d8b659fa528c8e439b1457dc
[ "MIT" ]
1
2020-05-10T04:04:21.000Z
2020-05-10T04:04:21.000Z
const got = require('@/utils/got'); const cheerio = require('cheerio'); const { art } = require('@/utils/render'); const path = require('path'); module.exports = async (ctx) => { const rootUrl = 'https://disinformationindex.org'; const currentUrl = `${rootUrl}/research`; const response = await got({ method: 'get', url: currentUrl, }); const $ = cheerio.load(response.data); const items = $('.elementor-widget-container .elementor-text-editor') .map((_, item) => { item = $(item); const title = item.find('h3, h4').eq(0); const image = item.parentsUntil('.elementor-container').find('.elementor-image img'); const firstLink = item.find('a.button').eq(0); let links = ''; item.find('a.button').each(function () { links += `<br><a href="${$(this).attr('href')}">${$(this).text()}</a>`; }); return { link: firstLink.attr('href'), title: title.text() || firstLink.text(), description: art(path.resolve(__dirname, 'templates/description.art'), { image: image ? image.attr('src') : undefined, title: title.next().html(), links, }), }; }) .get(); ctx.state.data = { title: $('title').text(), link: currentUrl, item: items, }; };
32.021739
97
0.496945
464f35fe9e7ebeb77b5c8f95ed59426c4675036b
111
php
PHP
module/Core/src/Core/Model/EntityException.php
mikesavegnago/blog
fd5e1e5b92332353dd70a2f66fe2f694cd30c57d
[ "BSD-3-Clause" ]
null
null
null
module/Core/src/Core/Model/EntityException.php
mikesavegnago/blog
fd5e1e5b92332353dd70a2f66fe2f694cd30c57d
[ "BSD-3-Clause" ]
null
null
null
module/Core/src/Core/Model/EntityException.php
mikesavegnago/blog
fd5e1e5b92332353dd70a2f66fe2f694cd30c57d
[ "BSD-3-Clause" ]
null
null
null
<?php namespace Core\Model; /** * @package Core\Model * */ class EntityException extends \Exception {}
12.333333
43
0.657658
c3961826c9a55648ea15a1901983e04136c83265
456
cs
C#
src/Core/LifetimeAttribute.cs
MapsysInc/Microsoft.Extensions.DependencyInjection.Attribute
0bc6755d10f9f0736ae05f11675fecc05adfd8fa
[ "MIT" ]
null
null
null
src/Core/LifetimeAttribute.cs
MapsysInc/Microsoft.Extensions.DependencyInjection.Attribute
0bc6755d10f9f0736ae05f11675fecc05adfd8fa
[ "MIT" ]
null
null
null
src/Core/LifetimeAttribute.cs
MapsysInc/Microsoft.Extensions.DependencyInjection.Attribute
0bc6755d10f9f0736ae05f11675fecc05adfd8fa
[ "MIT" ]
null
null
null
namespace MapsysInc.Extensions.DependencyInjection.AttributeRegistration { using Microsoft.Extensions.DependencyInjection; using System; public abstract class LifetimeAttribute : Attribute { protected LifetimeAttribute(ServiceLifetime serviceLifetime) { ServiceLifetime = serviceLifetime; } public ServiceLifetime ServiceLifetime { get; } public Type ServiceType { get; set; } } }
26.823529
73
0.699561
8c700b426ea3a27545df5ec07251d489ae3dfba4
1,778
rb
Ruby
lib/omniauth-slack/debug.rb
mode/omniauth-slack
bf7c80532d45364512bfd06007ad881aa5d39e44
[ "MIT" ]
35
2016-11-11T10:23:39.000Z
2022-03-17T22:14:41.000Z
lib/omniauth-slack/debug.rb
mode/omniauth-slack
bf7c80532d45364512bfd06007ad881aa5d39e44
[ "MIT" ]
17
2018-07-25T23:47:08.000Z
2022-02-16T13:05:21.000Z
lib/omniauth-slack/debug.rb
mode/omniauth-slack
bf7c80532d45364512bfd06007ad881aa5d39e44
[ "MIT" ]
20
2016-11-30T23:29:42.000Z
2021-03-07T16:02:00.000Z
require 'omniauth-slack/refinements' require 'logger' # Appends 'TRACE' option to Logger levels. sev_label_new = Logger::SEV_LABEL.dup sev_label_new << 'TRACE' Logger::Severity::TRACE = (sev_label_new.size - 1) Logger.send(:remove_const, :SEV_LABEL) Logger::SEV_LABEL = sev_label_new.freeze module OmniAuth module Slack module Debug #using ObjectRefinements LOG_ALL = %w(1 true yes all debug) LOG_NONE = %w(0 false no none nil nill null) include CallerMethodName def self.included(other) other.send(:include, CallerMethodName) other.send(:extend, Extensions) end module Extensions def debug(method_name = nil, klass=nil, &block) method_name ||= caller_method_name klass ||= self filter = ENV['OMNIAUTH_SLACK_DEBUG'] return if filter.nil? || filter.to_s=='' || LOG_NONE.include?(filter.to_s.downcase) klass = case klass when Class; klass.name when Module; klass.name when String; klass else klass.to_s end klass_name = klass.to_s.split('::').last.to_s log_text = yield full_text = "(#{klass_name} #{method_name}) #{log_text}" #{Thread.current.object_id} if filter && !LOG_ALL.include?(filter.to_s.downcase) regexp = filter.is_a?(Regexp) ? filter : Regexp.new(filter.to_s, true) return unless full_text[regexp] end OmniAuth.logger.log(Logger::TRACE, full_text) end end def debug(method_name=nil, klass=nil, &block) method_name ||= caller_method_name self.class.debug(method_name, klass, &block) end end end end
31.192982
97
0.609674
55e790c6dd7aef334479db4afad027779594a374
2,417
swift
Swift
Samples/EmbeddedAuthWithSDKs/EmbeddedAuth/View Controllers/TokenDetailViewController.swift
chrisdmills-okta/okta-idx-swift
1375a45816cf95994b14b5026e0c20ca92c16d3e
[ "Apache-2.0" ]
4
2021-05-11T16:00:19.000Z
2021-11-17T09:10:53.000Z
Samples/EmbeddedAuthWithSDKs/EmbeddedAuth/View Controllers/TokenDetailViewController.swift
chrisdmills-okta/okta-idx-swift
1375a45816cf95994b14b5026e0c20ca92c16d3e
[ "Apache-2.0" ]
9
2021-03-01T22:36:39.000Z
2021-08-04T21:57:08.000Z
Samples/EmbeddedAuthWithSDKs/EmbeddedAuth/View Controllers/TokenDetailViewController.swift
chrisdmills-okta/okta-idx-swift
1375a45816cf95994b14b5026e0c20ca92c16d3e
[ "Apache-2.0" ]
3
2021-10-11T14:01:19.000Z
2022-01-26T19:25:30.000Z
/* * Copyright (c) 2021-Present, Okta, Inc. and/or its affiliates. All rights reserved. * The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.") * * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and limitations under the License. */ import UIKit import OktaIdx class TokenDetailViewController: UIViewController { var client: IDXClient? var token: Token? @IBOutlet weak var textView: UITextView! override func viewDidLoad() { super.viewDidLoad() guard let token = token else { textView.text = "No token was found" return } let paragraph = NSMutableParagraphStyle() paragraph.lineBreakMode = .byCharWrapping paragraph.paragraphSpacing = 15 let bold = [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .headline)] let normal = [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .body), NSAttributedString.Key.paragraphStyle: paragraph] func addString(to string: NSMutableAttributedString, title: String, value: String) { string.append(NSAttributedString(string: "\(title):\n", attributes: bold)) string.append(NSAttributedString(string: "\(value)\n", attributes: normal)) } let string = NSMutableAttributedString() addString(to: string, title: "Access token", value: token.accessToken) if let refreshToken = token.refreshToken { addString(to: string, title: "Refresh token", value: refreshToken) } addString(to: string, title: "Expires in", value: "\(token.expiresIn) seconds") addString(to: string, title: "Scope", value: token.scope) addString(to: string, title: "Token type", value: token.tokenType) if let idToken = token.idToken { addString(to: string, title: "ID token", value: idToken) } textView.attributedText = string } }
39.622951
120
0.653289
e779aed9298ff4568e9cf72fdf2fe00d34de46f6
1,041
swift
Swift
OnBoarding/OnBoarding/OnBoardingTests/OnBoardingTests.swift
tauheed94/Onboarding-SampleApp
39cfa46050e1295d046ea79ece089cd5ac829bb4
[ "MIT" ]
null
null
null
OnBoarding/OnBoarding/OnBoardingTests/OnBoardingTests.swift
tauheed94/Onboarding-SampleApp
39cfa46050e1295d046ea79ece089cd5ac829bb4
[ "MIT" ]
1
2016-12-15T15:45:13.000Z
2016-12-15T15:45:13.000Z
OnBoarding/OnBoarding/OnBoardingTests/OnBoardingTests.swift
tauheed94/Onboarding-SampleApp
39cfa46050e1295d046ea79ece089cd5ac829bb4
[ "MIT" ]
null
null
null
// // OnBoardingTests.swift // OnBoardingTests // // Created by iMac on 12/13/16. // Copyright © 2016 codekindle. All rights reserved. // Copyright © 2016 Mohd Tauheed Uddin Siddiqui. All rights reserved. import XCTest @testable import OnBoarding class OnBoardingTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. // Use XCTAssert and related functions to verify your tests produce the correct results. } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
28.135135
111
0.645533
823866c622993947d13d44d2a93ed3a2d5c02c5f
5,408
rs
Rust
bindings/ergo-lib-c-core/src/constant.rs
ross-weir/sigma-rust
90591f327e9c0d7b6811308cafe9bab094272624
[ "CC0-1.0" ]
null
null
null
bindings/ergo-lib-c-core/src/constant.rs
ross-weir/sigma-rust
90591f327e9c0d7b6811308cafe9bab094272624
[ "CC0-1.0" ]
null
null
null
bindings/ergo-lib-c-core/src/constant.rs
ross-weir/sigma-rust
90591f327e9c0d7b6811308cafe9bab094272624
[ "CC0-1.0" ]
null
null
null
//! Ergo constant values use std::convert::TryFrom; use crate::{ ergo_box::{ConstErgoBoxPtr, ErgoBox, ErgoBoxPtr}, util::{const_ptr_as_ref, mut_ptr_as_mut}, Error, }; use ergo_lib::{ ergo_chain_types::Base16DecodedBytes, ergotree_ir::{ base16_str::Base16Str, mir::constant::{TryExtractFrom, TryExtractInto}, serialization::SigmaSerializable, sigma_protocol::{dlog_group::EcPoint, sigma_boolean::ProveDlog}, }, }; /// Ergo constant(evaluated) values #[derive(PartialEq, Eq, Debug, Clone)] pub struct Constant(pub(crate) ergo_lib::ergotree_ir::mir::constant::Constant); pub type ConstantPtr = *mut Constant; pub type ConstConstantPtr = *const Constant; /// Decode from base16 encoded serialized ErgoTree pub unsafe fn constant_from_base16_bytes( bytes_str: &str, constant_out: *mut ConstantPtr, ) -> Result<(), Error> { let constant_out = mut_ptr_as_mut(constant_out, "constant_out")?; let bytes = Base16DecodedBytes::try_from(bytes_str.to_string())?; let constant = ergo_lib::ergotree_ir::mir::constant::Constant::try_from(bytes).map(Constant)?; *constant_out = Box::into_raw(Box::new(constant)); Ok(()) } /// Encode as Base16-encoded ErgoTree serialized value or return an error if serialization failed pub unsafe fn constant_to_base16_str(constant_ptr: ConstConstantPtr) -> Result<String, Error> { let constant = const_ptr_as_ref(constant_ptr, "constant_ptr")?; let s = constant.0.base16_str()?; Ok(s) } /// Create from i32 value pub unsafe fn constant_from_i32(value: i32, constant_out: *mut ConstantPtr) -> Result<(), Error> { let constant_out = mut_ptr_as_mut(constant_out, "constant_out")?; *constant_out = Box::into_raw(Box::new(Constant(value.into()))); Ok(()) } /// Extract i32 value, returning error if wrong type pub unsafe fn constant_to_i32(constant_ptr: ConstConstantPtr) -> Result<i32, Error> { let constant = const_ptr_as_ref(constant_ptr, "constant_ptr")?; let i = i32::try_extract_from(constant.0.clone())?; Ok(i) } /// Create from i64 pub unsafe fn constant_from_i64(value: i64, constant_out: *mut ConstantPtr) -> Result<(), Error> { let constant_out = mut_ptr_as_mut(constant_out, "constant_out")?; *constant_out = Box::into_raw(Box::new(Constant(value.into()))); Ok(()) } /// Extract i64 value, returning error if wrong type pub unsafe fn constant_to_i64(constant_ptr: ConstConstantPtr) -> Result<i64, Error> { let constant = const_ptr_as_ref(constant_ptr, "constant_ptr")?; let i = i64::try_extract_from(constant.0.clone())?; Ok(i) } /// Create from byte array pub unsafe fn constant_from_bytes( bytes_ptr: *const u8, len: usize, constant_out: *mut ConstantPtr, ) -> Result<(), Error> { let constant_out = mut_ptr_as_mut(constant_out, "constant_out")?; let bytes = std::slice::from_raw_parts(bytes_ptr, len); *constant_out = Box::into_raw(Box::new(Constant(bytes.to_vec().into()))); Ok(()) } /// Extract byte array length, returning error if wrong type pub unsafe fn constant_bytes_len(constant_ptr: ConstConstantPtr) -> Result<usize, Error> { let constant = const_ptr_as_ref(constant_ptr, "constant_ptr")?; let len = Vec::<u8>::try_extract_from(constant.0.clone()).map(|v| v.len())?; Ok(len) } /// Convert to serialized bytes. Key assumption: enough memory has been allocated at the address /// pointed-to by `output`. Use `constant_bytes_len` to determine the length of the byte array. pub unsafe fn constant_to_bytes( constant_ptr: ConstConstantPtr, output: *mut u8, ) -> Result<(), Error> { let constant = const_ptr_as_ref(constant_ptr, "constant_ptr")?; let src = Vec::<u8>::try_extract_from(constant.0.clone())?; std::ptr::copy_nonoverlapping(src.as_ptr(), output, src.len()); Ok(()) } /// Parse raw [`EcPoint`] value from bytes and make [`ProveDlog`] constant pub unsafe fn constant_from_ecpoint_bytes( bytes_ptr: *const u8, len: usize, constant_out: *mut ConstantPtr, ) -> Result<(), Error> { let constant_out = mut_ptr_as_mut(constant_out, "constant_out")?; let bytes = std::slice::from_raw_parts(bytes_ptr, len); let ecp = EcPoint::sigma_parse_bytes(bytes)?; let c: ergo_lib::ergotree_ir::mir::constant::Constant = ProveDlog::new(ecp).into(); *constant_out = Box::into_raw(Box::new(Constant(c))); Ok(()) } /// Create from ErgoBox value pub unsafe fn constant_from_ergo_box( ergo_box_ptr: ConstErgoBoxPtr, constant_out: *mut ConstantPtr, ) -> Result<(), Error> { let ergo_box = const_ptr_as_ref(ergo_box_ptr, "ergo_box_ptr")?; let constant_out = mut_ptr_as_mut(constant_out, "constant_out")?; let c: ergo_lib::ergotree_ir::mir::constant::Constant = ergo_box.0.clone().into(); *constant_out = Box::into_raw(Box::new(Constant(c))); Ok(()) } /// Extract ErgoBox value, returning error if wrong type pub unsafe fn constant_to_ergo_box( constant_ptr: ConstConstantPtr, ergo_box_out: *mut ErgoBoxPtr, ) -> Result<(), Error> { let constant = const_ptr_as_ref(constant_ptr, "constant_ptr")?; let ergo_box_out = mut_ptr_as_mut(ergo_box_out, "ergo_box_out")?; let b = constant .0 .clone() .try_extract_into::<ergo_lib::ergotree_ir::chain::ergo_box::ErgoBox>() .map(Into::into)?; *ergo_box_out = Box::into_raw(Box::new(ErgoBox(b))); Ok(()) }
37.296552
98
0.699519
46c5fc10add6f8180c6a2fbb40cb858c05fe6d93
5,903
py
Python
choicer/test/core_tests.py
tonimichel/django-choicer
69bce93585c6b3711f90c893d449e3eb3ce44eb5
[ "MIT" ]
3
2016-03-28T16:26:33.000Z
2016-07-14T08:58:34.000Z
choicer/test/core_tests.py
tonimichel/django-choicer
69bce93585c6b3711f90c893d449e3eb3ce44eb5
[ "MIT" ]
null
null
null
choicer/test/core_tests.py
tonimichel/django-choicer
69bce93585c6b3711f90c893d449e3eb3ce44eb5
[ "MIT" ]
2
2017-08-16T12:16:48.000Z
2021-03-13T15:03:14.000Z
from __future__ import unicode_literals, print_function import unittest import choicer from choicer import exceptions class ChoicerTests(unittest.TestCase): def setUp(self): self.CHOICE_LIST = [ dict( name='approved', value=0, verbose_name='Approved' ), dict( name='dismissed', value=1, verbose_name='Dismissed' ), ] def _get_fake_model_class(self): """ Returns a newly created FakeModelClass in order to test patching in isolation for each patching test. Otherwise once applied patches will last for further patching test cases, too. :return: """ class FakeModel(object): state = 0 return FakeModel def test_basics(self): """ Tests get_choices, get_list and get_dict. :return: """ mychoicer = choicer.Choicer(self.CHOICE_LIST) self.assertEquals(len(mychoicer.get_choices()), len(self.CHOICE_LIST)) self.assertEquals( len(mychoicer.get_list()), len(self.CHOICE_LIST)) self.assertEquals(len(mychoicer.get_dict()), len(self.CHOICE_LIST)) def test_get_by(self): """ Tests the get_by_<name|value> functions. :return: """ mychoicer = choicer.Choicer(self.CHOICE_LIST) self.assertTrue( mychoicer.get_by_name('approved') == mychoicer.get_by_value(0) == self.CHOICE_LIST[0] ) def test_malformed_choice_definition_exceptions(self): """ Tests that a MalformedChoiceDefinition is raised in case choicer is initialized with a malformed choice. :return: """ try: choicer.Choicer([ dict(name='approved', value=0, verbose_name='Approved'), dict(name='dismissed') ]) except exceptions.MalformedChoiceDefinition as e: exception_list = e.errors self.assertTrue('choices[1]' in exception_list[0].keys()) def test_choice_does_not_exist_exceptions(self): """ Tests that an exception is raised if a choice is accessed that does not exist. :return: """ mychoicer = choicer.Choicer(self.CHOICE_LIST) self.assertRaises(exceptions.ChoiceDoesNotExist, mychoicer.get_by_name, 'xyz') self.assertRaises(exceptions.ChoiceDoesNotExist, mychoicer.get_by_value, 'xyz') def test_out_of_sync_exception(self): """ Tests that the ChoicesOutOfSyncError is raised in case the choice-storing field provide a value which not represented in the choices data structure. :return: """ mychoicer = choicer.Choicer(self.CHOICE_LIST) @mychoicer.apply(field_name='state') class MyModel(object): state = 1337 obj = MyModel() self.assertRaises(exceptions.ChoicesOutOfSyncError, obj.get_state) def test_enums(self): """ Tests that the choicer provides its values in choicer.ENUMS :return: """ mychoicer = choicer.Choicer(self.CHOICE_LIST) for choice in self.CHOICE_LIST: self.assertEquals( getattr(mychoicer.ENUMS, choice['name']), choice['value'] ) def test_separate_patching(self): """ Test the manual/separate patching. :return: """ model_class = self._get_fake_model_class() mychoicer = choicer.Choicer(self.CHOICE_LIST) mychoicer.patch_choice_getter(model_class, 'state') mychoicer.patch_getters(model_class, 'state') mychoicer.patch_setters(model_class, 'state') mychoicer.patch_choicer(model_class, 'STATE_CHOICER') self._assert_patches(model_class()) def test_patch_all(self): """ Tests the patch method which in under the hood calls all manual patch api functions subsequently, so we can apply the same asserting. :return: """ model_class = self._get_fake_model_class() mychoicer = choicer.Choicer(self.CHOICE_LIST) mychoicer.patch( model_class=model_class, field_name='state', attr='STATE_CHOICER' ) self._assert_patches(model_class()) def test_decorator(self): """ Tests the decorator way of patching. :return: """ mychoicer = choicer.Choicer(self.CHOICE_LIST) @mychoicer.apply(field_name='state') class MyModel(object): state = 0 self._assert_patches(MyModel()) def _assert_patches(self, fakemodel_obj): """ Asserts that the passed fakemodel_obj was patched succesfully. :param fakemodel_obj: :return: """ # check that getters have been patched self.assertTrue( hasattr(fakemodel_obj, 'is_state_approved') and hasattr(fakemodel_obj, 'is_state_dismissed') ) # check that setters have been patched self.assertTrue( hasattr(fakemodel_obj, 'set_state_approved') and hasattr(fakemodel_obj, 'set_state_dismissed') ) # check that the choicer itself has been pacthed self.assertTrue( hasattr(fakemodel_obj, 'STATE_CHOICER') ) # check that setter is working fakemodel_obj.set_state_dismissed() self.assertEquals( fakemodel_obj.state, fakemodel_obj.STATE_CHOICER.get_by_name('dismissed')['value'] ) # check that getter is working self.assertEquals( fakemodel_obj.is_state_dismissed(), fakemodel_obj.STATE_CHOICER.get_by_name('dismissed')['value'] )
30.117347
97
0.605624
fb39c57ce841164c41abdceedfece50172c6ecc8
43,524
rs
Rust
sbp-derive/src/lib.rs
4lDO2/sbp-rs
fba67c72a304f0c0a1d27893878633528d47eb92
[ "Apache-2.0", "MIT" ]
null
null
null
sbp-derive/src/lib.rs
4lDO2/sbp-rs
fba67c72a304f0c0a1d27893878633528d47eb92
[ "Apache-2.0", "MIT" ]
null
null
null
sbp-derive/src/lib.rs
4lDO2/sbp-rs
fba67c72a304f0c0a1d27893878633528d47eb92
[ "Apache-2.0", "MIT" ]
null
null
null
extern crate proc_macro; use proc_macro::TokenStream; use quote::quote; use syn::{parse_macro_input, ItemStruct}; #[derive(Clone, Copy, Debug)] enum Endianness { Little, Big, } fn match_single_angle_bracketed_type(args: &syn::PathArguments) -> Option<syn::Ident> { if let syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments { args, .. }) = args { if args.len() != 1 { return None; } if let syn::GenericArgument::Type(syn::Type::Path(syn::TypePath { qself: None, path: syn::Path { leading_colon: None, ref segments, }, })) = args.first().unwrap() { if segments.len() != 1 { return None; } Some(segments.first().unwrap().ident.clone()) } else { None } } else { None } } fn match_endianness_specifier(field: &syn::Field) -> Option<(Endianness, syn::Ident)> { if let syn::Type::Path(syn::TypePath { qself: None, path: syn::Path { leading_colon: None, ref segments, }, }) = field.ty { if segments.len() != 1 { return None; } let first = segments.first().unwrap(); let endianness = if first.ident == syn::Ident::new("Le", proc_macro2::Span::call_site()) { Endianness::Little } else if first.ident == syn::Ident::new("Be", proc_macro2::Span::call_site()) { Endianness::Big } else { return None; }; let ident = match match_single_angle_bracketed_type(&first.arguments) { Some(i) => i, None => return None, }; Some((endianness, ident)) } else { None } } #[derive(Clone, Debug)] enum Item { RegularField(Box<syn::Field>), FieldWithEndianness(syn::Visibility, syn::Ident, (Endianness, syn::Ident)), Align(syn::LitInt), Pad(syn::LitInt), Conditional(Vec<Item>, Box<syn::Expr>), CustomParsed(Box<syn::Field>, Box<syn::Type>, Box<syn::Expr>), } impl Item { fn ident(&self) -> Option<&syn::Ident> { match self { Self::RegularField(f) => f.ident.as_ref(), Self::FieldWithEndianness(_, i, _) => Some(i), Self::Conditional(items, _) => items.last().map(|item| item.ident().unwrap()), _ => None, } } } #[derive(Debug)] struct AttrParseError; fn parse_number(tokens: &proc_macro2::TokenStream) -> Result<syn::LitInt, AttrParseError> { let group = syn::parse2::<proc_macro2::Group>(tokens.clone()).map_err(|_| AttrParseError)?; if let syn::Lit::Int(int) = syn::parse2::<syn::Lit>(group.stream()).map_err(|_| AttrParseError)? { Ok(int) } else { Err(AttrParseError) } } fn field_attribute_items(field: &syn::Field) -> Vec<Item> { field .attrs .iter() .map(|attr| { let attr_path_ident = attr.path.get_ident().ok_or(AttrParseError)?; if attr_path_ident == &syn::Ident::new("align", proc_macro2::Span::call_site()) { Ok(Item::Align(parse_number(&attr.tokens)?)) } else if attr_path_ident == &syn::Ident::new("pad", proc_macro2::Span::call_site()) { Ok(Item::Pad(parse_number(&attr.tokens)?)) } else { Err(AttrParseError) } }) .collect::<Result<Vec<_>, _>>() .unwrap() } fn match_field_conditional(field: &mut syn::Field) -> Option<syn::Expr> { let (position, _, tokens) = match field .attrs .iter() .enumerate() .filter_map(|(idx, attr)| { attr.path .get_ident() .map(|ident| (idx, ident, attr.tokens.clone())) }) .find(|(_, ident, _)| { ident == &&syn::Ident::new("condition", proc_macro2::Span::call_site()) }) { Some(p) => p, None => return None, }; field.attrs.remove(position); Some(syn::parse2::<syn::Expr>(tokens).unwrap()) } fn match_field_custom(field: &mut syn::Field) -> Option<(syn::Type, syn::Expr)> { let (position, _, tokens) = match field .attrs .iter() .enumerate() .filter_map(|(idx, attr)| { attr.path .get_ident() .map(|ident| (idx, ident, attr.tokens.clone())) }) .find(|(_, ident, _)| ident == &&syn::Ident::new("custom", proc_macro2::Span::call_site())) { Some(p) => p, None => return None, }; field.attrs.remove(position); let tuple = syn::parse2::<syn::ExprTuple>(tokens).unwrap(); let mut iterator = tuple .elems .into_pairs() .map(syn::punctuated::Pair::into_value); let path = if let Some(syn::Expr::Path(syn::ExprPath { path, .. })) = iterator.next() { syn::Type::Path(syn::TypePath { qself: None, path }) } else { return None; }; let data_expr = if let Some(data_expr) = iterator.next() { data_expr } else { return None; }; if iterator.next() != None { return None; } Some((path, data_expr)) } fn item_from_field(mut field: syn::Field) -> Vec<Item> { if let Some(condition) = match_field_conditional(&mut field) { return vec![Item::Conditional( item_from_field(field), Box::new(condition), )]; } else if let Some((ty, meta)) = match_field_custom(&mut field) { return vec![Item::CustomParsed( Box::new(field), Box::new(ty), Box::new(meta), )]; } let mut items: Vec<Item> = vec![]; items.extend(field_attribute_items(&field)); items.push( if let Some((endianness, ty)) = match_endianness_specifier(&field) { Item::FieldWithEndianness(field.vis, field.ident.unwrap(), (endianness, ty)) } else { Item::RegularField(Box::new(field)) }, ); items } fn regular_parser_func(ty: &syn::Type) -> syn::Expr { let (qself, original_path) = match ty { syn::Type::Path(syn::TypePath { path: syn::Path { ref segments, .. }, ref qself, .. }) => (qself.clone(), segments.clone()), other => panic!("{:?}", other), }; let mut segments = original_path; segments.push(syn::PathSegment { ident: syn::Ident::new("parse", proc_macro2::Span::call_site()), arguments: syn::PathArguments::None, }); syn::Expr::Path(syn::ExprPath { attrs: vec![], qself, path: syn::Path { leading_colon: None, segments, }, }) } fn regular_serializer_func(ty: &syn::Type) -> syn::Expr { let (qself, original_path) = match ty { syn::Type::Path(syn::TypePath { path: syn::Path { ref segments, .. }, ref qself, .. }) => (qself.clone(), segments.clone()), other => panic!("{:?}", other), }; let mut segments = original_path; segments.push(syn::PathSegment { ident: syn::Ident::new("serialize", proc_macro2::Span::call_site()), arguments: syn::PathArguments::None, }); syn::Expr::Path(syn::ExprPath { attrs: vec![], qself, path: syn::Path { leading_colon: None, segments, }, }) } fn empty_tuple() -> syn::Expr { syn::Expr::Tuple(syn::ExprTuple { attrs: vec![], paren_token: Default::default(), elems: syn::punctuated::Punctuated::new(), }) } fn regular_parser_expr(field: syn::Field) -> syn::Expr { generic_parser_expr(field.ty.clone(), field.ty, empty_tuple()) } fn parser_or_serializer_as_trait( parser_type: syn::Type, trait_ident: syn::Ident, target_type: syn::Type, ) -> syn::Type { syn::Type::Path(syn::TypePath { qself: Some(syn::QSelf { as_token: Some(Default::default()), lt_token: Default::default(), gt_token: Default::default(), ty: Box::new(parser_type), position: 2, }), path: syn::Path { leading_colon: Some(syn::Token!(::)(proc_macro2::Span::call_site())), segments: vec![ syn::PathSegment { ident: syn::Ident::new("sbp", proc_macro2::Span::call_site()), arguments: syn::PathArguments::None, }, syn::PathSegment { ident: trait_ident, arguments: syn::PathArguments::AngleBracketed( syn::AngleBracketedGenericArguments { lt_token: syn::Token!(<)(proc_macro2::Span::call_site()), gt_token: syn::Token!(>)(proc_macro2::Span::call_site()), colon2_token: Some(syn::Token!(::)(proc_macro2::Span::call_site())), args: vec![ syn::GenericArgument::Lifetime(syn::Lifetime::new( "'_", proc_macro2::Span::call_site(), )), syn::GenericArgument::Type(target_type), ] .into_iter() .collect::<syn::punctuated::Punctuated<_, syn::Token![,]>>(), }, ), }, ] .into_iter() .collect(), }, }) } fn generic_parser_expr( parser_type: syn::Type, target_type: syn::Type, data_expr: syn::Expr, ) -> syn::Expr { // Assume that every type this function is called for is sbp::Parse, rather than sbp::Parser. let ty = parser_or_serializer_as_trait( parser_type, syn::Ident::new("Parser", proc_macro2::Span::call_site()), target_type, ); syn::Expr::Call(syn::ExprCall { attrs: vec![], func: Box::new(regular_parser_func(&ty)), paren_token: syn::token::Paren { span: proc_macro2::Span::call_site(), }, args: vec![ data_expr, syn::Expr::Reference(syn::ExprReference { attrs: vec![], expr: Box::new(syn::Expr::Index(syn::ExprIndex { attrs: vec![], bracket_token: Default::default(), expr: Box::new(simple_expr(syn::Ident::new( "__sbp_proc_macro_bytes", proc_macro2::Span::call_site(), ))), index: Box::new(syn::Expr::Range(syn::ExprRange { attrs: vec![], limits: syn::RangeLimits::HalfOpen(Default::default()), from: Some(Box::new(simple_expr(syn::Ident::new( "__sbp_proc_macro_offset", proc_macro2::Span::call_site(), )))), to: None, })), })), mutability: None, and_token: Default::default(), raw: Default::default(), }), ] .into_iter() .collect::<syn::punctuated::Punctuated<_, syn::Token![,]>>(), }) } fn optionize(ty: syn::Type) -> syn::Type { syn::Type::Path(syn::TypePath { qself: None, path: syn::Path { leading_colon: Some(Default::default()), segments: vec![ syn::PathSegment { arguments: syn::PathArguments::None, ident: syn::Ident::new("core", proc_macro2::Span::call_site()), }, syn::PathSegment { arguments: syn::PathArguments::None, ident: syn::Ident::new("option", proc_macro2::Span::call_site()), }, syn::PathSegment { arguments: syn::PathArguments::AngleBracketed( syn::AngleBracketedGenericArguments { colon2_token: None, gt_token: Default::default(), lt_token: Default::default(), args: vec![syn::GenericArgument::Type(ty)].into_iter().collect(), }, ), ident: syn::Ident::new("Option", proc_macro2::Span::call_site()), }, ] .into_iter() .collect(), }, }) } fn item_to_field(item: Item) -> Option<Vec<syn::Field>> { fn inner(item: Item, will_optionize: bool) -> Option<Vec<syn::Field>> { match item { Item::Align(_) => None, Item::Pad(_) => None, Item::FieldWithEndianness(vis, ident, (_, ty)) => Some(vec![syn::Field { attrs: vec![], ident: Some(ident), vis, ty: if !will_optionize { syn::Type::Path(syn::TypePath { qself: None, path: syn::Path::from(ty), }) } else { optionize(syn::Type::Path(syn::TypePath { qself: None, path: syn::Path::from(ty), })) }, colon_token: None, }]), Item::RegularField(field) => Some(vec![if !will_optionize { *field } else { syn::Field { attrs: field.attrs, colon_token: field.colon_token, ident: field.ident, vis: field.vis, ty: optionize(field.ty), } }]), Item::Conditional(items, _) => Some( items .into_iter() .filter_map(|item| inner(item, true)) .flatten() .collect(), ), Item::CustomParsed(field, _, _) => Some(vec![*field]), } } inner(item, false) } fn pattern() -> syn::Pat { syn::Pat::Tuple(syn::PatTuple { attrs: vec![], paren_token: Default::default(), elems: vec![ syn::Pat::Ident(syn::PatIdent { attrs: vec![], by_ref: None, mutability: None, ident: syn::Ident::new("value", proc_macro2::Span::call_site()), subpat: None, }), syn::Pat::Ident(syn::PatIdent { attrs: vec![], by_ref: None, mutability: None, ident: syn::Ident::new("additional_bytes", proc_macro2::Span::call_site()), subpat: None, }), ] .into_iter() .collect(), }) } fn simple_pattern(ident: syn::Ident) -> syn::Pat { syn::Pat::Ident(syn::PatIdent { attrs: vec![], by_ref: None, mutability: None, ident, subpat: None, }) } fn simple_path(ident: syn::Ident) -> syn::Path { syn::Path { leading_colon: None, segments: std::iter::once(syn::PathSegment { ident, arguments: syn::PathArguments::None, }) .collect::<syn::punctuated::Punctuated<_, syn::Token![::]>>(), } } fn simple_type(ident: syn::Ident) -> syn::Type { syn::Type::Path(syn::TypePath { qself: None, path: simple_path(ident), }) } fn simple_expr(ident: syn::Ident) -> syn::Expr { syn::Expr::Path(syn::ExprPath { attrs: vec![], qself: None, path: syn::Path { leading_colon: None, segments: std::iter::once(syn::PathSegment { arguments: syn::PathArguments::None, ident, }) .collect(), }, }) } fn pod_combinator_type(endianness: Endianness) -> syn::Type { syn::Type::Path(syn::TypePath { qself: None, path: syn::Path { leading_colon: Some(Default::default()), segments: vec![ syn::PathSegment { ident: syn::Ident::new("sbp", proc_macro2::Span::call_site()), arguments: syn::PathArguments::None, }, syn::PathSegment { ident: syn::Ident::new( match endianness { Endianness::Big => "Be", Endianness::Little => "Le", }, proc_macro2::Span::call_site(), ), arguments: syn::PathArguments::None, }, ] .into_iter() .collect::<syn::punctuated::Punctuated<_, syn::Token![::]>>(), }, }) } fn pod_expr(endianness: Endianness, ty: syn::Ident) -> syn::Expr { generic_parser_expr( pod_combinator_type(endianness), simple_type(ty), empty_tuple(), ) } fn offset_incr_expr(to_wrap: syn::Expr) -> syn::Expr { syn::Expr::Block(syn::ExprBlock { attrs: vec![], label: None, block: syn::Block { brace_token: Default::default(), stmts: vec![ syn::Stmt::Local(syn::Local { attrs: vec![], let_token: Default::default(), init: Some((Default::default(), Box::new(to_wrap))), semi_token: Default::default(), pat: pattern(), }), syn::Stmt::Semi( syn::Expr::AssignOp(syn::ExprAssignOp { attrs: vec![], op: syn::BinOp::AddEq(Default::default()), left: Box::new(syn::Expr::Path(syn::ExprPath { attrs: vec![], qself: None, path: simple_path(syn::Ident::new( "__sbp_proc_macro_offset", proc_macro2::Span::call_site(), )), })), right: Box::new(syn::Expr::Path(syn::ExprPath { attrs: vec![], qself: None, path: simple_path(syn::Ident::new( "additional_bytes", proc_macro2::Span::call_site(), )), })), }), Default::default(), ), syn::Stmt::Expr(simple_expr(syn::Ident::new( "value", proc_macro2::Span::call_site(), ))), ], }, }) } fn align_stmt( alignment: syn::LitInt, offset_expr: &syn::Expr, align_func: &syn::Expr, ) -> syn::Stmt { syn::Stmt::Semi( syn::Expr::Assign(syn::ExprAssign { attrs: vec![], eq_token: syn::Token!(=)(proc_macro2::Span::call_site()), left: Box::new(offset_expr.clone()), right: Box::new(syn::Expr::Call(syn::ExprCall { attrs: vec![], func: Box::new(align_func.clone()), paren_token: syn::token::Paren { span: proc_macro2::Span::call_site(), }, args: vec![ offset_expr.clone(), syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Int(alignment), attrs: vec![], }), ] .into_iter() .collect::<syn::punctuated::Punctuated<_, syn::Token![,]>>(), })), }), syn::Token!(;)(proc_macro2::Span::call_site()), ) } fn pad_stmt(padding: syn::LitInt, offset_expr: &syn::Expr) -> syn::Stmt { syn::Stmt::Semi( syn::Expr::AssignOp(syn::ExprAssignOp { attrs: vec![], left: Box::new(offset_expr.clone()), op: syn::BinOp::AddEq(Default::default()), right: Box::new(syn::Expr::Lit(syn::ExprLit { attrs: vec![], lit: syn::Lit::Int(padding), })), }), Default::default(), ) } fn item_to_decl( item: Item, offset_expr: &syn::Expr, align_func: &syn::Expr, field_idents: &[syn::Ident], ) -> syn::Stmt { match item { Item::Align(alignment) => align_stmt(alignment, offset_expr, align_func), Item::Pad(padment) => pad_stmt(padment, offset_expr), Item::RegularField(field) => syn::Stmt::Local(syn::Local { attrs: vec![], let_token: syn::Token!(let)(proc_macro2::Span::call_site()), pat: simple_pattern(field.ident.clone().unwrap()), init: Some(( syn::Token!(=)(proc_macro2::Span::call_site()), Box::new(offset_incr_expr(question_mark_operator_expr( regular_parser_expr(*field), ))), )), semi_token: Default::default(), }), Item::CustomParsed(field, parser_type, data_expr) => syn::Stmt::Local(syn::Local { attrs: vec![], let_token: syn::Token!(let)(proc_macro2::Span::call_site()), pat: simple_pattern(field.ident.clone().unwrap()), init: Some((syn::Token!(=)(proc_macro2::Span::call_site()), { let syn::Field { ty, ident, .. } = *field; Box::new(offset_incr_expr(question_mark_operator_expr( generic_parser_expr( *parser_type, ty, include_fields(*data_expr, field_idents, false, Some(&ident.unwrap())), ), ))) })), semi_token: Default::default(), }), Item::FieldWithEndianness(_, ident, (endianness, ty)) => syn::Stmt::Local(syn::Local { attrs: vec![], let_token: Default::default(), pat: simple_pattern(ident), init: Some(( Default::default(), Box::new(offset_incr_expr(question_mark_operator_expr(pod_expr( endianness, ty, )))), )), semi_token: Default::default(), }), Item::Conditional(items, condition) => { let ident = items.iter().filter_map(Item::ident).next().unwrap().clone(); syn::Stmt::Local(syn::Local { attrs: vec![], let_token: Default::default(), pat: simple_pattern( Item::Conditional(items.clone(), condition.clone()) .ident() .unwrap() .clone(), ), semi_token: Default::default(), init: Some(( Default::default(), Box::new(conditional_expr( items, include_fields(*condition, field_idents, false, Some(&ident)), offset_expr, align_func, field_idents, )), )), }) } } } fn generic_serialize( field_ident: syn::Ident, serializer_type: syn::Type, target_type: syn::Type, meta_expr: syn::Expr, unwrap: bool, ) -> syn::Expr { let ty = parser_or_serializer_as_trait( serializer_type, syn::Ident::new("Serializer", proc_macro2::Span::call_site()), target_type, ); let field_expr = syn::Expr::Field(syn::ExprField { attrs: vec![], dot_token: Default::default(), base: Box::new(simple_expr(syn::Ident::new( "__sbp_proc_macro_data", proc_macro2::Span::call_site(), ))), member: syn::Member::Named(field_ident), }); let field_ref_expr = if !unwrap { syn::Expr::Reference(syn::ExprReference { and_token: Default::default(), attrs: vec![], expr: Box::new(field_expr), mutability: None, raw: Default::default(), }) } else { syn::parse2(quote! { #field_expr.as_ref().unwrap() }).unwrap() }; question_mark_operator_expr(syn::Expr::Call(syn::ExprCall { attrs: vec![], func: Box::new(regular_serializer_func(&ty)), paren_token: Default::default(), args: vec![ field_ref_expr, meta_expr, syn::Expr::Reference(syn::ExprReference { attrs: vec![], expr: Box::new(syn::Expr::Index(syn::ExprIndex { attrs: vec![], bracket_token: Default::default(), expr: Box::new(simple_expr(syn::Ident::new( "__sbp_proc_macro_bytes", proc_macro2::Span::call_site(), ))), index: Box::new(syn::Expr::Range(syn::ExprRange { attrs: vec![], limits: syn::RangeLimits::HalfOpen(Default::default()), from: Some(Box::new(simple_expr(syn::Ident::new( "__sbp_proc_macro_offset", proc_macro2::Span::call_site(), )))), to: None, })), })), mutability: Some(Default::default()), and_token: Default::default(), raw: Default::default(), }), ] .into_iter() .collect::<syn::punctuated::Punctuated<_, syn::Token![,]>>(), })) } fn field_with_endianness_stmt( ident: syn::Ident, endianness: Endianness, ty: syn::Ident, offset_expr: &syn::Expr, unwrap: bool, ) -> syn::Stmt { syn::Stmt::Semi( syn::Expr::AssignOp(syn::ExprAssignOp { attrs: vec![], left: Box::new(offset_expr.clone()), op: syn::BinOp::AddEq(Default::default()), right: Box::new(generic_serialize( ident, pod_combinator_type(endianness), simple_type(ty), empty_tuple(), unwrap, )), }), Default::default(), ) } fn regular_field_stmt(field: syn::Field, offset_expr: &syn::Expr, unwrap: bool) -> syn::Stmt { syn::Stmt::Semi( syn::Expr::AssignOp(syn::ExprAssignOp { attrs: vec![], left: Box::new(offset_expr.clone()), op: syn::BinOp::AddEq(Default::default()), right: Box::new(generic_serialize( field.ident.unwrap(), field.ty.clone(), field.ty, empty_tuple(), unwrap, )), }), Default::default(), ) } fn include_fields( expr: syn::Expr, field_idents: &[syn::Ident], base: bool, self_ident: Option<&syn::Ident>, ) -> syn::Expr { if base { syn::parse2(quote! { { #(let #field_idents = &__sbp_proc_macro_data.#field_idents;)* #expr } }) .unwrap() } else { let field_idents = field_idents .iter() .take_while(|item| item != &self_ident.unwrap()); syn::parse2(quote! { { #(let #field_idents = &#field_idents;)* #expr } }) .unwrap() } } fn custom_parsed_stmt( field: syn::Field, parser: syn::Type, meta_expr: syn::Expr, offset_expr: &syn::Expr, field_idents: &[syn::Ident], unwrap: bool, ) -> syn::Stmt { syn::Stmt::Semi( syn::Expr::AssignOp(syn::ExprAssignOp { attrs: vec![], left: Box::new(offset_expr.clone()), op: syn::BinOp::AddEq(Default::default()), right: Box::new(generic_serialize( field.ident.unwrap(), parser, field.ty, include_fields(meta_expr, field_idents, true, None), unwrap, )), }), Default::default(), ) } fn conditional_stmt( items: Vec<Item>, cond: syn::Expr, offset_expr: &syn::Expr, align_func: &syn::Expr, field_idents: &[syn::Ident], ) -> syn::Stmt { syn::Stmt::Expr(syn::Expr::If(syn::ExprIf { attrs: vec![], cond: Box::new(include_fields(cond, field_idents, true, None)), else_branch: None, if_token: Default::default(), then_branch: syn::Block { brace_token: Default::default(), stmts: items .into_iter() .map(|item| item_to_stmt(item, offset_expr, align_func, field_idents, true)) .collect(), }, })) } fn item_to_stmt( item: Item, offset_expr: &syn::Expr, align_func: &syn::Expr, field_idents: &[syn::Ident], unwrap: bool, ) -> syn::Stmt { match item { Item::Align(alignment) => align_stmt(alignment, offset_expr, align_func), Item::Pad(padding) => pad_stmt(padding, offset_expr), Item::FieldWithEndianness(_, ident, (endianness, ty)) => { field_with_endianness_stmt(ident, endianness, ty, offset_expr, unwrap) } Item::RegularField(field) => regular_field_stmt(*field, offset_expr, unwrap), Item::CustomParsed(field, parser, meta_expr) => custom_parsed_stmt( *field, *parser, *meta_expr, offset_expr, field_idents, unwrap, ), Item::Conditional(items, cond) => { conditional_stmt(items, *cond, offset_expr, align_func, field_idents) } } } fn conditional_expr( items: Vec<Item>, condition: syn::Expr, offset_expr: &syn::Expr, align_func: &syn::Expr, field_idents: &[syn::Ident], ) -> syn::Expr { syn::Expr::If(syn::ExprIf { attrs: vec![], cond: Box::new(condition), if_token: Default::default(), then_branch: syn::Block { brace_token: Default::default(), stmts: items .iter() .cloned() .map(|item| { vec![ item_to_decl(item, offset_expr, align_func, field_idents), syn::Stmt::Expr(syn::Expr::Call(syn::ExprCall { attrs: vec![], func: Box::new(syn::Expr::Path(syn::ExprPath { attrs: vec![], qself: None, path: syn::Path { leading_colon: Some(Default::default()), segments: vec![ syn::PathSegment { arguments: syn::PathArguments::None, ident: syn::Ident::new( "core", proc_macro2::Span::call_site(), ), }, syn::PathSegment { arguments: syn::PathArguments::None, ident: syn::Ident::new( "option", proc_macro2::Span::call_site(), ), }, syn::PathSegment { arguments: syn::PathArguments::None, ident: syn::Ident::new( "Option", proc_macro2::Span::call_site(), ), }, syn::PathSegment { arguments: syn::PathArguments::None, ident: syn::Ident::new( "Some", proc_macro2::Span::call_site(), ), }, ] .into_iter() .collect(), }, })), paren_token: Default::default(), args: vec![simple_expr(items.last().unwrap().ident().unwrap().clone())] .into_iter() .collect(), })), ] }) .flatten() .collect(), }, else_branch: Some(( Default::default(), Box::new(syn::Expr::Block(syn::ExprBlock { attrs: vec![], label: None, block: syn::Block { brace_token: Default::default(), stmts: vec![syn::Stmt::Expr(syn::Expr::Path(syn::ExprPath { attrs: vec![], qself: None, path: syn::Path { leading_colon: Some(Default::default()), segments: vec![ syn::PathSegment { arguments: syn::PathArguments::None, ident: syn::Ident::new("core", proc_macro2::Span::call_site()), }, syn::PathSegment { arguments: syn::PathArguments::None, ident: syn::Ident::new( "option", proc_macro2::Span::call_site(), ), }, syn::PathSegment { arguments: syn::PathArguments::None, ident: syn::Ident::new( "Option", proc_macro2::Span::call_site(), ), }, syn::PathSegment { arguments: syn::PathArguments::None, ident: syn::Ident::new("None", proc_macro2::Span::call_site()), }, ] .into_iter() .collect(), }, }))], }, })), )), }) } fn question_mark_operator_expr(to_wrap: syn::Expr) -> syn::Expr { syn::Expr::Try(syn::ExprTry { attrs: vec![], expr: Box::new(to_wrap), question_token: Default::default(), }) } fn align_func() -> Box<syn::Expr> { Box::new(syn::Expr::Path(syn::ExprPath { attrs: vec![], qself: None, path: syn::Path { leading_colon: Some(Default::default()), segments: vec![ syn::PathSegment { ident: syn::Ident::new("sbp", proc_macro2::Span::call_site()), arguments: syn::PathArguments::None, }, syn::PathSegment { ident: syn::Ident::new("align", proc_macro2::Span::call_site()), arguments: syn::PathArguments::None, }, ] .into_iter() .collect::<syn::punctuated::Punctuated<_, syn::Token![::]>>(), }, })) } fn parsable(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as ItemStruct); let attrs = ast.attrs.into_iter(); let items = if let syn::Fields::Named(syn::FieldsNamed { ref named, .. }) = ast.fields { named .iter() .cloned() .map(item_from_field) .flatten() .collect::<Vec<_>>() } else { panic!() }; let fields = items .iter() .cloned() .filter_map(item_to_field) .flatten() .collect::<Vec<_>>(); let align_func = align_func(); let offset_expr = Box::new(simple_expr(syn::Ident::new( "__sbp_proc_macro_offset", proc_macro2::Span::call_site(), ))); let fields_idents = fields .iter() .cloned() .map(|field| field.ident.unwrap()) .collect::<Vec<_>>(); let declarations = items .into_iter() .map(|item| item_to_decl(item, &offset_expr, &align_func, &fields_idents)); let ident = &ast.ident; let visibility = &ast.vis; let tokens = quote! { #(#attrs)* #visibility struct #ident { #(#fields,)* } #[allow(unused_parens, unused_variables)] impl<'a> ::sbp::Parser<'a, #ident> for #ident { type Meta = (); type Error = Box<::sbp::DeriveError>; fn parse(_: Self::Meta, __sbp_proc_macro_bytes: &'a [u8]) -> Result<(Self, usize), Self::Error> { let mut __sbp_proc_macro_offset = 0; #(#declarations)* Ok((#ident { #(#fields_idents,)* }, __sbp_proc_macro_offset)) } } }; tokens.into() } fn serializable(input: TokenStream) -> TokenStream { let ast = parse_macro_input!(input as ItemStruct); let ident = ast.ident; let items = if let syn::Fields::Named(syn::FieldsNamed { ref named, .. }) = ast.fields { named .iter() .cloned() .map(item_from_field) .flatten() .collect::<Vec<_>>() } else { panic!() }; let fields = items .iter() .cloned() .filter_map(item_to_field) .flatten() .collect::<Vec<_>>(); let fields_idents = fields .iter() .cloned() .map(|field| field.ident.unwrap()) .collect::<Vec<_>>(); let align_func = align_func(); let offset_expr = Box::new(simple_expr(syn::Ident::new( "__sbp_proc_macro_offset", proc_macro2::Span::call_site(), ))); let statements = items .into_iter() .map(|item| item_to_stmt(item, &offset_expr, &align_func, &fields_idents, false)); let tokens = quote! { #[allow(unused_parens, unused_variables)] impl<'a> ::sbp::Serializer<'a, #ident> for #ident { type Meta = (); type Error = Box<dyn ::sbp::DeriveError>; fn serialize(__sbp_proc_macro_data: &Self, _: Self::Meta, __sbp_proc_macro_bytes: &'a mut [u8]) -> Result<usize, Self::Error> { let mut __sbp_proc_macro_offset = 0; #(#statements)* Ok(__sbp_proc_macro_offset) } } }; tokens.into() } /// A procedural macro for declaring compound structures that can be parsed and serialized. /// /// ## Usage /// The `sbp` macro takes either the form `#[sbp(parsable)]` or `#[sbp(parsable, serializable)]`, /// where the former declares a struct implementing `Parser<Target=Self> + Parse` and the latter declares a /// struct implementing `Serializer<Target=Self> + Serialize`. /// /// The struct is simply written as regular Rust structs, but since the primitive integers don't /// implement `Parse` or `Serialize`, those fields will have the type similar to `Le<u64>` or /// `Be<u128>`. The field may be prefixed with `#[align(X)]`, `#[pad(X)]`, `#[condition(X)]` or /// `#[custom(X, Y)]`. /// /// ### `#[align(<alignment>)]` /// Aligns the following field to the specified alignment. /// /// ### `#[pad(<padding>)]` /// Advances the internal counter by the specified padding. /// /// ### `#[condition(<conditional expression>)]` /// Parses or serializes the following field if the condition is true, and wraps the field in an /// `Option`. Internal struct fields are accessible, but borrowed when used. /// /// ### `#[custom(<parser type>, <meta>)]` /// Applies a custom parser with the target type being the type of the following field. The meta is /// forwarded directly into the parse or serialize functions, and can be used to e.g. specify the /// amount of bytes to take when using `Take`. The type pointed to must implement `Parser` if the /// `sbp` macro is called with `parsable`, and `Serialize` if it's called with `serializable` as /// well. /// /// ## Example /// ```rust /// # use sbp::{sbp, Parser}; /// # fn read_from_disk(len: usize) -> Result<Box<[u8]>, Box<dyn std::error::Error>> { /// # Ok(vec![0u8; len].into_boxed_slice()) /// # } /// # fn main() -> Result<(), Box<dyn std::error::Error>> { /// #[sbp(parsable, serializable)] /// pub struct SomeBinaryFormat { /// magic: Le<u64>, /// node_count: Le<u8>, /// len: Le<u32>, /// /// #[align(8)] /// version: Le<u64>, /// /// #[condition(*version > 0)] /// uuid: Be<u128>, /// } /// let count = 36; /// let bytes = read_from_disk(count)?; /// /// let (s, _len) = SomeBinaryFormat::parse((), &bytes)?; /// if s.version > 0 { /// assert_eq!(s.uuid, None); /// } /// # Ok(()) /// # } /// ``` #[proc_macro_attribute] pub fn sbp(attr: TokenStream, input: TokenStream) -> TokenStream { let attr = proc_macro2::TokenStream::from(attr); let mut output = proc_macro::TokenStream::from(quote! {}); // TODO: It doesn't seem like syn has a parser for the args of an attribute-like proc macro. let args = attr.into_iter().collect::<Vec<_>>(); // TODO: Flattening here isn't really correct. for arg in args .split(|tt| { if let proc_macro2::TokenTree::Punct(_) = tt { true } else { false } }) .flatten() { match arg { proc_macro2::TokenTree::Ident(ident) => { if ident == &syn::Ident::new("parsable", proc_macro2::Span::call_site()) { output.extend(parsable(input.clone())); } else if ident == &syn::Ident::new("serializable", proc_macro2::Span::call_site()) { output.extend(serializable(input.clone())); } } _ => panic!(), } } output }
33.199085
139
0.461286
cdbf29c5cfd4068dc6e8b5913e52f2f1aeaf3b64
3,170
cs
C#
src/Lucene.Net.Tests/Util/JunitCompat/TestBeforeAfterOverrides.cs
geocom-gis/lucenenet
24c07758b99ff5cd56fe49d10cd8389f792d9c65
[ "Apache-2.0" ]
1,659
2015-01-01T18:06:38.000Z
2022-03-29T07:44:04.000Z
src/Lucene.Net.Tests/Util/JunitCompat/TestBeforeAfterOverrides.cs
geocom-gis/lucenenet
24c07758b99ff5cd56fe49d10cd8389f792d9c65
[ "Apache-2.0" ]
321
2015-01-03T15:44:03.000Z
2022-03-31T22:16:25.000Z
src/Lucene.Net.Tests/Util/JunitCompat/TestBeforeAfterOverrides.cs
geocom-gis/lucenenet
24c07758b99ff5cd56fe49d10cd8389f792d9c65
[ "Apache-2.0" ]
608
2015-01-06T03:59:33.000Z
2022-03-16T08:05:12.000Z
using NUnit.Framework; namespace Lucene.Net.Util.JunitCompat { using After = org.junit.After; using Assert = org.junit.Assert; using Before = org.junit.Before; using Test = org.junit.Test; using JUnitCore = org.junit.runner.JUnitCore; using Result = org.junit.runner.Result; /* * 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. */ public class TestBeforeAfterOverrides : WithNestedTests { public TestBeforeAfterOverrides() : base(true) { } public class Before1 : WithNestedTests.AbstractNestedTest { //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Before public void before() public virtual void Before() { } public virtual void TestEmpty() { } } public class Before2 : Before1 { } public class Before3 : Before2 { //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Override @Before public void before() public override void Before() { } } public class After1 : WithNestedTests.AbstractNestedTest { //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @After public void after() public virtual void After() { } public virtual void TestEmpty() { } } public class After2 : Before1 { } public class After3 : Before2 { //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @After public void after() public virtual void After() { } } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testBefore() public virtual void TestBefore() { Result result = JUnitCore.runClasses(typeof(Before3)); Assert.AreEqual(1, result.FailureCount); Assert.IsTrue(result.Failures.Get(0).Trace.Contains("There are overridden methods")); } //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Test public void testAfter() public virtual void TestAfter() { Result result = JUnitCore.runClasses(typeof(Before3)); Assert.AreEqual(1, result.FailureCount); Assert.IsTrue(result.Failures.Get(0).Trace.Contains("There are overridden methods")); } } }
30.776699
104
0.726498
148d06d61d4f2850b61da0f3322a404362bbd249
61
ts
TypeScript
packages/stream-node/index.d.ts
jessysaurusrex/endo
a612cd67c6087091403375b0233cffdbaa7eea34
[ "Apache-2.0" ]
203
2021-03-15T09:28:14.000Z
2022-03-26T20:42:49.000Z
packages/stream-node/index.d.ts
jessysaurusrex/endo
a612cd67c6087091403375b0233cffdbaa7eea34
[ "Apache-2.0" ]
393
2021-03-13T00:38:24.000Z
2022-03-25T18:47:08.000Z
packages/stream-node/index.d.ts
jessysaurusrex/endo
a612cd67c6087091403375b0233cffdbaa7eea34
[ "Apache-2.0" ]
29
2021-03-18T15:34:29.000Z
2022-03-08T14:36:07.000Z
export { makeNodeReader, makeNodeWriter } from './index.js';
30.5
60
0.737705
ef50c8627dbd672e08c3533926394756da451ca3
284
php
PHP
src/Event/CartItemRemoveEvent.php
jamesdb/cart
7b426f9b58022f2421fece6e6b264dd8c4d9d0f7
[ "MIT" ]
11
2015-10-14T18:42:36.000Z
2021-02-25T09:16:08.000Z
src/Event/CartItemRemoveEvent.php
jamesdb/cart
7b426f9b58022f2421fece6e6b264dd8c4d9d0f7
[ "MIT" ]
null
null
null
src/Event/CartItemRemoveEvent.php
jamesdb/cart
7b426f9b58022f2421fece6e6b264dd8c4d9d0f7
[ "MIT" ]
null
null
null
<?php namespace jamesdb\Cart\Event; use jamesdb\Cart\Event\AbstractCartEvent; class CartItemRemoveEvent extends AbstractCartEvent { /** * Return the Event name. * * @return string */ public function getName() { return 'cart.remove'; } }
14.947368
51
0.630282
1f548fdcc5c910998bf6235ed028d85f18847193
2,452
cshtml
C#
src/HCMS.Web/Themes/ARXE_ASC/Pages/projects_filter.cshtml
m-esm/HCMS
ce235266096dbc9fa3d0658a1106bd7f550e031a
[ "MIT" ]
2
2017-12-26T13:01:07.000Z
2018-01-06T19:02:31.000Z
src/HCMS.Web/Themes/ARXE_ASC/Pages/projects_filter.cshtml
m-esm/HCMS
ce235266096dbc9fa3d0658a1106bd7f550e031a
[ "MIT" ]
null
null
null
src/HCMS.Web/Themes/ARXE_ASC/Pages/projects_filter.cshtml
m-esm/HCMS
ce235266096dbc9fa3d0658a1106bd7f550e031a
[ "MIT" ]
null
null
null
@{ var projects = HCMS.Dynamics.Data.DDB.GetTable("arxe_arch", "arch_project").DRows.Where(p => p.GetValue("Confirmed").Value == "true"); Response.ClearContent(); Response.ClearHeaders(); Response.ContentType = "application/javascript"; int size = 0; int status = 0; int program = 0; int year = 0; string term = ""; int intervention = 0; var model = projects; if (Request.QueryString["term"] != null) { term = Request.QueryString["term"].ToString().ToLower(); model = model.Where(p => p.GetValue("name").Value.ToLower().Contains(term) || p.GetValue("nameEn").Value.ToLower().Contains(term) || p.GetValue("description").Value.ToLower().Contains(term) || p.GetValue("descriptionEn").Value.ToLower().Contains(term)); } if (Request.QueryString["size"] != null) { int.TryParse(Request.QueryString["size"].ToString(), out size); if (size != 0) { model = model.Where(p => string.IsNullOrWhiteSpace(p.GetValue("size").Value) == false) .Where(p => int.Parse(p.GetValue("size").Value) < size); } } if (Request.QueryString["year"] != null) { int.TryParse(Request.QueryString["year"].ToString(), out year); if (year != 0) { model = model.Where(p => p.GetValue("year").Value == year.ToString()); } } if (Request.QueryString["program"] != null) { int.TryParse(Request.QueryString["program"].ToString(), out program); if (program != 0) { model = model.Where(p => p.GetValue("programId").Value.Contains(program.ToString())); } } if (Request.QueryString["status"] != null) { int.TryParse(Request.QueryString["status"].ToString(), out status); if (status != 0) { model = model.Where(p => p.GetValue("statusID").Value.Contains(status.ToString())); } } if (Request.QueryString["intervention"] != null) { int.TryParse(Request.QueryString["intervention"].ToString(), out intervention); if (intervention != 0) { model = model.Where(p => p.GetValue("interventionID").Value == (intervention.ToString())); } } string json = Newtonsoft.Json.JsonConvert.SerializeObject(model.Select(p => p.RowID).ToArray()); Response.Write(json); }
28.847059
138
0.569739
c4165c13cd4a8bee3f87127c8beddb720f43bd98
12,157
hpp
C++
src/framework/shared/inc/private/common/fxirp.hpp
IT-Enthusiast-Nepal/Windows-Driver-Frameworks
bfee6134f30f92a90dbf96e98d54582ecb993996
[ "MIT" ]
994
2015-03-18T21:37:07.000Z
2019-04-26T04:04:14.000Z
src/framework/shared/inc/private/common/fxirp.hpp
IT-Enthusiast-Nepal/Windows-Driver-Frameworks
bfee6134f30f92a90dbf96e98d54582ecb993996
[ "MIT" ]
9
2015-03-19T08:40:01.000Z
2019-03-24T22:54:51.000Z
src/framework/shared/inc/private/common/fxirp.hpp
IT-Enthusiast-Nepal/Windows-Driver-Frameworks
bfee6134f30f92a90dbf96e98d54582ecb993996
[ "MIT" ]
350
2015-03-19T04:29:46.000Z
2019-05-05T23:26:50.000Z
/*++ Copyright (c) Microsoft Corporation Module Name: FxIrp.hpp Abstract: This module implements a class for handling irps. Author: Environment: Both kernel and user mode Revision History: // A function for when not assigning MdIrp GetIrp( VOID ); VOID CompleteRequest( __in_opt CCHAR PriorityBoost=IO_NO_INCREMENT ); NTSTATUS CallDriver( __in MdDeviceObject DeviceObject ); NTSTATUS PoCallDriver( __in MdDeviceObject DeviceObject ); VOID StartNextPowerIrp( ); MdCompletionRoutine GetNextCompletionRoutine( VOID ); VOID SetCompletionRoutine( __in MdCompletionRoutine CompletionRoutine, __in PVOID Context, __in BOOLEAN InvokeOnSuccess = TRUE, __in BOOLEAN InvokeOnError = TRUE, __in BOOLEAN InvokeOnCancel = TRUE ); VOID SetCompletionRoutineEx( __in MdDeviceObject DeviceObject, __in MdCompletionRoutine CompletionRoutine, __in PVOID Context, __in BOOLEAN InvokeOnSuccess = TRUE, __in BOOLEAN InvokeOnError = TRUE, __in BOOLEAN InvokeOnCancel = TRUE ); MdCancelRoutine SetCancelRoutine( __in_opt MdCancelRoutine CancelRoutine ); // // SendIrpSynchronously achieves synchronous behavior by waiting on an // event after submitting the IRP. The event creation can fail in UM, but // not in KM. Hence, in UM the return code could either indicate event // creation failure or it could indicate the status set on the IRP by the // lower driver. In KM, the return code only indicates the status set on // the IRP by the lower lower, because event creation cannot fail. // CHECK_RETURN_IF_USER_MODE NTSTATUS SendIrpSynchronously( __in MdDeviceObject DeviceObject ); VOID CopyCurrentIrpStackLocationToNext( VOID ); VOID CopyToNextIrpStackLocation( __in PIO_STACK_LOCATION Stack ); VOID SetNextIrpStackLocation( VOID ); UCHAR GetMajorFunction( VOID ); UCHAR GetMinorFunction( VOID ); UCHAR GetCurrentStackFlags( VOID ); MdFileObject GetCurrentStackFileObject( VOID ); KPROCESSOR_MODE GetRequestorMode( VOID ); VOID SetContext( __in ULONG Index, __in PVOID Value ); VOID SetSystemBuffer( __in PVOID Value ); VOID SetUserBuffer( __in PVOID Value ); VOID SetMdlAddress( __in PMDL Value ); VOID SetFlags( __in ULONG Flags ); PVOID GetContext( __in ULONG Index ); ULONG GetFlags( VOID ); PIO_STACK_LOCATION GetCurrentIrpStackLocation( VOID ); PIO_STACK_LOCATION GetNextIrpStackLocation( VOID ); static PIO_STACK_LOCATION _GetAndClearNextStackLocation( __in MdIrp Irp ); VOID SkipCurrentIrpStackLocation( VOID ); VOID MarkIrpPending( ); BOOLEAN PendingReturned( ); VOID PropagatePendingReturned( VOID ); VOID SetStatus( __in NTSTATUS Status ); NTSTATUS GetStatus( ); BOOLEAN Cancel( VOID ); VOID SetCancel( __in BOOLEAN Cancel ); BOOLEAN IsCanceled( ); KIRQL GetCancelIrql( ); VOID SetInformation( __in ULONG_PTR Information ); ULONG_PTR GetInformation( ); CCHAR GetCurrentIrpStackLocationIndex( ); CCHAR GetStackCount( ); PLIST_ENTRY ListEntry( ); PVOID GetSystemBuffer( ); PVOID GetOutputBuffer( ); PMDL GetMdl( ); PMDL* GetMdlAddressPointer( ); PVOID GetUserBuffer( ); VOID Reuse( __in NTSTATUS Status = STATUS_SUCCESS ); // // Methods for IO_STACK_LOCATION members // VOID SetMajorFunction( __in UCHAR MajorFunction ); VOID SetMinorFunction( __in UCHAR MinorFunction ); // // Get Methods for IO_STACK_LOCATION.Parameters.Power // SYSTEM_POWER_STATE_CONTEXT GetParameterPowerSystemPowerStateContext( ); POWER_STATE_TYPE GetParameterPowerType( ); POWER_STATE GetParameterPowerState( ); DEVICE_POWER_STATE GetParameterPowerStateDeviceState( ); SYSTEM_POWER_STATE GetParameterPowerStateSystemState( ); POWER_ACTION GetParameterPowerShutdownType( ); MdFileObject GetFileObject( VOID ); // // Get/Set Method for IO_STACK_LOCATION.Parameters.QueryDeviceRelations // DEVICE_RELATION_TYPE GetParameterQDRType( ); VOID SetParameterQDRType( __in DEVICE_RELATION_TYPE DeviceRelation ); // // Get/Set Methods for IO_STACK_LOCATION.Parameters.DeviceCapabilities // PDEVICE_CAPABILITIES GetParameterDeviceCapabilities( ); VOID SetCurrentDeviceObject( __in MdDeviceObject DeviceObject ); MdDeviceObject GetDeviceObject( VOID ); VOID SetParameterDeviceCapabilities( __in PDEVICE_CAPABILITIES DeviceCapabilities ); // // Get/Set Methods for IO_STACK_LOCATION.Parameters.Write.ByteOffset.QuadPart // LONGLONG GetParameterWriteByteOffsetQuadPart( ); VOID SetNextParameterWriteByteOffsetQuadPart( __in LONGLONG DeviceOffset ); // // Get/Set Methods for IO_STACK_LOCATION.Parameters.Write.Length // ULONG GetCurrentParameterWriteLength( ); VOID SetNextParameterWriteLength( __in ULONG IoLength ); PVOID* GetNextStackParameterOthersArgument1Pointer( ); VOID SetNextStackParameterOthersArgument1( __in PVOID Argument1 ); PVOID* GetNextStackParameterOthersArgument2Pointer( ); PVOID* GetNextStackParameterOthersArgument4Pointer( ); // // Get/Set Methods for IO_STACK_LOCATION.Parameters.StartDevice // PCM_RESOURCE_LIST GetParameterAllocatedResources( ); VOID SetParameterAllocatedResources( __in PCM_RESOURCE_LIST AllocatedResources ); PCM_RESOURCE_LIST GetParameterAllocatedResourcesTranslated( ); VOID SetParameterAllocatedResourcesTranslated( __in PCM_RESOURCE_LIST AllocatedResourcesTranslated ); // // Get Method for IO_STACK_LOCATION.Parameters.QueryDeviceText // LCID GetParameterQueryDeviceTextLocaleId( ); DEVICE_TEXT_TYPE GetParameterQueryDeviceTextType( ); // // Get Method for IO_STACK_LOCATION.Parameters.SetLock // BOOLEAN GetParameterSetLockLock( ); // // Get Method for IO_STACK_LOCATION.Parameters.QueryId // BUS_QUERY_ID_TYPE GetParameterQueryIdType( ); // // Get/Set Methods for IO_STACK_LOCATION.Parameters.QueryInterface // PINTERFACE GetParameterQueryInterfaceInterface( ); const GUID* GetParameterQueryInterfaceType( ); USHORT GetParameterQueryInterfaceVersion( ); USHORT GetParameterQueryInterfaceSize( ); PVOID GetParameterQueryInterfaceInterfaceSpecificData( ); VOID SetParameterQueryInterfaceInterface( __in PINTERFACE Interface ); VOID SetParameterQueryInterfaceType( __in const GUID* InterfaceType ); VOID SetParameterQueryInterfaceVersion( __in USHORT Version ); VOID SetParameterQueryInterfaceSize( __in USHORT Size ); VOID SetParameterQueryInterfaceInterfaceSpecificData( __in PVOID InterfaceSpecificData ); // // Get Method for IO_STACK_LOCATION.Parameters.UsageNotification // DEVICE_USAGE_NOTIFICATION_TYPE GetParameterUsageNotificationType( ); BOOLEAN GetParameterUsageNotificationInPath( ); VOID SetParameterUsageNotificationInPath( __in BOOLEAN InPath ); BOOLEAN GetNextStackParameterUsageNotificationInPath( ); ULONG GetParameterIoctlCode( VOID ); ULONG GetParameterIoctlCodeBufferMethod( VOID ); ULONG GetParameterIoctlInputBufferLength( VOID ); ULONG GetParameterIoctlOutputBufferLength( VOID ); PVOID GetParameterIoctlType3InputBuffer( VOID ); // // Set Methods for IO_STACK_LOCATION.Parameters.DeviceControl members // VOID SetParameterIoctlCode( __in ULONG DeviceIoControlCode ); VOID SetParameterIoctlInputBufferLength( __in ULONG InputBufferLength ); VOID SetParameterIoctlOutputBufferLength( __in ULONG OutputBufferLength ); VOID SetParameterIoctlType3InputBuffer( __in PVOID Type3InputBuffer ); ULONG GetParameterReadLength( VOID ); ULONG GetParameterWriteLength( VOID ); VOID SetNextStackFlags( __in UCHAR Flags ); VOID SetNextStackFileObject( _In_ MdFileObject FileObject ); PVOID GetCurrentParametersPointer( VOID ); // // Methods for IO_STACK_LOCATION // VOID ClearNextStack( VOID ); VOID ClearNextStackLocation( VOID ); VOID InitNextStackUsingStack( __in FxIrp* Irp ); ULONG GetCurrentFlags( VOID ); VOID FreeIrp( VOID ); MdEThread GetThread( VOID ); BOOLEAN Is32bitProcess( VOID ); private: static NTSTATUS _IrpSynchronousCompletion( __in MdDeviceObject DeviceObject, __in MdIrp OriginalIrp, __in PVOID Context ); public: _Must_inspect_result_ static MdIrp AllocateIrp( _In_ CCHAR StackSize, _In_opt_ FxDevice* Device = NULL ); static MdIrp GetIrpFromListEntry( __in PLIST_ENTRY Ple ); _Must_inspect_result_ static NTSTATUS RequestPowerIrp( __in MdDeviceObject DeviceObject, __in UCHAR MinorFunction, __in POWER_STATE PowerState, __in MdRequestPowerComplete CompletionFunction, __in PVOID Context ); PIO_STATUS_BLOCK GetStatusBlock( VOID ); PVOID GetDriverContext( ); ULONG GetDriverContextSize( ); VOID CopyParameters( _Out_ PWDF_REQUEST_PARAMETERS Parameters ); VOID CopyStatus( _Out_ PIO_STATUS_BLOCK StatusBlock ); BOOLEAN HasStack( _In_ UCHAR StackCount ); BOOLEAN IsCurrentIrpStackLocationValid( VOID ); #if (FX_CORE_MODE == FX_CORE_USER_MODE) IWudfIoIrp* GetIoIrp( VOID ); IWudfIoIrp2* GetIoIrp2( VOID ); IWudfPnpIrp* GetPnpIrp( VOID ); #endif }; // // FxAutoIrp adds value to FxIrp by automatically freeing the associated MdIrp // when it goes out of scope // struct FxAutoIrp : public FxIrp { FxAutoIrp( __in_opt MdIrp Irp = NULL ) : FxIrp(Irp) { } ~FxAutoIrp(); }; #endif // _FXIRP_H_
14.302353
81
0.591182
af0b15443fe2162f244831fafb7bc412b4bb4a89
1,107
py
Python
igf_data/utils/seqrunutils.py
imperial-genomics-facility/data-management-python
7b867d8d4562a49173d0b823bdc4bf374a3688f0
[ "Apache-2.0" ]
7
2018-05-08T07:28:08.000Z
2022-02-21T14:56:49.000Z
igf_data/utils/seqrunutils.py
imperial-genomics-facility/data-management-python
7b867d8d4562a49173d0b823bdc4bf374a3688f0
[ "Apache-2.0" ]
15
2021-08-19T12:32:20.000Z
2022-02-09T19:52:51.000Z
igf_data/utils/seqrunutils.py
imperial-genomics-facility/data-management-python
7b867d8d4562a49173d0b823bdc4bf374a3688f0
[ "Apache-2.0" ]
2
2017-05-12T15:20:10.000Z
2020-05-07T16:25:11.000Z
import datetime from igf_data.igfdb.seqrunadaptor import SeqrunAdaptor from igf_data.utils.dbutils import read_dbconf_json, read_json_data def load_new_seqrun_data(data_file, dbconfig): ''' A method for loading new data for seqrun table ''' try: formatted_data=read_json_data(data_file) dbparam=read_dbconf_json(dbconfig) sr=SeqrunAdaptor(**dbparam) sr.start_session() sr.store_seqrun_and_attribute_data(data=formatted_data) sr.close_session() except: raise def get_seqrun_date_from_igf_id(seqrun_igf_id): ''' A utility method for fetching sequence run date from the igf id required params: seqrun_igf_id: A seqrun igf id string returns a string value of the date ''' try: seqrun_date=seqrun_igf_id.split('_')[0] # collect partial seqrun date from igf id seqrun_date=datetime.datetime.strptime(seqrun_date,'%y%m%d').date() # identify actual date seqrun_date=str(seqrun_date) # convert object to string return seqrun_date except: raise
32.558824
121
0.69196
e7c97ee0d77343e9506b256168754e198486e492
4,664
go
Go
server/fileserver.go
ngergs/webserver
a70ceae0d353a257b79b567242bacb28cfcce1bd
[ "MIT" ]
null
null
null
server/fileserver.go
ngergs/webserver
a70ceae0d353a257b79b567242bacb28cfcce1bd
[ "MIT" ]
null
null
null
server/fileserver.go
ngergs/webserver
a70ceae0d353a257b79b567242bacb28cfcce1bd
[ "MIT" ]
null
null
null
package server import ( "context" "io" "io/fs" "net/http" "path" "github.com/ngergs/websrv/utils" "github.com/rs/zerolog/log" ) // fileserverHandler is the main struct used for serving files type fileserverHandler struct { fetch fileFetch mediaTypeMap map[string]string } // fileFetch is a named function type. It is used to build chains of filefetching logics. The main route is zip/raw -> fallback -> zip/raw. See FileServerHandler for the setup. type fileFetch func(ctx context.Context, requestPath string, zipAccept bool) (file fs.File, path string, zipped bool, err error) // fetchWrapperZipOrNot calls the first prived fileFetch argument when the content should be zipped and the second one for raw content dependent on the Accept-Encoding header and the file extension. func fetchWrapperZipOrNot(gzipFileExtensions []string, nextZip fileFetch, nextUnzip fileFetch) fileFetch { return func(ctx context.Context, filepath string, zipAccept bool) (fs.File, string, bool, error) { if zipAccept && nextZip != nil && utils.Contains(gzipFileExtensions, path.Ext(filepath)) { return nextZip(ctx, filepath, zipAccept) } return nextUnzip(ctx, filepath, zipAccept) } } // fallbackFetch sets the path to the fallbackPath and calls the next fileFetch func fallbackFetch(fallbackPath string, next fileFetch) fileFetch { return func(ctx context.Context, path string, zipAccept bool) (fs.File, string, bool, error) { return next(ctx, fallbackPath, zipAccept) } } // fsFetch holds the actual logic for opening the file from the filesystem. Calls the next filefetcher if it is non-nill and an error occurs. func fsFetch(name string, filesystem fs.FS, zipped bool, next fileFetch) fileFetch { if filesystem == nil { log.Debug().Msgf("filesystem absent for fetcher %s, skipping configuration", name) return nil } return func(ctx context.Context, path string, zipAccept bool) (fs.File, string, bool, error) { file, err := filesystem.Open(path) log.Ctx(ctx).Debug().Msgf("fileFetch %s file miss for %s, trying next", name, path) if err != nil { log.Debug().Err(err).Msg("fsFetch missmatch") if next != nil { return next(ctx, path, zipAccept) } } return file, path, zipped, err } } // FileServerHandler implements the actual fileserver logic. zipfs can be set to nil if no pre-zipped file have been prepared. func FileServerHandler(fs fs.FS, zipfs fs.FS, fallbackFilepath string, config *Config) http.Handler { fallbackFetcher := fallbackFetch(fallbackFilepath, fetchWrapperZipOrNot(config.GzipFileExtensions(), fsFetch("zipped", zipfs, true, nil), fsFetch("unzipped", fs, false, nil))) fetcher := fetchWrapperZipOrNot(config.GzipFileExtensions(), fsFetch("zipped", zipfs, true, fallbackFetcher), fsFetch("unzipped", fs, false, fallbackFetcher)) handler := &fileserverHandler{ fetch: fetcher, mediaTypeMap: config.MediaTypeMap, } return handler } // ServeHttp implements the http.Handler interface func (handler *fileserverHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { ctx := r.Context() logEnter(ctx, "webserver") logger := log.Ctx(ctx) zipAccept := utils.ContainsAfterSplit(r.Header.Values("Accept-Encoding"), ",", "gzip") file, servedPath, zipped, err := handler.fetch(ctx, r.URL.Path, zipAccept) if err != nil { logger.Error().Err(err).Msgf("file %s not found", r.URL.Path) http.Error(w, "file not found", http.StatusNotFound) return } defer utils.Close(ctx, file) logger.Debug().Msgf("Serving file %s", servedPath) err = handler.setContentHeader(w, servedPath, zipped) if err != nil { logger.Error().Err(err).Msgf("content header error") http.Error(w, "internal server error", http.StatusInternalServerError) return } writeResponse(w, r, file) } // setContentHeader sets the Content-Type and the Content-Encoding (gzip or absent). func (handler *fileserverHandler) setContentHeader(w http.ResponseWriter, requestPath string, zipped bool) error { mediaType, ok := handler.mediaTypeMap[path.Ext(requestPath)] if !ok { mediaType = "application/octet-stream" } w.Header().Set("Content-Type", mediaType) if zipped { w.Header().Set("Content-Encoding", "gzip") } return nil } // writeResponse just streams the file content to the writer w and handles errors. func writeResponse(w http.ResponseWriter, r *http.Request, file io.Reader) { if r.Method == http.MethodHead { w.WriteHeader(http.StatusOK) return } _, err := io.Copy(w, file) if err != nil { log.Warn().Err(err).Msg("error copying requested file") http.Error(w, "failed to copy requested file, you can retry.", http.StatusInternalServerError) return } }
36.4375
198
0.735635
834bba1f3674a4650770a5452dbd4ca20a09ab7f
406
tsx
TypeScript
components/Footer.tsx
misa198/misadrop
918b1d920f4e112c688aac35701e6d5880e0bd60
[ "MIT" ]
1
2021-11-09T16:50:45.000Z
2021-11-09T16:50:45.000Z
components/Footer.tsx
misa198/misadrop
918b1d920f4e112c688aac35701e6d5880e0bd60
[ "MIT" ]
null
null
null
components/Footer.tsx
misa198/misadrop
918b1d920f4e112c688aac35701e6d5880e0bd60
[ "MIT" ]
null
null
null
import { FC } from 'react'; import { useAppSelector } from '../app/hooks/redux'; import User from './User'; import styles from './Footer.module.css'; const Footer: FC = () => { const user = useAppSelector((state) => state.user); return ( <div className={`w-full flex justify-center ${styles.footer}`}> <User name={user.name} color={user.color} /> </div> ); }; export default Footer;
23.882353
67
0.633005
fb56d618cde1550ff5eee56698eb738eb5946a79
1,641
dart
Dart
src/third_party/dart/samples-dev/swarm/BiIterator.dart
rhencke/engine
1016db292c4e73374a0a11536b18303c9522a224
[ "BSD-3-Clause" ]
8,969
2015-05-16T16:49:24.000Z
2022-03-31T19:54:40.000Z
samples-dev/swarm/BiIterator.dart
Fareed-Ahmad7/sdk
5183ba3ca4fe3787cae3c0a6cc7f8748ff01bcf5
[ "BSD-3-Clause" ]
30,202
2015-05-17T02:27:45.000Z
2022-03-31T22:54:46.000Z
samples-dev/swarm/BiIterator.dart
Fareed-Ahmad7/sdk
5183ba3ca4fe3787cae3c0a6cc7f8748ff01bcf5
[ "BSD-3-Clause" ]
1,619
2015-05-16T21:36:42.000Z
2022-03-29T20:36:59.000Z
// @dart = 2.9 part of swarmlib; /** * An iterator that allows the user to move forward and backward though * a set of items. (Bi-directional) */ class BiIterator<E> { /** * Provides forward and backward iterator functionality to keep track * which item is currently selected. */ ObservableValue<int> currentIndex; /** * The collection of items we will be iterating through. */ List<E> list; BiIterator(this.list, [List<ChangeListener> oldListeners = null]) : currentIndex = new ObservableValue<int>(0) { if (oldListeners != null) { currentIndex.listeners = oldListeners; } } /** * Returns the next section from the sections, given the current * position. Returns the last source if there is no next section. */ E next() { if (currentIndex.value < list.length - 1) { currentIndex.value += 1; } return list[currentIndex.value]; } /** * Returns the current Section (page in the UI) that the user is * looking at. */ E get current { return list[currentIndex.value]; } /** * Returns the previous section from the sections, given the current * position. Returns the front section if we are already at the front of * the list. */ E previous() { if (currentIndex.value > 0) { currentIndex.value -= 1; } return list[currentIndex.value]; } /** * Move the iterator pointer over so that it points to a given list item. */ void jumpToValue(E val) { for (int i = 0; i < list.length; i++) { if (identical(list[i], val)) { currentIndex.value = i; break; } } } }
23.112676
75
0.626447
c814bc03a4195db09ed8513475b64a57a3f8d30d
1,758
kt
Kotlin
src/main/kotlin/model/Model.kt
Vraiment/SSR
bc1b09e963b56ffbeb607a85a8175d7d205c7e0a
[ "MIT" ]
1
2019-01-05T08:36:01.000Z
2019-01-05T08:36:01.000Z
src/main/kotlin/model/Model.kt
Vraiment/SSR
bc1b09e963b56ffbeb607a85a8175d7d205c7e0a
[ "MIT" ]
null
null
null
src/main/kotlin/model/Model.kt
Vraiment/SSR
bc1b09e963b56ffbeb607a85a8175d7d205c7e0a
[ "MIT" ]
null
null
null
package vraiment.sage.ssr.model data class Id(val value: Int) data class IdInArea(val id: Id, val area: Id) data class Conversation(val area: Id, val id: Id, val number: Byte) data class Conversations(val conditions: Map<Condition, Boolean>, val entries: List<Conversation>) { enum class Condition { khaka1, khaka2, khaka3, khakadone, kmsk1, kmsk2, kmsk3, kgly1, kgly2, kgly3, kitem1_kitem3, kitem2, unused1, kquest1, kquest2, kquest3, kquest4, kquest5, kquest6, kquest7, kquest8, kquest9, kmisc1, kmisc2, kmisc3, kmisc4, kmisc5, kmisc6, kmisc7, kmisc8, kmisc9, krandom } } data class Quests( val quest0: Byte, val quest1: Byte, val quest2: Byte, val quest3: Byte, val quest4: Byte, val quest5: Byte ) data class Time(val area: Id, val value: Float) data class SaveFile( val version: Byte, val level: Byte, val area: Id, val position: Id, val look: Id, val toa: Id, val mask: Int, val glyph: Byte, val health: Byte, val energy: Byte, val tokens: List<IdInArea>, val maskList: List<IdInArea>, val glyphs: List<IdInArea>, val inventory: List<IdInArea>, val cinema: List<Id>, val conversations: Conversations, val times: List<Time>, val quests: Quests, val masks: Byte?, val glyphFound: Byte?, val stoneFound: Byte?, val hookFound: Byte?, val ammo: Short? )
21.439024
100
0.530717
afe6d5298da22a252d28515610529ef023c26611
5,324
py
Python
examples/proof-of-concept/mkparcol.py
minireference/paralleletex
f5fe5f8b5851c8181928bb6074dbdb9eaf6311ec
[ "MIT" ]
null
null
null
examples/proof-of-concept/mkparcol.py
minireference/paralleletex
f5fe5f8b5851c8181928bb6074dbdb9eaf6311ec
[ "MIT" ]
null
null
null
examples/proof-of-concept/mkparcol.py
minireference/paralleletex
f5fe5f8b5851c8181928bb6074dbdb9eaf6311ec
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import re LEFT_SOURCE_FILE = '11_solving_equationsFR.tex' LEFT_LANGUAGE = 'french' RIGHT_SOURCE_FILE = '11_solving_equationsEN.tex' RIGHT_LANGUAGE = 'english' PARCOL_OUT_FILE = '11_solving_equations_FR_en.tex' CHOOSE_SHARED = 'left' PAR_RE = re.compile('[.*]?\%\%[ ]?PAR(?P<par_id>[\d]{2,4})') SHARED_RE = re.compile('[.*]?\%\%[ ]?SHARED(?P<shared_id>[\d]{2,4})') END_OF_FILE_STR = '__END_OF_FILE__' def parse_line(line): if END_OF_FILE_STR in line: return {'kind': 'endoffile'} par_m = PAR_RE.search(line) if par_m: return { 'kind': 'newpar', 'par_id':par_m.groupdict()['par_id'] } shared_m = SHARED_RE.search(line) if shared_m: return { 'kind': 'newshared', 'shared_id': shared_m.groupdict()['shared_id'] } return { 'kind': 'regularline', 'line': line, } def parse_tex_source(filepath): """ Split the source text file on the %%SHARED and %%PAR markers in the source. Return a dictionary of the form: { 'sequence': ['SHARED001', 'PAR001', ...], 'chunks': { 'SHARED001': [(str)], # lines of the shaed chunk SHARED001 'PAR001': [(str)], # lines of the chunk PAR001 ... } } """ with open(filepath) as source_file: lines = source_file.readlines() lines.append('__END_OF_FILE__') # setup return dict data = { 'sequence': [], 'chunks': {} } cur_id = None cur_lines = None cur_state = 'filestart' for line in lines: line_dict = parse_line(line) # print('state:', cur_id, cur_lines, cur_state) # print('parsing', line_dict) kind = line_dict['kind'] if cur_state == 'filestart' and line_dict['kind'] == 'regularline': print('skipping start of file line', line) continue # close cur when encountering new chunk or end-of-file if cur_state in ['inpar', 'inshared'] and kind in ['newpar', 'newshared', 'endoffile']: data['sequence'].append(cur_id) data['chunks'][cur_id] = cur_lines # state machine logic: if line_dict['kind'] == 'regularline': cur_lines.append(line) elif line_dict['kind'] == 'newpar': # stuar new cur cur_id = 'PAR'+line_dict['par_id'] cur_lines = [] cur_state = 'inpar' elif line_dict['kind'] == 'newshared': # stuar new cur cur_id = 'SHARED'+line_dict['shared_id'] cur_lines = [] cur_state = 'inshared' elif line_dict['kind'] == 'endoffile': print('Reached end of file') else: print('ERROR: unexpected line', line) print_parsed(filepath, data) return data def print_parsed(filepath, data): print('Parsed version of', filepath) print('sequence:', data['sequence']) unused_seq_ids = set(data['chunks'].keys()) - set(data['sequence']) if unused_seq_ids: print('WARNING: unused sequence ids = ', unused_seq_ids) for seq_id in data['sequence']: print(seq_id) lines = data['chunks'][seq_id] print(''.join(lines)) FRENCH_PAR_TEMPLATE = """ \\begin{otherlanguage}{french} %s \\end{otherlanguage} """ ENGLISH_PAR_TEMPLATE = """ %s """ def wrap_par_text(text, language): if language == 'english': return ENGLISH_PAR_TEMPLATE % text elif language == 'french': return FRENCH_PAR_TEMPLATE % text else: raise ValueError('Unrecognized langauge ' + language) LEFT_COLUMN_TEMPLATE = """ \\begin{leftcolumn*} %s \\end{leftcolumn*} """ RIGHT_COLUMN_TEMPLATE = """ \\begin{rightcolumn} %s \\end{rightcolumn} """ SHARED_TEMPLATE = """ \\vspace{0.2cm} %s \\vspace{0.3cm} """ def wrap_left_column(text): return LEFT_COLUMN_TEMPLATE % text def wrap_right_column(text): return RIGHT_COLUMN_TEMPLATE % text def wrap_shared(text): return SHARED_TEMPLATE % text PARCOL_TEMPLATE = """ \\begin{paracol}{2} %s %s \\end{paracol} """ def wrap_parcol(left_col, right_col): return PARCOL_TEMPLATE % (left_col, right_col) def mkparcol(): left_data = parse_tex_source(LEFT_SOURCE_FILE) right_data = parse_tex_source(RIGHT_SOURCE_FILE) print('writing bilingual output file ', PARCOL_OUT_FILE) outf = open(PARCOL_OUT_FILE, 'w') for seq_id in left_data['sequence']: if 'SHARED' in seq_id: left_lines = left_data['chunks'][seq_id] text = ''.join(left_lines) text = wrap_shared(text) outf.write(text) elif 'PAR' in seq_id: left_lines = left_data['chunks'][seq_id] left_text = ''.join(left_lines) fr_text = wrap_par_text(left_text, 'french') left_col = wrap_left_column(fr_text) right_lines = right_data['chunks'][seq_id] right_text = ''.join(right_lines) en_text = wrap_par_text(right_text, 'english') right_col = wrap_right_column(en_text) outf.write(wrap_parcol(left_col, right_col)) outf.close() if __name__ == '__main__': mkparcol()
24.648148
95
0.589406
b2de66b1bce684dae12fb8eaee2dcd17243030c6
19,465
css
CSS
assets/css/style.css
kancha05656/Brows-Design-Center
5c932b6553bb3bef21417a41540b2a7de638dd43
[ "MIT" ]
null
null
null
assets/css/style.css
kancha05656/Brows-Design-Center
5c932b6553bb3bef21417a41540b2a7de638dd43
[ "MIT" ]
null
null
null
assets/css/style.css
kancha05656/Brows-Design-Center
5c932b6553bb3bef21417a41540b2a7de638dd43
[ "MIT" ]
null
null
null
/************** Default CSS **************/ :root { --body: #fff; --a: #5c656d; --p: #5c656d; --h: #202020; --dark: #1F1F20; --primary:#fb90b1; } body { font-family: 'Roboto', sans-serif; font-weight: normal; font-style: normal; background-color: var(--body); padding:0; margin:0; } a, .button, button { -webkit-transition: all 0.3s ease-out 0s; -o-transition: all 0.3s ease-out 0s; transition: all 0.3s ease-out 0s; } a:hover { text-decoration: none; } a:focus, button:focus, input:focus, textarea:focus { text-decoration: none; outline: none; } button { cursor: pointer } ul, ol { margin: 0px; padding: 0px; } li { list-style: none } h1, h2, h3, h4, h5, h6 { font-family: 'Lato', sans-serif; font-weight: 700; font-style: normal; color: var(--h); text-transform: capitalize; margin-top: 0px; } h1 { font-size: 40px; } h2 { font-size: 36px; font-weight: 700; } h3 { font-size: 28px; } h4 { font-size: 22px; } h5 { font-size: 18px; } h6 { font-size: 16px; } p { font-size: 17px; font-weight: 400; line-height: 30px; color: var(--p); margin-bottom: 15px; letter-spacing: 1px; } a { color: var(--a); font-size: 17px; font-weight: 400; } a:hover { color: #fb90b1 !important; } /************** Default CSS End **************/ .section-padding-top{ padding-top: 115px; } /************** Template CSS **************/ /*header */ a.navbar-brand img { width: 100%; max-width: 125px; } #home { background: url(../img/home_01.jpg); padding-bottom: 44%; position: relative; background-size: cover; background-repeat: no-repeat; height: 100%; } header { background-size: 100% 100%; position: relative; padding-bottom: 35%; } header#services{ background: url(../img/Services.jpg); background-position-x: 40%; background-size: cover; } header#gallery { background: url(../img/gellary.jpg); background-position-x: 20%; background-size: cover; } header#aboutus{ background: url(../img/about-us.jpg); background-position-x: 10%; background-size: cover; } header#contact{ background: url(../img/contact-us.jpg); background-position: 20%; background-size: cover; } .navbar-bg { background: #f7e4ea59; /* background: #e9eaeba6; */ position: static; width: 100%; top: 0; padding: 5px 0px; z-index: 9999; -webkit-box-shadow: 0 1px 6px 0 rgba(32, 33, 36, 0.28); box-shadow: 0 1px 6px 0 rgba(32, 33, 36, 0.28); } li.nav-item { position: relative; text-align: center; margin-right: 18px; } li.nav-item:after { position: absolute; left: 0; width: 0%; background: #fb90b1; content: ""; height: 3px; margin: 0 auto; display: block; -webkit-transition: 0.4s; -o-transition: 0.4s; transition: 0.4s; } li.nav-item:hover:after { width: 90%; } a.nav-link { font-weight: 500; padding-left: 0 !important; font-size: 15px; } li.nav-item:last-child { margin-right: 0; } a.nav-link:hover { color: #fb90b1; } .banner-img-overly { position: absolute; right: 8.5%; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); max-width: 700px; text-align: right; z-index: 999; } .banner-img img { max-width: 699px; width: 100%; } .banner-img { padding-bottom: 20px; } header:after { position: absolute; content: ""; width: 100%; height: 100%; background: #0000000d; top: 0; left: 0; } .custom-btn { display: inline-block; background: #fb90b1; color: #fff; font-weight: 700; border-radius: 27px; font-size: 15px; padding: 17px 48px; position: relative; letter-spacing: 1px; -webkit-transition: all 400ms; -o-transition: all 400ms; transition: all 400ms; text-transform: uppercase; line-height: 23px; border: 1px solid #fb90b1; } button.custom-btn { } .custom-btn:hover { background: transparent; border: 1px solid #fb90b1; color: #000; } .banner-des h1 { padding-top: 15px; padding-bottom: 20px; font-size:17px; font-weight: 600; line-height: 25px; } /*header css end*/ /*about section start */ section.about-section { padding: 114px 0px; } .section-title { text-align: center; padding-bottom: 35px; } .section-title span { font-weight: 600; color: #fb90b1; font-size: 16px; text-transform: uppercase; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; position: relative; z-index: 99; } .section-title h2 { margin-top: 8px; position: relative; z-index: 99; } .section-title { position: relative; z-index: 999; } .section-title p { padding-top: 10px; max-width: 900px; margin: 0 auto; margin-bottom: 15px; } .section-title:after { position: absolute; content: ""; left: 50%; width: 240px; height: 177px; top: 0; -webkit-transform: translateX(-50%); -ms-transform: translateX(-50%); transform: translateX(-50%); background: url(../img/eye2.png); background-size: contain; background-repeat: no-repeat; opacity: 0.05; margin-top: -3%; z-index: 6; } .section-title span:after { content: ''; -webkit-box-flex: 1; -ms-flex: 1; flex: 1; border-bottom: 1px solid; margin: auto 10px; max-width: 100px; } .section-title span:before { content: ''; -webkit-box-flex: 1; -ms-flex: 1; flex: 1; border-bottom: 1px solid; margin: auto 10px; max-width: 100px; } .our-services-card { padding-bottom: 20px; min-height: 320px; max-width: 350px; margin: 0 auto; margin-bottom: 50px; padding: 20px; border-radius: 5px; -webkit-box-shadow: 1px 2px 11px 4px rgb(250 164 191 / 14%); box-shadow: 1px 2px 11px 4px rgb(250 164 191 / 14%); } .our-service-img {text-align: center;padding-bottom: 20px;} .our-services-des h4 { padding-bottom: 5px; font-size: 22px; color: #202020; line-height: 27px; font-weight: 600; text-align: center; } .our-services-des p { font-size: 16px; line-height: 1.5; text-align: center; } .our-service-img img {width: 100%;width: 50px;margin-top: 5px;} section.our-service { padding-bottom: 74px; } /*price card start */ section.price-section { background: url(../img/price-bg.jpg); background-size: 100% 100%; background-repeat: no-repeat; padding-top: 80px; padding-bottom: 80px; } .price-card { min-height: 300px; text-align: center; border-radius: 8px; overflow: hidden; background: #fff; padding-bottom: 35px; margin-bottom: 25px; -webkit-box-shadow: 1px -1px 11px 4px rgb(250 164 191 / 14%); box-shadow: 1px -1px 11px 4px rgb(250 164 191 / 14%); } .price-card h5 { font-size: 60px; text-align: center; position: relative; display: inline-block; background: -webkit-gradient(linear, left top, right top, from(rgba(116,243,239, 0.8)), to(rgba(251,144,177, 0.8))) no-repeat center; background: -o-linear-gradient(left, rgba(116,243,239, 0.8) 0%, rgba(251,144,177, 0.8)) no-repeat center; background: linear-gradient(90deg, rgba(116,243,239, 0.8) 0%, rgba(251,144,177, 0.8)) no-repeat center; -webkit-background-clip: text; -webkit-text-fill-color: transparent; z-index: 11; } .price-card h5:before { position: absolute; content: "$"; left: -22px; top: 5px; font-size: 30px; z-index: 999; background: -webkit-gradient(linear, left top, right top, from(rgba(116,243,239, 0.8)), to(rgba(251,144,177, 0.8))) no-repeat center; background: -o-linear-gradient(left, rgba(116,243,239, 0.8) 0%, rgba(251,144,177, 0.8)) no-repeat center; background: linear-gradient(90deg, rgba(116,243,239, 0.8) 0%, rgba(251,144,177, 0.8)) no-repeat center; -webkit-background-clip: text; -webkit-text-fill-color: transparent; } .price-card a { margin-top: 30px; } .price-card h6 { font-size: 22px; line-height: 23px; margin-top: 20px; font-weight: 700; font-family: 'Lato', sans-serif; } .product-img img { width: 100%; } .product-img { overflow: hidden; position: relative; margin-bottom: 40px; max-height: 200px; } /*.product-img:after { position: absolute; left: 0; content: ""; height: 100%; background: linear-gradient(90deg, rgba(116,243,239, 0.8) 0%, rgba(251,144,177, 0.8)) no-repeat center; width: 100%; top:0; }*/ .slick-initialized .slick-slide { outline: none; } ul.slick-dots { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; margin-top: 15px; } ul.slick-dots li button { display: none; } ul.slick-dots li { width: 15px; height: 15px; background: #fb90b1; display: inline-block; margin-right: 10px; border-radius: 50%; cursor: pointer; } li.slick-active { background: #8be5e4 !important; } /*price card end*/ /*cta section start */ .cta-section-wrap{ background:url(../img/cta.jpg); background-position: center !important; background-repeat: no-repeat !important; background-size: cover !important; padding:70px 0px; } .cta-heading h5 { text-align: center; font-size: 35px; color: #fff; } .cta-button a { background: #fff; color: #fb90b1; } .cta-button a:hover { color: #fff !important; } footer { padding-top: 80px; } .footer-logo a img { width: 100%; max-width: 140px; } .footer-logo { padding-bottom: 15px; } .footer-useful-link { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: justify; -ms-flex-pack: justify; justify-content: space-between; } ul.list-unstyled.list-one { width: 40%; } ul.list-unstyled.list-tow { width: 50%; } footer ul li { margin-bottom: 10px; } footer ul li a { } .footer-useful-link ul li a { position: relative; padding-left: 20px; } .footer-useful-link ul li a:before { position: absolute; content: "\f101"; font-family: 'font awesome 5 Pro'; font-weight: 900; left: 0; font-size: 14px; top: 1px; -webkit-transition: all 0.3s ease-out 0s; -o-transition: all 0.3s ease-out 0s; transition: all 0.3s ease-out 0s; } .footer-useful-link ul li a:hover { padding-left: 24px; } .footer-useful-link ul li a:hover:before { left: 5px; } .footer-useful-link ul li a:hover { color: #fb90b1; } footer h5 { font-size: 20px; display: inline-block; border-bottom: 2px solid #fb90b1; padding-bottom: 10px; } a.btn-floating { width: 50px; height: 50px; font-size: 20px; border-radius: 50%; display: inline-block; padding: 15px; line-height: 20px; color: #fff; } a.btn-floating:hover i { -webkit-transform: rotate(360deg); -ms-transform: rotate(360deg); transform: rotate(360deg); -webkit-transition: 0.4s; -o-transition: 0.4s; transition: 0.4s; } .btn-fb{ background: #4267b2; } .btn-tw{ background: #1da1f2; } .btn-li{ background: #2977c9; } .btn-yelp{ background: #d32323; } .btn-instagram { background: -o-radial-gradient(30% 107%, circle, #fdf497 0%, #fdf497 5%, #fd5949 45%,#d6249f 60%,#285AEB 90%); background: radial-gradient(circle at 30% 107%, #fdf497 0%, #fdf497 5%, #fd5949 45%,#d6249f 60%,#285AEB 90%); } .btn-google{ background: #db4a39; } a.btn-floating:hover { color: #fff !important; } .footer-copyright { background: #fb90b1; color: #fff; margin-top: 5px; } .footer-copyright a { color: #fff; } /* cta sectin end */ /*tesmonial */ section.testimonial-section { padding: 114px 0px; } .testi-card-header { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } .testi-header-img { width: 70px; height: 70px; border-radius: 50%; overflow: hidden; margin-right: 15px; border: 3px solid #fb90b1; } .testi-header-img img { width: 100%; } .client-name h5 { font-size: 17px; } .testi-body p { font-size: 15px; line-height: 24px; } .testi-body { margin-top: 30px; padding: 20px; position: relative; margin-bottom: 20px; min-height: 250px; border-radius: 5px; -webkit-box-shadow: 1px 2px 11px 4px rgb(250 164 191 / 14%); box-shadow: 1px 2px 11px 4px rgb(250 164 191 / 14%); } .testi-body:after { position: absolute; left: 20px; width: 0; content: ""; top: -39px; border-right: 20px solid transparent; border-bottom: 20px solid #fff; border-left: 20px solid transparent; border-top: 20px solid transparent; } /*bradcumb*/ .breadcum { position: absolute; bottom: 0; -webkit-transform: translateX(-50%); -ms-transform: translateX(-50%); transform: translateX(-50%); left: 50%; background: #FAA4BF; width: 100%; max-width: 820px; border-radius: 10px; padding: 20px 0px; z-index: 999; } .breadcum ul { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } .breadcum ul li a { color: #fff; font-size: 17px; font-weight: bold; } .breadcum ul li:last-child a { color: rgba(255, 255, 255, 0.82); } .breadcum ul li { margin-right: 10px; } .breadcum ul li i { color: #fff; font-size: 17px; } .breadcum ul li a:hover { color: rgba(255, 255, 255, 0.82) !important; } /*gallery */ .item { max-height: 400px; position: relative; overflow: hidden; margin-bottom: 20px; } .item img { width: 100%; } .filters ul li { display: inline-block; font-size: 17px; padding: 5px 15px; margin-right: 15px; border: 1px solid #faa4bf; border-radius: 5px; cursor: pointer; font-weight: 500; position: relative; overflow: hidden; } .filters { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; padding-bottom: 25px; } .filters ul li.active { background: #faa4bf; color: #fff; } .filters ul li:after { position: absolute; width: 38%; height: 100%; background: hsla(0,0%,100%,.23); content: ""; left: -100%; top: 0; -webkit-transform: skewX(-15deg); -ms-transform: skewX(-15deg); transform: skewX(-15deg); z-index: 999; -webkit-transition: 0.9s; -o-transition: 0.9s; transition: 0.9s; } .filters ul li:hover { background: #faa4bf; color: #fff; } .filters ul li:hover:after { left: 110%; } .item-overly { position: absolute; width: 100%; height: 100%; background: -o-linear-gradient(320deg, rgba(116,243,239, 0.95) 0%, rgba(251,144,177, 0.95)) no-repeat center; background: linear-gradient(130deg, rgba(116,243,239, 0.95) 0%, rgba(251,144,177, 0.95)) no-repeat center; content: ""; display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: center; -ms-flex-pack: center; justify-content: center; -webkit-box-align: center; -ms-flex-align: center; align-items: center; } .item-overly a i { font-size: 25px; color: #fff; } /*about us page */ .about-us-des h3 { font-size: 22px; font-weight: 500; margin-top: 0; font-style: italic; } .counter-wrap { display: -webkit-box; display: -ms-flexbox; display: flex; } .counter-img img { width: 100%; max-width: 50px; } .counter-img { margin-right: 20px; } .counter h3 { font-size: 35px; font-weight: 800; margin-bottom: 5px; } section.counter-section { background: rgba(250, 164, 191, 0.3); padding: 40px 0px; } h3.counter-number { position: relative; } h3.counter-number:after {content: "\f067";position: absolute;font-family: "Font Awesome 5 Pro";font-size: 18px;top: 13px;margin-left: 5px;} .contact-form-sidebar { background: rgba(250, 164, 191, 0.3); padding: 40px 25px; padding-bottom: 20px; border-radius: 5px; border-left: 2px solid #FAA4BF; } .sidebar-header h3 { font-size: 22px; margin-bottom: 3px; } .sidebar-header p { font-size: 14px; } .sidebar-body { padding-top: 15px; } .sidebar-item h5 { font-size: 17px; margin-bottom: 3px; } .sidebar-item h5 i { font-size: 17px; margin-right: 5px; } .sidebar-item p { font-size: 15px; } .form-group { margin-bottom: 25px !important; } .form-control { padding: 22px 20px !important; } .contact-wrap { -webkit-box-shadow: 1px 2px 11px 4px rgb(250 164 191 / 14%); box-shadow: 1px 2px 11px 4px rgb(250 164 191 / 14%); padding: 40px; border-radius: 8px; } .form-control:focus { border-color: #fee3ec !important; -webkit-box-shadow: 0 0 0 0.2rem rgb(254 227 236) !important; box-shadow: 0 0 0 0.2rem rgb(254 227 236) !important; } section.map-section { padding-bottom: 90px; padding-top: 20px; } footer.page-footer.contact-page-footer { padding-top: 40px; border-top: 1px dotted #fb90b191; } /*timer */ /*.hour-wrap { margin: 0 auto; border: 5px solid #fb90b1; padding: 15px; text-align: center; padding-top: 0; } .hour-icon { text-align: center; margin: 0 auto; background: #fb90b1; padding: 15px 15px; max-width: 135px; margin-bottom: 3px; } .hour-icon i { font-size: 30px; display: inline-block; color: #fff; } .hour-icon p { color: #fff; font-size: 25px; text-align: center; margin: 0; } .time h5 { font-size: 25px; margin-top: 30px; font-weight: 700; text-transform: uppercase; }*/ .hour-wrap { text-align: center; /* background: #fb90b194; */ border-radius: 8px; margin: 0 auto; overflow: hidden; max-width: 255px; margin-bottom: 50px; -webkit-box-shadow: 1px 2px 11px 4px rgb(250 164 191 / 14%); box-shadow: 1px 2px 11px 4px rgb(250 164 191 / 14%); } .hour-header h4 { font-size: 28px; font-style: italic; } .hour-header { padding: 20px 0px; background: #fb90b16b; } .time h5 { font-size: 28px; line-height: 1.5; font-weight: 900; } .time p { font-size: 20px; color: #000000c7; font-weight: 500; } .time { padding: 20px 0px; } .bottom-text { display: -webkit-box; display: -ms-flexbox; display: flex; -webkit-box-pack: justify; -ms-flex-pack: justify; justify-content: space-between; padding: 10px 0px; } .bottom-text p { margin: 0; color: #fff; } .bottom-text p a:hover { color: #fff!important; }
19.083333
141
0.600257
b7a949166a0b0b094aafdef28e98cab9985b4041
2,727
cpp
C++
src/3d/qgscamerapose.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/3d/qgscamerapose.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/3d/qgscamerapose.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
1
2021-12-25T08:40:30.000Z
2021-12-25T08:40:30.000Z
/*************************************************************************** qgscamerapose.cpp -------------------------------------- Date : July 2018 Copyright : (C) 2018 by Martin Dobias Email : wonder dot sk at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgscamerapose.h" #include <Qt3DRender/QCamera> #include <QDomDocument> QDomElement QgsCameraPose::writeXml( QDomDocument &doc ) const { QDomElement elemCamera = doc.createElement( QStringLiteral( "camera-pose" ) ); elemCamera.setAttribute( QStringLiteral( "x" ), mCenterPoint.x() ); elemCamera.setAttribute( QStringLiteral( "y" ), mCenterPoint.y() ); elemCamera.setAttribute( QStringLiteral( "z" ), mCenterPoint.z() ); elemCamera.setAttribute( QStringLiteral( "dist" ), mDistanceFromCenterPoint ); elemCamera.setAttribute( QStringLiteral( "pitch" ), mPitchAngle ); elemCamera.setAttribute( QStringLiteral( "heading" ), mHeadingAngle ); return elemCamera; } void QgsCameraPose::readXml( const QDomElement &elem ) { double x = elem.attribute( QStringLiteral( "x" ) ).toDouble(); double y = elem.attribute( QStringLiteral( "y" ) ).toDouble(); double z = elem.attribute( QStringLiteral( "z" ) ).toDouble(); mCenterPoint = QgsVector3D( x, y, z ); mDistanceFromCenterPoint = elem.attribute( QStringLiteral( "dist" ) ).toFloat(); mPitchAngle = elem.attribute( QStringLiteral( "pitch" ) ).toFloat(); mHeadingAngle = elem.attribute( QStringLiteral( "heading" ) ).toFloat(); } void QgsCameraPose::updateCamera( Qt3DRender::QCamera *camera ) { // basic scene setup: // - x grows to the right // - z grows to the bottom // - y grows towards camera // so a point on the plane (x',y') is transformed to (x,-z) in our 3D world camera->setUpVector( QVector3D( 0, 0, -1 ) ); camera->setPosition( QVector3D( mCenterPoint.x(), mDistanceFromCenterPoint + mCenterPoint.y(), mCenterPoint.z() ) ); camera->setViewCenter( QVector3D( mCenterPoint.x(), mCenterPoint.y(), mCenterPoint.z() ) ); camera->rotateAboutViewCenter( QQuaternion::fromEulerAngles( mPitchAngle, mHeadingAngle, 0 ) ); }
47.017241
118
0.582325
be4129bdb5fb08b6f89c6109f3300e41f1b0856a
152
sql
SQL
5.2.3/Database/Indexes/AFW_12_GROUP_GADGT_UTILS_UK1.sql
lgcarrier/AFW
a58ef2a26cb78bb0ff9b4db725df5bd4118e4945
[ "MIT" ]
1
2017-07-06T14:53:28.000Z
2017-07-06T14:53:28.000Z
5.2.3/Database/Indexes/AFW_12_GROUP_GADGT_UTILS_UK1.sql
lgcarrier/AFW
a58ef2a26cb78bb0ff9b4db725df5bd4118e4945
[ "MIT" ]
null
null
null
5.2.3/Database/Indexes/AFW_12_GROUP_GADGT_UTILS_UK1.sql
lgcarrier/AFW
a58ef2a26cb78bb0ff9b4db725df5bd4118e4945
[ "MIT" ]
null
null
null
SET DEFINE OFF; CREATE UNIQUE INDEX AFW_12_GROUP_GADGT_UTILS_UK1 ON AFW_12_GROUP_GADGT_UTILS (REF_UTILS_DEMDR, REF_UTILS, REF_TABL_BORD, NOM) LOGGING /
25.333333
76
0.855263
3b647e9e5134f1d0d96549934262cf4cc616e117
422
swift
Swift
Package.swift
TharinduMPerera/Nantes
c7e278e0fc8becb15037aa3ba96d49095b668afa
[ "Apache-2.0" ]
null
null
null
Package.swift
TharinduMPerera/Nantes
c7e278e0fc8becb15037aa3ba96d49095b668afa
[ "Apache-2.0" ]
null
null
null
Package.swift
TharinduMPerera/Nantes
c7e278e0fc8becb15037aa3ba96d49095b668afa
[ "Apache-2.0" ]
null
null
null
// swift-tools-version:4.2 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "Nantes", dependencies: [], // Note: SPM requires 1 target to build the package targets: [ .target( name: "Nantes", path: "Source/Classes", exclude: ["Nantes.h"] ) ] )
22.210526
96
0.599526
6e27290d1469f081c98ea8b4005de9e833d91011
72
sql
SQL
src/test/resources/sql/create_table/e258ce90.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
66
2018-06-15T11:34:03.000Z
2022-03-16T09:24:49.000Z
src/test/resources/sql/create_table/e258ce90.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
13
2019-03-19T11:56:28.000Z
2020-08-05T04:20:50.000Z
src/test/resources/sql/create_table/e258ce90.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
28
2019-01-05T19:59:02.000Z
2022-03-24T11:55:50.000Z
-- file:domain.sql ln:462 expect:true create table ddtest2(f1 ddtest1d)
24
37
0.777778
76701484f7e2863a2b9448b845f4564271b06e54
2,240
dart
Dart
lib/src/generated/vision/VNGenerateImageSaliencyRequest.dart
rodydavis/cupertino_ffi_generated
4d59f68921a5ae1ba58831c9de83ea0d7979148f
[ "MIT" ]
2
2021-05-10T01:24:08.000Z
2021-12-13T10:24:41.000Z
lib/src/generated/vision/VNGenerateImageSaliencyRequest.dart
rodydavis/cupertino_ffi_generated
4d59f68921a5ae1ba58831c9de83ea0d7979148f
[ "MIT" ]
null
null
null
lib/src/generated/vision/VNGenerateImageSaliencyRequest.dart
rodydavis/cupertino_ffi_generated
4d59f68921a5ae1ba58831c9de83ea0d7979148f
[ "MIT" ]
null
null
null
// AUTOMATICALLY GENERATED. DO NOT EDIT. part of cupertino_ffi.vision; /// Static methods for Objective-C class `VNGenerateImageSaliencyRequest`. /// See also instance methods in [VNGenerateImageSaliencyRequestPointer]. /// /// Find detailed documentation at: [developer.apple.com/documentation/vision?language=objc](https://developer.apple.com/documentation/vision?language=objc) class VNGenerateImageSaliencyRequest extends Struct { /// Allocates a new instance of VNGenerateImageSaliencyRequest. static Pointer<VNGenerateImageSaliencyRequest> allocate() { _ensureDynamicLibraryHasBeenOpened(); return _objc.allocateByClassName<VNGenerateImageSaliencyRequest>( 'VNGenerateImageSaliencyRequest'); } } /// Instance methods for [VNGenerateImageSaliencyRequest] (Objective-C class `VNGenerateImageSaliencyRequest`). /// /// Find detailed documentation at: [developer.apple.com/documentation/vision?language=objc](https://developer.apple.com/documentation/vision?language=objc) extension VNGenerateImageSaliencyRequestPointer on Pointer<VNGenerateImageSaliencyRequest> { /// Objective-C method `internalPerformRevision:inContext:error:`. @ObjcMethodInfo( selector: 'internalPerformRevision:inContext:error:', returnType: 'c', parameterTypes: ['@', ':', 'Q', '@', '^@'], ) int internalPerformRevision( int arg, { @required Pointer inContext, @required Pointer<Pointer> error, }) { _ensureDynamicLibraryHasBeenOpened(); return _objc_call.call_ptr_ptr_uint64_ptr_ptr_returns_int8( this, _objc.getSelector( 'internalPerformRevision:inContext:error:', ), arg, inContext, error, ); } /// Objective-C method `willAcceptCachedResultsFromRequestWithConfiguration:`. @ObjcMethodInfo( selector: 'willAcceptCachedResultsFromRequestWithConfiguration:', returnType: 'c', parameterTypes: ['@', ':', '@'], ) int willAcceptCachedResultsFromRequestWithConfiguration( Pointer arg, ) { _ensureDynamicLibraryHasBeenOpened(); return _objc_call.call_ptr_ptr_ptr_returns_int8( this, _objc.getSelector( 'willAcceptCachedResultsFromRequestWithConfiguration:', ), arg, ); } }
34.461538
156
0.738839
6af66d75c73fa2b0ba0c3fb9ee7ac45d7df2bf7d
20,548
c
C
src/backend/catalog/pgxc_key_values.c
miusuncle/TBase
bdd2e750d414d091b26f927227f767af9d5e7272
[ "BSD-3-Clause" ]
1,303
2019-11-07T08:45:56.000Z
2022-03-29T14:39:35.000Z
src/backend/catalog/pgxc_key_values.c
neobiG/TBase
3295393cbabd6f17676c53078cf4cc03aa9dc1fd
[ "BSD-3-Clause" ]
112
2019-11-07T09:17:04.000Z
2022-03-29T12:25:56.000Z
src/backend/catalog/pgxc_key_values.c
neobiG/TBase
3295393cbabd6f17676c53078cf4cc03aa9dc1fd
[ "BSD-3-Clause" ]
254
2019-11-07T09:10:42.000Z
2022-03-18T18:17:32.000Z
/* * Tencent is pleased to support the open source community by making TBase available. * * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. * * TBase is licensed under the BSD 3-Clause License, except for the third-party component listed below. * * A copy of the BSD 3-Clause License is included in this file. * * Other dependencies and licenses: * * Open Source Software Licensed Under the PostgreSQL License: * -------------------------------------------------------------------- * 1. Postgres-XL XL9_5_STABLE * Portions Copyright (c) 2015-2016, 2ndQuadrant Ltd * Portions Copyright (c) 2012-2015, TransLattice, Inc. * Portions Copyright (c) 2010-2017, Postgres-XC Development Group * Portions Copyright (c) 1996-2015, The PostgreSQL Global Development Group * Portions Copyright (c) 1994, The Regents of the University of California * * Terms of the PostgreSQL License: * -------------------------------------------------------------------- * Permission to use, copy, modify, and distribute this software and its * documentation for any purpose, without fee, and without a written agreement * is hereby granted, provided that the above copyright notice and this * paragraph and the following two paragraphs appear in all copies. * * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING * LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS * DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * * Terms of the BSD 3-Clause License: * -------------------------------------------------------------------- * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of THL A29 Limited nor the names of its contributors may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE 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 HOLDER 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. * */ #include "postgres.h" #include "access/skey.h" #include "access/htup.h" #include "access/htup_details.h" #include "access/heapam.h" #include "access/genam.h" #include "catalog/indexing.h" #include "catalog/pgxc_key_values.h" #include "pgxc/nodemgr.h" #include "pgxc/shardmap.h" #include "utils/syscache.h" #include "utils/catcache.h" #include "utils/relcache.h" #include "utils/rel.h" #include "utils/elog.h" #include "utils/fmgroids.h" #include "utils/tqual.h" #include "utils/builtins.h" #include "utils/inval.h" #include "access/xact.h" #include "miscadmin.h" #include "catalog/pgxc_shard_map.h" #include "utils/lsyscache.h" #include "catalog/heap.h" static Oid IsKeyValuesDup(Oid db, Oid rel, char *value) { HeapTuple tup; tup = SearchSysCache(SHARDKEYVALUE, ObjectIdGetDatum(db), ObjectIdGetDatum(rel), CStringGetDatum(value), 0); if (HeapTupleIsValid(tup)) { ReleaseSysCache(tup); return true; } return false; } void CreateKeyValues(Oid db, Oid rel, int32 nValues, char **keyvalues, Oid nodeGroup, Oid coldGroup) { Relation kvrel; HeapTuple htup; bool nulls[Natts_pgxc_key_value]; Datum values[Natts_pgxc_key_value]; NameData name; Relation relation; int i; for (i = 0; i < nValues; i++) { if (true == IsKeyValuesDup(db, rel, keyvalues[i])) { elog(ERROR , "value:%s has been already created on db:%u, rel:%u", keyvalues[i], db, rel); } } /* make and insert shard map record */ for(i = 0; i < Natts_pgxc_key_value; i++) { nulls[i] = false; values[i] = (Datum)0; } kvrel = heap_open(PgxcKeyValueRelationId, AccessExclusiveLock); for(i = 0; i < nValues; i++) { namestrcpy(&name, keyvalues[i]); values[Anum_pgxc_key_valuew_db - 1] = ObjectIdGetDatum(db); values[Anum_pgxc_key_values_rel - 1] = ObjectIdGetDatum(rel); values[Anum_pgxc_key_value_value - 1] = NameGetDatum(&name);; values[Anum_pgxc_key_value_group -1] = ObjectIdGetDatum(nodeGroup); values[Anum_pgxc_key_value_cold_group -1] = ObjectIdGetDatum(coldGroup); htup = heap_form_tuple(kvrel->rd_att, values, nulls); CatalogTupleInsert(kvrel, htup); } CommandCounterIncrement(); heap_close(kvrel, AccessExclusiveLock); /* tell other backend to refresh backend relcache of the rel */ relation = heap_open(rel,AccessShareLock); CacheInvalidateRelcache(relation); heap_close(relation,AccessShareLock); } /* * Check Key Value hot and cold group valid */ void CheckKeyValueGroupValid(Oid hot, Oid cold, bool create_table) {// #lizard forgives HeapScanDesc scan; HeapTuple tup; Form_pgxc_key_value pgxc_key_value; Relation rel; rel = heap_open(PgxcKeyValueRelationId, AccessShareLock); scan = heap_beginscan_catalog(rel, 0, NULL); tup = heap_getnext(scan,ForwardScanDirection); while(HeapTupleIsValid(tup)) { pgxc_key_value = (Form_pgxc_key_value)GETSTRUCT(tup); if (OidIsValid(cold)) { if (OidIsValid(pgxc_key_value->nodegroup)) { if(cold == pgxc_key_value->nodegroup) { elog(ERROR, "cold group %u conflict exist table:%u key value:%s hot group %u", cold, pgxc_key_value->reloid, NameStr(pgxc_key_value->keyvalue), pgxc_key_value->nodegroup); } } if (create_table) { if (OidIsValid(pgxc_key_value->coldnodegroup)) { if(cold == pgxc_key_value->coldnodegroup) { elog(ERROR, "cold group %u conflict exist key value cold group %u", cold, pgxc_key_value->coldnodegroup); } } } } if (OidIsValid(hot)) { if (OidIsValid(pgxc_key_value->coldnodegroup)) { if(hot == pgxc_key_value->coldnodegroup) { elog(ERROR, "hot group %u conflict exist key value cold group %u", hot, pgxc_key_value->coldnodegroup); } } } tup = heap_getnext(scan,ForwardScanDirection); } heap_endscan(scan); heap_close(rel, AccessShareLock); } /* * Check Key Value hot and cold group valid */ void CheckPgxcGroupValid(Oid tablehot) { HeapScanDesc scan; HeapTuple tup; Form_pgxc_key_value pgxc_key_value; Relation rel; if (!OidIsValid(tablehot)) { return; } rel = heap_open(PgxcKeyValueRelationId, AccessShareLock); scan = heap_beginscan_catalog(rel, 0, NULL); tup = heap_getnext(scan,ForwardScanDirection); while(HeapTupleIsValid(tup)) { pgxc_key_value = (Form_pgxc_key_value)GETSTRUCT(tup); if (OidIsValid(pgxc_key_value->nodegroup)) { if(tablehot == pgxc_key_value->nodegroup) { elog(ERROR, "table hot group %u conflict exist key value hot group %u", tablehot, pgxc_key_value->nodegroup); } } tup = heap_getnext(scan,ForwardScanDirection); } heap_endscan(scan); heap_close(rel, AccessShareLock); } bool GatherRelationKeyValueGroup(Oid relation, int32 *hot, Oid **group, int32 *cold, Oid **coldgroup) {// #lizard forgives bool found = false; bool exist = false; int32 i = 0; int32 hotNum = 0; int32 coldNum = 0; Oid hotGroup[MAX_SHARDING_NODE_GROUP]; Oid coldGroup[MAX_SHARDING_NODE_GROUP]; HeapScanDesc scan; HeapTuple tup; Form_pgxc_key_value pgxc_key_value; Relation rel; rel = heap_open(PgxcKeyValueRelationId, AccessShareLock); scan = heap_beginscan_catalog(rel, 0, NULL); tup = heap_getnext(scan,ForwardScanDirection); exist = false; while(HeapTupleIsValid(tup)) { pgxc_key_value = (Form_pgxc_key_value)GETSTRUCT(tup); if(relation == pgxc_key_value->reloid) { exist = true; if (OidIsValid(pgxc_key_value->nodegroup)) { found = false; for (i = 0; i < hotNum; i++) { if (hotGroup[i] == pgxc_key_value->nodegroup) { found = true; break; } } if (!found && i < MAX_SHARDING_NODE_GROUP) { hotGroup[i] = pgxc_key_value->nodegroup; hotNum++; } } if (OidIsValid(pgxc_key_value->coldnodegroup)) { found = false; for (i = 0; i < coldNum; i++) { if (coldGroup[i] == pgxc_key_value->coldnodegroup) { found = true; break; } } if (!found && i < MAX_SHARDING_NODE_GROUP) { coldGroup[i] = pgxc_key_value->coldnodegroup; coldNum++; } } } tup = heap_getnext(scan,ForwardScanDirection); } heap_endscan(scan); heap_close(rel, AccessShareLock); if (exist) { *hot = hotNum; if (*hot) { *group = (Oid*)palloc(sizeof(Oid) * hotNum); memcpy((void*)*group, (void*)hotGroup, sizeof(Oid) * hotNum); } *cold = coldNum; if (*cold) { *coldgroup = (Oid*)palloc(sizeof(Oid) * coldNum); memcpy((void*)*coldgroup, (void*)coldGroup, sizeof(Oid) * coldNum); } } return exist; } void GetRelationSecondGroup(Oid rel, Oid **groups, int32 *nGroup) {// #lizard forgives bool dup; int32 i; int32 numGroup = 0; Relation keyvalue; SysScanDesc scan; HeapTuple tuple; Form_pgxc_key_value pgxc_keyvalue; ScanKeyData skey[2]; Oid groupvec[MAX_SHARDING_NODE_GROUP]; keyvalue = heap_open(PgxcKeyValueRelationId, AccessShareLock); ScanKeyInit(&skey[0], Anum_pgxc_key_valuew_db, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(MyDatabaseId)); ScanKeyInit(&skey[1], Anum_pgxc_key_values_rel, BTEqualStrategyNumber, F_OIDEQ, ObjectIdGetDatum(rel)); scan = systable_beginscan(keyvalue, PgxcShardKeyGroupIndexID,true, NULL, 2, skey); numGroup = 0; tuple = systable_getnext(scan); while(HeapTupleIsValid(tuple)) { pgxc_keyvalue = (Form_pgxc_key_value) GETSTRUCT(tuple); /* hot node group */ dup = false; for (i = 0; i < numGroup; i++) { if (groupvec[i] == pgxc_keyvalue->nodegroup) { dup = true; break; } } if (!dup) { groupvec[numGroup] = pgxc_keyvalue->nodegroup; numGroup++; } /* cold node group */ if (OidIsValid(pgxc_keyvalue->coldnodegroup)) { dup = false; for (i = 0; i < numGroup; i++) { if (groupvec[i] == pgxc_keyvalue->coldnodegroup) { dup = true; break; } } if (!dup) { groupvec[numGroup] = pgxc_keyvalue->coldnodegroup; numGroup++; } } tuple = systable_getnext(scan); } systable_endscan(scan); heap_close(keyvalue,AccessShareLock); if (numGroup) { *nGroup = numGroup; *groups = (Oid*)palloc(sizeof(Oid) * numGroup); memcpy((char*)*groups, (char*)groupvec, sizeof(Oid) * numGroup); } else { *nGroup = 0; } } char *BuildKeyValueCheckoverlapsStr(Oid hotgroup, Oid coldgroup) {// #lizard forgives int32 offset = 0; int32 i = 0; int32 hotNumber = 0; int32 coldNumber = 0; Oid *hotGroupMem = NULL; Oid *coldGroupMem = NULL; char *string = NULL; char *nodename = NULL; if (OidIsValid(hotgroup)) { if (!is_group_sharding_inited(hotgroup)) { elog(ERROR, "please initialize group:%u sharding map first", hotgroup); } hotNumber = get_pgxc_groupmembers(hotgroup, &hotGroupMem); offset = 0; string = (char*)palloc0(BLCKSZ); offset = snprintf(string, BLCKSZ, "CHECK OVERLAPS "); for (i = 0; i < hotNumber; ) { nodename = get_pgxc_nodename(hotGroupMem[i]); offset += snprintf(string + offset, BLCKSZ - offset, "%s", nodename); pfree(nodename); i++; if (i < hotNumber) { offset += snprintf(string + offset, BLCKSZ - offset, ","); } } pfree(hotGroupMem); if (OidIsValid(coldgroup)) { if (!is_group_sharding_inited(coldgroup)) { elog(ERROR, "please initialize group:%u sharding map first", coldgroup); } coldNumber = get_pgxc_groupmembers(coldgroup, &coldGroupMem); if (coldNumber) { offset += snprintf(string + offset, BLCKSZ - offset, " TO "); for (i = 0; i < coldNumber; ) { nodename = get_pgxc_nodename(coldGroupMem[i]); offset += snprintf(string + offset, BLCKSZ - offset, "%s", nodename); pfree(nodename); i++; if (i < coldNumber) { offset += snprintf(string + offset, BLCKSZ - offset, ","); } } pfree(coldGroupMem); } } offset += snprintf(string + offset, BLCKSZ - offset, ";"); return string; } return NULL; } char *BuildRelationCheckoverlapsStr(DistributeBy *distributeby, PGXCSubCluster *subcluster) {// #lizard forgives int32 offset = 0; int32 i = 0; int32 hotNumber = 0; int32 coldNumber = 0; int32 groupNum = 0; Oid group[2] = {InvalidOid}; /* max 2 groups to distribute */ Oid *hotGroupMem = NULL; Oid *coldGroupMem = NULL; char *string = NULL; char *nodename = NULL; if (distributeby) { if(DISTTYPE_SHARD == distributeby->disttype) { groupNum = GetDistributeGroup(subcluster, distributeby->disttype, group); if (groupNum) { if (!is_group_sharding_inited(group[0])) { elog(ERROR, "please initialize group:%u sharding map first", group[0]); } hotNumber = get_pgxc_groupmembers(group[0], &hotGroupMem); if (groupNum > 1) { if (!is_group_sharding_inited(group[1])) { elog(ERROR, "please initialize group:%u sharding map first", group[1]); } coldNumber = get_pgxc_groupmembers(group[1], &coldGroupMem); } } if (hotNumber || coldNumber) { offset = 0; string = (char*)palloc0(BLCKSZ); offset = snprintf(string, BLCKSZ, "CHECK OVERLAPS "); for (i = 0; i < hotNumber; ) { nodename = get_pgxc_nodename(hotGroupMem[i]); offset += snprintf(string + offset, BLCKSZ - offset, "%s", nodename); pfree(nodename); i++; if (i < hotNumber) { offset += snprintf(string + offset, BLCKSZ - offset, ","); } } pfree(hotGroupMem); if (coldNumber) { offset += snprintf(string + offset, BLCKSZ - offset, " TO "); for (i = 0; i < coldNumber; ) { nodename = get_pgxc_nodename(coldGroupMem[i]); offset += snprintf(string + offset, BLCKSZ - offset, "%s", nodename); pfree(nodename); i++; if (i < coldNumber) { offset += snprintf(string + offset, BLCKSZ - offset, ","); } } pfree(coldGroupMem); } offset += snprintf(string + offset, BLCKSZ - offset, ";"); return string; } } } return NULL; } Oid GetKeyValuesGroup(Oid db, Oid rel, char *value, Oid *coldgroup) { Oid group; HeapTuple tup; Form_pgxc_key_value keyvalue; tup = SearchSysCache(SHARDKEYVALUE, ObjectIdGetDatum(db), ObjectIdGetDatum(rel), CStringGetDatum(value), 0); if (!HeapTupleIsValid(tup)) { return InvalidOid; } keyvalue = (Form_pgxc_key_value) GETSTRUCT(tup); group = keyvalue->nodegroup; *coldgroup = keyvalue->coldnodegroup; ReleaseSysCache(tup); return group; } bool IsKeyValues(Oid db, Oid rel, char *value) { return SearchSysCacheExists(SHARDKEYVALUE, ObjectIdGetDatum(db), ObjectIdGetDatum(rel), CStringGetDatum(value), 0); }
33.303079
192
0.534164
bd337900006b6d5b0865204eb054683c10c45ea2
7,647
html
HTML
_ng1_docs/0.2.14/site/partials/api/ui.router.util.$templateFactory.html
RajeshRP/ui-router.github.io
5a98c73171ec501a7b8319bfe1d2434d676940d6
[ "MIT" ]
4
2016-09-06T08:40:16.000Z
2018-07-18T13:48:24.000Z
_ng1_docs/0.2.14/site/partials/api/ui.router.util.$templateFactory.html
RajeshRP/ui-router.github.io
5a98c73171ec501a7b8319bfe1d2434d676940d6
[ "MIT" ]
25
2016-10-20T23:51:56.000Z
2020-12-21T21:14:44.000Z
_ng1_docs/0.2.14/site/partials/api/ui.router.util.$templateFactory.html
RajeshRP/ui-router.github.io
5a98c73171ec501a7b8319bfe1d2434d676940d6
[ "MIT" ]
40
2016-08-04T14:35:29.000Z
2020-05-08T03:13:16.000Z
<h1><code ng:non-bindable="">$templateFactory</code> <div><span class="hint">service in module <code ng:non-bindable="">ui.router.util</code> </span> </div> </h1> <div><h2 id="description">Description</h2> <div class="description"><div class="ui-router-util-templatefactory-page"><p>Service. Manages loading of templates.</p> </div></div> <h2 id="dependencies">Dependencies</h2> <ul class="dependencies"><li><code ng:non-bindable=""><a href="#/api/ng.$http">$http</a></code> </li> <li><code ng:non-bindable=""><a href="#/api/ng.$templateCache">$templateCache</a></code> </li> <li><code ng:non-bindable=""><a href="#/api/ng.$injector">$injector</a></code> </li> </ul> <div class="member method"><h2 id="methods">Methods</h2> <ul class="methods"><li><h3 id="methods_fromconfig">fromConfig(config, params, locals)</h3> <div class="fromconfig"><div class="ui-router-util-templatefactory-fromconfig-page"><p>Creates a template from a configuration object. </p> </div><h5 id="methods_fromconfig_parameters">Parameters</h5><table class="variables-matrix table table-bordered table-striped"><thead><tr><th>Param</th><th>Type</th><th>Details</th></tr></thead><tbody><tr><td>config</td><td><a href="" class="label type-hint type-hint-object">object</a></td><td><div class="ui-router-util-templatefactory-fromconfig-page"><p>Configuration object for which to load a template. The following properties are search in the specified order, and the first one that is defined is used to create the template:</p> </div></td></tr><tr><td>config.template</td><td><a href="" class="label type-hint type-hint-string">string</a><a href="" class="label type-hint type-hint-object">object</a></td><td><div class="ui-router-util-templatefactory-fromconfig-page"><p>html string template or function to load via <a href="#/api/ui.router.util.$templateFactory#fromstring">fromString</a>.</p> </div></td></tr><tr><td>config.templateUrl</td><td><a href="" class="label type-hint type-hint-string">string</a><a href="" class="label type-hint type-hint-object">object</a></td><td><div class="ui-router-util-templatefactory-fromconfig-page"><p>url to load or a function returning the url to load via <a href="#/api/ui.router.util.$templateFactory#fromurl">fromUrl</a>.</p> </div></td></tr><tr><td>config.templateProvider</td><td><a href="" class="label type-hint type-hint-function">Function</a></td><td><div class="ui-router-util-templatefactory-fromconfig-page"><p>function to invoke via <a href="#/api/ui.router.util.$templateFactory#fromprovider">fromProvider</a>.</p> </div></td></tr><tr><td>params</td><td><a href="" class="label type-hint type-hint-object">object</a></td><td><div class="ui-router-util-templatefactory-fromconfig-page"><p>Parameters to pass to the template function.</p> </div></td></tr><tr><td>locals</td><td><a href="" class="label type-hint type-hint-object">object</a></td><td><div class="ui-router-util-templatefactory-fromconfig-page"><p>Locals to pass to <code>invoke</code> if the template is loaded via a <code>templateProvider</code>. Defaults to <code>{ params: params }</code>.</p> </div></td></tr></tbody></table><h5 id="methods_fromconfig_returns">Returns</h5><table class="variables-matrix"><tr><td><a href="" class="label type-hint type-hint-string">string|object</a></td><td><div class="ui-router-util-templatefactory-fromconfig-page"><p>The template html as a string, or a promise for that string,or <code>null</code> if no template is configured.</p> </div></td></tr></table></div> </li> <li><h3 id="methods_fromprovider">fromProvider(provider, params, locals)</h3> <div class="fromprovider"><div class="ui-router-util-templatefactory-fromprovider-page"><p>Creates a template by invoking an injectable provider function.</p> </div><h5 id="methods_fromprovider_parameters">Parameters</h5><table class="variables-matrix table table-bordered table-striped"><thead><tr><th>Param</th><th>Type</th><th>Details</th></tr></thead><tbody><tr><td>provider</td><td><a href="" class="label type-hint type-hint-function">Function</a></td><td><div class="ui-router-util-templatefactory-fromprovider-page"><p>Function to invoke via <code>$injector.invoke</code></p> </div></td></tr><tr><td>params</td><td><a href="" class="label type-hint type-hint-object">Object</a></td><td><div class="ui-router-util-templatefactory-fromprovider-page"><p>Parameters for the template.</p> </div></td></tr><tr><td>locals</td><td><a href="" class="label type-hint type-hint-object">Object</a></td><td><div class="ui-router-util-templatefactory-fromprovider-page"><p>Locals to pass to <code>invoke</code>. Defaults to <code>{ params: params }</code>.</p> </div></td></tr></tbody></table><h5 id="methods_fromprovider_returns">Returns</h5><table class="variables-matrix"><tr><td><a href="" class="label type-hint type-hint-string">string|Promise.&lt;string&gt;</a></td><td><div class="ui-router-util-templatefactory-fromprovider-page"><p>The template html as a string, or a promise for that string.</p> </div></td></tr></table></div> </li> <li><h3 id="methods_fromstring">fromString(template, params)</h3> <div class="fromstring"><div class="ui-router-util-templatefactory-fromstring-page"><p>Creates a template from a string or a function returning a string.</p> </div><h5 id="methods_fromstring_parameters">Parameters</h5><table class="variables-matrix table table-bordered table-striped"><thead><tr><th>Param</th><th>Type</th><th>Details</th></tr></thead><tbody><tr><td>template</td><td><a href="" class="label type-hint type-hint-string">string</a><a href="" class="label type-hint type-hint-object">object</a></td><td><div class="ui-router-util-templatefactory-fromstring-page"><p>html template as a string or function that returns an html template as a string.</p> </div></td></tr><tr><td>params</td><td><a href="" class="label type-hint type-hint-object">object</a></td><td><div class="ui-router-util-templatefactory-fromstring-page"><p>Parameters to pass to the template function.</p> </div></td></tr></tbody></table><h5 id="methods_fromstring_returns">Returns</h5><table class="variables-matrix"><tr><td><a href="" class="label type-hint type-hint-string">string|object</a></td><td><div class="ui-router-util-templatefactory-fromstring-page"><p>The template html as a string, or a promise for that string.</p> </div></td></tr></table></div> </li> <li><h3 id="methods_fromurl">fromUrl(url, params)</h3> <div class="fromurl"><div class="ui-router-util-templatefactory-fromurl-page"><p>Loads a template from the a URL via <code>$http</code> and <code>$templateCache</code>.</p> </div><h5 id="methods_fromurl_parameters">Parameters</h5><table class="variables-matrix table table-bordered table-striped"><thead><tr><th>Param</th><th>Type</th><th>Details</th></tr></thead><tbody><tr><td>url</td><td><a href="" class="label type-hint type-hint-string">string</a><a href="" class="label type-hint type-hint-function">Function</a></td><td><div class="ui-router-util-templatefactory-fromurl-page"><p>url of the template to load, or a function that returns a url.</p> </div></td></tr><tr><td>params</td><td><a href="" class="label type-hint type-hint-object">Object</a></td><td><div class="ui-router-util-templatefactory-fromurl-page"><p>Parameters to pass to the url function.</p> </div></td></tr></tbody></table><h5 id="methods_fromurl_returns">Returns</h5><table class="variables-matrix"><tr><td><a href="" class="label type-hint type-hint-string">string|Promise.&lt;string&gt;</a></td><td><div class="ui-router-util-templatefactory-fromurl-page"><p>The template html as a string, or a promise for that string.</p> </div></td></tr></table></div> </li> </ul> </div> </div>
114.134328
464
0.717667
bed56554069e3f6bad6ce6e5bb7078f8e8bc50f4
1,383
ts
TypeScript
src/index.ts
PSPDFKit-labs/pdfjs-web-component
1b660f751b744cf6d74d583452e0e7a85ddfb6c8
[ "MIT" ]
3
2020-02-06T11:47:56.000Z
2022-03-11T17:36:55.000Z
src/index.ts
PSPDFKit-labs/pdfjs-web-component
1b660f751b744cf6d74d583452e0e7a85ddfb6c8
[ "MIT" ]
null
null
null
src/index.ts
PSPDFKit-labs/pdfjs-web-component
1b660f751b744cf6d74d583452e0e7a85ddfb6c8
[ "MIT" ]
null
null
null
import pdfjs from 'pdfjs-dist'; class MyPdfElement extends HTMLElement { readyPromise: Promise<void> resolveReady: () => void static get observedAttributes() { return ['pdf']; } constructor() { super(); this.readyPromise = new Promise((resolve) => { this.resolveReady = resolve; }); } connectedCallback() { this.resolveReady(); this.attachShadow({mode: 'open'}); this.shadowRoot.innerHTML = ` <style> canvas { box-shadow: 0 3px 6px #0004; border-radius: 6px; } </style> <canvas></canvas> ` } attributeChangedCallback(attr: string, oldVal: string, val: string) { if (attr === 'pdf' && val != null) { console.log(`[MyPdfElement] PDF path changed from ${oldVal} to ${val}.`); this.setPdf(val); } } async setPdf(path: string) { await this.readyPromise; console.log(`[MyPdfElement] Loading PDF at path ${path}.`); const pdf = await pdfjs.getDocument(path).promise; const page = await pdf.getPage(1); const viewport = page.getViewport(1); const canvas: HTMLCanvasElement = this.shadowRoot.querySelector('canvas'); const ctx = canvas.getContext('2d'); canvas.width = viewport.width; canvas.height = viewport.height; const renderCtx: pdfjs.PDFRenderParams = { canvasContext: ctx, viewport: viewport, }; page.render(renderCtx); } } customElements.define('x-pdf', MyPdfElement);
20.954545
76
0.665221
cddd7f3bbd10ca47edbf14b5337814ea2d55d287
1,852
cs
C#
benchmark_runner/src/SqlOptimizerBechmark/SqlOptimizerBenchmark/Benchmark/StatementList.cs
RadimBaca/QueryOptimizerBenchmark
e4ef5ec1dcc6b92f513c1174228311f9f7987c66
[ "Apache-2.0" ]
1
2021-02-22T14:40:43.000Z
2021-02-22T14:40:43.000Z
benchmark_runner/src/SqlOptimizerBechmark/SqlOptimizerBenchmark/Benchmark/StatementList.cs
RadimBaca/QueryOptimizerBenchmark
e4ef5ec1dcc6b92f513c1174228311f9f7987c66
[ "Apache-2.0" ]
null
null
null
benchmark_runner/src/SqlOptimizerBechmark/SqlOptimizerBenchmark/Benchmark/StatementList.cs
RadimBaca/QueryOptimizerBenchmark
e4ef5ec1dcc6b92f513c1174228311f9f7987c66
[ "Apache-2.0" ]
1
2021-02-22T14:40:57.000Z
2021-02-22T14:40:57.000Z
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SqlOptimizerBenchmark.Benchmark { public class StatementList : BenchmarkObject { private Script script; private ObservableCollection<Statement> statements = new ObservableCollection<Statement>(); public override IBenchmarkObject ParentObject => script; public override IEnumerable<IBenchmarkObject> ChildObjects { get { foreach (Statement statement in statements) { yield return statement; } } } public ObservableCollection<Statement> Statements { get => statements; } public StatementList(Script script) { this.script = script; statements.CollectionChanged += Statements_CollectionChanged; } private void Statements_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { NotifyChange(); } public override void SaveToXml(BenchmarkXmlSerializer serializer) { serializer.WriteCollection<Statement>("statements", "statement", statements); } public override void LoadFromXml(BenchmarkXmlSerializer serializer) { serializer.ReadCollection<Statement>("statements", "statement", statements, delegate () { return new Statement(this); }); } public override DbTableInfo GetTableInfo() { DbTableInfo ret = base.GetTableInfo(); ret.TableName = "StatementList"; return ret; } } }
27.641791
131
0.62041
9b3ae6a3f2ec701373829c394bfb6468001afd83
16,761
lua
Lua
flufachievements/lua/autorun/client/flufchieve_achievementui.lua
snortlines/Achievements
c42a6fa467ffd27234bb93ce52b649697233f55b
[ "MIT" ]
4
2018-08-21T18:18:20.000Z
2020-01-12T18:57:58.000Z
flufachievements/lua/autorun/client/flufchieve_achievementui.lua
snortlines/Achievements
c42a6fa467ffd27234bb93ce52b649697233f55b
[ "MIT" ]
null
null
null
flufachievements/lua/autorun/client/flufchieve_achievementui.lua
snortlines/Achievements
c42a6fa467ffd27234bb93ce52b649697233f55b
[ "MIT" ]
null
null
null
--[[---------------------------------------------------------------------- ______ ________ / __/ /_ __/ __/ __/_ __ / /_/ / / / / /_/ /_/ / / / / __/ / /_/ / __/ __/ /_/ / /_/ /_/\__,_/_/ /_/ \__, / ___ __ /____/ __ / | _____/ /_ (_)__ _ _____ ____ ___ ___ ____ / /______ / /| |/ ___/ __ \/ / _ \ | / / _ \/ __ `__ \/ _ \/ __ \/ __/ ___/ / ___ / /__/ / / / / __/ |/ / __/ / / / / / __/ / / / /_(__ ) /_/ |_\___/_/ /_/_/\___/|___/\___/_/ /_/ /_/\___/_/ /_/\__/____/ ------------------------------------------------------------------------]] floofAchievements = floofAchievements or {} surface.CreateFont( "flufChieve_Buttons", { font = "Roboto Lt", size = 16, antialias = true, weight = 1 } ) surface.CreateFont( "flufChieve_ButtonsSmall", { font = "Roboto Lt", size = 14, antialias = true, weight = 1 } ) surface.CreateFont( "flufChieve_ButtonsExtraSmall", { font = "Roboto Lt", size = 13, antialias = true, weight = 1 } ) surface.CreateFont( "flufChieve_ButtonsTitle", { font = "Roboto Lt", size = 20, antialias = true, weight = 1 } ) --[[--------------------------------------------------------- Name: xPos - So I don't have to type ( ScrW() / 2 ) * .1 -----------------------------------------------------------]] local function x( times ) return ( ScrW() / 2 ) * times end --[[--------------------------------------------------------- Name: yPos - So I don't have to type ( ScrH() / 2 ) * .1 -----------------------------------------------------------]] local function y( times ) return ( ScrH() / 2 ) * times end local I = 0 local AI = 0 local gradient = Material( "gui/center_gradient" ) local icon = Material( "flufmaterials/icon.png" ) floofAchievements.Active = false floofAchievements.pnl = nil local blur = Material( "pp/blurscreen" ) local function DrawBlur( panel, amount ) local x, y = panel:LocalToScreen( 0, 0 ) local scrW, scrH = ScrW(), ScrH() surface.SetDrawColor( 255, 255, 255, 255 ) surface.SetMaterial( blur ) for i = 1, 3 do blur:SetFloat( "$blur", ( i / 3 ) * ( amount or 6 ) ) blur:Recompute() render.UpdateScreenEffectTexture() surface.DrawTexturedRect( x * -1, y * -1, scrW, scrH ) end end local PANEL = {} --[[--------------------------------------------------------- Name: Category Holder Desc: Holds all of our categories -----------------------------------------------------------]] function PANEL:CreateCategoryHolder() self.CategoryHolder = vgui.Create( "DFrame", self ) self.CategoryHolder:SetPos( 0, 0 ) self.CategoryHolder:SetSize( x( .25 ), self:GetTall() ) self.CategoryHolder:SetTitle( "" ) self.CategoryHolder:ShowCloseButton( false ) self.CategoryHolder:SetDraggable( false ) self.CategoryHolder.Paint = function( p, w, h ) draw.RoundedBox( 0, 0, 0, w, h, Color( 0, 0, 0, 175 ) ) draw.RoundedBox( 0, x( .249 ), 0, x( .001 ), h, Color( 0, 0, 0, 175 ) ) end self.Exit = vgui.Create( "DButton", self.CategoryHolder ) self.Exit:SetPos( x( .01 ), y( 1.13 ) ) self.Exit:SetSize( x( .23 ), y( .05 ) ) self.Exit:SetText( "" ) self.Exit.Paint = function( p, w, h ) draw.RoundedBox( 0, 0, 0, w, h, Color( 0, 0, 0, 100 ) ) draw.RoundedBox( 0, 0, y( .047 ), w, y( .002 ), Color( 68, 123, 17, 100 ) ) draw.DrawText( "Exit", "flufChieve_Buttons", x( .002 ), y( .005 ), p:IsHovered() and Color( 68, 123, 17, 100 ) or Color( 255, 255, 255, 255 ), TEXT_ALIGN_LEFT ) end self.Exit.DoClick = function() self:Remove() end return self.CategoryHolder end --[[--------------------------------------------------------- Name: Category Buttons Desc: Creates our button(s) -----------------------------------------------------------]] function PANEL:CreateCategoryButton( parent, text, func ) func = func or function() return end self.CategoryButton = vgui.Create( "DButton", parent ) self.CategoryButton:SetPos( x( .01 ), ( y( .0198 ) + y( I ) ) ) self.CategoryButton:SetSize( x( .23 ), y( .05 ) ) self.CategoryButton:SetText( "" ) self.CategoryButton.Paint = function( p, w, h ) draw.RoundedBox( 0, 0, 0, w, h, Color( 0, 0, 0, 100 ) ) draw.RoundedBox( 0, 0, y( .047 ), w, y( .002 ), Color( 68, 123, 17, 100 ) ) draw.DrawText( text, "flufChieve_Buttons", x( .002 ), y( .005 ), p:IsHovered() and Color( 68, 123, 17, 100 ) or Color( 255, 255, 255, 255 ), TEXT_ALIGN_LEFT ) surface.SetDrawColor( Color( 0, 0, 0, 100 ) ) surface.DrawOutlinedRect( 0, 0, w, h ) end self.CategoryButton.DoClick = func I = I + .06 return self.CategoryButton end --[[--------------------------------------------------------- Name: Summary Panel Desc: Very different than our normal panels. -----------------------------------------------------------]] function PANEL:CreateSummaryPanel() AI = 0 if ( IsValid( self.SummaryPanel ) ) then self.SummaryPanel:Remove() end if ( IsValid( self.AchievementPanel ) ) then self.AchievementPanel:Remove() end local maxAchieve = math.min( floofAchievements.TotalCreatedAchievements, ( floofAchievements.CompletedAchivements == floofAchievements.TotalCreatedAchievements and floofAchievements.CompletedAchivements ) or 0 ) local ratio = math.Min( floofAchievements.CompletedAchivements / floofAchievements.TotalCreatedAchievements, 1 ) self.SummaryPanel = vgui.Create( "DFrame", self ) self.SummaryPanel:SetPos( x( .25 ) , 0 ) self.SummaryPanel:SetSize( self:GetWide(), self:GetTall() ) self.SummaryPanel:SetTitle( "" ) self.SummaryPanel:ShowCloseButton( false ) self.SummaryPanel:SetDraggable( false ) self.SummaryPanel.Paint = function( p, w, h ) draw.RoundedBox( 0, 0, 0, w, h, Color( 0, 0, 0, 175 ) ) surface.SetDrawColor( Color( 0, 0, 0, 150 ) ) surface.SetMaterial( gradient ) surface.DrawTexturedRect( x( .02 ), y( .02 ), x( .7 ), y( .05 ) ) surface.DrawTexturedRect( x( .02 ), y( .73 ), x( .7 ), y( .05 ) ) draw.DrawText( "Recent Achievements", "flufChieve_Buttons", x( .36 ), y( .025 ), Color( 255, 255, 255, 255 ), TEXT_ALIGN_CENTER ) draw.DrawText( "Progress Overview", "flufChieve_Buttons", x( .355 ), y( .735 ), Color( 255, 255, 255, 255 ), TEXT_ALIGN_CENTER ) surface.SetDrawColor( Color( 0, 0, 0, 175 ) ) surface.DrawOutlinedRect( x( .009 ), y( .799 ), x( .7314 ), y( .05 ) ) draw.RoundedBox( 0, x( .009 ), y( .8 ), x( .729 ) * ratio, y( .046 ), Color( 0, 100, 0, 175 ) ) draw.DrawText( floofAchievements.CompletedAchivements .. "/" .. floofAchievements.TotalCreatedAchievements, "flufChieve_Buttons", x( .73 ), y( .803 ), Color( 255, 255, 255, 255 ), TEXT_ALIGN_RIGHT ) draw.DrawText( "Achievements Earned", "flufChieve_Buttons", x( .015 ), y( .803 ), Color( 255, 255, 255, 255 ), TEXT_ALIGN_LEFT ) if ( #floofAchievements.RecentAchievements < 1 ) then draw.DrawText( "Complete Achievements to see your recent Achievements!", "flufChieve_Buttons", x( .36 ), y( .08 ), Color( 255, 255, 255, 255 ), TEXT_ALIGN_CENTER ) end end for k, v in pairs( floofAchievements.RecentAchievements ) do local mat if ( v.unlocked ) then mat = Material( "flufmaterials/checked.png" ) else mat = Material( "flufmaterials/cross.png" ) end self.RecentAchievement = vgui.Create( "DButton", self.SummaryPanel ) self.RecentAchievement:SetPos( x( .009 ), ( y( .0798 ) + y( AI ) ) ) self.RecentAchievement:SetSize( x( .733 ), y( .12 ) ) self.RecentAchievement:SetText( "" ) self.RecentAchievement.Paint = function( p, w, h ) draw.RoundedBox( 0, 0, 0, w, h, Color( 0, 0, 0, 100 ) ) surface.SetDrawColor( Color( 0, 0, 0, 175 ) ) surface.DrawOutlinedRect( 0, 0, w, h ) if ( v.unlocked ) then surface.SetDrawColor( Color( 0, 100, 0, 255 ) ) surface.SetMaterial( mat ) surface.DrawTexturedRect( x( .7 ), y( .015 ), 16, 16 ) else surface.SetDrawColor( Color( 100, 0, 0, 255 ) ) surface.SetMaterial( mat ) surface.DrawTexturedRect( x( .7 ), y( .015 ), 16, 16 ) end surface.SetDrawColor( Color( 0, 0, 0, 150 ) ) surface.SetMaterial( gradient ) surface.DrawTexturedRect( x( .01 ), y( .01 ), x( .7 ), y( .05 ) ) draw.DrawText( v.title, "flufChieve_ButtonsTitle", x( .35 ), y( .01 ), Color( 255, 255, 255, 200 ), TEXT_ALIGN_CENTER ) draw.DrawText( v.description, "flufChieve_Buttons", x( .35 ), y( .06 ), Color( 255, 255, 255, 200 ), TEXT_ALIGN_CENTER ) draw.DrawText( v.unlockdate, "flufChieve_ButtonsSmall", x( .69 ), y( .017 ), Color( 255, 255, 255, 100 ), TEXT_ALIGN_RIGHT ) surface.SetDrawColor( Color( 0, 0, 0, 200 ) ) surface.SetMaterial( icon ) surface.DrawTexturedRect( x( .01 ), y( .01 ), 32, 32 ) end AI = AI + .13 end return self.SummaryPanel end --[[--------------------------------------------------------- Name: Achievement Panel Desc: Here's where we're going to store our Achievements. -----------------------------------------------------------]] function PANEL:CreateAchievementPanel() if ( IsValid( self.AchievementPanel ) ) then self.AchievementPanel:Remove() end AI = 0 self.AchievementPanel = vgui.Create( "DScrollPanel", self ) self.AchievementPanel:SetPos( x( .25 ) , 0 ) self.AchievementPanel:SetSize( self:GetWide(), self:GetTall() ) self.AchievementPanel.Paint = function( p, w, h ) draw.RoundedBox( 0, 0, 0, w, h, Color( 0, 0, 0, 175 ) ) end return self.AchievementPanel end --[[--------------------------------------------------------- Name: Achievement Buttons Desc: Creates our button(s) -----------------------------------------------------------]] function PANEL:CreateAchievementButton( parent, title, desc, rewardType, rewardInt, unlocked, unlockdate, progress, needed, func ) func = func or function() return end local prefix = "Reward: " rewardType = rewardType or "" rewardInt = rewardInt or "" unlocked = tobool( unlocked ) if ( rewardType == "" or rewardType == nil ) then prefix = "" end local mat if ( unlocked ) then mat = Material( "flufmaterials/checked.png" ) else mat = Material( "flufmaterials/cross.png" ) end self.AchievementButton = vgui.Create( "DButton", parent ) self.AchievementButton:SetPos( x( .009 ), ( y( .0198 ) + y( AI ) ) ) self.AchievementButton:SetSize( x( .733 ), y( .2 ) ) self.AchievementButton:SetText( "" ) self.AchievementButton.Paint = function( p, w, h ) if ( progress != "" and needed != "" ) then local percentage = math.Clamp( progress / needed, 0, 1 ) local poly = { { x = x( .2 ), y = y( .198 ) }, { x = x( .2 ), y = y( .17 ) }, { x = x( .212 ), y = y( .15 ) }, { x = x( .4 ), y = y( .15 ) }, { x = x( .517 ), y = y( .15 ) }, { x = x( .529 ), y = y( .172 ) }, { x = x( .529 ), y = y( .198 ) }, } render.ClearStencil() render.SetStencilEnable(true) render.SetStencilWriteMask( 1 ) render.SetStencilTestMask( 1 ) render.SetStencilFailOperation( STENCILOPERATION_REPLACE ) render.SetStencilPassOperation( STENCILOPERATION_ZERO ) render.SetStencilZFailOperation( STENCILOPERATION_ZERO ) render.SetStencilCompareFunction( STENCILCOMPARISONFUNCTION_NEVER ) render.SetStencilReferenceValue( 1 ) surface.SetDrawColor( color_white ) draw.NoTexture() surface.DrawPoly( poly ) surface.DrawRect( x( .002 ), y( .172 ), x( .221 ), y( .028 ) ) surface.DrawRect( x( .51 ), y( .172 ), x( .221 ), y( .028 ) ) render.SetStencilFailOperation( STENCILOPERATION_ZERO ) render.SetStencilPassOperation( STENCILOPERATION_REPLACE ) render.SetStencilZFailOperation( STENCILOPERATION_ZERO ) render.SetStencilCompareFunction( STENCILCOMPARISONFUNCTION_EQUAL ) render.SetStencilReferenceValue( 1 ) draw.RoundedBox( 0, 0, y( .15 ), w * percentage, y( .05 ), Color( 0, 100, 0, 175 ) ) render.SetStencilEnable(false) render.ClearStencil() end draw.RoundedBox( 0, 0, 0, w, h, Color( 0, 0, 0, 100 ) ) surface.SetDrawColor( Color( 0, 0, 0, 175 ) ) surface.DrawOutlinedRect( 0, 0, w, h ) if ( unlocked ) then surface.SetDrawColor( Color( 0, 100, 0, 255 ) ) surface.SetMaterial( mat ) surface.DrawTexturedRect( x( .7 ), y( .015 ), 16, 16 ) else surface.SetDrawColor( Color( 100, 0, 0, 255 ) ) surface.SetMaterial( mat ) surface.DrawTexturedRect( x( .7 ), y( .015 ), 16, 16 ) end surface.SetDrawColor( Color( 0, 0, 0, 150 ) ) surface.SetMaterial( gradient ) surface.DrawTexturedRect( x( .01 ), y( .01 ), x( .7 ), y( .05 ) ) draw.DrawText( title, "flufChieve_ButtonsTitle", x( .35 ), y( .01 ), Color( 255, 255, 255, 200 ), TEXT_ALIGN_CENTER ) draw.DrawText( desc, "flufChieve_Buttons", x( .35 ), y( .06 ), Color( 255, 255, 255, 200 ), TEXT_ALIGN_CENTER ) draw.DrawText( prefix .. rewardInt .. " " .. rewardType, "flufChieve_Buttons", x( .36 ), y( .15 ), Color( 255, 255, 255, 200 ), TEXT_ALIGN_CENTER ) draw.DrawText( unlockdate or "", "flufChieve_ButtonsSmall", x( .69 ), y( .015 ), Color( 255, 255, 255, 100 ), TEXT_ALIGN_RIGHT ) surface.SetDrawColor( Color( 0, 0, 0, 200 ) ) surface.SetMaterial( icon ) surface.DrawTexturedRect( x( .01 ), y( .01 ), 32, 32 ) if ( rewardType ~= "" or rewardTpye ~= nil ) then //DrawLine xdddd surface.DrawLine( x( .2 ), y( .17 ), 0, y( .17 ) ) surface.DrawLine( x( .2113 ), y( .15 ), x( .2 ), y( .17 ) ) surface.DrawLine( x( .4 ), y( .15 ), x( .211 ), y( .15 ) ) surface.DrawLine( x( .4 ), y( .15 ), x( .517 ), y( .15 ) ) surface.DrawLine( x( .517 ), y( .15 ), x( .529 ), y( .172 ) ) surface.DrawLine( x( .529 ), y( .171 ), x( .75 ), y( .171 ) ) end if ( progress != "" and needed != "" ) then draw.DrawText( "Progress: " .. progress .. "/" .. needed, "flufChieve_ButtonsExtraSmall", x( .002 ), y( .168 ), Color( 255, 255, 255, 100 ), TEXT_ALIGN_LEFT ) end end self.AchievementButton.OnMousePressed = function() func( self.AchievementButton, parent ) end AI = AI + .21 return self.AchievementButton end function PANEL:Init() I = 0 AI = 0 self:SetPos( x( .5 ), y( .4 ) ) self:SetSize( x( 1 ), y( 1.2 ) ) self:SetTitle( "" ) self:ShowCloseButton( false ) self:SetDraggable( false ) self:MakePopup() local cat = self:CreateCategoryHolder() self:CreateCategoryButton( cat, "Summary", function() self:CreateSummaryPanel() end ) for k, v in SortedPairsByValue( floofAchievements.Categories ) do self:CreateCategoryButton( cat, k, function() local AchievementFrame = self:CreateAchievementPanel() if ( IsValid( self.SummaryPanel ) ) then self.SummaryPanel:Remove() end for _, Achievements in SortedPairsByMemberValue( floofAchievements.Achievements, "unlocked" ) do if ( Achievements.category == k ) then self:CreateAchievementButton( AchievementFrame, Achievements.title, Achievements.description, Achievements.rewardType, Achievements.rewardInt, Achievements.unlocked, Achievements.unlockdate, Achievements.progress or "", Achievements.needed or "" ) end end end ) end floofAchievements.Active = true floofAchievements.pnl = self self:CreateSummaryPanel() end function PANEL:Paint( w, h ) DrawBlur( self, 5 ) draw.RoundedBox( 0, 0, 0, w, h, Color( 0, 0, 0, 175 ) ) surface.SetDrawColor( Color( 20, 20, 20, 200 ) ) surface.DrawOutlinedRect( 0, 0, w, h ) end derma.DefineControl( "flufchieve_achievementui", "", PANEL, "DFrame" )
35.814103
253
0.547879
a4251e7294e8ca473f03f0023b5dceebc0a48e71
4,862
c
C
lua/src/luaInterpreter.c
hidetzu/lua_emeded_c
ad2c74a9ee6ad110f9b75dab93b461b0ca2aa1a3
[ "Apache-2.0" ]
null
null
null
lua/src/luaInterpreter.c
hidetzu/lua_emeded_c
ad2c74a9ee6ad110f9b75dab93b461b0ca2aa1a3
[ "Apache-2.0" ]
null
null
null
lua/src/luaInterpreter.c
hidetzu/lua_emeded_c
ad2c74a9ee6ad110f9b75dab93b461b0ca2aa1a3
[ "Apache-2.0" ]
null
null
null
#include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <lua.h> #include <lualib.h> #include <lauxlib.h> #include "luaUtil.h" #define MAX_COLOR (255) typedef struct _ColorTable { char* name; unsigned char red; unsigned char green; unsigned char blue; }ColorTable; static void loadfile(lua_State* L, const char* fname); static int getfield(lua_State* L, const char* key); static void setfield(lua_State* L, const char* index, int value); static void setcolor(lua_State* L, ColorTable* ct); static void call_va(lua_State*L, const char* func, const char* sig, ...); static void call_va(lua_State*L, const char* func, const char* sig, ...) { va_list vl; int narg; /**< 引数の数 */ int nres; /**< 戻り値の数 */ va_start(vl, sig); /* 関数をプッシュする */ lua_getglobal(L, func); /* 引数を取り出してプッシュする*/ for(narg = 0; *sig; narg++) { luaL_checkstack(L, 1, "too many arguments"); switch(*sig++) { case 'd': lua_pushnumber(L, va_arg(vl,double)); break; case 'i': lua_pushnumber(L, va_arg(vl,int)); break; case 's': lua_pushstring(L, va_arg(vl,char*)); break; case '>': goto endargs; break; default: lua_errorAbort(L, "invalid option (%c)", *(sig-1)); break; } } endargs: nres = strlen(sig); if(lua_pcall(L, narg, nres, 0) != 0) lua_errorAbort(L, "error calling '%s' :%s", func, lua_tostring(L,-1)); nres = -nres; while(*sig) { switch(*sig++) { case 'd': if( !lua_isnumber(L, -1) ) { lua_errorAbort(L, "'wrong result type"); } { *va_arg(vl,double*) = lua_tonumber(L,nres); } break; case 'i': if( !lua_isnumber(L, -1) ) { lua_errorAbort(L, "'wrong result type"); } *va_arg(vl, int*) = lua_tonumber(L, nres); break; case 's': if( !lua_isstring(L, -1) ) { lua_errorAbort(L, "'wrong result type"); } *va_arg(vl, const char**) = lua_tostring(L, nres); break; default: lua_errorAbort(L, "invalid option (%c)", *(sig-1)); break; } nres++; } va_end(vl); return; } ColorTable colortable[] = { { "WHITE", MAX_COLOR, MAX_COLOR, MAX_COLOR}, { "RED", MAX_COLOR, 0, 0}, { NULL, 0, 0, 0}, }; static int getfield(lua_State* L, const char* key){ int result = 0; lua_pushstring(L, key); lua_gettable(L, -2); if(!lua_isnumber(L, -1)) { lua_errorAbort(L, "'invalied componet is background color"); } result = (int)lua_tonumber(L,-1); lua_pop(L,1); return result; } static void loadfile(lua_State* L, const char* fname) { if( luaL_loadfile(L, fname) || lua_pcall(L, 0, 0, 0) ) { lua_errorAbort(L, "cannot run config. file: %s", lua_tostring(L,-1)); } } static void setfield(lua_State* L, const char* index, int value) { lua_pushnumber(L, (double)value/MAX_COLOR); lua_setfield(L, -2, index); } static void setcolor(lua_State* L, ColorTable* ct) { lua_newtable(L); setfield(L, "r", ct->red); setfield(L, "g", ct->green); setfield(L, "b", ct->blue); lua_setglobal(L, ct->name); } #if 0 static void load(lua_State* L, const char* fname, int* w, int* h) { if( luaL_loadfile(L, fname) || lua_pcall(L, 0, 0, 0) ) { lua_errorAbort(L, "cannot run config. file: %s", lua_tostring(L,-1)); } lua_getglobal(L,"width"); lua_getglobal(L,"height"); if(!lua_isnumber(L,-2)) { lua_errorAbort(L, "'width' should be a number\n"); } if(!lua_isnumber(L,-1)) { lua_errorAbort(L, "'height' should be a number\n"); } *w = lua_tointeger(L, -2); *h = lua_tointeger(L, -1); } #endif int main(int argc, char const* argv[]) { lua_State* L = luaL_newstate(); luaL_openlibs(L); int i = 0; while(colortable[i].name != NULL ) setcolor(L, &colortable[i++]); loadfile(L,"./conf/config.lua"); call_va(L, "print", "s", "hello", "NULL"); double result = 0; call_va(L, "f", "dd>d", 2.0, 3.0, &result); printf("z=%lf\n", result); #if 0 int w = 0; int h = 0; load(L, "./script/config.lua", &w, &h); printf("width=%d\n", w); printf("height=%d\n", h); #endif lua_getglobal(L, "bcakground"); if(!lua_istable(L,-1)) lua_errorAbort(L, "'bcakground' is not a table"); int red = getfield(L, "r"); int green =getfield(L, "g"); int blue = getfield(L,"b"); printf("red=%d green=%d blue=%d\n", red,green,blue); lua_close(L); return 0; }
23.601942
78
0.541135
aebc1718759cb2c750698af46bf0acf8534556f7
1,587
psd1
PowerShell
eval/dsc/akshcihost/xActiveDirectory/3.0.0.0/DSCResources/MSFT_xADManagedServiceAccount/en-US/MSFT_xADManagedServiceAccount.strings.psd1
olaseniadeniji/aks-hci
39c54d080a5c9278903f7141be15b5e26ef9bad8
[ "MIT" ]
153
2017-09-27T14:21:28.000Z
2022-03-11T22:56:51.000Z
eval/dsc/akshcihost/xActiveDirectory/3.0.0.0/DSCResources/MSFT_xADManagedServiceAccount/en-US/MSFT_xADManagedServiceAccount.strings.psd1
olaseniadeniji/aks-hci
39c54d080a5c9278903f7141be15b5e26ef9bad8
[ "MIT" ]
138
2020-09-23T13:20:48.000Z
2022-03-29T18:27:56.000Z
eval/dsc/akshcihost/xActiveDirectory/3.0.0.0/DSCResources/MSFT_xADManagedServiceAccount/en-US/MSFT_xADManagedServiceAccount.strings.psd1
olaseniadeniji/aks-hci
39c54d080a5c9278903f7141be15b5e26ef9bad8
[ "MIT" ]
29
2017-08-18T14:59:00.000Z
2021-09-23T04:26:14.000Z
# culture='en-US' ConvertFrom-StringData @' AddingManagedServiceAccount = Adding AD Managed Service Account '{0}'. (MSA0001) RemovingManagedServiceAccount = Removing AD Managed Service Account '{0}'. (MSA0003) MovingManagedServiceAccount = Moving AD Managed Service Account '{0}' to '{1}'. (MSA0004) ManagedServiceAccountNotFound = AD Managed Service Account '{0}' was not found. (MSA0005) RetrievingServiceAccount = Retrieving AD Managed Service Account '{0}'. (MSA0006) AccountTypeForceNotTrue = The 'AccountTypeForce' was either not specified or set to false. To convert from a '{0}' MSA to a '{1}' MSA, AccountTypeForce must be set to true. (MSA0007) NotDesiredPropertyState = AD Managed Service Account '{0}' is not correct. Expected '{1}', actual '{2}'. (MSA0008) MSAInDesiredState = AD Managed Service Account '{0}' is in the desired state. (MSA0009) MSANotInDesiredState = AD Managed Service Account '{0}' is NOT in the desired state. (MSA0010) UpdatingManagedServiceAccountProperty = Updating AD Managed Service Account property '{0}' to '{1}'. (MSA0011) AddingManagedServiceAccountError = Error adding AD Managed Service Account '{0}'. (MSA0012) RetrievingPrincipalMembers = Retrieving Principals Allowed To Retrieve Managed Password based on '{0}' property. (MSA0013) RetrievingServiceAccountError = There was an error when retrieving the AD Managed Service Account '{0}'. (MSA0014) '@
93.352941
200
0.681159
f6bc448afe331afe6e174bafcc3f134143a999b9
1,388
lua
Lua
bin/Data/LuaScripts/Test.lua
cjmxp/Urho3D
a9998c5c0231a32ce866813c181a5719dbca4fce
[ "MIT" ]
null
null
null
bin/Data/LuaScripts/Test.lua
cjmxp/Urho3D
a9998c5c0231a32ce866813c181a5719dbca4fce
[ "MIT" ]
null
null
null
bin/Data/LuaScripts/Test.lua
cjmxp/Urho3D
a9998c5c0231a32ce866813c181a5719dbca4fce
[ "MIT" ]
null
null
null
-- A simple 'HelloWorld' GUI created purely from code. -- This sample demonstrates: -- - Creation of controls and building a UI hierarchy -- - Loading UI style from XML and applying it to controls -- - Handling of global and per-control events -- For more advanced users (beginners can skip this section): -- - Dragging UIElements -- - Displaying tooltips -- - Accessing available Events data (eventData) require "LuaScripts/Utilities/Sample" local window = nil local dragBeginPosition = IntVector2(0, 0) function Start() -- Execute the common startup for samples SampleStart() -- Enable OS cursor input.mouseVisible = true -- Load XML file containing default UI style sheet local style = cache:GetResource("XMLFile", "UI/DefaultStyle.xml") -- Set the loaded style as default style ui.root.defaultStyle = style -- Initialize Window -- Create and add some controls to the Window InitControls() -- Create a draggable Fish -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_FREE) end function InitControls() local text = RichText:new() text:SetText([[<img src="Urho2D/Ball.png" />tcp test <text color=0xff0000ff font="Fonts/Anonymous Pro.ttf" size=50>123123123]]) text:SetMinSize(1000, 500) text:SetSize(1000, 500) ui.root:AddChild(text) ui:DebugDraw(text) end
28.916667
131
0.700288
8540dceae3b214596c4f744ff2f1580b2a04a1ea
175
cs
C#
src/Melville.Generators.INPC.Test/IntegrationTests/NameSpaceDecl.cs
JohnN6TSM/Melville
5e8adb0d799e26d0340f5898ddda53eaf45eadc1
[ "MIT" ]
null
null
null
src/Melville.Generators.INPC.Test/IntegrationTests/NameSpaceDecl.cs
JohnN6TSM/Melville
5e8adb0d799e26d0340f5898ddda53eaf45eadc1
[ "MIT" ]
null
null
null
src/Melville.Generators.INPC.Test/IntegrationTests/NameSpaceDecl.cs
JohnN6TSM/Melville
5e8adb0d799e26d0340f5898ddda53eaf45eadc1
[ "MIT" ]
null
null
null
using Melville.INPC; namespace Melville.Generators.INPC.Test.IntegrationTests; public partial class NameSpaceDecl { [AutoNotify] private int specialName; }
19.444444
57
0.742857
5302e52e58ef9348ae14f0118e6c93411eb5c63b
1,654
rb
Ruby
test/test_append_suffix.rb
pulibrary/lcsort
85a5c764fc2792df3c545a843283a9dbcdfecf28
[ "MIT" ]
18
2015-01-16T00:51:32.000Z
2020-07-30T15:41:58.000Z
test/test_append_suffix.rb
pulibrary/lcsort
85a5c764fc2792df3c545a843283a9dbcdfecf28
[ "MIT" ]
17
2015-05-28T20:32:15.000Z
2019-09-13T14:32:13.000Z
test/test_append_suffix.rb
pulibrary/lcsort
85a5c764fc2792df3c545a843283a9dbcdfecf28
[ "MIT" ]
1
2015-06-03T00:18:27.000Z
2015-06-03T00:18:27.000Z
require 'minitest_helper' # Test :append_suffix mainly to make sure it still sorts before EVERYTHING # after the call number it's appended to. class TestAppendSuffix < Minitest::Test def test_append_suffix # suffix that will sort too late if not done right suffix = "~ZZ suffix" # Make sure it's doing something refute_equal Lcsort.normalize("AB 101"), Lcsort.normalize("AB 101", :append_suffix => suffix) assert Lcsort.normalize("AB 101", :append_suffix => suffix).end_with?(suffix) assert_append_sorts_after( ["AB 101", :append_suffix => suffix], [ "AB 101 aextra extra", "AB 101 .A234", "AB 101 .A234 aaextra extra", "AB 102" ] ) assert_append_sorts_after( ["AB 101 already existing extra", :append_suffix => suffix], [ "AB 101 bb-next extra", "AB 101 .B1", "AB 101 .B1 aextra extra", "AB 102" ] ) assert_append_sorts_after( ["AB 101 .A123", :append_suffix => suffix], [ "AB 101 .A123 aextra extra", "AB 101 .B1", "AB 101 .B1 aextra extra", "AB 102" ] ) assert_append_sorts_after( ["AB 101 .A123 already existing extra", :append_suffix => suffix], [ "AB 101 .A123 bb-next extra" ] ) end def assert_append_sorts_after(args, list_of_later) with_appended_suffix = Lcsort.normalize(*args) list_of_later.each do |callnum| n = Lcsort.normalize(callnum) assert n > with_appended_suffix, "Expected normalized #{callnum}(#{n}) to sort after #{args}(#{with_appended_suffix})" end end end
26.253968
124
0.616687
0b5e9befcea0a1ebaa85ca3de055f7f86b2fbdc3
514
sql
SQL
sql/article.sql
Nicolac84/echelonews
f5dbff0f4fe43f7685672a8d3037ead0f4ef5438
[ "MIT" ]
1
2022-03-16T18:01:22.000Z
2022-03-16T18:01:22.000Z
sql/article.sql
Nicolac84/echelonews
f5dbff0f4fe43f7685672a8d3037ead0f4ef5438
[ "MIT" ]
3
2021-05-11T15:45:41.000Z
2022-01-22T12:43:39.000Z
sql/article.sql
includej/EcheloNews
a8227f71cdfa418e586a1312b43a3af0684c6b6d
[ "MIT" ]
null
null
null
-- echelonews - postgres table definitions -- News article CREATE TABLE Article ( id SERIAL PRIMARY KEY, -- Article univocal ID source INTEGER NOT NULL, -- Source newspaper title VARCHAR NOT NULL, -- Article title preview VARCHAR NOT NULL, -- Article short description topics VARCHAR[] NOT NULL, -- Treated topics origin VARCHAR NOT NULL, -- Reference URL to the full article created TIMESTAMP NOT NULL, -- Creation date and time FOREIGN KEY (source) REFERENCES Newspaper(id) );
36.714286
66
0.715953
ff4e7121af623e15b4d4a863b9fcc3e2099a9e32
566
py
Python
Introducing_Gemma_M0/Gemma_I2Csi7021.py
joewalk102/Adafruit_Learning_System_Guides
2bda607f8c433c661a2d9d40b4db4fd132334c9a
[ "MIT" ]
665
2017-09-27T21:20:14.000Z
2022-03-31T09:09:25.000Z
Introducing_Gemma_M0/Gemma_I2Csi7021.py
joewalk102/Adafruit_Learning_System_Guides
2bda607f8c433c661a2d9d40b4db4fd132334c9a
[ "MIT" ]
641
2017-10-03T19:46:37.000Z
2022-03-30T18:28:46.000Z
Introducing_Gemma_M0/Gemma_I2Csi7021.py
joewalk102/Adafruit_Learning_System_Guides
2bda607f8c433c661a2d9d40b4db4fd132334c9a
[ "MIT" ]
734
2017-10-02T22:47:38.000Z
2022-03-30T14:03:51.000Z
# I2C sensor demo import time import adafruit_si7021 import board import busio i2c = busio.I2C(board.SCL, board.SDA) # lock the I2C device before we try to scan while not i2c.try_lock(): pass print("I2C addresses found:", [hex(i) for i in i2c.scan()]) # unlock I2C now that we're done scanning. i2c.unlock() # Create library object on our I2C port si7021 = adafruit_si7021.SI7021(i2c) # Use library to read the data! while True: print("Temp: %0.2F *C Humidity: %0.1F %%" % (si7021.temperature, si7021.relative_humidity)) time.sleep(1)
20.962963
59
0.699647
77bddd926b43a91c2c67b6be0cd3298faabe1d49
4,268
dart
Dart
lib/src/widgets/dropdown.dart
camilo1498/gallery_media_picker
417c5ebe7a14957215bd097b39db4d56a2f7ac1f
[ "CC0-1.0" ]
null
null
null
lib/src/widgets/dropdown.dart
camilo1498/gallery_media_picker
417c5ebe7a14957215bd097b39db4d56a2f7ac1f
[ "CC0-1.0" ]
null
null
null
lib/src/widgets/dropdown.dart
camilo1498/gallery_media_picker
417c5ebe7a14957215bd097b39db4d56a2f7ac1f
[ "CC0-1.0" ]
1
2022-03-22T06:56:28.000Z
2022-03-22T06:56:28.000Z
import 'dart:async'; import 'package:flutter/material.dart'; typedef DropdownWidgetBuilder<T> = Widget Function( BuildContext context, ValueSetter<T> close); class FeatureController<T> { final Completer<T?> completer; final ValueSetter<T?> close; FeatureController(this.completer, this.close); Future<T?> get closed => completer.future; } FeatureController<T> _showDropDown<T>({ required BuildContext context, required DropdownWidgetBuilder<T> builder, double? height, Duration animationDuration = const Duration(milliseconds: 250), required TickerProvider tickerProvider, }) { final animationController = AnimationController( vsync: tickerProvider, duration: animationDuration, ); final completer = Completer<T?>(); var isReply = false; OverlayEntry? entry; void close(T? value) async { if (isReply) { return; } isReply = true; animationController.animateTo(0).whenCompleteOrCancel(() async { await Future.delayed(const Duration(milliseconds: 16)); completer.complete(value); entry?.remove(); }); } final screenHeight = MediaQuery.of(context).size.height; final screenWidth = MediaQuery.of(context).size.width; final space = screenHeight - height!; /// overlay widget entry = OverlayEntry(builder: (context) { return Padding( padding: EdgeInsets.only( top: space, ), child: Align( alignment: Alignment.topLeft, child: Builder( builder: (ctx) => GestureDetector( onTap: () { close(null); }, child: AnimatedBuilder( child: builder(ctx, close), animation: animationController, builder: (BuildContext context, child) { return Stack( children: [ Container( color: Colors.transparent, height: height * animationController.value, width: screenWidth, ), SizedBox( height: height * animationController.value, width: screenWidth * 0.5, child: child, ), ], ); }, ), ), ), ), ); }); Overlay.of(context)!.insert(entry); animationController.animateTo(1); return FeatureController( completer, close, ); } class DropDown<T> extends StatefulWidget { final Widget child; final DropdownWidgetBuilder<T> dropdownWidgetBuilder; final ValueChanged<T?>? onResult; final ValueChanged<bool>? onShow; final GlobalKey? relativeKey; const DropDown({ Key? key, required this.child, required this.dropdownWidgetBuilder, this.onResult, this.onShow, this.relativeKey, }) : super(key: key); @override _DropDownState<T> createState() => _DropDownState<T>(); } class _DropDownState<T> extends State<DropDown<T>> with TickerProviderStateMixin { FeatureController<T?>? controller; var isShow = false; @override Widget build(BuildContext context) { return GestureDetector( /// return album list child: widget.child, /// on tap dropdown onTap: () async { if (controller != null) { controller!.close(null); return; } /// render overlay final height = MediaQuery.of(context).size.height; final ctx = widget.relativeKey?.currentContext ?? context; RenderBox box = ctx.findRenderObject() as RenderBox; final offsetStart = box.localToGlobal(Offset.zero); final dialogHeight = height - (offsetStart.dy + box.paintBounds.bottom); widget.onShow?.call(true); controller = _showDropDown<T>( context: context, height: dialogHeight, builder: (_, close) { return widget.dropdownWidgetBuilder.call(context, close); }, tickerProvider: this, ); isShow = true; var result = await controller!.closed; controller = null; isShow = false; widget.onResult!(result); widget.onShow?.call(false); }, ); } }
27.535484
80
0.597001
ae5c70c8c07b2e65560e119514090cdb227046c9
1,325
cs
C#
src/Mvp24Hours.Infrastructure.Pipe/Operations/Custom/OperationMapper.cs
kallebelins/mvp24hours-netcore
7ae2242e8db4b4c39d5d04b8b8fda932f5816815
[ "MIT" ]
5
2021-12-29T13:11:22.000Z
2022-02-25T13:36:03.000Z
src/Mvp24Hours.Infrastructure.Pipe/Operations/Custom/OperationMapper.cs
kallebelins/mvp24hours-netcore
7ae2242e8db4b4c39d5d04b8b8fda932f5816815
[ "MIT" ]
1
2022-02-17T18:35:57.000Z
2022-02-17T18:35:57.000Z
src/Mvp24Hours.Infrastructure.Pipe/Operations/Custom/OperationMapper.cs
kallebelins/mvp24hours-netcore
7ae2242e8db4b4c39d5d04b8b8fda932f5816815
[ "MIT" ]
3
2022-01-14T17:20:14.000Z
2022-02-18T18:57:34.000Z
//===================================================================================== // Developed by Kallebe Lins (https://github.com/kallebelins) //===================================================================================== // Reproduction or sharing is free! Contribute to a better world! //===================================================================================== using Mvp24Hours.Core.Contract.Infrastructure.Pipe; namespace Mvp24Hours.Infrastructure.Pipe.Operations.Custom { /// <summary> /// Abstraction of mapping operations /// </summary> public abstract class OperationMapper<T> : OperationBase { /// <summary> /// Key defined for content attached to the message (mapped object) /// </summary> public virtual string ContentKey => null; public override void Execute(IPipelineMessage input) { var result = Mapper(input); if (result != null) { if (string.IsNullOrEmpty(ContentKey)) { input.AddContent(result); } else { input.AddContent(ContentKey, result); } } } public abstract T Mapper(IPipelineMessage input); } }
33.974359
87
0.448302
8d6fab7746c4fb2ce3ea2102c4b7cab875399497
10,774
js
JavaScript
dist/js/register.0050d03d.js
pinkcao/customize-data-visualization
8f8994f0075c2b545ce8f31c2697882851c2472e
[ "MIT" ]
3
2020-12-03T07:08:22.000Z
2021-03-28T16:37:52.000Z
dist/js/register.0050d03d.js
pinkcao/customize-data-visualization
8f8994f0075c2b545ce8f31c2697882851c2472e
[ "MIT" ]
null
null
null
dist/js/register.0050d03d.js
pinkcao/customize-data-visualization
8f8994f0075c2b545ce8f31c2697882851c2472e
[ "MIT" ]
null
null
null
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["register"],{"3c35":function(t,e){(function(e){t.exports=e}).call(this,{})},6199:function(module,exports,__webpack_require__){(function(process,global){var __WEBPACK_AMD_DEFINE_RESULT__; /* * [js-sha1]{@link https://github.com/emn178/js-sha1} * * @version 0.6.0 * @author Chen, Yi-Cyuan [[email protected]] * @copyright Chen, Yi-Cyuan 2014-2017 * @license MIT */(function(){"use strict";var root="object"===typeof window?window:{},NODE_JS=!root.JS_SHA1_NO_NODE_JS&&"object"===typeof process&&process.versions&&process.versions.node;NODE_JS&&(root=global);var COMMON_JS=!root.JS_SHA1_NO_COMMON_JS&&"object"===typeof module&&module.exports,AMD=__webpack_require__("3c35"),HEX_CHARS="0123456789abcdef".split(""),EXTRA=[-2147483648,8388608,32768,128],SHIFT=[24,16,8,0],OUTPUT_TYPES=["hex","array","digest","arrayBuffer"],blocks=[],createOutputMethod=function(t){return function(e){return new Sha1(!0).update(e)[t]()}},createMethod=function(){var t=createOutputMethod("hex");NODE_JS&&(t=nodeWrap(t)),t.create=function(){return new Sha1},t.update=function(e){return t.create().update(e)};for(var e=0;e<OUTPUT_TYPES.length;++e){var r=OUTPUT_TYPES[e];t[r]=createOutputMethod(r)}return t},nodeWrap=function(method){var crypto=eval("require('crypto')"),Buffer=eval("require('buffer').Buffer"),nodeMethod=function(t){if("string"===typeof t)return crypto.createHash("sha1").update(t,"utf8").digest("hex");if(t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(void 0===t.length)return method(t);return crypto.createHash("sha1").update(new Buffer(t)).digest("hex")};return nodeMethod};function Sha1(t){t?(blocks[0]=blocks[16]=blocks[1]=blocks[2]=blocks[3]=blocks[4]=blocks[5]=blocks[6]=blocks[7]=blocks[8]=blocks[9]=blocks[10]=blocks[11]=blocks[12]=blocks[13]=blocks[14]=blocks[15]=0,this.blocks=blocks):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.h0=1732584193,this.h1=4023233417,this.h2=2562383102,this.h3=271733878,this.h4=3285377520,this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}Sha1.prototype.update=function(t){if(!this.finalized){var e="string"!==typeof t;e&&t.constructor===root.ArrayBuffer&&(t=new Uint8Array(t));var r,s,o=0,i=t.length||0,a=this.blocks;while(o<i){if(this.hashed&&(this.hashed=!1,a[0]=this.block,a[16]=a[1]=a[2]=a[3]=a[4]=a[5]=a[6]=a[7]=a[8]=a[9]=a[10]=a[11]=a[12]=a[13]=a[14]=a[15]=0),e)for(s=this.start;o<i&&s<64;++o)a[s>>2]|=t[o]<<SHIFT[3&s++];else for(s=this.start;o<i&&s<64;++o)r=t.charCodeAt(o),r<128?a[s>>2]|=r<<SHIFT[3&s++]:r<2048?(a[s>>2]|=(192|r>>6)<<SHIFT[3&s++],a[s>>2]|=(128|63&r)<<SHIFT[3&s++]):r<55296||r>=57344?(a[s>>2]|=(224|r>>12)<<SHIFT[3&s++],a[s>>2]|=(128|r>>6&63)<<SHIFT[3&s++],a[s>>2]|=(128|63&r)<<SHIFT[3&s++]):(r=65536+((1023&r)<<10|1023&t.charCodeAt(++o)),a[s>>2]|=(240|r>>18)<<SHIFT[3&s++],a[s>>2]|=(128|r>>12&63)<<SHIFT[3&s++],a[s>>2]|=(128|r>>6&63)<<SHIFT[3&s++],a[s>>2]|=(128|63&r)<<SHIFT[3&s++]);this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.block=a[16],this.start=s-64,this.hash(),this.hashed=!0):this.start=s}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},Sha1.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>2]|=EXTRA[3&e],this.block=t[16],e>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}},Sha1.prototype.hash=function(){var t,e,r,s=this.h0,o=this.h1,i=this.h2,a=this.h3,n=this.h4,h=this.blocks;for(e=16;e<80;++e)r=h[e-3]^h[e-8]^h[e-14]^h[e-16],h[e]=r<<1|r>>>31;for(e=0;e<20;e+=5)t=o&i|~o&a,r=s<<5|s>>>27,n=r+t+n+1518500249+h[e]<<0,o=o<<30|o>>>2,t=s&o|~s&i,r=n<<5|n>>>27,a=r+t+a+1518500249+h[e+1]<<0,s=s<<30|s>>>2,t=n&s|~n&o,r=a<<5|a>>>27,i=r+t+i+1518500249+h[e+2]<<0,n=n<<30|n>>>2,t=a&n|~a&s,r=i<<5|i>>>27,o=r+t+o+1518500249+h[e+3]<<0,a=a<<30|a>>>2,t=i&a|~i&n,r=o<<5|o>>>27,s=r+t+s+1518500249+h[e+4]<<0,i=i<<30|i>>>2;for(;e<40;e+=5)t=o^i^a,r=s<<5|s>>>27,n=r+t+n+1859775393+h[e]<<0,o=o<<30|o>>>2,t=s^o^i,r=n<<5|n>>>27,a=r+t+a+1859775393+h[e+1]<<0,s=s<<30|s>>>2,t=n^s^o,r=a<<5|a>>>27,i=r+t+i+1859775393+h[e+2]<<0,n=n<<30|n>>>2,t=a^n^s,r=i<<5|i>>>27,o=r+t+o+1859775393+h[e+3]<<0,a=a<<30|a>>>2,t=i^a^n,r=o<<5|o>>>27,s=r+t+s+1859775393+h[e+4]<<0,i=i<<30|i>>>2;for(;e<60;e+=5)t=o&i|o&a|i&a,r=s<<5|s>>>27,n=r+t+n-1894007588+h[e]<<0,o=o<<30|o>>>2,t=s&o|s&i|o&i,r=n<<5|n>>>27,a=r+t+a-1894007588+h[e+1]<<0,s=s<<30|s>>>2,t=n&s|n&o|s&o,r=a<<5|a>>>27,i=r+t+i-1894007588+h[e+2]<<0,n=n<<30|n>>>2,t=a&n|a&s|n&s,r=i<<5|i>>>27,o=r+t+o-1894007588+h[e+3]<<0,a=a<<30|a>>>2,t=i&a|i&n|a&n,r=o<<5|o>>>27,s=r+t+s-1894007588+h[e+4]<<0,i=i<<30|i>>>2;for(;e<80;e+=5)t=o^i^a,r=s<<5|s>>>27,n=r+t+n-899497514+h[e]<<0,o=o<<30|o>>>2,t=s^o^i,r=n<<5|n>>>27,a=r+t+a-899497514+h[e+1]<<0,s=s<<30|s>>>2,t=n^s^o,r=a<<5|a>>>27,i=r+t+i-899497514+h[e+2]<<0,n=n<<30|n>>>2,t=a^n^s,r=i<<5|i>>>27,o=r+t+o-899497514+h[e+3]<<0,a=a<<30|a>>>2,t=i^a^n,r=o<<5|o>>>27,s=r+t+s-899497514+h[e+4]<<0,i=i<<30|i>>>2;this.h0=this.h0+s<<0,this.h1=this.h1+o<<0,this.h2=this.h2+i<<0,this.h3=this.h3+a<<0,this.h4=this.h4+n<<0},Sha1.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,s=this.h3,o=this.h4;return HEX_CHARS[t>>28&15]+HEX_CHARS[t>>24&15]+HEX_CHARS[t>>20&15]+HEX_CHARS[t>>16&15]+HEX_CHARS[t>>12&15]+HEX_CHARS[t>>8&15]+HEX_CHARS[t>>4&15]+HEX_CHARS[15&t]+HEX_CHARS[e>>28&15]+HEX_CHARS[e>>24&15]+HEX_CHARS[e>>20&15]+HEX_CHARS[e>>16&15]+HEX_CHARS[e>>12&15]+HEX_CHARS[e>>8&15]+HEX_CHARS[e>>4&15]+HEX_CHARS[15&e]+HEX_CHARS[r>>28&15]+HEX_CHARS[r>>24&15]+HEX_CHARS[r>>20&15]+HEX_CHARS[r>>16&15]+HEX_CHARS[r>>12&15]+HEX_CHARS[r>>8&15]+HEX_CHARS[r>>4&15]+HEX_CHARS[15&r]+HEX_CHARS[s>>28&15]+HEX_CHARS[s>>24&15]+HEX_CHARS[s>>20&15]+HEX_CHARS[s>>16&15]+HEX_CHARS[s>>12&15]+HEX_CHARS[s>>8&15]+HEX_CHARS[s>>4&15]+HEX_CHARS[15&s]+HEX_CHARS[o>>28&15]+HEX_CHARS[o>>24&15]+HEX_CHARS[o>>20&15]+HEX_CHARS[o>>16&15]+HEX_CHARS[o>>12&15]+HEX_CHARS[o>>8&15]+HEX_CHARS[o>>4&15]+HEX_CHARS[15&o]},Sha1.prototype.toString=Sha1.prototype.hex,Sha1.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,s=this.h3,o=this.h4;return[t>>24&255,t>>16&255,t>>8&255,255&t,e>>24&255,e>>16&255,e>>8&255,255&e,r>>24&255,r>>16&255,r>>8&255,255&r,s>>24&255,s>>16&255,s>>8&255,255&s,o>>24&255,o>>16&255,o>>8&255,255&o]},Sha1.prototype.array=Sha1.prototype.digest,Sha1.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(20),e=new DataView(t);return e.setUint32(0,this.h0),e.setUint32(4,this.h1),e.setUint32(8,this.h2),e.setUint32(12,this.h3),e.setUint32(16,this.h4),t};var exports=createMethod();COMMON_JS?module.exports=exports:(root.sha1=exports,AMD&&(__WEBPACK_AMD_DEFINE_RESULT__=function(){return exports}.call(exports,__webpack_require__,exports,module),void 0===__WEBPACK_AMD_DEFINE_RESULT__||(module.exports=__WEBPACK_AMD_DEFINE_RESULT__)))})()}).call(this,__webpack_require__("4362"),__webpack_require__("c8ba"))},7803:function(t,e,r){"use strict";r.r(e);var s=function(){var t=this,e=t.$createElement,r=t._self._c||e;return r("div",{staticClass:"register-main-wrapper"},[r("div",{staticClass:"register-main-pane"},[r("el-form",{ref:"ruleForm",attrs:{model:t.ruleForm,"label-width":"80px",rules:t.rules}},[r("el-form-item",[r("div",{staticStyle:{"margin-bottom":"20px","margin-left":"50px"}},[r("span",{staticStyle:{"font-family":"'PingFang SC'","font-size":"40px","font-weight":"bold","letter-spacing":"10px"}},[t._v("注册")])])]),r("el-form-item",{attrs:{label:"账号",prop:"account"}},[r("el-input",{attrs:{placeholder:"请输入账号",autofocus:""},model:{value:t.ruleForm.account,callback:function(e){t.$set(t.ruleForm,"account",e)},expression:"ruleForm.account"}})],1),r("el-form-item",{attrs:{label:"密码",prop:"pass"}},[r("el-input",{attrs:{placeholder:"请输入密码","show-password":"",type:"password",autocomplete:"off"},model:{value:t.ruleForm.pass,callback:function(e){t.$set(t.ruleForm,"pass",e)},expression:"ruleForm.pass"}})],1),r("el-form-item",{attrs:{label:"确认密码",prop:"checkPass"}},[r("el-input",{attrs:{placeholder:"请重复密码",type:"password",autocomplete:"off"},model:{value:t.ruleForm.checkPass,callback:function(e){t.$set(t.ruleForm,"checkPass",e)},expression:"ruleForm.checkPass"}})],1),r("el-form-item",{attrs:{label:"邮件地址",prop:"email"}},[r("el-input",{attrs:{placeholder:"请输入邮件地址"},model:{value:t.ruleForm.email,callback:function(e){t.$set(t.ruleForm,"email",e)},expression:"ruleForm.email"}})],1),r("el-form-item",[r("el-button",{staticStyle:{width:"100%"},attrs:{round:"",type:"primary"},on:{keydown:function(e){return!e.type.indexOf("key")&&t._k(e.keyCode,"enter",13,e.key,"Enter")?null:t.onSubmit(e)},click:function(e){return t.onSubmit("ruleForm")}}},[t._v("提交")])],1),r("el-form-item",[r("el-button",{staticStyle:{width:"100%"},attrs:{round:""},on:{click:t.routeToLogin}},[t._v("返回")])],1)],1)],1)])},o=[],i=r("6199"),a=r.n(i),n=(r("a15e"),{name:"login",data:function(){var t=this,e=function(e,r,s){t.$axios({url:t.$url.validateAccount,method:"post",data:{account:r}}).then((function(t){200==t.status&&(1==t.data?s():s("用户名重复"))}))},r=function(e,r,s){""===r?s(new Error("请输入密码")):(""!==t.ruleForm.checkPass&&t.$refs.ruleForm.validateField("checkPass"),s())},s=function(e,r,s){""===r?s(new Error("请再次输入密码")):r!==t.ruleForm.pass?s(new Error("两次输入密码不一致!")):s()};return{loadingInstance:null,ruleForm:{account:"",pass:"",checkPass:"",email:""},rules:{account:[{validator:e,trigger:"blur",required:!0}],pass:[{validator:r,trigger:"blur",required:!0},{min:8,max:20,message:"长度在 8 到 20 个字符",trigger:"blur"}],checkPass:[{validator:s,trigger:"blur",required:!0}],email:[{type:"email",message:"请输入正确邮件地址",trigger:"blur",required:!0}]}}},computed:{},created:function(){},mounted:function(){},methods:{onSubmit:function(t){var e=this;this.loadingInstance=this.$loading({fullscreen:!0,spinner:"el-icon-loading",background:"rgba(0, 0, 0, 0.8)",text:"注册中..."}),this.$refs[t].validate((function(t){if(!t)return e.$message({type:"error",message:"提交失败、请检查校验项!"}),!1;e.$axios({url:e.$url.userRegister,method:"post",data:{userAccount:e.ruleForm.account,userPassword:a()(e.ruleForm.checkPass),userEmail:e.ruleForm.email}}).then((function(t){200==t.status&&1==t.data.registerStatus?(e.loadingInstance.close(),e.$message({type:"success",message:"注册成功!"}),e.$router.push("/login")):(e.loadingInstance.close(),e.$message({type:"error",message:"注册失败!"}))}))}))},routeToLogin:function(){this.$router.push("/login")}}}),h=n,l=(r("7fba"),r("0c7c")),c=Object(l["a"])(h,s,o,!1,null,null,null);e["default"]=c.exports},"7fba":function(t,e,r){"use strict";r("b619")},b619:function(t,e,r){}}]); //# sourceMappingURL=register.0050d03d.js.map
1,077.4
10,304
0.669946
2e6e1ba77b788970425901b9f3825a756680f9fa
7,643
rs
Rust
src/kv_mdbx.rs
rust-vapory/vapdb
f2c10c4881f2e8684b1d1bc9f4d1cee190ccb449
[ "Apache-2.0" ]
null
null
null
src/kv_mdbx.rs
rust-vapory/vapdb
f2c10c4881f2e8684b1d1bc9f4d1cee190ccb449
[ "Apache-2.0" ]
null
null
null
src/kv_mdbx.rs
rust-vapory/vapdb
f2c10c4881f2e8684b1d1bc9f4d1cee190ccb449
[ "Apache-2.0" ]
null
null
null
use crate::{traits, Bucket, Cursor, CursorDupSort, DupSort, MutableCursor}; use anyhow::anyhow; use async_trait::async_trait; use bytes::Bytes; use futures::future::LocalBoxFuture; use std::future::Future; #[async_trait(?Send)] impl traits::KV for heed::Env { type Tx<'kv> = EnvWrapper<'kv, heed::RoTxn<'kv>>; async fn begin<'kv>(&'kv self, _flags: u8) -> anyhow::Result<Self::Tx<'kv>> { Ok(EnvWrapper { env: self, v: self.read_txn()?, }) } } #[async_trait(?Send)] impl traits::MutableKV for heed::Env { type MutableTx<'kv> = EnvWrapper<'kv, heed::RwTxn<'kv, 'kv>>; async fn begin_mutable<'kv>(&'kv self) -> anyhow::Result<Self::MutableTx<'kv>> { Ok(EnvWrapper { env: self, v: self.write_txn()?, }) } } pub struct EnvWrapper<'e, T> { env: &'e heed::Env, v: T, } #[async_trait(?Send)] impl<'e> traits::Transaction for EnvWrapper<'e, heed::RoTxn<'e>> { type Cursor<'tx, B: Bucket> = heed::RoCursor<'tx>; type CursorDupSort<'tx, B: Bucket + DupSort> = heed::RoCursor<'tx>; async fn cursor<'tx, B: Bucket>(&'tx self) -> anyhow::Result<Self::Cursor<'tx, B>> { Ok(self .env .open_database::<(), ()>(Some(B::DB_NAME))? .ok_or_else(|| anyhow!("no database"))? .cursor(&self.v)?) } async fn cursor_dup_sort<'tx, B: Bucket + DupSort>( &'tx self, ) -> anyhow::Result<Self::Cursor<'tx, B>> { self.cursor::<B>().await } } #[async_trait(?Send)] impl<'e> traits::Transaction for EnvWrapper<'e, heed::RwTxn<'e, 'e>> { type Cursor<'tx, B: Bucket> = heed::RoCursor<'tx>; type CursorDupSort<'tx, B: Bucket + DupSort> = heed::RoCursor<'tx>; async fn cursor<'tx, B: Bucket>(&'tx self) -> anyhow::Result<Self::Cursor<'tx, B>> { Ok(self .env .open_database::<(), ()>(Some(B::DB_NAME))? .ok_or_else(|| anyhow!("no database"))? .cursor(&self.v)?) } async fn cursor_dup_sort<'tx, B: Bucket + DupSort>( &'tx self, ) -> anyhow::Result<Self::Cursor<'tx, B>> { self.cursor::<B>().await } } #[async_trait(?Send)] impl<'e> traits::MutableTransaction for EnvWrapper<'e, heed::RwTxn<'e, 'e>> { type MutableCursor<'tx, B: Bucket> = heed::RwCursor<'tx>; async fn mutable_cursor<'tx, B: Bucket>( &'tx self, ) -> anyhow::Result<Self::MutableCursor<'tx, B>> { todo!() } async fn commit(self) -> anyhow::Result<()> { todo!() } async fn bucket_size<B: Bucket>(&self) -> anyhow::Result<u64> { todo!() } fn comparator<B: Bucket>(&self) -> crate::ComparatorFunc { todo!() } fn cmp<B: Bucket>(a: &[u8], b: &[u8]) -> std::cmp::Ordering { todo!() } fn dcmp<B: Bucket>(a: &[u8], b: &[u8]) -> std::cmp::Ordering { todo!() } async fn sequence<B: Bucket>(&self, amount: usize) -> anyhow::Result<usize> { todo!() } } // Cursor fn first<'tx, B: Bucket>( cursor: &mut heed::RoCursor<'tx>, ) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { Ok(cursor .move_on_first()? .map(|(k, v)| (k.into(), v.into())) .ok_or_else(|| anyhow!("not found"))?) } fn seek_general<'tx, B: Bucket>( cursor: &mut heed::RoCursor<'tx>, key: &[u8], ) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { todo!() } fn seek_general_dupsort<'tx, B: Bucket + DupSort>( cursor: &mut heed::RoCursor<'tx>, key: &[u8], ) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { if B::AUTO_KEYS_CONVERSION { return seek_dupsort::<B>(cursor, key); } seek_general::<B>(cursor, key) } fn seek_dupsort<'tx, B: Bucket + DupSort>( cursor: &mut heed::RoCursor<'tx>, key: &[u8], ) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { todo!() } fn next<'tx, B: Bucket>( cursor: &mut heed::RoCursor<'tx>, ) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { cursor .move_on_next()? .map(|(k, v)| (k.into(), v.into())) .ok_or_else(|| anyhow!("not found")) } fn prev<'tx, B: Bucket>( cursor: &mut heed::RoCursor<'tx>, ) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { cursor .move_on_prev()? .map(|(k, v)| (k.into(), v.into())) .ok_or_else(|| anyhow!("not found")) } fn last<'tx, B: Bucket>( cursor: &mut heed::RoCursor<'tx>, ) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { cursor .move_on_last()? .map(|(k, v)| (k.into(), v.into())) .ok_or_else(|| anyhow!("not found")) } fn current<'tx, B: Bucket>( cursor: &mut heed::RoCursor<'tx>, ) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { cursor .current()? .map(|(k, v)| (k.into(), v.into())) .ok_or_else(|| anyhow!("not found")) } #[async_trait(?Send)] impl<'tx, B: Bucket> Cursor<'tx, B> for heed::RoCursor<'tx> { async fn first(&mut self) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { first::<B>(self) } default async fn seek(&mut self, key: &[u8]) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { seek_general::<B>(self, key) } async fn seek_exact(&mut self, key: &[u8]) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { todo!() } async fn next(&mut self) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { next::<B>(self) } async fn prev(&mut self) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { prev::<B>(self) } async fn last(&mut self) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { last::<B>(self) } async fn current(&mut self) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { current::<B>(self) } } #[async_trait(?Send)] impl<'tx, B: Bucket + DupSort> Cursor<'tx, B> for heed::RoCursor<'tx> { async fn seek(&mut self, key: &[u8]) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { seek_general_dupsort::<B>(self, key) } } #[async_trait(?Send)] impl<'tx, B: Bucket + DupSort> CursorDupSort<'tx, B> for heed::RoCursor<'tx> { async fn seek_both_exact( &mut self, key: &[u8], value: &[u8], ) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { todo!() } async fn seek_both_range( &mut self, key: &[u8], value: &[u8], ) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { todo!() } async fn first_dup(&mut self) -> anyhow::Result<Bytes<'tx>> { todo!() } async fn next_dup(&mut self) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { todo!() } async fn next_no_dup(&mut self) -> anyhow::Result<(Bytes<'tx>, Bytes<'tx>)> { todo!() } async fn last_dup(&mut self, key: &[u8]) -> anyhow::Result<Bytes<'tx>> { todo!() } } #[async_trait(?Send)] impl<'tx, B: Bucket> MutableCursor<'tx, B> for heed::RwCursor<'tx> { async fn put(&mut self, key: &[u8], value: &[u8]) -> anyhow::Result<()> { todo!() } async fn append(&mut self, key: &[u8], value: &[u8]) -> anyhow::Result<()> { Ok(self.append(key, value)?) } async fn delete(&mut self, key: &[u8], value: &[u8]) -> anyhow::Result<()> { todo!() } async fn delete_current(&mut self) -> anyhow::Result<()> { self.del_current()?; Ok(()) } async fn reserve(&mut self, key: &[u8], n: usize) -> anyhow::Result<Bytes<'tx>> { todo!() } async fn put_current(&mut self, key: &[u8], value: &[u8]) -> anyhow::Result<()> { self.put_current(key, value)?; Ok(()) } async fn count(&mut self) -> anyhow::Result<usize> { todo!() } }
26.264605
94
0.530943
6d7162b2263a47f73e951762801e440b6f8c6e64
3,188
h
C
src/TritonMacroPlace/src/ParquetFP/src/parsers.h
ibrahimkhairy/OpenROAD
399a51332ce32e816b914f38cd38b9d0fe77785f
[ "BSD-3-Clause-Clear" ]
15
2019-07-21T02:15:52.000Z
2021-04-13T01:14:18.000Z
src/TritonMacroPlace/src/ParquetFP/src/parsers.h
QuantamHD/OpenROAD
5a8314e60cfebd07b843e91c41a13b42a22f55e4
[ "BSD-3-Clause-Clear" ]
6
2019-08-12T19:20:42.000Z
2020-07-03T08:29:53.000Z
src/TritonMacroPlace/src/ParquetFP/src/parsers.h
QuantamHD/OpenROAD
5a8314e60cfebd07b843e91c41a13b42a22f55e4
[ "BSD-3-Clause-Clear" ]
12
2019-12-12T02:57:08.000Z
2021-12-21T13:18:39.000Z
/************************************************************************** *** *** Copyright (c) 2000-2006 Regents of the University of Michigan, *** Saurabh N. Adya, Hayward Chan, Jarrod A. Roy *** and Igor L. Markov *** *** Contact author(s): [email protected], [email protected] *** Original Affiliation: University of Michigan, EECS Dept. *** Ann Arbor, MI 48109-2122 USA *** *** 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. *** *** ***************************************************************************/ #ifndef PARSERS_H #define PARSERS_H #include <iostream> #include <iomanip> #include <algorithm> #include <cmath> namespace parse_utils { struct ltstr { inline bool operator ()(const char* s1, const char* s2) const { return strcmp(s1, s2) < 0; } }; struct Point { float x; float y; }; struct IntPoint { int x; int y; }; // global parsing functions inline void eatblank(std::ifstream& i); inline void skiptoeol(std::ifstream& i); inline void eathash(std::ifstream& i); inline bool needCaseChar(std::ifstream& i, char character); } // namespace parse_utils // ========================= // IMPLEMENTATIONS // ========================= inline void parse_utils::eatblank(std::ifstream& i) { while (i.peek()==' ' || i.peek()=='\t') i.get(); } // -------------------------------------------------------- inline void parse_utils::skiptoeol(std::ifstream& i) { while (!i.eof() && i.peek()!='\n' && i.peek()!='\r') i.get(); i.get(); } // -------------------------------------------------------- inline bool parse_utils::needCaseChar(std::ifstream& i, char character) { while(!i.eof() && i.peek() != character) i.get(); if(i.eof()) return false; else return true; } // -------------------------------------------------------- inline void parse_utils::eathash(std::ifstream& i) { skiptoeol(i); } // -------------------------------------------------------- #endif
30.951456
78
0.550816
3842326e423c4ba9581e48a832b4445affc83c4e
2,220
php
PHP
app/REST/AuthGroup.php
YanDatsiuk/social-network-rest-api-backend
329253c0551e1e2531d13fe8ce1c08c18b50f5a7
[ "MIT" ]
4
2019-10-03T06:13:08.000Z
2021-01-23T20:21:12.000Z
app/REST/AuthGroup.php
YanDatsiuk/social-network-rest-api-backend
329253c0551e1e2531d13fe8ce1c08c18b50f5a7
[ "MIT" ]
3
2017-06-01T06:40:32.000Z
2017-06-01T13:36:23.000Z
app/REST/AuthGroup.php
YanDatsiuk/apartment-rentals-rest-api-backend
67448ba18becac176ef2c6ba49c929f15a98a74d
[ "MIT" ]
1
2021-11-02T12:49:14.000Z
2021-11-02T12:49:14.000Z
<?php namespace App\REST; use Illuminate\Database\Eloquent\Model; /** * App\REST\AuthGroup * * @property int $id * @property string|null $name * @property-read \Illuminate\Database\Eloquent\Collection|\App\REST\AuthActionGroup[] $authActionGroups * @property-read \Illuminate\Database\Eloquent\Collection|\App\REST\AuthAction[] $authActions * @property-read \Illuminate\Database\Eloquent\Collection|\App\REST\AuthGroupUser[] $authGroupUsers * @property-read \Illuminate\Database\Eloquent\Collection|\App\REST\User[] $users * @method static \Illuminate\Database\Query\Builder|\App\REST\AuthGroup whereId($value) * @method static \Illuminate\Database\Query\Builder|\App\REST\AuthGroup whereName($value) * @mixin \Eloquent */ class AuthGroup extends Model { /** * Indicates if the model should be timestamped. * * @var bool */ public $timestamps = false; /** * Table Name. * * @var string */ protected $table = 'auth_groups'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', ]; /** * authActionGroups. * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function authActionGroups() { return $this->hasMany('App\REST\AuthActionGroup', 'group_id'); } /** * authGroupUsers. * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function authGroupUsers() { return $this->hasMany('App\REST\AuthGroupUser', 'group_id'); } /** * AuthActions. * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function authActions() { return $this->belongsToMany( 'App\REST\AuthAction', 'auth_action_group', 'group_id', 'action_id'); } /** * Users. * * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function users() { return $this->belongsToMany( 'App\REST\User', 'auth_group_user', 'group_id', 'user_id'); } }
22.2
104
0.606757
9e2b82e30b0d292ecd32da0147345e580eb81289
701
cs
C#
TCC.Core/Parsing/Messages/S_WHISPER.cs
sarisia/Tera-custom-cooldowns
9d1cf230340252aa92543ccc063a588bbe37e252
[ "MIT" ]
null
null
null
TCC.Core/Parsing/Messages/S_WHISPER.cs
sarisia/Tera-custom-cooldowns
9d1cf230340252aa92543ccc063a588bbe37e252
[ "MIT" ]
null
null
null
TCC.Core/Parsing/Messages/S_WHISPER.cs
sarisia/Tera-custom-cooldowns
9d1cf230340252aa92543ccc063a588bbe37e252
[ "MIT" ]
null
null
null
using TCC.TeraCommon.Game.Messages; using TCC.TeraCommon.Game.Services; namespace TCC.Parsing.Messages { public class S_WHISPER : ParsedMessage { public ulong PlayerId { get; private set; } public string Author { get; private set; } public string Recipient { get; private set; } public string Message { get; private set; } public S_WHISPER(TeraMessageReader reader) : base(reader) { reader.Skip(6); PlayerId = reader.ReadUInt64(); reader.Skip(3); Author = reader.ReadTeraString(); Recipient = reader.ReadTeraString(); Message = reader.ReadTeraString(); } } }
30.478261
65
0.606277
c687a467871bf155c67343c044f3f07b013cbdad
3,995
py
Python
pybingwallpaper/webutil.py
jing5460/pybingwallpaper
5150d72e4427cf6ca0eb441a62961682de11839f
[ "MIT" ]
571
2015-01-05T16:24:18.000Z
2022-03-27T02:13:03.000Z
pybingwallpaper/webutil.py
jing5460/pybingwallpaper
5150d72e4427cf6ca0eb441a62961682de11839f
[ "MIT" ]
44
2015-01-19T05:37:22.000Z
2021-11-20T18:29:46.000Z
pybingwallpaper/webutil.py
jing5460/pybingwallpaper
5150d72e4427cf6ca0eb441a62961682de11839f
[ "MIT" ]
121
2015-01-09T08:30:42.000Z
2022-03-11T02:21:33.000Z
#!/usr/bin/env python import gzip import ssl from io import BytesIO from . import log from .ntlmauth import HTTPNtlmAuthHandler from .py23 import get_moved_attr, import_moved _logger = log.getChild('webutil') Request = get_moved_attr('urllib2', 'urllib.request', 'Request') urlopen = get_moved_attr('urllib2', 'urllib.request', 'urlopen') URLError = get_moved_attr('urllib2', 'urllib.error', 'URLError') urlparse = get_moved_attr('urlparse', 'urllib.parse', 'urlparse') parse_qs = get_moved_attr('urlparse', 'urllib.parse', 'parse_qs') urlencode = get_moved_attr('urllib', 'urllib.parse', 'urlencode') urljoin = get_moved_attr('urlparse', 'urllib.parse', 'urljoin') url_request = import_moved('urllib2', 'urllib.request') def setup_proxy(proxy_protocols, proxy_url, proxy_port, sites, username="", password=""): proxy_dict = {p: '%s:%s' % (proxy_url, proxy_port) for p in proxy_protocols} ph = url_request.ProxyHandler(proxy_dict) passman = url_request.HTTPPasswordMgrWithDefaultRealm() _logger.info('add proxy site %s', sites) passman.add_password(None, sites, username, password) pnah = HTTPNtlmAuthHandler.ProxyNtlmAuthHandler(passman) pbah = url_request.ProxyBasicAuthHandler(passman) pdah = url_request.ProxyDigestAuthHandler(passman) cp = url_request.HTTPCookieProcessor() context = ssl.create_default_context() opener = url_request.build_opener(cp, url_request.HTTPSHandler(debuglevel=1, context=context), url_request.HTTPHandler(debuglevel=99), ph, pnah, pbah, pdah, url_request.HTTPErrorProcessor()) url_request.install_opener(opener) def _ungzip(html): if html[:6] == b'\x1f\x8b\x08\x00\x00\x00': html = gzip.GzipFile(fileobj=BytesIO(html)).read() return html def loadurl(url, headers=None, optional=False): headers = headers or dict() if not url: return None _logger.debug('getting url %s, headers %s', url, headers) if 'User-Agent' not in headers: headers[ 'User-Agent' ] = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1521.3 Safari/537.36' try: req = Request(url=url, headers=headers) con = urlopen(req) except Exception as err: if not optional: _logger.error('error %s occurs during load %s with header %s', err, url, headers) _logger.debug('', exc_info=1) return None if con: _logger.debug("Hit %s code: %s", str(con), con.getcode()) data = con.read() data = _ungzip(data) _logger.log(log.PAGEDUMP, repr(data)) return data else: _logger.error("No data returned.") return None def loadpage(url, codec=('utf8', 'strict'), headers=None, optional=False): headers = headers or dict() data = loadurl(url, headers=headers, optional=optional) return data.decode(*codec) if data else None def postto(url, datadict, headers=None, decodec='gbk'): headers = headers or dict() params = urlencode(datadict) _logger.info('Post %s to %s, headers %s', params, url, headers) try: req = Request(url=url, data=params) for k, v in list(headers.items()): req.add_header(k, v) con = urlopen(req) if con: _logger.debug("Hit %s %d", str(con), con.getcode()) data = con.read(-1) return data.decode(decodec) else: _logger.error("No data returned.") return None except Exception as err: _logger.error('error %s occurs during post %s to %s', err, params, url) _logger.debug('', exc_info=1) def test_header(url, extra_headers=None): headers = { 'method': 'HEAD', } if extra_headers: headers.update(extra_headers) resp = loadurl(url, headers, True) return resp is not None
35.353982
114
0.638048
5c9d514e9b51db530ad5ecc0efe7a3df1c1d545a
954
dart
Dart
application/mobile_app/lib/features/domain/entities/message.dart
quabynah-bilson/coded-dating-platform
cb179d1257de252153c95208ac92cd76682fc36e
[ "Apache-2.0" ]
1
2022-03-13T14:40:39.000Z
2022-03-13T14:40:39.000Z
application/mobile_app/lib/features/domain/entities/message.dart
quabynah-bilson/coded-dating-platform
cb179d1257de252153c95208ac92cd76682fc36e
[ "Apache-2.0" ]
null
null
null
application/mobile_app/lib/features/domain/entities/message.dart
quabynah-bilson/coded-dating-platform
cb179d1257de252153c95208ac92cd76682fc36e
[ "Apache-2.0" ]
null
null
null
import 'package:moor_flutter/moor_flutter.dart'; class Messages extends Table { TextColumn get key => text()(); TextColumn get message => text().withDefault(const Constant(''))(); TextColumn get sender => text()(); TextColumn get recipient => text()(); TextColumn get type => text().withDefault(Constant(Messages.TYPE_TEXT)).nullable()(); BoolColumn get read => boolean().withDefault(Constant(false))(); BoolColumn get starred => boolean().withDefault(Constant(false))(); BoolColumn get archived => boolean().withDefault(Constant(false))(); IntColumn get timestamp => integer() .withDefault(Constant(DateTime.now().millisecondsSinceEpoch)).nullable()(); // Message types static const TYPE_TEXT = "text"; static const TYPE_AUDIO = "audio"; static const TYPE_IMAGE = "image"; static const TYPE_OTHER = "other"; @override Set<Column> get primaryKey => {key}; // ignore: sdk_version_set_literal }
27.257143
81
0.694969
b304a8a0ec5b6c10876a973d320e1f0fc9420547
12,361
py
Python
pysnmp/CISCO-SYS-INFO-LOG-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
11
2021-02-02T16:27:16.000Z
2021-08-31T06:22:49.000Z
pysnmp/CISCO-SYS-INFO-LOG-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
75
2021-02-24T17:30:31.000Z
2021-12-08T00:01:18.000Z
pysnmp/CISCO-SYS-INFO-LOG-MIB.py
agustinhenze/mibs.snmplabs.com
1fc5c07860542b89212f4c8ab807057d9a9206c7
[ "Apache-2.0" ]
10
2019-04-30T05:51:36.000Z
2022-02-16T03:33:41.000Z
# # PySNMP MIB module CISCO-SYS-INFO-LOG-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-SYS-INFO-LOG-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:57:12 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") InetAddress, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress", "InetAddressType") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup") IpAddress, MibIdentifier, TimeTicks, Integer32, ModuleIdentity, Bits, Gauge32, ObjectIdentity, NotificationType, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, iso, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "MibIdentifier", "TimeTicks", "Integer32", "ModuleIdentity", "Bits", "Gauge32", "ObjectIdentity", "NotificationType", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "iso", "Counter32") DisplayString, TextualConvention, RowStatus, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "RowStatus", "TruthValue") ciscoSysInfoLogMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 330)) ciscoSysInfoLogMIB.setRevisions(('2005-08-12 10:00', '2003-01-24 10:00',)) if mibBuilder.loadTexts: ciscoSysInfoLogMIB.setLastUpdated('200508121000Z') if mibBuilder.loadTexts: ciscoSysInfoLogMIB.setOrganization('Cisco System, Inc.') ciscoSysInfoLogMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 330, 0)) ciscoSysInfoLogMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 330, 1)) ciscoSysInfoLogMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 330, 2)) csilGlobalConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 1)) csilServerConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 2)) csilCommandConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 3)) csilSysInfoLogEnabled = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 1, 1), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: csilSysInfoLogEnabled.setStatus('current') csilSysInfoLogNotifEnabled = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 1, 2), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: csilSysInfoLogNotifEnabled.setStatus('current') csilMaxServerAllowed = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 2, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setUnits('servers').setMaxAccess("readwrite") if mibBuilder.loadTexts: csilMaxServerAllowed.setStatus('current') csilMaxProfilePerServerAllowed = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 2, 2), Unsigned32()).setUnits('profiles').setMaxAccess("readonly") if mibBuilder.loadTexts: csilMaxProfilePerServerAllowed.setStatus('current') csilServerTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 2, 3), ) if mibBuilder.loadTexts: csilServerTable.setStatus('current') csilServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 2, 3, 1), ).setIndexNames((0, "CISCO-SYS-INFO-LOG-MIB", "csilServerIndex")) if mibBuilder.loadTexts: csilServerEntry.setStatus('current') csilServerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 2, 3, 1, 1), Unsigned32()) if mibBuilder.loadTexts: csilServerIndex.setStatus('current') csilServerAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 2, 3, 1, 2), InetAddressType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: csilServerAddressType.setStatus('current') csilServerAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 2, 3, 1, 3), InetAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: csilServerAddress.setStatus('current') csilServerProfileIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 2, 3, 1, 4), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: csilServerProfileIndex.setStatus('current') csilServerProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 2, 3, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("tftp", 1), ("rcp", 2), ("ftp", 3)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: csilServerProtocol.setStatus('current') csilServerRcpUserName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 2, 3, 1, 6), SnmpAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: csilServerRcpUserName.setStatus('current') csilServerInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 2, 3, 1, 7), Unsigned32().clone(1440)).setUnits('minutes').setMaxAccess("readcreate") if mibBuilder.loadTexts: csilServerInterval.setStatus('current') csilServerLoggingFileName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 2, 3, 1, 8), SnmpAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: csilServerLoggingFileName.setStatus('current') csilServerLastStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 2, 3, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=NamedValues(("none", 1), ("noLogFile", 2), ("noCommand", 3), ("linkBlock", 4), ("authError", 5), ("addrError", 6), ("copying", 7), ("writeError", 8), ("success", 9), ("ftpError", 10)))).setMaxAccess("readonly") if mibBuilder.loadTexts: csilServerLastStatus.setStatus('current') csilServerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 2, 3, 1, 10), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: csilServerRowStatus.setStatus('current') csilMaxCommandPerProfile = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 3, 1), Unsigned32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: csilMaxCommandPerProfile.setStatus('current') csilCommandsTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 3, 2), ) if mibBuilder.loadTexts: csilCommandsTable.setStatus('current') csilCommandsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 3, 2, 1), ).setIndexNames((0, "CISCO-SYS-INFO-LOG-MIB", "csilCommandProfileIndex"), (0, "CISCO-SYS-INFO-LOG-MIB", "csilCommandIndex")) if mibBuilder.loadTexts: csilCommandsEntry.setStatus('current') csilCommandProfileIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 3, 2, 1, 1), Unsigned32()) if mibBuilder.loadTexts: csilCommandProfileIndex.setStatus('current') csilCommandIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 3, 2, 1, 2), Unsigned32()) if mibBuilder.loadTexts: csilCommandIndex.setStatus('current') csilCommandString = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 3, 2, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readcreate") if mibBuilder.loadTexts: csilCommandString.setStatus('current') csilCommandExecOrder = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 3, 2, 1, 4), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: csilCommandExecOrder.setStatus('current') csilCommandStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 330, 1, 3, 2, 1, 5), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: csilCommandStatus.setStatus('current') csilLoggingFailNotif = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 330, 0, 1)).setObjects(("CISCO-SYS-INFO-LOG-MIB", "csilServerLastStatus")) if mibBuilder.loadTexts: csilLoggingFailNotif.setStatus('current') ciscoSysInfoLogMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 330, 2, 1)) ciscoSysInfoLogMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 330, 2, 2)) ciscoSysInfoLogMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 330, 2, 1, 1)).setObjects(("CISCO-SYS-INFO-LOG-MIB", "csilGlobalConfigGroup"), ("CISCO-SYS-INFO-LOG-MIB", "csilServerConfigGroup"), ("CISCO-SYS-INFO-LOG-MIB", "csilCommandConfigGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoSysInfoLogMIBCompliance = ciscoSysInfoLogMIBCompliance.setStatus('current') csilGlobalConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 330, 2, 2, 1)).setObjects(("CISCO-SYS-INFO-LOG-MIB", "csilSysInfoLogEnabled")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): csilGlobalConfigGroup = csilGlobalConfigGroup.setStatus('current') csilServerConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 330, 2, 2, 2)).setObjects(("CISCO-SYS-INFO-LOG-MIB", "csilMaxServerAllowed"), ("CISCO-SYS-INFO-LOG-MIB", "csilMaxProfilePerServerAllowed"), ("CISCO-SYS-INFO-LOG-MIB", "csilServerAddress"), ("CISCO-SYS-INFO-LOG-MIB", "csilServerAddressType"), ("CISCO-SYS-INFO-LOG-MIB", "csilServerProfileIndex"), ("CISCO-SYS-INFO-LOG-MIB", "csilServerProtocol"), ("CISCO-SYS-INFO-LOG-MIB", "csilServerInterval"), ("CISCO-SYS-INFO-LOG-MIB", "csilServerLoggingFileName"), ("CISCO-SYS-INFO-LOG-MIB", "csilServerRcpUserName"), ("CISCO-SYS-INFO-LOG-MIB", "csilServerLastStatus"), ("CISCO-SYS-INFO-LOG-MIB", "csilServerRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): csilServerConfigGroup = csilServerConfigGroup.setStatus('current') csilCommandConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 330, 2, 2, 3)).setObjects(("CISCO-SYS-INFO-LOG-MIB", "csilMaxCommandPerProfile"), ("CISCO-SYS-INFO-LOG-MIB", "csilCommandString"), ("CISCO-SYS-INFO-LOG-MIB", "csilCommandExecOrder"), ("CISCO-SYS-INFO-LOG-MIB", "csilCommandStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): csilCommandConfigGroup = csilCommandConfigGroup.setStatus('current') csilNotifControlGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 330, 2, 2, 4)).setObjects(("CISCO-SYS-INFO-LOG-MIB", "csilSysInfoLogNotifEnabled")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): csilNotifControlGroup = csilNotifControlGroup.setStatus('current') csilLoggingFailNotifGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 9, 9, 330, 2, 2, 5)).setObjects(("CISCO-SYS-INFO-LOG-MIB", "csilLoggingFailNotif")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): csilLoggingFailNotifGroup = csilLoggingFailNotifGroup.setStatus('current') mibBuilder.exportSymbols("CISCO-SYS-INFO-LOG-MIB", csilCommandIndex=csilCommandIndex, csilServerProfileIndex=csilServerProfileIndex, csilCommandConfig=csilCommandConfig, csilServerEntry=csilServerEntry, csilCommandProfileIndex=csilCommandProfileIndex, csilCommandConfigGroup=csilCommandConfigGroup, csilGlobalConfigGroup=csilGlobalConfigGroup, ciscoSysInfoLogMIBObjects=ciscoSysInfoLogMIBObjects, csilLoggingFailNotifGroup=csilLoggingFailNotifGroup, csilGlobalConfig=csilGlobalConfig, csilCommandString=csilCommandString, ciscoSysInfoLogMIBCompliance=ciscoSysInfoLogMIBCompliance, ciscoSysInfoLogMIB=ciscoSysInfoLogMIB, ciscoSysInfoLogMIBCompliances=ciscoSysInfoLogMIBCompliances, csilMaxProfilePerServerAllowed=csilMaxProfilePerServerAllowed, csilServerRcpUserName=csilServerRcpUserName, csilServerRowStatus=csilServerRowStatus, csilServerConfigGroup=csilServerConfigGroup, csilServerInterval=csilServerInterval, csilSysInfoLogNotifEnabled=csilSysInfoLogNotifEnabled, csilServerIndex=csilServerIndex, ciscoSysInfoLogMIBNotifs=ciscoSysInfoLogMIBNotifs, csilNotifControlGroup=csilNotifControlGroup, csilServerAddressType=csilServerAddressType, csilCommandStatus=csilCommandStatus, csilLoggingFailNotif=csilLoggingFailNotif, PYSNMP_MODULE_ID=ciscoSysInfoLogMIB, csilServerLastStatus=csilServerLastStatus, csilCommandExecOrder=csilCommandExecOrder, ciscoSysInfoLogMIBGroups=ciscoSysInfoLogMIBGroups, csilServerProtocol=csilServerProtocol, csilSysInfoLogEnabled=csilSysInfoLogEnabled, csilServerConfig=csilServerConfig, ciscoSysInfoLogMIBConform=ciscoSysInfoLogMIBConform, csilCommandsTable=csilCommandsTable, csilServerAddress=csilServerAddress, csilServerLoggingFileName=csilServerLoggingFileName, csilMaxServerAllowed=csilMaxServerAllowed, csilCommandsEntry=csilCommandsEntry, csilMaxCommandPerProfile=csilMaxCommandPerProfile, csilServerTable=csilServerTable)
124.858586
1,859
0.75633
2cc029785f36a64242e7cb5f91e128444d80da67
1,469
cpp
C++
core/projects/redmax/Actuator/ActuatorMotor.cpp
eanswer/DiffHand
d7b9c068b7fa364935f3dc9d964d63e1e3a774c8
[ "MIT" ]
36
2021-07-13T19:28:50.000Z
2022-01-09T14:52:15.000Z
core/projects/redmax/Actuator/ActuatorMotor.cpp
eanswer/DiffHand
d7b9c068b7fa364935f3dc9d964d63e1e3a774c8
[ "MIT" ]
null
null
null
core/projects/redmax/Actuator/ActuatorMotor.cpp
eanswer/DiffHand
d7b9c068b7fa364935f3dc9d964d63e1e3a774c8
[ "MIT" ]
6
2021-07-15T02:06:29.000Z
2021-11-23T03:06:14.000Z
#include "Actuator/ActuatorMotor.h" #include "Joint/Joint.h" namespace redmax { ActuatorMotor::ActuatorMotor(Joint* joint, VectorX ctrl_min, VectorX ctrl_max, std::string name) : Actuator(joint->_ndof, ctrl_min, ctrl_max, name) { _joint = joint; } ActuatorMotor::ActuatorMotor(Joint* joint, dtype ctrl_min, dtype ctrl_max, std::string name) : Actuator(joint->_ndof, ctrl_min, ctrl_max, name) { _joint = joint; } void ActuatorMotor::computeForce(VectorX& fm, VectorX& fr) { VectorX u = _u.cwiseMin(VectorX::Ones(_joint->_ndof)).cwiseMax(VectorX::Ones(_joint->_ndof) * -1.); fr.segment(_joint->_index[0], _joint->_ndof) += ((u + VectorX::Ones(_joint->_ndof)) / 2.).cwiseProduct(_ctrl_max - _ctrl_min) + _ctrl_min; } void ActuatorMotor::computeForceWithDerivative(VectorX& fm, VectorX& fr, MatrixX& Km, MatrixX& Dm, MatrixX& Kr, MatrixX& Dr) { VectorX u = _u.cwiseMin(VectorX::Ones(_joint->_ndof)).cwiseMax(VectorX::Ones(_joint->_ndof) * -1.); fr.segment(_joint->_index[0], _joint->_ndof) += ((u + VectorX::Ones(_joint->_ndof)) / 2.).cwiseProduct(_ctrl_max - _ctrl_min) + _ctrl_min; } void ActuatorMotor::compute_dfdu(MatrixX& dfm_du, MatrixX& dfr_du) { for (int i = 0;i < _joint->_ndof;i++) if (_u[i] < -1. || _u[i] > 1.) { dfr_du(_joint->_index[i], _index[i]) += 0.; } else { dfr_du(_joint->_index[i], _index[i]) += (_ctrl_max[i] - _ctrl_min[i]) / 2.; } } }
38.657895
142
0.650783
c8c684ca183bc464d87097d673cdfc51e6c9ba52
1,185
css
CSS
app/javascript/vendor/jquery.fluidbox.css
zwdgit/bbs-v2back
799e0ac59b75689fc7d5932b8f514e0e627eceea
[ "Ruby", "CC-BY-4.0", "MIT" ]
1,802
2016-10-20T09:06:17.000Z
2022-03-31T04:45:23.000Z
app/javascript/vendor/jquery.fluidbox.css
zwdgit/bbs-v2back
799e0ac59b75689fc7d5932b8f514e0e627eceea
[ "Ruby", "CC-BY-4.0", "MIT" ]
429
2016-10-20T10:15:18.000Z
2022-03-29T07:54:30.000Z
app/javascript/vendor/jquery.fluidbox.css
zwdgit/bbs-v2back
799e0ac59b75689fc7d5932b8f514e0e627eceea
[ "Ruby", "CC-BY-4.0", "MIT" ]
619
2016-10-20T13:22:05.000Z
2022-03-30T09:45:33.000Z
.fluidbox { outline: none; } .fluidbox-overlay { cursor: pointer; cursor: -webkit-zoom-out; cursor: -moz-zoom-out; opacity: 0; position: fixed; top: 0; left: 0; bottom: 0; right: 0; transition: all .25s ease-in-out; } .fluidbox-wrap { background-position: center center; background-size: cover; margin: 0 auto; position: relative; transition: all .25s ease-in-out; text-align: center; } .fluidbox-ghost { background-size: cover; background-position: center center; position: absolute; z-index: 2000 !important; transition: all .25s ease-in-out; } .fluidbox-closed .fluidbox-ghost { -webkit-transition: top, left, opacity, -webkit-transform; -moz-transition: top, left, opacity, -moz-transform; -o-transition: top, left, opacity, -o-transform; transition: top, left, opacity, transform; transition-delay: 0, 0, .25s, 0; } .fluidbox-opened { cursor: pointer; cursor: -webkit-zoom-out !important; cursor: -moz-zoom-out !important; } .fluidbox-opened .fluidbox-overlay { z-index: 2000 !important; background: var(--navbar-background-color) !important; } .fluidbox-opened .fluidbox-wrap { z-index: 2001 !important; }
20.789474
60
0.688608
144b647a5cc52ee192f1a062120198509e8540ef
35
ts
TypeScript
src/index.ts
yardenShacham/jx-injector
7b4b341cc47125988c9349e3d72e646a9db5242e
[ "MIT" ]
null
null
null
src/index.ts
yardenShacham/jx-injector
7b4b341cc47125988c9349e3d72e646a9db5242e
[ "MIT" ]
null
null
null
src/index.ts
yardenShacham/jx-injector
7b4b341cc47125988c9349e3d72e646a9db5242e
[ "MIT" ]
null
null
null
export {injector} from './injector'
35
35
0.742857
581fde81790ed72c41ddc0d1504051f9c5894c0f
898
rb
Ruby
test/integration/verify/controls/azurerm_virtual_networks.rb
jnahelou/inspec-azure
040d03729ab702c5604f247e86c6eab98cc14391
[ "Apache-2.0" ]
79
2018-07-12T12:08:23.000Z
2022-03-29T05:40:10.000Z
test/integration/verify/controls/azurerm_virtual_networks.rb
jnahelou/inspec-azure
040d03729ab702c5604f247e86c6eab98cc14391
[ "Apache-2.0" ]
404
2018-07-02T17:40:32.000Z
2022-03-31T09:44:15.000Z
test/integration/verify/controls/azurerm_virtual_networks.rb
Rohit1509/inspec-azure
fa2e6f452c17e85cbf769ba526aee1c29086047c
[ "Apache-2.0" ]
92
2018-07-04T03:48:19.000Z
2022-03-25T21:54:45.000Z
resource_group = input('resource_group', value: nil) vnet = input('vnet_name', value: nil) control 'azurerm_virtual_networks' do describe azurerm_virtual_networks(resource_group: resource_group) do it { should exist } its('names') { should be_an(Array) } its('names') { should include(vnet) } end describe azurerm_virtual_networks(resource_group: 'fake-group') do it { should_not exist } its('names') { should_not include('fake') } end describe azurerm_virtual_networks(resource_group: resource_group) .where(name: vnet) do it { should exist } end end control 'azure_virtual_networks' do impact 1.0 title 'Ensure that the resource tests all virtual networks in a subscription.' describe azure_virtual_networks do it { should exist } end end
29.933333
80
0.646993
8453be3181494a471f7adeb5c2718d6d313df89c
1,059
dart
Dart
lib/settings/settings_screen.dart
Lytra/calculator
0e817d896f763e4c69fef6dbd365f328a627b2a4
[ "MIT" ]
1
2018-09-30T20:27:42.000Z
2018-09-30T20:27:42.000Z
lib/settings/settings_screen.dart
Lytra/calculator
0e817d896f763e4c69fef6dbd365f328a627b2a4
[ "MIT" ]
null
null
null
lib/settings/settings_screen.dart
Lytra/calculator
0e817d896f763e4c69fef6dbd365f328a627b2a4
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:calculator/settings/setting.dart'; import 'package:calculator/settings/settings_types.dart'; import 'package:calculator/settings/shared_preferences_settings_adapter.dart'; class SettingsScreen extends StatelessWidget { static final _adapter = SharedPreferencesSettingsAdapter(); final List<SettingScaffold> _settings = [ SettingScaffold( title: "Input Hand", description: "In landscape orientation, display the keypad on the left or right side of the screen.", icon: Icon(Icons.compare_arrows), setting: ListSetting( adapterKey: "input_hand", adapter: _adapter, items: ["Left", "Right"], defaultValue: 0 ) ) ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Settings") ), body: ListView.builder( itemBuilder: (context, index) { return _settings[index]; }, itemCount: _settings.length, ) ); } }
27.868421
108
0.661945
a35cd0dd31d4c54bba57b36796bb22191d9db518
12,395
java
Java
app/build/generated/not_namespaced_r_class_sources/debug/r/android/support/coreui/R.java
saytoonz/YouSave
21cac4f04f2b179b095edd738222d26e1278a0e7
[ "MIT" ]
6
2019-10-30T23:14:43.000Z
2022-03-16T16:37:23.000Z
app/build/generated/not_namespaced_r_class_sources/release/r/android/support/coreui/R.java
saytoonz/YouSave
21cac4f04f2b179b095edd738222d26e1278a0e7
[ "MIT" ]
null
null
null
app/build/generated/not_namespaced_r_class_sources/release/r/android/support/coreui/R.java
saytoonz/YouSave
21cac4f04f2b179b095edd738222d26e1278a0e7
[ "MIT" ]
null
null
null
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package android.support.coreui; public final class R { private R() {} public static final class attr { private attr() {} public static final int alpha = 0x7f030027; public static final int coordinatorLayoutStyle = 0x7f0300a9; public static final int font = 0x7f0300dc; public static final int fontProviderAuthority = 0x7f0300df; public static final int fontProviderCerts = 0x7f0300e0; public static final int fontProviderFetchStrategy = 0x7f0300e1; public static final int fontProviderFetchTimeout = 0x7f0300e2; public static final int fontProviderPackage = 0x7f0300e3; public static final int fontProviderQuery = 0x7f0300e4; public static final int fontStyle = 0x7f0300e5; public static final int fontVariationSettings = 0x7f0300e6; public static final int fontWeight = 0x7f0300e7; public static final int keylines = 0x7f030113; public static final int layout_anchor = 0x7f030118; public static final int layout_anchorGravity = 0x7f030119; public static final int layout_behavior = 0x7f03011a; public static final int layout_dodgeInsetEdges = 0x7f030146; public static final int layout_insetEdge = 0x7f03014f; public static final int layout_keyline = 0x7f030150; public static final int statusBarBackground = 0x7f0301ce; public static final int ttcIndex = 0x7f030230; } public static final class color { private color() {} public static final int notification_action_color_filter = 0x7f05007b; public static final int notification_icon_bg_color = 0x7f05007c; public static final int ripple_material_light = 0x7f050086; public static final int secondary_text_default_material_light = 0x7f050089; } public static final class dimen { private dimen() {} public static final int compat_button_inset_horizontal_material = 0x7f06005a; public static final int compat_button_inset_vertical_material = 0x7f06005b; public static final int compat_button_padding_horizontal_material = 0x7f06005c; public static final int compat_button_padding_vertical_material = 0x7f06005d; public static final int compat_control_corner_material = 0x7f06005e; public static final int compat_notification_large_icon_max_height = 0x7f06005f; public static final int compat_notification_large_icon_max_width = 0x7f060060; public static final int notification_action_icon_size = 0x7f0600f2; public static final int notification_action_text_size = 0x7f0600f3; public static final int notification_big_circle_margin = 0x7f0600f4; public static final int notification_content_margin_start = 0x7f0600f5; public static final int notification_large_icon_height = 0x7f0600f6; public static final int notification_large_icon_width = 0x7f0600f7; public static final int notification_main_column_padding_top = 0x7f0600f8; public static final int notification_media_narrow_margin = 0x7f0600f9; public static final int notification_right_icon_size = 0x7f0600fa; public static final int notification_right_side_padding_top = 0x7f0600fb; public static final int notification_small_icon_background_padding = 0x7f0600fc; public static final int notification_small_icon_size_as_large = 0x7f0600fd; public static final int notification_subtext_size = 0x7f0600fe; public static final int notification_top_pad = 0x7f0600ff; public static final int notification_top_pad_large_text = 0x7f060100; } public static final class drawable { private drawable() {} public static final int notification_action_background = 0x7f070095; public static final int notification_bg = 0x7f070096; public static final int notification_bg_low = 0x7f070097; public static final int notification_bg_low_normal = 0x7f070098; public static final int notification_bg_low_pressed = 0x7f070099; public static final int notification_bg_normal = 0x7f07009a; public static final int notification_bg_normal_pressed = 0x7f07009b; public static final int notification_icon_background = 0x7f07009c; public static final int notification_template_icon_bg = 0x7f07009d; public static final int notification_template_icon_low_bg = 0x7f07009e; public static final int notification_tile_bg = 0x7f07009f; public static final int notify_panel_notification_icon_bg = 0x7f0700a0; } public static final class id { private id() {} public static final int action_container = 0x7f08000f; public static final int action_divider = 0x7f080011; public static final int action_image = 0x7f080013; public static final int action_text = 0x7f08001a; public static final int actions = 0x7f08001b; public static final int async = 0x7f080024; public static final int blocking = 0x7f08002a; public static final int bottom = 0x7f08002b; public static final int chronometer = 0x7f08003a; public static final int end = 0x7f08006a; public static final int forever = 0x7f080075; public static final int icon = 0x7f080080; public static final int icon_group = 0x7f080081; public static final int info = 0x7f080089; public static final int italic = 0x7f08008b; public static final int left = 0x7f080094; public static final int line1 = 0x7f080095; public static final int line3 = 0x7f080096; public static final int none = 0x7f0800a8; public static final int normal = 0x7f0800a9; public static final int notification_background = 0x7f0800aa; public static final int notification_main_column = 0x7f0800ab; public static final int notification_main_column_container = 0x7f0800ac; public static final int right = 0x7f0800c1; public static final int right_icon = 0x7f0800c2; public static final int right_side = 0x7f0800c3; public static final int start = 0x7f0800ef; public static final int tag_transition_group = 0x7f0800f6; public static final int tag_unhandled_key_event_manager = 0x7f0800f7; public static final int tag_unhandled_key_listeners = 0x7f0800f8; public static final int text = 0x7f0800f9; public static final int text2 = 0x7f0800fa; public static final int time = 0x7f080103; public static final int title = 0x7f080104; public static final int top = 0x7f080109; } public static final class integer { private integer() {} public static final int status_bar_notification_info_maxnum = 0x7f09000e; } public static final class layout { private layout() {} public static final int notification_action = 0x7f0b0057; public static final int notification_action_tombstone = 0x7f0b0058; public static final int notification_template_custom_big = 0x7f0b0059; public static final int notification_template_icon_group = 0x7f0b005a; public static final int notification_template_part_chronometer = 0x7f0b005b; public static final int notification_template_part_time = 0x7f0b005c; } public static final class string { private string() {} public static final int status_bar_notification_info_overflow = 0x7f0e0056; } public static final class style { private style() {} public static final int TextAppearance_Compat_Notification = 0x7f0f0129; public static final int TextAppearance_Compat_Notification_Info = 0x7f0f012a; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0f012b; public static final int TextAppearance_Compat_Notification_Time = 0x7f0f012c; public static final int TextAppearance_Compat_Notification_Title = 0x7f0f012d; public static final int Widget_Compat_NotificationActionContainer = 0x7f0f01d3; public static final int Widget_Compat_NotificationActionText = 0x7f0f01d4; public static final int Widget_Support_CoordinatorLayout = 0x7f0f020b; } public static final class styleable { private styleable() {} public static final int[] ColorStateListItem = { 0x10101a5, 0x101031f, 0x7f030027 }; public static final int ColorStateListItem_android_color = 0; public static final int ColorStateListItem_android_alpha = 1; public static final int ColorStateListItem_alpha = 2; public static final int[] CoordinatorLayout = { 0x7f030113, 0x7f0301ce }; public static final int CoordinatorLayout_keylines = 0; public static final int CoordinatorLayout_statusBarBackground = 1; public static final int[] CoordinatorLayout_Layout = { 0x10100b3, 0x7f030118, 0x7f030119, 0x7f03011a, 0x7f030146, 0x7f03014f, 0x7f030150 }; public static final int CoordinatorLayout_Layout_android_layout_gravity = 0; public static final int CoordinatorLayout_Layout_layout_anchor = 1; public static final int CoordinatorLayout_Layout_layout_anchorGravity = 2; public static final int CoordinatorLayout_Layout_layout_behavior = 3; public static final int CoordinatorLayout_Layout_layout_dodgeInsetEdges = 4; public static final int CoordinatorLayout_Layout_layout_insetEdge = 5; public static final int CoordinatorLayout_Layout_layout_keyline = 6; public static final int[] FontFamily = { 0x7f0300df, 0x7f0300e0, 0x7f0300e1, 0x7f0300e2, 0x7f0300e3, 0x7f0300e4 }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f0300dc, 0x7f0300e5, 0x7f0300e6, 0x7f0300e7, 0x7f030230 }; public static final int FontFamilyFont_android_font = 0; public static final int FontFamilyFont_android_fontWeight = 1; public static final int FontFamilyFont_android_fontStyle = 2; public static final int FontFamilyFont_android_ttcIndex = 3; public static final int FontFamilyFont_android_fontVariationSettings = 4; public static final int FontFamilyFont_font = 5; public static final int FontFamilyFont_fontStyle = 6; public static final int FontFamilyFont_fontVariationSettings = 7; public static final int FontFamilyFont_fontWeight = 8; public static final int FontFamilyFont_ttcIndex = 9; public static final int[] GradientColor = { 0x101019d, 0x101019e, 0x10101a1, 0x10101a2, 0x10101a3, 0x10101a4, 0x1010201, 0x101020b, 0x1010510, 0x1010511, 0x1010512, 0x1010513 }; public static final int GradientColor_android_startColor = 0; public static final int GradientColor_android_endColor = 1; public static final int GradientColor_android_type = 2; public static final int GradientColor_android_centerX = 3; public static final int GradientColor_android_centerY = 4; public static final int GradientColor_android_gradientRadius = 5; public static final int GradientColor_android_tileMode = 6; public static final int GradientColor_android_centerColor = 7; public static final int GradientColor_android_startX = 8; public static final int GradientColor_android_startY = 9; public static final int GradientColor_android_endX = 10; public static final int GradientColor_android_endY = 11; public static final int[] GradientColorItem = { 0x10101a5, 0x1010514 }; public static final int GradientColorItem_android_color = 0; public static final int GradientColorItem_android_offset = 1; } }
58.466981
185
0.739976
20d134c42d2db12bf738cc2a0a0947887d9b0a4f
7,744
py
Python
scripts/tests/test_pypi_upload.py
brianbruggeman/ves
6d3c237d08f1e6f6c85fe54865b56c65d9f6a77e
[ "MIT" ]
3
2018-01-31T19:55:28.000Z
2019-05-30T20:21:18.000Z
scripts/tests/test_pypi_upload.py
brianbruggeman/ves
6d3c237d08f1e6f6c85fe54865b56c65d9f6a77e
[ "MIT" ]
12
2019-01-18T16:16:19.000Z
2019-06-14T03:26:34.000Z
scripts/tests/test_pypi_upload.py
brianbruggeman/ves
6d3c237d08f1e6f6c85fe54865b56c65d9f6a77e
[ "MIT" ]
1
2019-01-18T16:20:15.000Z
2019-01-18T16:20:15.000Z
from dataclasses import asdict, dataclass, field from pathlib import Path from typing import Dict import pytest @dataclass class Counts: """Stores call counts of various api methods and contains methods to help capture and validate call counts Attributes: create: expected call count for vsh.api.create enter: expected call count for vsh.api.enter remove: expected call count for vsh.api.remove show_envs: expected call count for vsh.api.show_envs show_version: expected call count for vsh.api.show_version """ create: int = 0 enter: int = 0 remove: int = 0 show_envs: int = 0 show_version: int = 0 def check(self) -> Dict[str, bool]: """Returns a dictionary of boolean which represents whether or not the actual call counts matched the expected call counts. """ import vsh.api counts = { method_name: getattr(vsh.api, method_name).call_count == expected_call_count for method_name, expected_call_count in asdict(self).items() } return counts def mock_all(self, mocker, venv_path: Path, exit_code: int = 0): """Mocks all tracked api methods Args: mocker: pytest-mock's mocker fixture venv_path: path to virtual environment under test exit_code: the expected exit code of the vsh.api.enter call """ self.mock_create(mocker=mocker, venv_path=venv_path) self.mock_enter(mocker=mocker, exit_code=exit_code) self.mock_remove(mocker=mocker, venv_path=venv_path) self.mock_show_envs(mocker=mocker) self.mock_show_version(mocker=mocker) def mock_create(self, mocker, venv_path: Path): mocker.patch('vsh.api.create', return_value=venv_path) def mock_enter(self, mocker, exit_code: int = 0): mocker.patch('vsh.api.enter', return_value=exit_code) def mock_remove(self, mocker, venv_path: Path): mocker.patch('vsh.api.remove', return_value=venv_path) def mock_show_envs(self, mocker): mocker.patch('vsh.api.show_envs') def mock_show_version(self, mocker): mocker.patch('vsh.api.show_version') # ###################################################################### @dataclass class CleanupTestCase: venv_path: Path = field(default_factory=Path) repo_path: Path = field(default_factory=Path) verbose: int = 0 counts: Counts = field(default_factory=Counts) @property def kwds(self): kwds = asdict(self) kwds.pop('counts') return kwds @pytest.mark.parametrize('test_case', [ CleanupTestCase(counts=Counts(remove=1)) ]) def test_cleanup(test_case, venv_path, repo_path, mocker): import shutil # noqa from ..pypi_upload import cleanup test_case.venv_path = venv_path test_case.repo_path = repo_path test_case.counts.mock_all(mocker=mocker, venv_path=venv_path) mocker.patch('shutil.rmtree') cleanup(**test_case.kwds) checked = test_case.counts.check() assert all(checked.values()) # ###################################################################### @dataclass class CreateDistTestCase: venv_path: Path = field(default_factory=Path) verbose: int = 0 counts: Counts = field(default_factory=Counts) @property def kwds(self): kwds = asdict(self) kwds.pop('counts') return kwds @pytest.mark.parametrize('test_case', [ CreateDistTestCase(counts=Counts(enter=1)) ]) def test_create_distribution(test_case, venv_path, mocker): from ..pypi_upload import create_distribution test_case.venv_path = venv_path test_case.counts.mock_all(mocker=mocker, venv_path=venv_path) create_distribution(**test_case.kwds) checked = test_case.counts.check() assert all(checked.values()) # ###################################################################### @dataclass class FindMatchedGpgTestCase: repo_path: Path = field(default_factory=Path) counts: Counts = field(default_factory=Counts) @property def kwds(self): kwds = asdict(self) kwds.pop('counts') return kwds @pytest.mark.parametrize('test_case', [ FindMatchedGpgTestCase(), ]) def test_find_matched_gpg(test_case, repo_path, venv_path, mocker): from ..pypi_upload import find_matched_gpg test_case.repo_path = repo_path test_case.counts.mock_all(mocker=mocker, venv_path=venv_path) find_matched_gpg(**test_case.kwds) checked = test_case.counts.check() assert all(checked.values()) # ###################################################################### @dataclass class SetupVenvTestCase: venv_path: Path = field(default_factory=Path) repo_path: Path = field(default_factory=Path) verbose: int = 0 counts: Counts = field(default_factory=Counts) @property def kwds(self): kwds = asdict(self) kwds.pop('counts') return kwds @pytest.mark.parametrize('test_case', [ SetupVenvTestCase(counts=Counts(create=1, enter=2)) ]) def test_setup_venv(test_case, repo_path, venv_path, mocker): from ..pypi_upload import setup_venv mocker.patch('shutil.rmtree') test_case.repo_path = repo_path test_case.counts.mock_all(mocker=mocker, venv_path=venv_path) setup_venv(**test_case.kwds) checked = test_case.counts.check() assert all(checked.values()) # ###################################################################### @dataclass class RunTestsTestCase: venv_path: Path = field(default_factory=Path) verbose: int = 0 counts: Counts = field(default_factory=Counts) @property def kwds(self): kwds = asdict(self) kwds.pop('counts') return kwds @pytest.mark.parametrize('test_case', [ RunTestsTestCase(counts=Counts(enter=1)) ]) def test_run_tests(test_case, venv_path, mocker): from ..pypi_upload import run_tests test_case.venv_path = venv_path test_case.counts.mock_all(mocker=mocker, venv_path=venv_path) run_tests(**test_case.kwds) checked = test_case.counts.check() assert all(checked.values()) # ###################################################################### @dataclass class UploadDistTestCase: venv_path: Path = field(default_factory=Path) repo_path: Path = field(default_factory=Path) prod: bool = False verbose: int = 0 matched_dist_file_path: Path = field(default_factory=Path) matched_gpg_path: Path = field(default_factory=Path) counts: Counts = field(default_factory=Counts) @property def kwds(self): kwds = asdict(self) kwds.pop('counts') kwds.pop('matched_dist_file_path') kwds.pop('matched_gpg_path') return kwds @pytest.mark.parametrize('test_case', [ UploadDistTestCase(matched_dist_file_path=Path('/tmp/dist-path'), matched_gpg_path=Path('/tmp/gpg_path'), prod=False, counts=Counts(enter=1)), UploadDistTestCase(matched_dist_file_path=Path('/tmp/dist-path'), matched_gpg_path=Path('/tmp/gpg_path'), prod=True, counts=Counts(enter=1)), ]) def test_upload_distribution(test_case, repo_path, venv_path, mocker): from ..pypi_upload import find_matched_gpg, upload_distribution mocker.patch( 'scripts.pypi_upload.find_matched_gpg', return_value=(test_case.matched_dist_file_path, test_case.matched_gpg_path) ) test_case.venv_path = venv_path test_case.venv_path = repo_path test_case.counts.mock_all(mocker=mocker, venv_path=venv_path) upload_distribution(**test_case.kwds) find_matched_gpg.call_count = 1 checked = test_case.counts.check() assert all(checked.values())
29.784615
146
0.656121
7ad8ed99f322e51a473e0451c7abb5a5c7130de5
596
cs
C#
CommunityPlugin/Non Native Modifications/TopMenu/CreateCustomFields.cs
WyndhamCapital/CommunityPlugin
b8759a01451316b1d50e1e42000ce94f0eb5eaad
[ "MIT" ]
null
null
null
CommunityPlugin/Non Native Modifications/TopMenu/CreateCustomFields.cs
WyndhamCapital/CommunityPlugin
b8759a01451316b1d50e1e42000ce94f0eb5eaad
[ "MIT" ]
null
null
null
CommunityPlugin/Non Native Modifications/TopMenu/CreateCustomFields.cs
WyndhamCapital/CommunityPlugin
b8759a01451316b1d50e1e42000ce94f0eb5eaad
[ "MIT" ]
null
null
null
using CommunityPlugin.Objects; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CommunityPlugin.Non_Native_Modifications.TopMenu { public class CreateCustomFields : MenuItemBase { public override bool CanRun() { return PluginAccess.CheckAccess(nameof(CreateCustomFields)); } protected override void menuItem_Click(object sender, EventArgs e) { CreateCustomFields_Form f = new CreateCustomFields_Form(); f.Show(); } } }
23.84
74
0.682886
fe4575e0c7afeb0334739a69e7010d636171e7bc
1,694
swift
Swift
Timmee/TasksKit/Sources/Service layer/Entities/Todo/Subtask.swift
NoFearJoe/Timmee
13cb056300129d252b758cb482cae8a8fbf8881f
[ "Apache-2.0" ]
null
null
null
Timmee/TasksKit/Sources/Service layer/Entities/Todo/Subtask.swift
NoFearJoe/Timmee
13cb056300129d252b758cb482cae8a8fbf8881f
[ "Apache-2.0" ]
null
null
null
Timmee/TasksKit/Sources/Service layer/Entities/Todo/Subtask.swift
NoFearJoe/Timmee
13cb056300129d252b758cb482cae8a8fbf8881f
[ "Apache-2.0" ]
null
null
null
// // Subtask.swift // Timmee // // Created by Ilya Kharabet on 05.10.17. // Copyright © 2017 Mesterra. All rights reserved. // import Foundation public final class Subtask { public let id: String public var title: String public var isDone: Bool public var sortPosition: Int public let creationDate: Date public init(id: String, title: String, isDone: Bool, sortPosition: Int, creationDate: Date) { self.id = id self.title = title self.isDone = isDone self.sortPosition = sortPosition self.creationDate = creationDate } public convenience init(id: String, title: String, sortPosition: Int) { self.init(id: id, title: title, isDone: false, sortPosition: sortPosition, creationDate: Date()) } public convenience init(entity: SubtaskEntity) { self.init(id: entity.id ?? "", title: entity.title ?? "", isDone: entity.isDone, sortPosition: Int(entity.sortPosition), creationDate: entity.creationDate! as Date) } public var copy: Subtask { return Subtask(id: id, title: title, isDone: isDone, sortPosition: sortPosition, creationDate: creationDate) } } extension Subtask: Equatable { public static func == (lhs: Subtask, rhs: Subtask) -> Bool { return lhs.id == rhs.id && lhs.title == rhs.title && lhs.isDone == rhs.isDone && lhs.sortPosition == rhs.sortPosition } }
27.770492
97
0.551358
a35b30437e06ccbe3b2151c18546d96847af791c
4,740
java
Java
grouper-ui/java/src/edu/internet2/middleware/grouper/ui/util/SubjectAsMap.java
manasys/grouper
f6fc9e9d93768a971187289afd9df6d650a128e8
[ "Apache-2.0" ]
63
2015-02-02T17:24:08.000Z
2022-02-18T07:20:13.000Z
grouper-ui/java/src/edu/internet2/middleware/grouper/ui/util/SubjectAsMap.java
manasys/grouper
f6fc9e9d93768a971187289afd9df6d650a128e8
[ "Apache-2.0" ]
92
2015-01-21T14:40:00.000Z
2022-02-10T23:56:03.000Z
grouper-ui/java/src/edu/internet2/middleware/grouper/ui/util/SubjectAsMap.java
manasys/grouper
f6fc9e9d93768a971187289afd9df6d650a128e8
[ "Apache-2.0" ]
70
2015-03-23T08:50:33.000Z
2022-03-18T07:00:57.000Z
/******************************************************************************* * Copyright 2012 Internet2 * * 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. ******************************************************************************/ /* Copyright 2004-2007 University Corporation for Advanced Internet Development, Inc. Copyright 2004-2007 The University Of Bristol 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 edu.internet2.middleware.grouper.ui.util; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import org.apache.commons.beanutils.WrapDynaBean; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import edu.internet2.middleware.subject.Subject; import edu.internet2.middleware.subject.SubjectNotFoundException; import edu.internet2.middleware.subject.SubjectNotUniqueException; /** * Wraps a Subject - allows non persistent values to be stored for the UI and * works well with JSTL * <p /> * * @author Gary Brown. * @version $Id: SubjectAsMap.java,v 1.13 2009-03-04 15:36:09 isgwb Exp $ */ public class SubjectAsMap extends ObjectAsMap { protected static final Log LOG = LogFactory.getLog(SubjectAsMap.class); protected String objType = "I2miSubject"; private Subject subject = null; protected SubjectAsMap() { } /** * @param subject * to wrap */ public SubjectAsMap(Subject subject) { super(); init(subject); } protected void init(Subject subject) { super.objType = objType; dynaBean = new WrapDynaBean(subject); if (subject == null) throw new NullPointerException( "Cannot create SubjectAsMap with a null Subject"); this.subject = subject; wrappedObject = subject; } /* * (non-Javadoc) * * @see java.util.Map#get(java.lang.Object) */ public Object get(Object key) { try { Object obj = getByIntrospection(key); if(obj!=null) return obj; obj = super.get(key); //Map overrides wrapped Subject if(obj==null && "useMulti".equals(key)) { return null; } if(obj!=null && !"".equals(obj)) return obj; //if (values != null && values.size() != 0) // obj = values.iterator().next(); if ("id".equals(key)||"subjectId".equals(key)) obj = subject.getId(); else if ("description".equals(key) || "desc".equals(key)) { obj = subject.getDescription(); if((obj==null || "".equals(obj)) && subject.getType().getName().equals("group")) { obj = subject.getAttributeValue("displayExtension"); } } else if ("subjectType".equals(key)) obj = subject.getType().getName(); else if ("sourceId".equals(key)) obj = subject.getSource().getId(); if (obj == null) { //No value so check wrapped Subject for value String sep = (String)this.get("useMulti"); if(sep==null) { obj = subject.getAttributeValue((String) key); }else{ StringBuffer sb = new StringBuffer(); Set values = (Set)subject.getAttributeValues((String)key); if(values==null) return null; Iterator it = values.iterator(); Object val; int count=0; while(it.hasNext()) { val=it.next(); if(count>0) { sb.append(sep); sb.append(" "); } sb.append(val); } obj=sb.toString(); } } return obj; }catch(Exception e) { LOG.error(e); return "Unresolvable"; } } protected Set getExtraKeys() { Set keys = new HashSet(); keys.add("sourceId"); keys.add("subjectType"); keys.add("subjectId"); return keys; } }
30.191083
89
0.62827
1a71474cb1b32cb52d07bbfaa0809f5cd9da371f
820
py
Python
teste_chrome.py
FranciscoACLima/Robo_NFP_Selenium
7702854f94355fee8d78a4c04fc134cf099db5f0
[ "MIT" ]
null
null
null
teste_chrome.py
FranciscoACLima/Robo_NFP_Selenium
7702854f94355fee8d78a4c04fc134cf099db5f0
[ "MIT" ]
16
2020-09-05T16:03:40.000Z
2022-03-19T17:42:05.000Z
teste_chrome.py
FranciscoACLima/Robo_NFP_Selenium
7702854f94355fee8d78a4c04fc134cf099db5f0
[ "MIT" ]
null
null
null
"""teste para abertua do navegador""" from subprocess import Popen, PIPE from nfp.servicos.interface import abrir_popup from nfp import CHREXEC, CHRPREFS, URLBASE def abrir_chrome(): chrexec = '"{}" --remote-debugging-port=9222 --user-data-dir="{}" {}'.format(CHREXEC, CHRPREFS, URLBASE) chrexec = [ CHREXEC, '--remote-debugging-port=9222', '--user-data-dir="{}"'.format(CHRPREFS), URLBASE ] Popen(chrexec, shell=False, stdout=PIPE).stdout msg = 'ROBÔ EM ESPERA\n\nFaça o login no sistema e responda ao captcha.\n' msg += 'Após o login, feche esta janela para iniciar a execução.\n' abrir_popup(msg) def test_get_versao(): from nfp.servicos.chrome import conferir_chrome print(conferir_chrome()) if __name__ == "__main__": test_get_versao()
28.275862
108
0.67561
b8953fbfd9902a32ccbaaa3c147346cbdf4652b8
19,849
h
C
src/btree.h
Minooc/CSE190-Project2
3f32bee83c42f543770b59f77098bfbabad1a5e8
[ "Apache-2.0" ]
1
2020-04-30T11:27:37.000Z
2020-04-30T11:27:37.000Z
src/btree.h
YYYTTT-code/CSE190-Project2
3f32bee83c42f543770b59f77098bfbabad1a5e8
[ "Apache-2.0" ]
null
null
null
src/btree.h
YYYTTT-code/CSE190-Project2
3f32bee83c42f543770b59f77098bfbabad1a5e8
[ "Apache-2.0" ]
1
2020-04-30T11:27:33.000Z
2020-04-30T11:27:33.000Z
/** * @author See Contributors.txt for code contributors and overview of BadgerDB. * * @section LICENSE * Copyright (c) 2012 Database Group, Computer Sciences Department, University of Wisconsin-Madison. */ #pragma once #include <iostream> #include <string> #include "string.h" #include <sstream> #include "types.h" #include "page.h" #include "file.h" #include "buffer.h" namespace badgerdb { /** * @brief Datatype enumeration type. */ enum Datatype { INTEGER = 0, DOUBLE = 1, STRING = 2 }; /** * @brief Scan operations enumeration. Passed to BTreeIndex::startScan() method. */ enum Operator { LT, /* Less Than */ LTE, /* Less Than or Equal to */ GTE, /* Greater Than or Equal to */ GT /* Greater Than */ }; /** * @brief Size of String key. */ const int STRINGSIZE = 10; /** * @brief Number of key slots in B+Tree leaf for INTEGER key. */ // sibling ptr key rid const int INTARRAYLEAFSIZE = ( Page::SIZE - sizeof( PageId ) ) / ( sizeof( int ) + sizeof( RecordId ) ); /** * @brief Number of key slots in B+Tree leaf for DOUBLE key. */ // sibling ptr key rid const int DOUBLEARRAYLEAFSIZE = ( Page::SIZE - sizeof( PageId ) ) / ( sizeof( double ) + sizeof( RecordId ) ); /** * @brief Number of key slots in B+Tree leaf for STRING key. */ // sibling ptr key rid const int STRINGARRAYLEAFSIZE = ( Page::SIZE - sizeof( PageId ) ) / ( 10 * sizeof(char) + sizeof( RecordId ) ); /** * @brief Number of key slots in B+Tree non-leaf for INTEGER key. */ // level extra pageNo key pageNo const int INTARRAYNONLEAFSIZE = ( Page::SIZE - sizeof( int ) - sizeof( PageId ) ) / ( sizeof( int ) + sizeof( PageId ) ); /** * @brief Number of key slots in B+Tree leaf for DOUBLE key. */ // level extra pageNo key pageNo -1 due to structure padding const int DOUBLEARRAYNONLEAFSIZE = (( Page::SIZE - sizeof( int ) - sizeof( PageId ) ) / ( sizeof( double ) + sizeof( PageId ) )) - 1; /** * @brief Number of key slots in B+Tree leaf for STRING key. */ // level extra pageNo key pageNo const int STRINGARRAYNONLEAFSIZE = ( Page::SIZE - sizeof( int ) - sizeof( PageId ) ) / ( 10 * sizeof(char) + sizeof( PageId ) ); /** * @brief Structure to store a key-rid pair. It is used to pass the pair to functions that * add to or make changes to the leaf node pages of the tree. Is templated for the key member. */ template <class T> class RIDKeyPair{ public: RecordId rid; T key; void set( RecordId r, T k) { rid = r; key = k; } }; /** * @brief Structure to store a key page pair which is used to pass the key and page to functions that make * any modifications to the non leaf pages of the tree. */ template <class T> class PageKeyPair{ public: PageId pageNo; T key; void set( int p, T k) { pageNo = p; key = k; } }; /** * @brief Overloaded operator to compare the key values of two rid-key pairs * and if they are the same compares to see if the first pair has * a smaller rid.pageNo value. */ template <class T> bool operator<( const RIDKeyPair<T>& r1, const RIDKeyPair<T>& r2 ) { if( r1.key != r2.key ) return r1.key < r2.key; else return r1.rid.page_number < r2.rid.page_number; } /** * @brief The meta page, which holds metadata for Index file, is always first page of the btree index file and is cast * to the following structure to store or retrieve information from it. * Contains the relation name for which the index is created, the byte offset * of the key value on which the index is made, the type of the key and the page no * of the root page. Root page starts as page 2 but since a split can occur * at the root the root page may get moved up and get a new page no. */ struct IndexMetaInfo{ /** * Name of base relation. */ char relationName[20]; /** * Offset of attribute, over which index is built, inside the record stored in pages. */ int attrByteOffset; /** * Type of the attribute over which index is built. */ Datatype attrType; /** * Page number of root page of the B+ Tree inside the file index file. */ PageId rootPageNo; }; /* Each node is a page, so once we read the page in we just cast the pointer to the page to this struct and use it to access the parts These structures basically are the format in which the information is stored in the pages for the index file depending on what kind of node they are. The level memeber of each non leaf structure seen below is set to 1 if the nodes at this level are just above the leaf nodes. Otherwise set to 0. */ /** * @brief Structure for all non-leaf nodes when the key is of INTEGER type. */ struct NonLeafNodeInt{ /** * Level of the node in the tree. */ int level; /** * Stores keys. */ int keyArray[ INTARRAYNONLEAFSIZE ]; /** * Stores page numbers of child pages which themselves are other non-leaf/leaf nodes in the tree. */ PageId pageNoArray[ INTARRAYNONLEAFSIZE + 1 ]; }; /** * @brief Structure for all non-leaf nodes when the key is of DOUBLE type. */ struct NonLeafNodeDouble{ /** * Level of the node in the tree. */ int level; /** * Stores keys. */ double keyArray[ DOUBLEARRAYNONLEAFSIZE ]; /** * Stores page numbers of child pages which themselves are other non-leaf/leaf nodes in the tree. */ PageId pageNoArray[ DOUBLEARRAYNONLEAFSIZE + 1 ]; }; /** * @brief Structure for all non-leaf nodes when the key is of STRING type. */ struct NonLeafNodeString{ /** * Level of the node in the tree. */ int level; /** * Stores keys. */ char keyArray[ STRINGARRAYNONLEAFSIZE ][ STRINGSIZE ]; /** * Stores page numbers of child pages which themselves are other non-leaf/leaf nodes in the tree. */ PageId pageNoArray[ STRINGARRAYNONLEAFSIZE + 1 ]; }; /** * @brief Structure for all leaf nodes when the key is of INTEGER type. */ struct LeafNodeInt{ /** * Stores keys. */ int keyArray[ INTARRAYLEAFSIZE ]; /** * Stores RecordIds. */ RecordId ridArray[ INTARRAYLEAFSIZE ]; /** * Page number of the leaf on the right side. * This linking of leaves allows to easily move from one leaf to the next leaf during index scan. */ PageId rightSibPageNo; }; /** * @brief Structure for all leaf nodes when the key is of DOUBLE type. */ struct LeafNodeDouble{ /** * Stores keys. */ double keyArray[ DOUBLEARRAYLEAFSIZE ]; /** * Stores RecordIds. */ RecordId ridArray[ DOUBLEARRAYLEAFSIZE ]; /** * Page number of the leaf on the right side. * This linking of leaves allows to easily move from one leaf to the next leaf during index scan. */ PageId rightSibPageNo; }; /** * @brief Structure for all leaf nodes when the key is of STRING type. */ struct LeafNodeString{ /** * Stores keys. */ char keyArray[ STRINGARRAYLEAFSIZE ][ STRINGSIZE ]; /** * Stores RecordIds. */ RecordId ridArray[ STRINGARRAYLEAFSIZE ]; /** * Page number of the leaf on the right side. * This linking of leaves allows to easily move from one leaf to the next leaf during index scan. */ PageId rightSibPageNo; }; /** * @brief BTreeIndex class. It implements a B+ Tree index on a single attribute of a * relation. This index supports only one scan at a time. */ class BTreeIndex { private: /** * File object for the index file. */ File *file; /** * Buffer Manager Instance. */ BufMgr *bufMgr; /** * Page number of meta page. */ PageId headerPageNum; /** * page number of root page of B+ tree inside index file. */ PageId rootPageNum; /** * Datatype of attribute over which index is built. */ Datatype attributeType; /** * Offset of attribute, over which index is built, inside records. */ int attrByteOffset; /** * Number of nodes in the tree. */ int numOfNodes; /** * Number of keys in leaf node, depending upon the type of key. */ int leafOccupancy; /** * Number of keys in non-leaf node, depending upon the type of key. */ int nodeOccupancy; // MEMBERS SPECIFIC TO SCANNING /** * True if an index scan has been started. */ bool scanExecuting; /** * Index of next entry to be scanned in current leaf being scanned. */ int nextEntry; /** * Page number of current page being scanned. */ PageId currentPageNum; /** * Current Page being scanned. */ Page *currentPageData; /** * Low INTEGER value for scan. */ int lowValInt; /** * Low DOUBLE value for scan. */ double lowValDouble; /** * Low STRING value for scan. */ std::string lowValString; /** * High INTEGER value for scan. */ int highValInt; /** * High DOUBLE value for scan. */ double highValDouble; /** * High STRING value for scan. */ std::string highValString; /** * Low Operator. Can only be GT(>) or GTE(>=). */ Operator lowOp; /** * High Operator. Can only be LT(<) or LTE(<=). */ Operator highOp; /** * To keep track the startScanIndex for scanner functionalities */ int startScanIndex; /** * String default value for string insertion (\0\0\0\0\0\0\0\0\0\0) */ char* STRINGDEFVAL; public: /** * BTreeIndex Constructor. * Check to see if the corresponding index file exists. If so, open the file. * If not, create it and insert entries for every tuple in the base relation using FileScan class. * * @param relationName Name of file. * @param outIndexName Return the name of index file. * @param bufMgrIn Buffer Manager Instance * @param attrByteOffset Offset of attribute, over which index is to be built, in the record * @param attrType Datatype of attribute over which index is built * @throws BadIndexInfoException If the index file already exists for the corresponding attribute, but values in metapage(relationName, attribute byte offset, attribute type etc.) do not match with values received through constructor parameters. */ BTreeIndex(const std::string & relationName, std::string & outIndexName, BufMgr *bufMgrIn, const int attrByteOffset, const Datatype attrType); /** * BTreeIndex Destructor. * End any initialized scan, flush index file, after unpinning any pinned pages, from the buffer manager * and delete file instance thereby closing the index file. * Destructor should not throw any exceptions. All exceptions should be caught in here itself. * */ ~BTreeIndex(); /**insertEntry and insertEntryString * Insert a new entry indicated by key and record. * These function is the main entry of inserting data into the tree and helpers functions will be called * from here to handle if the tree needs to be splitted. * insertEntry and insertEntryString: * @param key Key to insert, pointer to integer/double/char string * @param rid Record ID of a record whose entry is getting inserted into the index. * insertEntry: *@param leafType The type of the leaf that is going to be inserted into *@param nonLeafType The type of the leaf that is going to be inserted into **/ template <typename T, typename L, typename NL> const void insertEntry(L* leafType, NL* nonLeafType, T key, const RecordId rid); const void insertEntryString(const void* key, const RecordId rid); /* *fullNodeHandlerNumber and fullNodeHandlerString * These functions will be called when an element that is just inserted into a function * makes the node full, and hence tree split would be neccessary. * These functions also will restructure the tree once the tree has been splitted after insertion *fullHandlerNumber and fullHandlerString: *@param: currNode The current node that just got inserted into *@param: parentNode The parent node of the node that just got inserted into. *@param: currPageNo the page number of the current node that just got inserted into *@param: isLeaf Flag to indicate leaf node is calling the function *fullNodeHandlerString: *@param: LeafType Leaf node to indicate which type of leaf node we're inserting into *@param: nonleafType Non leaf node to indicate which type of non-leaf node we're inserting into *@param: isRoot Flag to indicate root node is calling the function */ template<typename L, typename NL> void fullNodeHandlerNumber(L* leafType, NL* nonLeafType, void* currNode, NL* parentNode, PageId currPageNo, bool isLeaf, bool isRoot); void fullNodeHandlerString(void * currNode, NonLeafNodeString *parentNode, PageId currPageNo, bool isLeaf); /* *insertToNodeNumber and insertToNodeString *These functions handle basic insertion to the leaf node and it's always guaranteed *the node is never full before inserted *@param: node The leaf node that is going to be inserted into *@param: keyValue key that is going to be inserted into node *@param: recordId record id that is going to be inserted into node **/ template<typename T, typename L> const void insertToNodeNumber(L * node, T keyValue, const RecordId rid); const void insertToNodeString(LeafNodeString * node, const void * key, const RecordId rid); /* *splitLeafNode and splitLeafNodeString *These functions handle the splitting of the leaf nodes into two parts: left and right * nodes while also assigning middleKey and newly created pageId by reference *@param: leftNode The full leaf node that is going to be splitted *@param: middleKey The new middle key that is going to be assigned by reference *@param: pid Page id of the newly created node and assigned by reference */ template<typename T, typename L> void splitLeafNode(L *& leftNode, T& middleKey, PageId &pid); void splitLeafNodeString(LeafNodeString *& leftNode, char* middleKey, PageId &pid); /* *splitNonLeafNode and splitNonLeafNnodeString *Same concept as splitLeafNode and splitNonLeafNode, this will handle the node splitting * of a leafNode while alsoo assigning middle key and newly created node's page id by reffrence *@param: leftNode The full leaf node that needs to be splitted *@param: middleKey The new middle key that is going to be assigned by reference *@param: pid Page id of the newly created node and assigned by reference */ template<typename T, typename NL> void splitNonLeafNode(NL *& leftNode, T& middleKey, PageId &pid); void splitNonLeafNodeString(NonLeafNodeString *& leftNode, char* middleKey, PageId &pid); /* *traverseAndInsertNumber and traverseAndInsertString *These functions will find the appropriate node for a record to be inserted into. *Once it find the appropriate node, it will also directly insert into it. *It will also call fullNodeHandler if the node before of after insertion is full *traverse and traverseString: *@params: currNode the root node of the tree *@params: key the key of the record that is going to be inserted *@params: rid the record id of the record that is going to be inserted *traverse: *@param: LeafType Leaf node to indicate which type of root node of the tree *@param: nonleafType Non leaf node to indicate which type of non-leaf of the tree * */ template <typename T, typename L, typename NL> void traverseAndInsertNumber(L* leafType, NL* nonLeafType, NL * currNode, T key, const RecordId rid); void traverseAndInsertString(NonLeafNodeString * currNode, const void* key, const RecordId rid); /* *printTree *Simply print tree for debugging purposes */ void printTree(); /** *initializeInt/Double/String. Node intialzer based on the data type. *This functions will populate the node that is passed into the function with the default values. *Default values are: -1 for Int and Double, \0\0\0\0\0\0\0\0\0\0 for String. *@param rootNode: the node that is going to be initialized with default value. */ const void initializeInt(LeafNodeInt* rootNode); const void initializeDouble(LeafNodeDouble* rootNode); const void initializeString(LeafNodeString* rootNode); /** * startScan: The main entry of scanning the records. * Begin a filtered scan of the index. This function will simply call another starScan * functions based on the type of the tree * @param lowVal Low value of range, pointer to integer / double / char string * @param lowOp Low operator (GT/GTE) * @param highVal High value of range, pointer to integer / double / char string * @param highOp High operator (LT/LTE) * @throws BadOpcodesException If lowOp and highOp do not contain one of their their expected values * @throws BadScanrangeException If lowVal > highval * @throws NoSuchKeyFoundException If there is no key in the B+ tree that satisfies the scan criteria. **/ const void startScan(const void* lowVal, const Operator lowOp, const void* highVal, const Operator highOp); /* * startScanNumber and startScanString * These functions will find an appropriate node to where the searched recorded * being laid out on the node * startScanGeneric and startScanString * @param lowVal Low value of range, pointer to integer / double / char string * @param lowOp Low operator (GT/GTE) * @param highVal High value of range, pointer to integer / double / char string * @param highOp High operator (LT/LTE) * startScanNumber: *@param: LeafType Leaf node to indicate which type of root node of the tree *@param: nonleafType Non leaf node to indicate which type of non-leaf of the tree */ template <typename T, typename L, typename NL> const void startScanNumber (L* leafType, NL* nonLeafType, T lowVal, T highVal); const void startScanString (const void* lowVal, const Operator lowOp, const void * highVal, const Operator highOp); /** * scanNext * The main entry to scanNext. This function will call the scanner helper function based on the data type. * Fetch the record id of the next index entry that matches the scan. * Return the next record from current page being scanned. If current page has been scanned to its entirety, * move on to the right sibling of current page, if any exists, to start scanning that page. * @param outRid RecordId of next record found that satisfies the scan criteria returned in this * @throws ScanNotInitializedException If no scan has been initialized. **/ const void scanNext(RecordId& outRid); // returned record id /** * scanNextNumber and scanNextString * These functions contains the algorithm that will find the appropriate the next appropriate * record in the node of the tree while keeping track of last scanned index. * scanNextGeneric and scanNextString: * @param outRid RecordId of next record found that satisfies the scan criteria returned in this * scanNextNumber: * @param lowVal Low value of range, pointer to integer / double / char string * @param lowOp Low operator (GT/GTE) * @param highVal High value of range, pointer to integer / double / char string * @param highOp High operator (LT/LTE) * @throws IndexScanCompletedException If no more records, satisfying the scan criteria, are left to be scanned. */ template <typename T, typename L> const void scanNextNumber(L* leafType, RecordId& outRid, T lowVal, T highVal); const void scanNextString(RecordId& outRid); /** * Terminate the current scan. Unpin any pinned pages. Reset scan specific variables. * @throws ScanNotInitializedException If no scan has been initialized. **/ const void endScan(); }; }
32.118123
253
0.690362
f1de4331a842d5f180ac4092adde068262dbd0f1
2,072
kt
Kotlin
plugins/git4idea/src/git4idea/log/GitDirectoryVirtualFile.kt
NecroRayder/intellij-community
4381105ab77263736ad7362008532b6129c0a90e
[ "Apache-2.0" ]
1
2018-10-13T19:43:36.000Z
2018-10-13T19:43:36.000Z
plugins/git4idea/src/git4idea/log/GitDirectoryVirtualFile.kt
NecroRayder/intellij-community
4381105ab77263736ad7362008532b6129c0a90e
[ "Apache-2.0" ]
null
null
null
plugins/git4idea/src/git4idea/log/GitDirectoryVirtualFile.kt
NecroRayder/intellij-community
4381105ab77263736ad7362008532b6129c0a90e
[ "Apache-2.0" ]
1
2018-10-03T12:35:06.000Z
2018-10-03T12:35:06.000Z
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea.log import com.intellij.openapi.vcs.RemoteFilePath import com.intellij.openapi.vcs.vfs.AbstractVcsVirtualFile import com.intellij.openapi.vcs.vfs.VcsFileSystem import com.intellij.openapi.vcs.vfs.VcsVirtualFile import com.intellij.openapi.vfs.VirtualFile import com.intellij.vcs.log.VcsCommitMetadata import git4idea.GitFileRevision import git4idea.GitRevisionNumber import git4idea.index.GitIndexUtil import git4idea.repo.GitRepository class GitDirectoryVirtualFile( private val repo: GitRepository, parent: VirtualFile?, name: String, private val commit: VcsCommitMetadata ) : AbstractVcsVirtualFile(parent, name, VcsFileSystem.getInstance()) { override fun isDirectory(): Boolean = true override fun contentsToByteArray(): ByteArray { throw UnsupportedOperationException() } private val cachedChildren by lazy { val gitRevisionNumber = GitRevisionNumber(commit.id.asString()) val remotePath = if (path.isEmpty()) "." else path + "/" val tree = GitIndexUtil.listTree(repo, listOf(RemoteFilePath(remotePath, true)), gitRevisionNumber) val result = tree.map { when(it) { is GitIndexUtil.StagedDirectory -> GitDirectoryVirtualFile(repo, this, it.path.name, commit) else -> VcsVirtualFile(this, it.path.name, GitFileRevision(repo.project, RemoteFilePath(it.path.path, false), gitRevisionNumber), VcsFileSystem.getInstance()) } } result.toTypedArray<VirtualFile>() } override fun getChildren(): Array<VirtualFile> = cachedChildren override fun equals(other: Any?): Boolean { val otherFile = other as? GitDirectoryVirtualFile ?: return false return repo == otherFile.repo && path == otherFile.path && commit.id == otherFile.commit.id } override fun hashCode(): Int { return repo.hashCode() * 31 * 31 + path.hashCode() * 31 + commit.id.hashCode() } }
37.672727
140
0.730212
e70604027b3c79d0fdfe79f51b903bcea30a1ef0
17,185
php
PHP
program.php
cybernerdie/fitnesswebsite
a33d6fff5a02de146a78d2739224b16e788aa314
[ "MIT" ]
null
null
null
program.php
cybernerdie/fitnesswebsite
a33d6fff5a02de146a78d2739224b16e788aa314
[ "MIT" ]
1
2021-05-11T09:41:07.000Z
2021-05-11T09:41:07.000Z
program.php
Veecthorpaul/fitnesswebsite
a33d6fff5a02de146a78d2739224b16e788aa314
[ "MIT" ]
null
null
null
<?php require_once("Includes/DB.php"); ?> <?php require_once("Includes/Functions.php"); ?> <?php require_once("Includes/Sessions.php"); ?> <?php if(isset($_POST["Submit"])){ $Fname = $_POST["FirstName"]; $Lname = $_POST["LastName"]; $Phone = $_POST["Phone"]; $Message = $_POST["Message"]; $Date = $_POST["Date"]; $Time = $_POST["Time"]; if(empty($Fname)||empty($Lname)||empty($Phone)||empty($Message)||empty($Date)||empty($Time)){ $_SESSION["ErrorMessage"]= "All fields must be filled out"; Redirect_to("program.php"); }elseif (strlen($Message)>500) { $_SESSION["ErrorMessage"]= "Message length should be less than 500 characters"; Redirect_to("program.php"); }else{ // Query to insert comment in DB When everything is fine global $ConnectingDB; $sql = "INSERT INTO appointments(date,time,fname,lname,phone,message)"; $sql .= "VALUES(:date,:time,:fname,:lname,:phone,:message)"; $stmt = $ConnectingDB->prepare($sql); $stmt -> bindValue(':date',$Date); $stmt -> bindValue(':time',$Time); $stmt -> bindValue(':fname',$Fname); $stmt -> bindValue(':lname',$Lname); $stmt -> bindValue(':phone',$Phone); $stmt -> bindValue(':message',$Message); $Execute = $stmt -> execute(); //var_dump($Execute); if($Execute){ $_SESSION["SuccessMessage"]="Appointment Booked Successfully"; Redirect_to("program.php"); }else { $_SESSION["ErrorMessage"]="Something went wrong. Try Again !"; Redirect_to("program.php"); } } } //Ending of Submit Button If-Condition ?> <?php if (isset($_GET['page']) && $_GET['page']!="") { $page = $_GET['page']; } else { $page = 1; } $result_count = "SELECT COUNT(*) as total_records FROM programs"; $stmt = $ConnectingDB->prepare( $result_count ); $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_ASSOC); $total_records = $row['total_records']; $TotalPerPage=6; $Previous = $page - 1; $Next = $page + 1; $TotalPages = ceil($total_records / $TotalPerPage) ?> <!DOCTYPE html> <html lang="en"> <head> <title>Strong | Fitness Website</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link href="https://fonts.googleapis.com/css?family=Barlow+Semi+Condensed:100,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <link rel="stylesheet" href="css/open-iconic-bootstrap.min.css"> <link rel="stylesheet" href="css/animate.css"> <link rel="stylesheet" href="css/owl.carousel.min.css"> <link rel="stylesheet" href="css/owl.theme.default.min.css"> <link rel="stylesheet" href="css/magnific-popup.css"> <link rel="stylesheet" href="css/aos.css"> <link rel="stylesheet" href="css/ionicons.min.css"> <link rel="stylesheet" href="css/bootstrap-datepicker.css"> <link rel="stylesheet" href="css/jquery.timepicker.css"> <link rel="stylesheet" href="css/flaticon.css"> <link rel="stylesheet" href="css/icomoon.css"> <link rel="stylesheet" href="css/style.css"> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark ftco_navbar bg-dark ftco-navbar-light" id="ftco-navbar"> <div class="container"> <a class="navbar-brand py-2 px-4" href="index.php">strong</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#ftco-nav" aria-controls="ftco-nav" aria-expanded="false" aria-label="Toggle navigation"> <span class="oi oi-menu"></span> Menu </button> <div class="collapse navbar-collapse" id="ftco-nav"> <ul class="navbar-nav ml-auto"> <li class="nav-item"><a href="index.php" class="nav-link">Home</a></li> <li class="nav-item active"><a href="program.php" class="nav-link">Program</a></li> <li class="nav-item"><a href="coaches.php" class="nav-link">Coaches</a></li> <li class="nav-item"><a href="schedule.php" class="nav-link">Schedule</a></li> <li class="nav-item"><a href="about.php" class="nav-link">About</a></li> <li class="nav-item"><a href="blog.php" class="nav-link">Blog</a></li> <li class="nav-item"><a href="contact.php" class="nav-link">Contact</a></li> </ul> </div> </div> </nav> <!-- END nav --> <section class="hero-wrap js-fullheight" style="background-image: url('images/bg_2.jpg');"> <div class="overlay"></div> <div class="container"> <div class="row no-gutters slider-text js-fullheight align-items-center justify-content-center"> <div class="col-md-9 ftco-animate text-center"> <h1 class="mb-3 bread">Workout Classes</h1> <p class="breadcrumbs"><span class="mr-2"><a href="index.php">Home</a></span> <span>Program</span></p> </div> </div> </div> </section> <section class="ftco-section"> <div class="container-fluid"> <div class="row"> <?php global $ConnectingDB; // SQL query when Searh button is active if(isset($_GET["SearchButton"])){ $Search = $_GET["Search"]; $sql = "SELECT * FROM programs WHERE datetime LIKE :search OR title LIKE :search OR category LIKE :search OR post LIKE :search"; $stmt = $ConnectingDB->prepare($sql); $stmt->bindValue(':search','%'.$Search.'%'); $stmt->execute(); }// Query When Pagination is Active i.e index.php?page=1 elseif (isset($_GET["page"])) { $Page = $_GET["page"]; $Next = $Page + 1; $previous = $Page - 1; if($Page==0||$Page<1){ $ShowPostFrom=1; $TotalPerPage=6; }else{ $ShowPostFrom=($Page-1) *$TotalPerPage; } $sql ="SELECT * FROM programs ORDER BY id desc LIMIT $ShowPostFrom,$TotalPerPage"; $stmt=$ConnectingDB->query($sql); } // Query When Category is active in URL Tab elseif (isset($_GET["category"])) { $Category = $_GET["category"]; $sql = "SELECT * FROM programs WHERE category='$Category' ORDER BY id desc"; $stmt=$ConnectingDB->query($sql); } // The default SQL query else{ $sql = "SELECT * FROM programs ORDER BY id desc LIMIT 0,$TotalPerPage"; $stmt =$ConnectingDB->query($sql); } while ($DataRows = $stmt->fetch()) { $ProgramId = $DataRows["id"]; $Name = $DataRows["name"]; $Description = $DataRows["description"]; $Benefit = $DataRows["benefit"]; $Duration = $DataRows["duration"]; $Image = $DataRows["image"]; $Trainer = $DataRows["trainer"]; ?> <div class="col-md-6 col-lg-4 col-sm-6"> <div class="package-program ftco-animate"> <a href="programs.php?id=<?php echo $ProgramId; ?>"> <img src="Uploads/<?php echo htmlentities($Image); ?>" class="block-20 d-flex justify-content-center align-items-center" href="trainer.php" /></a> <div class="text mt-3"> <h3><a href="#"><?php echo $Name; ?></a></h3> <p><?php if (strlen($Description)>100) { $Description = substr($Description,0,100)."...";} echo htmlentities($Description); ?></p> <a href="programs.php?id=<?php echo $ProgramId; ?>" style="text-align: right">Learn More</a> </div> </div> </div> <?php } ?> </div> <div class="row mt-5"> <div class="col text-center"> <div class="block-27"> <div style='padding: 10px 20px 0px; border-top: dotted 1px #CCC;'> <strong>Page <?php echo $page." of ".$TotalPages; ?></strong> </div> <ul> <?php // if($page > 1){ echo "<li><a href='?page=1'>First Page</a></li>"; } ?> <li <?php if($page <= 1){ echo "class='disabled'"; } ?>> <a <?php if($page > 1){ echo "href='?page=$Previous'"; } ?>>&lt;</a> </li> <?php if ($TotalPages <= 10){ for ($counter = 1; $counter <= $TotalPages; $counter++){ if ($counter == $page) { echo "<li class='active'><a>$counter</a></li>"; }else{ echo "<li><a href='?page=$counter'>$counter</a></li>"; } } } elseif($TotalPages > 10){ if($page <= 4) { for ($counter = 1; $counter < 8; $counter++){ if ($counter == $page) { echo "<li class='active'><a>$counter</a></li>"; }else{ echo "<li><a href='?page=$counter'>$counter</a></li>"; } } echo "<li><a>...</a></li>"; echo "<li><a href='?page=$second_last'>$second_last</a></li>"; echo "<li><a href='?page=$TotalPages'>$TotalPages</a></li>"; } elseif($page > 4 && $page < $TotalPages - 4) { echo "<li><a href='?page=1'>1</a></li>"; echo "<li><a href='?page=2'>2</a></li>"; echo "<li><a>...</a></li>"; for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++) { if ($counter == $page) { echo "<li class='active'><a>$counter</a></li>"; }else{ echo "<li><a href='?page=$counter'>$counter</a></li>"; } } echo "<li><a>...</a></li>"; echo "<li><a href='?page=$second_last'>$second_last</a></li>"; echo "<li><a href='?page=$TotalPages'>$TotalPages</a></li>"; } else { echo "<li><a href='?page=1'>1</a></li>"; echo "<li><a href='?page=2'>2</a></li>"; echo "<li><a>...</a></li>"; for ($counter = $TotalPages - 6; $counter <= $TotalPages; $counter++) { if ($counter == $page) { echo "<li class='active'><a>$counter</a></li>"; }else{ echo "<li><a href='?page=$counter'>$counter</a></li>"; } } } } ?> <li <?php if($page >= $TotalPages){ echo "class='disabled'"; } ?>> <a <?php if($page < $TotalPages) { echo "href='?page=$Next'"; } ?>>&gt;</a> </li> </ul> </div> </div> </div> </div> </section> <section class="ftco-appointment"> <div class="overlay"></div> <div class="container-wrap"> <div class="row no-gutters d-md-flex align-items-center"> <div class="col-md-6 d-flex align-self-stretch img" style="background-image: url(images/about-3.jpg);"> </div> <div class="col-md-6 appointment ftco-animate"> <?php echo ErrorMessage(); echo SuccessMessage(); ?> <h3 class="mb-3">Book a Appointment</h3> <form action="program.php" class="appointment-form" method="post"> <div class="d-md-flex"> <div class="form-group"> <input type="text" class="form-control" name="FirstName" placeholder="First Name" required> </div> <div class="form-group ml-md-4"> <input type="text" class="form-control" name="LastName" placeholder="Last Name" required> </div> </div> <div class="d-md-flex"> <div class="form-group"> <div class="input-wrap"> <div class="icon"><span class="ion-md-calendar"></span></div> <input type="text" class="form-control appointment_date" name="Date" placeholder="Date" required> </div> </div> <div class="form-group ml-md-4"> <div class="input-wrap"> <div class="icon"><span class="ion-ios-clock"></span></div> <input type="text" class="form-control appointment_time" name="Time" placeholder="Time" required> </div> </div> <div class="form-group ml-md-4"> <input type="text" class="form-control" name="Phone" placeholder="Phone" required> </div> </div> <div class="d-md-flex"> <div class="form-group"> <textarea name="Message" id="" cols="30" rows="2" class="form-control" placeholder="Message" required></textarea> </div> <div class="form-group ml-md-4"> <input type="submit" value="Book" name="Submit" class="btn btn-primary py-3 px-4"> </div> </div> </form> </div> </div> </div> </section> <footer class="ftco-footer ftco-section img"> <div class="overlay"></div> <div class="container"> <div class="row mb-5"> <div class="col-lg-3 col-md-6 mb-5 mb-md-5"> <div class="ftco-footer-widget mb-4"> <h2 class="ftco-heading-2">About Us</h2> <p>Strong Fitness is committed to facilitating the accessibility and usability of content and features on its website, including this blog.</p> <ul class="ftco-footer-social list-unstyled float-md-left float-lft mt-5"> <li class="ftco-animate"><a href="https://twitter.com/veecthorpaul"><span class="icon-twitter"></span></a></li> <li class="ftco-animate"><a href="https://facebook.com/veecthorpaul"><span class="icon-facebook"></span></a></li> <li class="ftco-animate"><a href="https://instagram.com/veecthorpaul"><span class="icon-instagram"></span></a></li> </ul> </div> </div> <div class="col-lg-4 col-md-6 mb-5 mb-md-5"> <div class="ftco-footer-widget mb-4"> <h2 class="ftco-heading-2"></h2> <div class="block-21 mb-4 d-flex"> <a class="blog-img mr-4" style=""></a> <div class="text"> <h3 class="heading"><a href="#"></a></h3> <div class="meta"> </div> </div> </div> </div> </div> <div class="col-lg-2 col-md-6 mb-5 mb-md-5"> <div class="ftco-footer-widget mb-4 ml-md-4"> <h2 class="ftco-heading-2">Services</h2> <ul class="list-unstyled"> <li><a href="program.php" class="py-2 d-block">Boost Your Body</a></li> <li><a href="program.php" class="py-2 d-block">Achieve Your Goal</a></li> <li><a href="program.php" class="py-2 d-block">Analyze Your Goal</a></li> <li><a href="program.php" class="py-2 d-block">Improve Your Performance</a></li> </ul> </div> </div> <div class="col-lg-3 col-md-6 mb-5 mb-md-5"> <div class="ftco-footer-widget mb-4"> <h2 class="ftco-heading-2">Have a Questions?</h2> <div class="block-23 mb-3"> <ul> <li><span class="icon icon-map-marker"></span><span class="text">35, Oyedeji Street, Ajegunle, Apapa Lagos</span></li> <li><a href="#"><span class="icon icon-phone"></span><span class="text">+2347031952383</span></a></li> <li><a href="#"><span class="icon icon-envelope"></span><span class="text">[email protected]</span></a></li> </ul> </div> </div> </div> </div> <div class="row"> <div class="col-md-12 text-center"> <p><!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. --> Copyright &copy; <script>document.write(new Date().getFullYear());</script> <a href="https://about.me/pauljoshua" target="_blank">Josh Paul Media</a> <!-- Link back to Colorlib can't be removed. Template is licensed under CC BY 3.0. --></p> </div> </div> </div> </footer> <!-- loader --> <div id="ftco-loader" class="show fullscreen"><svg class="circular" width="48px" height="48px"><circle class="path-bg" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke="#eeeeee"/><circle class="path" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke-miterlimit="10" stroke="#F96D00"/></svg></div> <script src="js/jquery.min.js"></script> <script src="js/jquery-migrate-3.0.1.min.js"></script> <script src="js/popper.min.js"></script> <script src="js/bootstrap.min.js"></script> <script src="js/jquery.easing.1.3.js"></script> <script src="js/jquery.waypoints.min.js"></script> <script src="js/jquery.stellar.min.js"></script> <script src="js/owl.carousel.min.js"></script> <script src="js/jquery.magnific-popup.min.js"></script> <script src="js/aos.js"></script> <script src="js/jquery.animateNumber.min.js"></script> <script src="js/bootstrap-datepicker.js"></script> <script src="js/jquery.timepicker.min.js"></script> <script src="js/scrollax.min.js"></script> <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBVWaKrjvy3MaE7SQ74_uJiULgl1JY0H2s&sensor=false"></script> <script src="js/google-map.js"></script> <script src="js/main.js"></script> </body> </html>
41.711165
317
0.544021