hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
a8317509161b0fdcdc16bb8068f2300b0effb09d
503
dart
Dart
ecommers/lib/core/models/notification_model.dart
epam-cross-platform-lab/flutter-ecommers-sample
ad9fac52e53d22514834aee447b602cc0b775148
[ "Apache-2.0" ]
20
2020-02-13T13:23:15.000Z
2021-12-21T16:14:57.000Z
ecommers/lib/core/models/notification_model.dart
HAFDIAHMED/flutter-ecommers-sample
ad9fac52e53d22514834aee447b602cc0b775148
[ "Apache-2.0" ]
89
2020-02-17T14:24:58.000Z
2020-05-14T07:44:42.000Z
ecommers/lib/core/models/notification_model.dart
HAFDIAHMED/flutter-ecommers-sample
ad9fac52e53d22514834aee447b602cc0b775148
[ "Apache-2.0" ]
15
2020-02-13T15:10:24.000Z
2021-04-22T16:25:20.000Z
import 'dart:ui'; class NotificationModel { final String orderNumber; final String notificationUsualText; final String statusText; final bool isCheckedItem; final Color backgroundColor; final Color shadowColor; final String imgPath; final DateTime day; NotificationModel({ this.orderNumber, this.notificationUsualText, this.isCheckedItem, this.statusText, this.backgroundColor, this.shadowColor, this.imgPath, this.day, }); }
20.958333
38
0.697813
1f21f96bd0b69e83d92510b8a4672c4fb1db8596
3,902
cs
C#
src/AdjacencyList._Tests/DirectedGraphTests.cs
sdcondon/SCGraphTheory.AdjacencyList
c090fb907cf04e7b2cd2b5233510f0e54fb5e896
[ "MIT" ]
2
2022-03-24T00:46:41.000Z
2022-03-30T17:53:32.000Z
src/AdjacencyList._Tests/DirectedGraphTests.cs
sdcondon/SCGraphTheory.AdjacencyList
c090fb907cf04e7b2cd2b5233510f0e54fb5e896
[ "MIT" ]
null
null
null
src/AdjacencyList._Tests/DirectedGraphTests.cs
sdcondon/SCGraphTheory.AdjacencyList
c090fb907cf04e7b2cd2b5233510f0e54fb5e896
[ "MIT" ]
null
null
null
using FluentAssertions; using FlUnit; namespace SCGraphTheory.AdjacencyList { public static class DirectedGraphTests { public static Test Construction => TestThat .When(() => { var graph = new Graph<Node, Edge>(); Node node1, node2, node3; graph.Add(node1 = new Node()); graph.Add(node2 = new Node()); graph.Add(node3 = new Node()); Edge edge1, edge2, edge3; graph.Add(edge1 = new Edge(node1, node2)); graph.Add(edge2 = new Edge(node2, node3)); graph.Add(edge3 = new Edge(node3, node1)); return new { graph, node1, node2, node3, edge1, edge2, edge3 }; }) .ThenReturns(o => o.graph.Nodes.Should().BeEquivalentTo(new[] { o.node1, o.node2, o.node3 })) .And(o => o.graph.Edges.Should().BeEquivalentTo(new[] { o.edge1, o.edge2, o.edge3 })) .And(o => o.node1.Edges.Should().BeEquivalentTo(new[] { o.edge1 })) .And(o => o.node2.Edges.Should().BeEquivalentTo(new[] { o.edge2 })) .And(o => o.node3.Edges.Should().BeEquivalentTo(new[] { o.edge3 })); public static Test EdgeRemoval => TestThat .Given(() => { var graph = new Graph<Node, Edge>(); Node node1, node2, node3; graph.Add(node1 = new Node()); graph.Add(node2 = new Node()); graph.Add(node3 = new Node()); Edge edge1, edge2, edge3; graph.Add(edge1 = new Edge(node1, node2)); graph.Add(edge2 = new Edge(node2, node3)); graph.Add(edge3 = new Edge(node3, node1)); return new { graph, node1, node2, node3, edge1, edge2, edge3 }; }) .When(given => given.graph.Remove(given.edge3)) .ThenReturns((_, returnValue) => returnValue.Should().BeTrue()) .And((given, _) => given.graph.Nodes.Should().BeEquivalentTo(new[] { given.node1, given.node2, given.node3 })) .And((given, _) => given.graph.Edges.Should().BeEquivalentTo(new[] { given.edge1, given.edge2 })) .And((given, _) => given.node1.Edges.Should().BeEquivalentTo(new[] { given.edge1 })) .And((given, _) => given.node2.Edges.Should().BeEquivalentTo(new[] { given.edge2 })) .And((given, _) => given.node3.Edges.Should().BeEmpty()); public static Test NodeRemoval => TestThat .Given(() => { var graph = new Graph<Node, Edge>(); Node node1, node2, node3; graph.Add(node1 = new Node()); graph.Add(node2 = new Node()); graph.Add(node3 = new Node()); Edge edge1, edge2, edge3; graph.Add(edge1 = new Edge(node1, node2)); graph.Add(edge2 = new Edge(node2, node3)); graph.Add(edge3 = new Edge(node3, node1)); return new { graph, node1, node2, node3, edge1, edge2, edge3 }; }) .When(given => given.graph.Remove(given.node3)) .ThenReturns((_, returnValue) => returnValue.Should().BeTrue()) .And((given, _) => given.graph.Nodes.Should().BeEquivalentTo(new[] { given.node1, given.node2 })) .And((given, _) => given.graph.Edges.Should().BeEquivalentTo(new[] { given.edge1 })) .And((given, _) => given.node1.Edges.Should().BeEquivalentTo(new[] { given.edge1 })) .And((given, _) => given.node2.Edges.Should().BeEmpty()); private class Node : NodeBase<Node, Edge> { } private class Edge : EdgeBase<Node, Edge> { public Edge(Node from, Node to) : base(from, to) { } } } }
41.956989
122
0.516402
63ad7040d6764b594001f3150cf2637d11c392ce
72
rs
Rust
src/test/ui/issues/issue-9918.rs
Eric-Arellano/rust
0f6f2d681b39c5f95459cd09cb936b6ceb27cd82
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
66,762
2015-01-01T08:32:03.000Z
2022-03-31T23:26:40.000Z
src/test/ui/issues/issue-9918.rs
Eric-Arellano/rust
0f6f2d681b39c5f95459cd09cb936b6ceb27cd82
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
76,993
2015-01-01T00:06:33.000Z
2022-03-31T23:59:15.000Z
src/test/ui/issues/issue-9918.rs
Eric-Arellano/rust
0f6f2d681b39c5f95459cd09cb936b6ceb27cd82
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
11,787
2015-01-01T00:01:19.000Z
2022-03-31T19:03:42.000Z
// run-pass pub fn main() { assert_eq!((0 + 0u8) as char, '\0'); }
12
40
0.5
054bc8118829e6840435f95c0750d7e1f4596bb9
4,633
rb
Ruby
lib/server.rb
hirura/hrr_rb_ne_cli_sim
e6e9630804b7305c82e1f7e5cd5bd71e79a738a0
[ "Apache-2.0" ]
null
null
null
lib/server.rb
hirura/hrr_rb_ne_cli_sim
e6e9630804b7305c82e1f7e5cd5bd71e79a738a0
[ "Apache-2.0" ]
null
null
null
lib/server.rb
hirura/hrr_rb_ne_cli_sim
e6e9630804b7305c82e1f7e5cd5bd71e79a738a0
[ "Apache-2.0" ]
null
null
null
# coding: utf-8 # vim: et ts=2 sw=2 require 'bundler/setup' require 'hrr_rb_ssh' require 'fileutils' require 'logger' require 'socket' def instantiate_ne ne, logger logger.info { "Load model: #{ne['model']}" } klass = Class.new klass.class_eval File.read(File.join(File.expand_path(File.dirname(__FILE__)), ne['model'] + ".rb")) klass.class_eval do def singleton_method_added method @logger.info { "override method: #{method}" } end end ne_instance = klass.new ne['hostname'], ne['username'], logger begin logger.info { "Load host specific behavior: #{ne['hostname']}" } ne_instance.instance_eval File.read(File.join(File.expand_path(File.dirname(__FILE__)), ne['hostname'] + ".rb")) rescue Errno::ENOENT logger.info { "Load failed. No override" } end ne_instance end def auth_password ne HrrRbSsh::Authentication::Authenticator.new { |context| context.verify ne['username'], ne['password'] } end def conn_cli ne HrrRbSsh::Connection::RequestHandler.new { |context| context.chain_proc { |chain| log_dir = File.join(File.expand_path(File.dirname(__FILE__)), '..', 'log', 'ne') log_file = File.join(log_dir, "#{ne['hostname']}.cli.log") log_shift_age = 0 log_shift_size = 1048576 FileUtils.mkdir_p(log_dir) logger = ::Logger.new(log_file, log_shift_age, log_shift_size) logger.level = ::Logger::INFO begin ne_instance = instantiate_ne(ne, logger) logger.info { "send: #{ne_instance.prompt.inspect}" } context.io[1].write ne_instance.prompt loop do if ne_instance.closed? logger.info { "closed and exit" } break end input_str = context.io[0].readpartial(10240) logger.info { "receive: #{input_str.inspect}" } output_str = ne_instance.run(input_str) logger.info { "send: #{output_str.inspect}" } context.io[1].write output_str end exitstatus = 0 rescue => e logger.error([e.backtrace[0], ": ", e.message, " (", e.class.to_s, ")\n\t", e.backtrace[1..-1].join("\n\t")].join) exitstatus = 1 end exitstatus } } end def start_server ne log_dir = File.join(File.expand_path(File.dirname(__FILE__)), '..', 'log', 'ne') log_file = File.join(log_dir, "#{ne['hostname']}.ssh.log") log_shift_age = 0 log_shift_size = 1048576 FileUtils.mkdir_p(log_dir) logger = ::Logger.new(log_file, log_shift_age, log_shift_size) logger.level = ::Logger::INFO begin server = TCPServer.new ne['ip_address'], ne['port'] logger.info { "Started TCP server #{server.inspect}" } loop do Thread.new(server.accept) do |io| logger.info { "Accepted TCP connection from #{io.peeraddr.inspect}" } begin pid = fork do begin options = { 'authentication_password_authenticator' => auth_password(ne), 'connection_channel_request_shell' => conn_cli(ne), } HrrRbSsh::Logger.initialize logger HrrRbSsh::Server.new(io, options).start rescue => e logger.error { [e.backtrace[0], ": ", e.message, " (", e.class.to_s, ")\n\t", e.backtrace[1..-1].join("\n\t")].join } exit false end end logger.info { "process #{pid} started" } io.close rescue nil pid, status = Process.waitpid2 pid rescue => e logger.error { [e.backtrace[0], ": ", e.message, " (", e.class.to_s, ")\n\t", e.backtrace[1..-1].join("\n\t")].join } ensure status ||= nil logger.info { "process #{pid} finished with status #{status.inspect}" } end end end rescue => e logger.error { [e.backtrace[0], ": ", e.message, " (", e.class.to_s, ")\n\t", e.backtrace[1..-1].join("\n\t")].join } end end def ne_cli_sim nes log_dir = File.join(File.expand_path(File.dirname(__FILE__)), '..', 'log') log_file = File.join(log_dir, 'ne_cli_sim.log') log_shift_age = 0 log_shift_size = 1048576 FileUtils.mkdir_p(log_dir) logger = ::Logger.new(log_file, log_shift_age, log_shift_size) logger.level = ::Logger::INFO ts = [] nes.each{ |ne| logger.info { "Binding #{ne['hostname']}(#{ne['model']}) to #{ne['username']}@#{ne['ip_address']}:#{ne['port']}" } begin ts.push(Thread.new{ start_server ne }) rescue => e logger.error { [e.backtrace[0], ": ", e.message, " (", e.class.to_s, ")\n\t", e.backtrace[1..-1].join("\n\t")].join } end } ts.each(&:join) end
33.572464
131
0.601554
aff5d638d7da6d03034e57dcdfbc03f30632db6e
5,277
dart
Dart
lib/views/leitores_view.dart
ErickHen/Pi_Biblioteca
eee54a116cecffc0d89020adedadd0c0b3b63aec
[ "MIT" ]
1
2021-11-03T22:25:27.000Z
2021-11-03T22:25:27.000Z
lib/views/leitores_view.dart
ErickHen/PI_Biblioteca
eee54a116cecffc0d89020adedadd0c0b3b63aec
[ "MIT" ]
null
null
null
lib/views/leitores_view.dart
ErickHen/PI_Biblioteca
eee54a116cecffc0d89020adedadd0c0b3b63aec
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:portfolio_website/utils/project_model.dart'; import 'package:portfolio_website/utils/theme_selector.dart'; import 'package:portfolio_website/utils/view_wrapper.dart'; import 'package:portfolio_website/widgets/navigation_arrow.dart'; import 'package:portfolio_website/widgets/project_entry.dart'; import 'package:portfolio_website/widgets/project_image.dart'; class LeitoresView extends StatefulWidget { const LeitoresView({Key key}) : super(key: key); @override _LeitoresViewState createState() => _LeitoresViewState(); } class _LeitoresViewState extends State<LeitoresView> { double screenWidth; double screenHeight; int selectedIndex = 0; List<Project> projects = [ Project( title: 'Cadastrar Leitores', imageURL: 'leitura2.jpg', description: 'Cadastrar os usuários do tipo leitor no sistema.'), Project( title: 'Leitores Cadastrados', imageURL: 'leitura.jpg', description: 'Registrar todos os leitores já cadastrados.'), ]; @override void didChangeDependencies() { precacheImage(AssetImage('project1.jpg'), context); precacheImage(AssetImage('project2.jpg'), context); precacheImage(AssetImage('project3.jpg'), context); super.didChangeDependencies(); } @override Widget build(BuildContext context) { screenHeight = MediaQuery.of(context).size.height; screenWidth = MediaQuery.of(context).size.width; return ViewWrapper( desktopView: desktopView(), mobileView: mobileView(), ); } Widget desktopView() { double space = MediaQuery.of(context).size.height * 0.03; List<Widget> images = List.generate((projects.length * 1.5).ceil(), (index) { if (index.isEven) { return ProjectImage( project: projects[index ~/ 2], onPressed: () => updateIndex(index ~/ 2)); } else { return SizedBox(height: space); } }); return Stack( children: [ NavigationArrow(isBackArrow: true), Padding( padding: EdgeInsets.symmetric( vertical: screenHeight * 0.05, horizontal: screenWidth * 0.1), child: Row( children: [ Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: images, ), SizedBox(width: space), Container( height: screenHeight * 0.2 * 2 + space * 2, child: Stack( children: [ Column( children: [ SizedBox(height: 20), RaisedButton( onPressed: () { Navigator.of(context).pushNamed('/leitores'); }, child: Text('Cadastrar'), ), SizedBox(height: 215), RaisedButton( onPressed: () { Navigator.of(context) .pushNamed('/consultaLeitores'); }, child: Text('Consultar'), ), ], ), AnimatedAlign( alignment: selectedIndex == 0 ? Alignment.topCenter : selectedIndex == 1 ? Alignment.center : Alignment.bottomCenter, duration: Duration(milliseconds: 1000), curve: Curves.fastOutSlowIn, child: Container( color: Colors.white, width: screenWidth * 0.05, height: 3, ), ) ], ), ), SizedBox(width: space), Expanded(child: ProjectEntry(project: projects[selectedIndex])) ], ), ) ], ); } Widget mobileView() { List<Widget> projectList = List.generate(projects.length, (index) { return Column( children: [ Text( projects[index].title, style: ThemeSelector.selectSubHeadline(context), ), SizedBox(height: screenHeight * 0.01), Container( height: screenHeight * 0.1, width: screenWidth, child: ClipRRect( borderRadius: BorderRadius.circular(20), child: Image.asset( projects[index].imageURL, fit: BoxFit.cover, ), ), ), SizedBox(height: screenHeight * 0.01), Text( projects[index].description, style: ThemeSelector.selectBodyText(context), ), SizedBox(height: screenHeight * 0.1), ], ); }); return Column(children: projectList); } void updateIndex(int newIndex) { setState(() { selectedIndex = newIndex; }); } }
32.374233
77
0.514307
dfc38f2767efa163b5b0daecfa8675140eaac7d8
7,339
rb
Ruby
lib/new_relic/agent/transaction/distributed_tracing.rb
Izzette/rpm
12961aa4a42dee200054a3c62ac6a985670f3a64
[ "Ruby" ]
null
null
null
lib/new_relic/agent/transaction/distributed_tracing.rb
Izzette/rpm
12961aa4a42dee200054a3c62ac6a985670f3a64
[ "Ruby" ]
null
null
null
lib/new_relic/agent/transaction/distributed_tracing.rb
Izzette/rpm
12961aa4a42dee200054a3c62ac6a985670f3a64
[ "Ruby" ]
1
2020-02-07T10:51:02.000Z
2020-02-07T10:51:02.000Z
# encoding: utf-8 # This file is distributed under New Relic's license terms. # See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details. require 'new_relic/agent/distributed_trace_payload' require 'new_relic/agent/distributed_trace_intrinsics' require 'new_relic/agent/distributed_trace_metrics' module NewRelic module Agent class Transaction module DistributedTracing attr_accessor :distributed_trace_payload SUPPORTABILITY_CREATE_PAYLOAD_SUCCESS = "Supportability/DistributedTrace/CreatePayload/Success".freeze SUPPORTABILITY_CREATE_PAYLOAD_EXCEPTION = "Supportability/DistributedTrace/CreatePayload/Exception".freeze def create_distributed_trace_payload unless Agent.config[:'distributed_tracing.enabled'] && (Agent.config[:'distributed_tracing.format'] == NR_FORMAT) NewRelic::Agent.logger.warn "Not configured to create New Relic distributed trace payload" return end self.distributed_trace_payload_created = true payload = DistributedTracePayload.for_transaction self NewRelic::Agent.increment_metric SUPPORTABILITY_CREATE_PAYLOAD_SUCCESS payload rescue => e NewRelic::Agent.increment_metric SUPPORTABILITY_CREATE_PAYLOAD_EXCEPTION NewRelic::Agent.logger.warn "Failed to create distributed trace payload", e nil end SUPPORTABILITY_ACCEPT_PAYLOAD_SUCCESS = "Supportability/DistributedTrace/AcceptPayload/Success".freeze SUPPORTABILITY_ACCEPT_PAYLOAD_EXCEPTION = "Supportability/DistributedTrace/AcceptPayload/Exception".freeze def accept_distributed_trace_payload payload unless Agent.config[:'distributed_tracing.enabled'] && (Agent.config[:'distributed_tracing.format'] == NR_FORMAT) NewRelic::Agent.logger.warn "Not configured to accept New Relic distributed trace payload" return end return false if check_payload_ignored(payload) return false unless check_payload_present(payload) return false unless payload = decode_payload(payload) return false unless check_required_fields_present(payload) return false unless check_valid_version(payload) return false unless check_trusted_account(payload) assign_payload_and_sampling_params(payload) NewRelic::Agent.increment_metric SUPPORTABILITY_ACCEPT_PAYLOAD_SUCCESS true rescue => e NewRelic::Agent.increment_metric SUPPORTABILITY_ACCEPT_PAYLOAD_EXCEPTION NewRelic::Agent.logger.warn "Failed to accept distributed trace payload", e false end def distributed_trace_payload_created? @distributed_trace_payload_created ||= false end attr_writer :distributed_trace_payload_created def append_distributed_trace_info transaction_payload return unless Agent.config[:'distributed_tracing.enabled'] DistributedTraceIntrinsics.copy_from_transaction \ self, distributed_trace_payload, transaction_payload end NR_FORMAT = "newrelic".freeze def nr_distributed_tracing_enabled? Agent.config[:'distributed_tracing.enabled'] && (Agent.config[:'distributed_tracing.format'] == NR_FORMAT) && Agent.instance.connected? end private SUPPORTABILITY_CREATE_BEFORE_ACCEPT_PAYLOAD = "Supportability/DistributedTrace/AcceptPayload/Ignored/CreateBeforeAccept".freeze SUPPORTABILITY_MULTIPLE_ACCEPT_PAYLOAD = "Supportability/DistributedTrace/AcceptPayload/Ignored/Multiple".freeze SUPPORTABILITY_PAYLOAD_ACCEPT_IGNORED_NULL = "Supportability/DistributedTrace/AcceptPayload/Ignored/Null".freeze SUPPORTABILITY_PAYLOAD_ACCEPT_IGNORED_BROWSER = "Supportability/DistributedTrace/AcceptPayload/Ignored/BrowserAgentInjected".freeze def check_payload_ignored(payload) if distributed_trace_payload NewRelic::Agent.increment_metric SUPPORTABILITY_MULTIPLE_ACCEPT_PAYLOAD return true elsif distributed_trace_payload_created? NewRelic::Agent.increment_metric SUPPORTABILITY_CREATE_BEFORE_ACCEPT_PAYLOAD return true end false end NULL_PAYLOAD = 'null'.freeze def check_payload_present(payload) # We might be passed a Ruby `nil` object _or_ the JSON "null" if payload.nil? || payload == NULL_PAYLOAD NewRelic::Agent.increment_metric SUPPORTABILITY_PAYLOAD_ACCEPT_IGNORED_NULL return nil end payload end SUPPORTABILITY_PAYLOAD_ACCEPT_IGNORED_PARSE_EXCEPTION = "Supportability/DistributedTrace/AcceptPayload/ParseException".freeze LBRACE = "{".freeze def decode_payload(payload) decoded = if payload.start_with? LBRACE DistributedTracePayload.from_json payload else DistributedTracePayload.from_http_safe payload end return nil unless check_payload_present(decoded) decoded rescue => e NewRelic::Agent.increment_metric SUPPORTABILITY_PAYLOAD_ACCEPT_IGNORED_PARSE_EXCEPTION NewRelic::Agent.logger.warn "Error parsing distributed trace payload", e nil end def check_required_fields_present(payload) if \ !payload.version.nil? && !payload.parent_account_id.nil? && !payload.parent_app_id.nil? && !payload.parent_type.nil? && (!payload.transaction_id.nil? || !payload.id.nil?) && !payload.trace_id.nil? && !payload.timestamp.nil? true else NewRelic::Agent.increment_metric SUPPORTABILITY_PAYLOAD_ACCEPT_IGNORED_PARSE_EXCEPTION false end end SUPPORTABILITY_PAYLOAD_ACCEPT_IGNORED_MAJOR_VERSION = "Supportability/DistributedTrace/AcceptPayload/Ignored/MajorVersion".freeze def check_valid_version(payload) if DistributedTracePayload.major_version_matches?(payload) true else NewRelic::Agent.increment_metric SUPPORTABILITY_PAYLOAD_ACCEPT_IGNORED_MAJOR_VERSION false end end SUPPORTABILITY_PAYLOAD_ACCEPT_UNTRUSTED_ACCOUNT = "Supportability/DistributedTrace/AcceptPayload/Ignored/UntrustedAccount".freeze def check_trusted_account(payload) compare_key = payload.trusted_account_key || payload.parent_account_id unless compare_key == NewRelic::Agent.config[:trusted_account_key] NewRelic::Agent.increment_metric SUPPORTABILITY_PAYLOAD_ACCEPT_UNTRUSTED_ACCOUNT return false end true end def assign_payload_and_sampling_params(payload) self.distributed_trace_payload = payload @trace_id = payload.trace_id @parent_transaction_id = payload.transaction_id @parent_span_id = payload.id unless payload.sampled.nil? self.sampled = payload.sampled self.priority = payload.priority if payload.priority end end end end end end
40.324176
145
0.700232
3f7590af52a5445a6d74cff69d592151fd0180e8
864
php
PHP
src/Logger/src/Transport/JagerUDPTransport.php
maria-rollun/rollun-logger
861e41cb357cb11d3450859b3c932e88d3951eee
[ "BSD-3-Clause" ]
null
null
null
src/Logger/src/Transport/JagerUDPTransport.php
maria-rollun/rollun-logger
861e41cb357cb11d3450859b3c932e88d3951eee
[ "BSD-3-Clause" ]
9
2017-09-05T08:06:38.000Z
2020-06-29T12:26:18.000Z
src/Logger/src/Transport/JagerUDPTransport.php
maria-rollun/rollun-logger
861e41cb357cb11d3450859b3c932e88d3951eee
[ "BSD-3-Clause" ]
10
2017-11-23T13:46:21.000Z
2021-10-13T10:15:23.000Z
<?php namespace rollun\logger\Transport; use Jaeger\Transport\TUDPTransport; /** * Class JagerUDPTransport * @package rollun\logger\Transport * @deprecated use rollun\logger\Transport\UDPTransport */ class JagerUDPTransport implements TransportInterface { /** * @var TUDPTransport */ private $transport; protected $options = []; public function __construct(TUDPTransport $transport, $options = []) { $this->transport = $transport; $this->options = $options; } public function write(string $message): void { $this->transport->write($message); } public function flush(): void { $this->transport->flush(); } public function close(): void { $this->transport->close(); } public function getName(): string { return 'UDP'; } }
18
72
0.614583
a3199831c05495701089332c0f0eaeef6a045d6f
220
java
Java
src/main/java/com/scnu/peexamsystem/service/classes/ClassService.java
Moenya1030/PEExamSystem
248feab51613867cb7b70973f8c25be8b9a5b7a8
[ "MIT" ]
2
2020-10-24T11:00:20.000Z
2020-10-28T09:26:39.000Z
src/main/java/com/scnu/peexamsystem/service/classes/ClassService.java
Moenya1030/PEExamSystem
248feab51613867cb7b70973f8c25be8b9a5b7a8
[ "MIT" ]
null
null
null
src/main/java/com/scnu/peexamsystem/service/classes/ClassService.java
Moenya1030/PEExamSystem
248feab51613867cb7b70973f8c25be8b9a5b7a8
[ "MIT" ]
1
2020-10-28T09:33:30.000Z
2020-10-28T09:33:30.000Z
package com.scnu.peexamsystem.service.classes; import java.util.Map; public interface ClassService { Map<String, Object> getGradeList(); Map<String, Object> queryClassList(String instituteNo, String grade); }
22
73
0.763636
1a6b30e88a6f30aa2a3a8b20000c5cddd916bfb3
648
py
Python
backend/pycloud_api/models/schemas/package.py
git-albertomarin/pycloud
2d273096bc16d09ec2890ca3e3200ad64bde92d3
[ "Apache-2.0" ]
3
2020-02-23T12:54:47.000Z
2021-01-09T11:32:49.000Z
backend/pycloud_api/models/schemas/package.py
git-albertomarin/pycloud
2d273096bc16d09ec2890ca3e3200ad64bde92d3
[ "Apache-2.0" ]
5
2021-03-09T22:04:10.000Z
2022-02-18T14:07:29.000Z
backend/pycloud_api/models/schemas/package.py
albmarin/Pycloud
2d273096bc16d09ec2890ca3e3200ad64bde92d3
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- from typing import Optional, List from pydantic import UrlStr, constr from .dbmodel import DBModelMixin, ObjectIdStr from .rwmodel import RWModel from .user import UserInDB class Package(RWModel): name: str summary: Optional[str] = "" maintainers: Optional[List[UserInDB]] class PackageInDB(DBModelMixin, Package): pass class Release(RWModel): description: str download_url: Optional[UrlStr] home_page: Optional[UrlStr] version: constr(max_length=80) keywords: constr(max_length=255) package: Optional[ObjectIdStr] = None class ReleaseInDB(DBModelMixin, Release): pass
19.636364
46
0.726852
c6ab8608fd60b1b412c385f936a346db9fa33ef8
2,538
py
Python
build/lib/libvivp/vPackage.py
AdityaNG/VPM
49673c0a4a6fe96c656a41ee49ad4e84f65816fd
[ "MIT" ]
null
null
null
build/lib/libvivp/vPackage.py
AdityaNG/VPM
49673c0a4a6fe96c656a41ee49ad4e84f65816fd
[ "MIT" ]
null
null
null
build/lib/libvivp/vPackage.py
AdityaNG/VPM
49673c0a4a6fe96c656a41ee49ad4e84f65816fd
[ "MIT" ]
null
null
null
import json from .utils import is_vivp_file """ { 'packageDetails': { 'packageName' : '', 'packageAuthors' : [], }, 'packageURL': '', 'fileList': [], 'testBench': [], 'dependencyList': [] } """ class vPackage: """ vPackage """ def __init__(self, data=None, filePath=False, saveable=False, createNew=False): if filePath and not data: # filePath is provided self.filePath = filePath self.saveable = saveable if is_vivp_file(filePath): # load from filePath with open(filePath) as f: self.data = json.load(f) elif createNew: # create new self.data = self.getBlankPackageData() self.save() else: raise Exception("Not a vPackage") elif data and not filePath: # data is provided if saveable: raise Exception("vPackage without filePath is not saveable") self.data = data self.filePath = False self.saveable = False else: raise Exception("vPackage initializes with either data or filePath, not both") pass def load(self): with open(self.filePath) as f: self.data = json.load(f) def save(self): if not self.saveable: raise Exception("Write attempt to write protected package") # Save to self.filePath with open(self.filePath, 'w') as json_file: json.dump(self.data, json_file) def getBlankPackageData(self): return { 'packageDetails': { 'packageName' : '', 'packageAuthors' : [], }, 'packageURL': '', 'fileList': [], 'testBench': [], 'dependencyList': [] } def has_dependency(self, d): for dep in self.data['dependencyList']: if d == dep: return True return False def has_file(self, d): for dep in self.data['fileList']: if d == dep: return True return False def has_testbench(self, d): for dep in self.data['testBench']: if d == dep: return True return False def __repr__(self): return "vPackage()" def __str__(self): return json.dumps(self.data, indent=4, sort_keys=True)
27.586957
90
0.503546
8d0ec27c48f8528167fb084b020b9f6e92cc7ee7
453
dart
Dart
lib/util/mixins/use_assets_loader.dart
TaylorHo/bonfire
c0541a89f175a7e44534a71bc1acdd0cd82b6bc4
[ "MIT" ]
null
null
null
lib/util/mixins/use_assets_loader.dart
TaylorHo/bonfire
c0541a89f175a7e44534a71bc1acdd0cd82b6bc4
[ "MIT" ]
null
null
null
lib/util/mixins/use_assets_loader.dart
TaylorHo/bonfire
c0541a89f175a7e44534a71bc1acdd0cd82b6bc4
[ "MIT" ]
null
null
null
import 'package:bonfire/base/game_component.dart'; import '../assets_loader.dart'; /// /// Created by /// /// ─▄▀─▄▀ /// ──▀──▀ /// █▀▀▀▀▀█▄ /// █░░░░░█─█ /// ▀▄▄▄▄▄▀▀ /// /// Rafaelbarbosatec /// on 04/02/22 mixin UseAssetsLoader on GameComponent { /// Used to load assets in [onLoad] AssetsLoader? loader = AssetsLoader(); @override Future<void> onLoad() async { await loader?.load(); loader = null; return super.onLoad(); } }
17.423077
50
0.569536
0d66dff5fd1523dde12eb9e50405be5cc2a4a672
1,946
cs
C#
Magenic.SharedKernel/Uri.cs
Magenic/Magenic.ShareKernel
30521b1c2a2a45837c248f1954e314133986ff60
[ "MIT" ]
3
2017-08-02T18:51:53.000Z
2020-03-20T07:26:11.000Z
Magenic.SharedKernel/Uri.cs
Magenic/Magenic.ShareKernel
30521b1c2a2a45837c248f1954e314133986ff60
[ "MIT" ]
null
null
null
Magenic.SharedKernel/Uri.cs
Magenic/Magenic.ShareKernel
30521b1c2a2a45837c248f1954e314133986ff60
[ "MIT" ]
1
2017-09-10T17:41:38.000Z
2017-09-10T17:41:38.000Z
using System; namespace Magenic.SharedKernel { /// <summary> /// Contains Uri helper methods. /// </summary> public static class UriEx { #region Public Methods /// <summary> /// Adds port to Uri. /// </summary> /// <param name="baseUri">Base Uri.</param> /// <param name="port">Port number.</param> /// <returns>Uri.</returns> public static Uri AddPort(string baseUri, int port) { UriBuilder builder = new UriBuilder(baseUri); builder.Port = port; return builder.Uri; } /// <summary> /// Builds Uri from Base Uri and Relative Uri. /// </summary> /// <param name="baseUri">Base Uri.</param> /// <param name="relativeUri">Relative Uri.</param> /// <returns>Combined Uri.</returns> public static Uri Create(string baseUri, string relativeUri) => new Uri( new Uri(baseUri.EndsWith("/") ? baseUri : $"{baseUri}/"), relativeUri); /// <summary> /// Builds Uri from Base Uri and Relative Uri. /// </summary> /// <param name="baseUri">Base Uri.</param> /// <param name="relativeUri">Relative Uri.</param> /// <returns>Combined Uri.</returns> public static Uri Create(Uri baseUri, string relativeUri) => Create(baseUri.AbsoluteUri, relativeUri); /// <summary> /// Sets scheme. /// </summary> /// <param name="baseUri">Base Uri.</param> /// <param name="scheme">Scheme.</param> /// <returns>Uri with scheme set.</returns> public static Uri SetScheme( Uri baseUri, string scheme = "HTTP") { UriBuilder builder = new UriBuilder(baseUri); builder.Scheme = scheme; return builder.Uri; } #endregion } }
29.044776
73
0.527749
db8cd35eeb75282f95c3f032a1a0cc60d36309e6
1,516
php
PHP
edit.php
isdiego/PIM-WEB
4ad74defd255d8ed1cb56b42bc3028952cb93271
[ "MIT" ]
null
null
null
edit.php
isdiego/PIM-WEB
4ad74defd255d8ed1cb56b42bc3028952cb93271
[ "MIT" ]
null
null
null
edit.php
isdiego/PIM-WEB
4ad74defd255d8ed1cb56b42bc3028952cb93271
[ "MIT" ]
null
null
null
<?php require_once 'connect.php'; // resgata os valores do formulário $curso = isset($_POST['curso']) ? $_POST['curso'] : null; $periodo = isset($_POST['periodo']) ? $_POST['periodo'] : null; $semestre = isset($_POST['semestre']) ? $_POST['semestre'] : null; $turma = isset($_POST['turma']) ? $_POST['turma'] : null; $bloco = isset($_POST['bloco']) ? $_POST['bloco'] : null; $andar = isset($_POST['andar']) ? $_POST['andar'] : null; $sala = isset($_POST['sala']) ? $_POST['sala'] : null; $id_curso = isset($_POST['id_curso']) ? $_POST['id_curso'] : null; // validação (bem simples, mais uma vez) if (empty($curso) || empty($periodo) || empty($semestre) || empty($turma) || empty($bloco) || empty($andar) || empty($sala)) { echo "Volte e preencha todos os campos"; exit; } // atualiza o banco $PDO = db_connect(); $sql = "UPDATE cursos SET curso = :curso, periodo = :periodo, semestre = :semestre, turma = :turma, bloco = :bloco, andar = :andar, sala = :sala WHERE id_curso = :id_curso"; $stmt = $PDO->prepare($sql); $stmt->bindParam(':curso', $curso); $stmt->bindParam(':periodo', $periodo); $stmt->bindParam(':semestre', $semestre); $stmt->bindParam(':turma', $turma); $stmt->bindParam(':bloco', $bloco); $stmt->bindParam(':andar', $andar); $stmt->bindParam(':sala', $sala); $stmt->bindParam(':id_curso', $id_curso, PDO::PARAM_INT); if ($stmt->execute()) { header('Location: consulta.php'); } else { echo "Erro ao alterar"; print_r($stmt->errorInfo()); } ?>
38.871795
174
0.617414
4be49611f35d74c116398b08df0374e79e03b1a5
1,821
h
C
src/tween.h
Piglit/SeriousProton
6be74d1aca54d6c7f99fa403b0c3d2891a5ca8dc
[ "MIT" ]
null
null
null
src/tween.h
Piglit/SeriousProton
6be74d1aca54d6c7f99fa403b0c3d2891a5ca8dc
[ "MIT" ]
null
null
null
src/tween.h
Piglit/SeriousProton
6be74d1aca54d6c7f99fa403b0c3d2891a5ca8dc
[ "MIT" ]
null
null
null
#ifndef TWEEN_H #define TWEEN_H #include <glm/gtc/type_precision.hpp> /** Tweening functions. Allows for none-linear effects and stuff. */ template<typename T> class Tween { protected: static T tweenApply(float f, const T& value0, const T& value1); public: static inline T linear(float time_now, float time_start, float time_end, const T& value0, const T& value1) { float t = (time_now - time_start) / (time_end - time_start); return tweenApply(t, value0, value1); } static inline T easeInQuad(float time_now, float time_start, float time_end, const T& value0, const T& value1) { float t = (time_now - time_start) / (time_end - time_start); return tweenApply(t * t, value0, value1); } static inline T easeOutQuad(float time_now, float time_start, float time_end, const T& value0, const T& value1) { float t = (time_now - time_start) / (time_end - time_start); return tweenApply(-t * (t - 2.0f), value0, value1); } static inline T easeInCubic(float time_now, float time_start, float time_end, const T& value0, const T& value1) { float t = (time_now - time_start) / (time_end - time_start); return tweenApply(t * t * t, value0, value1); } static inline T easeOutCubic(float time_now, float time_start, float time_end, const T& value0, const T& value1) {//BUGGED! float t = (time_now - time_start) / (time_end - time_start); t -= 1.0; return tweenApply(-(t * t * t + 1), value0, value1); } }; template<typename T> T Tween<T>::tweenApply(float f, const T& value0, const T& value1) { return value0 + (value1 - value0) * f; } template<> glm::u8vec4 Tween<glm::u8vec4>::tweenApply(float f, const glm::u8vec4& value0, const glm::u8vec4& value1); #endif//TWEEN_H
35.019231
117
0.65788
18e651e9999925bbea975005469df39a1ddc0f8b
22
rs
Rust
src/models/validators/oauth/mod.rs
modrinth/minos
b22e5592f9085c8083039fc405f80ddcc24fe7db
[ "Apache-2.0" ]
6
2021-03-21T23:00:38.000Z
2021-11-24T18:24:30.000Z
src/models/validators/oauth/mod.rs
modrinth/minos
b22e5592f9085c8083039fc405f80ddcc24fe7db
[ "Apache-2.0" ]
1
2022-03-23T06:34:46.000Z
2022-03-23T06:37:24.000Z
src/models/validators/oauth/mod.rs
modrinth/minos
b22e5592f9085c8083039fc405f80ddcc24fe7db
[ "Apache-2.0" ]
2
2021-03-22T07:01:50.000Z
2021-11-24T18:24:36.000Z
pub mod oauth_client;
11
21
0.818182
905dcd5912bf7499263c1f9027bbea9d26c77d46
2,354
rs
Rust
src/p00xx/p31.rs
Houjuu-Nue/leetcode-rs
9c54af5f3cf810745796cf9bd4075117070a1b3d
[ "MIT" ]
1
2019-10-03T15:46:00.000Z
2019-10-03T15:46:00.000Z
src/p00xx/p31.rs
Houjuu-Nue/leetcode-rs
9c54af5f3cf810745796cf9bd4075117070a1b3d
[ "MIT" ]
null
null
null
src/p00xx/p31.rs
Houjuu-Nue/leetcode-rs
9c54af5f3cf810745796cf9bd4075117070a1b3d
[ "MIT" ]
null
null
null
//! //! Next Permutation //! //! https://leetcode.com/problems/next-permutation/ //! //! Implement **next permutation**, which rearranges numbers into the lexicographically next greater permutation of numbers. //! //! If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order). //! //! The replacement must be [in-place](http://en.wikipedia.org/wiki/In-place_algorithm) and use only constant extra memory. //! //! Here are some examples. //! Inputs are in the left-hand column and its corresponding outputs are in the right-hand column. //! //! `1,2,3` → `1,3,2` //! //! `3,2,1` → `1,2,3` //! //! `1,1,5` → `1,5,1` //! pub type Input = Vec<i32>; pub type Output = (); pub trait Solution { fn next_permutation(&self, nums: &mut Vec<i32>); } // ----------------------------------------------------------------------------- /// Approach 0: Search from end to start. pub struct Solution0; impl Solution for Solution0 { fn next_permutation(&self, nums: &mut Vec<i32>) { for i in (0..(nums.len() - 1)).rev() { for j in ((i + 1)..nums.len()).rev() { if nums[j] > nums[i] { nums.swap(i, j); nums[(i + 1)..].sort_unstable(); return } } } nums.sort_unstable(); } } // ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- /// Approach 1: Single Pass Approach. pub struct Solution1; impl Solution for Solution1 { fn next_permutation(&self, nums: &mut Vec<i32>) { let len = nums.len(); if len < 2 { return } let mut i = (len - 2) as i32; while i >= 0 { if nums[i as usize] < nums[(i + 1) as usize] { break } i -= 1; } if i < 0 { nums.sort_unstable(); return } let i = i as usize; let mut j = len - 1; while i < j { if nums[i] < nums[j] { nums.swap(i, j); nums[(i + 1)..len].sort_unstable(); return } j -= 1; } } } // -----------------------------------------------------------------------------
26.155556
124
0.442651
ee21afce590692a97b1f09c248dc75e1a636f4a7
1,035
dart
Dart
lib/widgets/elements/Frame/Spacing/AnimatedPadding/index.dart
HelloCore/flutter-go
9f7a25c89afa8d2b9acc7343365f50960a540d3f
[ "MIT" ]
3
2019-07-10T02:39:26.000Z
2021-07-28T00:59:09.000Z
lib/widgets/elements/Frame/Spacing/AnimatedPadding/index.dart
PopFisher/flutter-go
4d1080a619f35913c398c3dbebc263df4f6098f5
[ "MIT" ]
null
null
null
lib/widgets/elements/Frame/Spacing/AnimatedPadding/index.dart
PopFisher/flutter-go
4d1080a619f35913c398c3dbebc263df4f6098f5
[ "MIT" ]
2
2019-03-02T10:21:05.000Z
2019-07-10T02:39:27.000Z
/* * @Author: 一凨 * @Date: 2018-11-28 20:44:13 * @Last Modified by: 一凨 * @Last Modified time: 2019-01-14 17:02:20 */ import 'package:flutter/material.dart'; import 'package:flutter_go/components/widget_demo.dart'; import './animatedPadding_demo.dart'; const contentDesc0 = ''' ### **简介** > 属于Flutter动画成员的一部分 '''; const contentDesc1 = ''' ### **基本用法** > 动画版本的Padding - 在给定的时间内,自动完成转换缩进到给定的padding值 - 通过设置curve 来指定动画的运行速率动画 '''; class Demo extends StatefulWidget { static const String routeName = '/element/Frame/spacing/AnimatedPadding'; _DemoState createState() => _DemoState(); } class _DemoState extends State<Demo> { @override Widget build(BuildContext context) { return WidgetDemo( title: 'AnimatedPadding', contentList: [ contentDesc0, contentDesc1, AnimatedPaddingDemo(), ], docUrl: 'https://docs.flutter.io/flutter/widgets/AnimatedPadding-class.html', codeUrl: 'elements/Frame/Spacing/AnimatedPadding/animatedPadding_demo.dart', ); } }
23.522727
82
0.683092
6b36b8ec06fa3bf74bc67479ec2dd0a086ef5028
4,476
cc
C++
mojo/public/cpp/system/string_data_pipe_producer.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
mojo/public/cpp/system/string_data_pipe_producer.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
mojo/public/cpp/system/string_data_pipe_producer.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "mojo/public/cpp/system/string_data_pipe_producer.h" #include <algorithm> #include "base/bind.h" #include "base/callback.h" #include "base/location.h" #include "base/task_scheduler/post_task.h" namespace mojo { namespace { // Attempts to write data to a producer handle. Outputs the actual number of // bytes written in |*size|, and returns a result indicating the status of the // last attempted write operation. MojoResult WriteDataToProducerHandle(DataPipeProducerHandle producer, const char* data, size_t* size) { void* dest; uint32_t bytes_left = static_cast<uint32_t>(*size); // We loop here since the pipe's available capacity may be larger than its // *contiguous* capacity, and hence two independent consecutive two-phase // writes may succeed. The goal here is to write as much of |data| as possible // until we either run out of data or run out of capacity. MojoResult result; do { uint32_t capacity = bytes_left; result = producer.BeginWriteData(&dest, &capacity, MOJO_WRITE_DATA_FLAG_NONE); if (result == MOJO_RESULT_SHOULD_WAIT) { result = MOJO_RESULT_OK; break; } else if (result != MOJO_RESULT_OK) { break; } capacity = std::min(capacity, bytes_left); memcpy(dest, data, capacity); MojoResult end_result = producer.EndWriteData(capacity); DCHECK_EQ(MOJO_RESULT_OK, end_result); data += capacity; bytes_left -= capacity; } while (bytes_left); *size -= bytes_left; return result; } } // namespace StringDataPipeProducer::StringDataPipeProducer( ScopedDataPipeProducerHandle producer) : producer_(std::move(producer)), watcher_(FROM_HERE, SimpleWatcher::ArmingPolicy::AUTOMATIC, base::SequencedTaskRunnerHandle::Get()), weak_factory_(this) {} StringDataPipeProducer::~StringDataPipeProducer() = default; void StringDataPipeProducer::Write(const base::StringPiece& data, AsyncWritingMode mode, CompletionCallback callback) { DCHECK(!callback_); callback_ = std::move(callback); // Immediately attempt to write data without making an extra copy. If we can // get it all in one shot, we're done aleady. size_t size = data.size(); MojoResult result = WriteDataToProducerHandle(producer_.get(), data.data(), &size); if (result == MOJO_RESULT_OK && size == data.size()) { base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&StringDataPipeProducer::InvokeCallback, weak_factory_.GetWeakPtr(), MOJO_RESULT_OK)); } else { // Copy whatever data didn't make the cut and try again when the pipe has // some more capacity. if (mode == AsyncWritingMode::STRING_MAY_BE_INVALIDATED_BEFORE_COMPLETION) { data_ = std::string(data.data() + size, data.size() - size); data_view_ = data_; } else { data_view_ = base::StringPiece(data.data() + size, data.size() - size); } watcher_.Watch(producer_.get(), MOJO_HANDLE_SIGNAL_WRITABLE, MOJO_WATCH_CONDITION_SATISFIED, base::Bind(&StringDataPipeProducer::OnProducerHandleReady, base::Unretained(this))); } } void StringDataPipeProducer::InvokeCallback(MojoResult result) { // May delete |this|. std::move(callback_).Run(result); } void StringDataPipeProducer::OnProducerHandleReady( MojoResult ready_result, const HandleSignalsState& state) { bool failed = false; size_t size = data_view_.size(); if (ready_result == MOJO_RESULT_OK) { MojoResult write_result = WriteDataToProducerHandle(producer_.get(), data_view_.data(), &size); if (write_result != MOJO_RESULT_OK) failed = true; } else { failed = true; } if (failed) { watcher_.Cancel(); // May delete |this|. std::move(callback_).Run(MOJO_RESULT_ABORTED); return; } if (size == data_view_.size()) { watcher_.Cancel(); // May delete |this|. std::move(callback_).Run(MOJO_RESULT_OK); return; } data_view_ = base::StringPiece(data_view_.data() + size, data_view_.size() - size); } } // namespace mojo
32.201439
80
0.66555
2fb153dc1a8b21c31a7b9e950dbe6d8ea75a14ba
1,806
py
Python
app/webdriver/mouseActuator.py
enricoteterra/virtual-agent
fa07df4789ebf265bd56726f6d9aad6fce411c97
[ "MIT" ]
null
null
null
app/webdriver/mouseActuator.py
enricoteterra/virtual-agent
fa07df4789ebf265bd56726f6d9aad6fce411c97
[ "MIT" ]
null
null
null
app/webdriver/mouseActuator.py
enricoteterra/virtual-agent
fa07df4789ebf265bd56726f6d9aad6fce411c97
[ "MIT" ]
null
null
null
from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys class MouseActuator(object): """ enables agent to look around the virtual environment by performing drag and drop actions with the mouse. """ def __init__(self, webDriver): self.driver = webDriver self.canvas = webDriver.find_element_by_tag_name('canvas') def scaleFactor(self, factor): """ we want a number between 0 and 1 to describe how far to scroll relative to the screen dimensions. we need to translate that number into pixels. @TODO: come up with something smarter """ return factor * 300 def scrollUp(self, distance=20): self.centerCursor() ActionChains(self.driver)\ .click_and_hold()\ .move_by_offset(0, -distance)\ .release()\ .perform() def scrollDown(self, distance=20): self.centerCursor() ActionChains(self.driver)\ .click_and_hold()\ .move_by_offset(0, distance)\ .release()\ .perform() def scrollLeft(self, distance=20): self.centerCursor() ActionChains(self.driver)\ .click_and_hold()\ .move_by_offset(-distance, 0)\ .release()\ .perform() def scrollRight(self, distance=20): self.centerCursor() ActionChains(self.driver)\ .click_and_hold()\ .move_by_offset(distance, 0)\ .release()\ .perform() def centerCursor(self): ActionChains(self.driver)\ .move_to_element(self.canvas)\ .perform()
27.363636
79
0.565891
5d150329f2789c3e0520090ca211fca8fda2b42c
640
go
Go
mdw/mdw_limit_api.go
Xwudao/junet
2eb7cbbc638d8693216b976b9ecf2258ca71fa23
[ "MIT" ]
null
null
null
mdw/mdw_limit_api.go
Xwudao/junet
2eb7cbbc638d8693216b976b9ecf2258ca71fa23
[ "MIT" ]
null
null
null
mdw/mdw_limit_api.go
Xwudao/junet
2eb7cbbc638d8693216b976b9ecf2258ca71fa23
[ "MIT" ]
null
null
null
package mdw import ( "github.com/gin-gonic/gin" "go.uber.org/ratelimit" "sync" ) type ApiLimitOpt struct { Path string `json:"path"` CountPerSeconds int `json:"count_per_seconds"` Slack int `json:"slack"` } func ApiLimitMiddleware(opts []ApiLimitOpt) gin.HandlerFunc { var syncMap sync.Map for _, opt := range opts { syncMap.LoadOrStore(opt.Path, ratelimit.New(opt.CountPerSeconds, ratelimit.WithSlack(opt.Slack))) } return func(c *gin.Context) { pt := c.Request.URL.Path limiter, ok := syncMap.Load(pt) if !ok { c.Next() return } limiter.(ratelimit.Limiter).Take() c.Next() } }
20.645161
99
0.664063
a9e66ff551dde00548dc78b5b4b8faf795bf540f
5,669
php
PHP
resources/views/admin/master.blade.php
hieudt/Shop-Laravel
b037741dbc31160d3c9d207a972c00ba3c8b2104
[ "MIT" ]
1
2021-12-10T15:44:17.000Z
2021-12-10T15:44:17.000Z
resources/views/admin/master.blade.php
hieudt/Shop-Laravel
b037741dbc31160d3c9d207a972c00ba3c8b2104
[ "MIT" ]
null
null
null
resources/views/admin/master.blade.php
hieudt/Shop-Laravel
b037741dbc31160d3c9d207a972c00ba3c8b2104
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang="{{ app()->getLocale() }}"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="csrf-token" content="{{ csrf_token() }}"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <title>@yield('title')</title> <!-- plugins:css --> <link rel="stylesheet" href="{{asset('@styleadmin/css/mdi.css')}}"> <link rel="stylesheet" href="{{asset('@styleadmin/node_modules/flag-icon-css/css/flag-icon.min.css')}}"> <link rel="stylesheet" href="{{asset('@styleadmin/node_modules/perfect-scrollbar/css/perfect-scrollbar.css')}}"> <link rel="stylesheet" href="{{asset('@styleadmin/node_modules/jquery-toast-plugin/dist/jquery.toast.min.css')}}"> <link rel="stylesheet" href="{{asset('@styleadmin/css/home.css')}}"> <!-- endinject --> <!-- plugin css for this page --> @yield('css') <!-- End plugin css for this page --> <!-- inject:css --> <link rel="stylesheet" href="{{asset('@styleadmin/css/style.css')}}"> <!-- endinject --> <link rel="shortcut icon" href="{{asset('@styleadmin/images/favicon.png')}}" /> </head> <body> <div class="container-scroller"> @include('admin.elements.header') <div class="container-fluid page-body-wrapper"> @include('admin.elements.themes') @include('admin.elements.sidebar') <div class="main-panel"> <div class="content-wrapper"> <div id="app"> @yield('content') </div> </div> <!-- content-wrapper ends --> <!-- partial:{{asset('@styleadmin/partials/_footer.html')}} --> @include('admin.elements.footer') <!-- partial --> </div> <!-- main-panel ends --> </div> <!-- page-body-wrapper ends --> </div> <div class="modal fade" id="SiriModal" tabindex="-1" role="dialog" aria-labelledby="SubCategoryLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="SubCategoryLabel">ROG Siri</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="form-group"> <label for="message-text" class="col-form-label">Hi Im Siri </label><br/> <div class="input-single"> <textarea id="note-textarea" placeholder="Chào ngài ! Ngài muốn làm gì?? " rows="6"></textarea> </div> </div> </div> <div class="modal-footer" id="submodalFooter"> </div> </div> </div> </div> <div class="modal fade" id="changepassModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Đổi mật khẩu quản trị</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="recipient-name" class="col-form-label">Mật Khẩu Cũ : </label> <input type="password" class="form-control" id="pwOld"> </div> <div class="form-group"> <label for="recipient-name" class="col-form-label">Mật Khẩu Mới : </label> <input type="password" class="form-control" id="pwNew"> </div> <div class="form-group"> <label for="recipient-name" class="col-form-label">Nhập lại MK Mới : </label> <input type="password" class="form-control" id="pwNewRe"> </div> </form> </div> <div class="modal-footer" id="modalFooter"> <button type="button" class="btn btn-success" id="btnChangePass">Đổi</button> <button type="button" class="btn btn-default" data-dismiss="modal">Đóng</button> </div> </div> </div> </div> <!-- container-scroller --> <!-- plugins:js --> <script src="{{asset('@styleadmin/node_modules/jquery/dist/jquery.min.js')}}"></script> <script src="{{asset('@styleadmin/node_modules/popper.js/dist/umd/popper.min.js')}}"></script> <script src="{{asset('@styleadmin/node_modules/bootstrap/dist/js/bootstrap.min.js')}}"></script> <script src="{{asset('@styleadmin/node_modules/jquery-toast-plugin/dist/jquery.toast.min.js')}}"></script> <script src="{{asset('@styleadmin/js/toastDemo.js')}}"></script> <script src="{{asset('@styleadmin/js/pusher.min.js')}}"></script> <script src="{{asset('@styleadmin/js/myjs.js')}}"></script> <script src="{{asset('@styleadmin/js/pace.min.js')}}"></script> <script src="{{asset('@styleadmin/node_modules/perfect-scrollbar/dist/perfect-scrollbar.min.js')}}"></script> <!-- endinject --> <!-- Plugin js for this page--> <!-- End plugin js for this page--> <!-- inject:js --> <script src="{{asset('@styleadmin/js/off-canvas.js')}}"></script> <script src="{{asset('@styleadmin/js/hoverable-collapse.js')}}"></script> <script src="{{asset('@styleadmin/js/misc.js')}}"></script> <script src="{{asset('@styleadmin/js/settings.js')}}"></script> <script src="{{asset('@styleadmin/js/todolist.js')}}"></script> <!-- endinject --> <!-- Custom js for this page--> @yield('javascript') <!-- End custom js for this page--> </body> @include('admin.elements.siri') </html>
42.62406
123
0.592168
ddbaa8cf9c49c4608c781cb197cb69de555fa12d
3,380
java
Java
testsuite/integration-arquillian/tests/other/console/src/test/java/org/keycloak/testsuite/console/events/AdminEventsTest.java
plivo/keycloak
cf7a194ea3d8b93da00edd02c23ddb9790bbd7a6
[ "Apache-2.0" ]
null
null
null
testsuite/integration-arquillian/tests/other/console/src/test/java/org/keycloak/testsuite/console/events/AdminEventsTest.java
plivo/keycloak
cf7a194ea3d8b93da00edd02c23ddb9790bbd7a6
[ "Apache-2.0" ]
1
2021-02-23T14:13:32.000Z
2021-02-23T15:30:40.000Z
testsuite/integration-arquillian/tests/other/console/src/test/java/org/keycloak/testsuite/console/events/AdminEventsTest.java
isabella232/keycloak
cf7a194ea3d8b93da00edd02c23ddb9790bbd7a6
[ "Apache-2.0" ]
3
2016-03-24T18:44:57.000Z
2020-11-12T10:25:31.000Z
package org.keycloak.testsuite.console.events; import org.jboss.arquillian.graphene.page.Page; import org.junit.Before; import org.junit.Test; import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.console.AbstractConsoleTest; import org.keycloak.testsuite.console.clients.AbstractClientTest; import org.keycloak.testsuite.console.page.clients.Clients; import org.keycloak.testsuite.console.page.events.AdminEvents; import org.keycloak.testsuite.console.page.events.Config; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import javax.ws.rs.core.Response; import java.util.List; import static org.junit.Assert.assertEquals; import org.keycloak.admin.client.resource.ClientsResource; import static org.keycloak.testsuite.console.page.clients.CreateClientForm.OidcAccessType.CONFIDENTIAL; /** * @author mhajas */ public class AdminEventsTest extends AbstractConsoleTest { @Page private AdminEvents adminEventsPage; @Page private Config configPage; @Page private Clients clientsPage; private ClientRepresentation newClient; @Before public void beforeAdminEventsTest() { RealmRepresentation realm = testRealmResource().toRepresentation(); realm.setAdminEventsEnabled(true); realm.setAdminEventsDetailsEnabled(true); testRealmResource().update(realm); } @Test public void clientsAdminEventsTest() { newClient = AbstractClientTest.createOidcClientRep(CONFIDENTIAL, "test_client", "http://example.test/test_client/*"); Response response = clientsResource().create(newClient); String id = ApiUtil.getCreatedId(response); response.close(); newClient.setClientId("test_client2"); clientsResource().get(id).update(newClient); clientsResource().get(id).remove(); adminEventsPage.navigateTo(); adminEventsPage.table().filter(); adminEventsPage.table().filterForm().addOperationType("CREATE"); adminEventsPage.table().update(); List<WebElement> resultList = adminEventsPage.table().rows(); assertEquals(1, resultList.size()); resultList.get(0).findElement(By.xpath("//td[text()='CREATE']")); resultList.get(0).findElement(By.xpath("//td[text()='clients/" + id + "']")); adminEventsPage.table().reset(); adminEventsPage.table().filterForm().addOperationType("UPDATE"); adminEventsPage.table().update(); resultList = adminEventsPage.table().rows(); assertEquals(1, resultList.size()); resultList.get(0).findElement(By.xpath("//td[text()='UPDATE']")); resultList.get(0).findElement(By.xpath("//td[text()='clients/" + id + "']")); adminEventsPage.table().reset(); adminEventsPage.table().filterForm().addOperationType("DELETE"); adminEventsPage.table().update(); resultList = adminEventsPage.table().rows(); assertEquals(1, resultList.size()); resultList.get(0).findElement(By.xpath("//td[text()='DELETE']")); resultList.get(0).findElement(By.xpath("//td[text()='clients/" + id + "']")); } public ClientsResource clientsResource() { return testRealmResource().clients(); } }
35.957447
125
0.705325
1a75b5e6f9080a6d4cba5520e303ca8429ab8e9b
760
cs
C#
Drone.Configuration/Validation/AbstractConfigurationValidator.cs
cyclopunk/Rigger
7789c18d6e89fc0b37cf774f70dde2165afd0b2a
[ "Apache-2.0" ]
null
null
null
Drone.Configuration/Validation/AbstractConfigurationValidator.cs
cyclopunk/Rigger
7789c18d6e89fc0b37cf774f70dde2165afd0b2a
[ "Apache-2.0" ]
2
2020-09-03T01:03:24.000Z
2020-09-04T19:42:53.000Z
Drone.Configuration/Validation/AbstractConfigurationValidator.cs
cyclopunk/Rigger
7789c18d6e89fc0b37cf774f70dde2165afd0b2a
[ "Apache-2.0" ]
null
null
null
using System.Collections.Generic; using System.Linq; using Rigger.Configuration; using Rigger.Configuration.Validation; namespace Drone.Configuration.Validation { /// <summary> /// Configuration Validator abstract class. /// </summary> public abstract class AbstractConfigurationValidator : IConfigurationValidator { public virtual bool IsValid(params IConfigurationSource[] sources) { IEnumerable<ConfigurationValidationResult> validations = Validate(sources); return validations == null || !validations.Any(); // true if validation results are null or empty } public abstract IEnumerable<ConfigurationValidationResult> Validate(params IConfigurationSource[] sources); } }
33.043478
115
0.723684
33be54aaefbb454d71c64311f7949021e06fdfff
131
lua
Lua
ex-1.3.lua
fbonnet33/pil-4th
417e4604cef776024c353fc1b3ae8652ffef3841
[ "MIT" ]
3
2020-11-25T11:57:51.000Z
2021-12-26T17:07:50.000Z
ex-1.3.lua
fbonnet33/pil-4th
417e4604cef776024c353fc1b3ae8652ffef3841
[ "MIT" ]
null
null
null
ex-1.3.lua
fbonnet33/pil-4th
417e4604cef776024c353fc1b3ae8652ffef3841
[ "MIT" ]
2
2021-03-14T21:37:54.000Z
2021-12-16T10:54:45.000Z
-- Exercise 1.3: Can you name other languages that use "--" for -- comments? -- Ada, Eiffel, Haskell, SQL and VHDL to name a few.
26.2
63
0.671756
ed43156cdd1d217539f273c5efc4112b10d4bea6
402
c
C
UVa/AOAPC_I/V1_Elementary_Problem_Solving/Maths_SimpleGeometry/10387.c
wh-acmer/minixalpha-acm
cb684ad70eaa61d42a445364cb3ee195b9e9302e
[ "MIT" ]
null
null
null
UVa/AOAPC_I/V1_Elementary_Problem_Solving/Maths_SimpleGeometry/10387.c
wh-acmer/minixalpha-acm
cb684ad70eaa61d42a445364cb3ee195b9e9302e
[ "MIT" ]
null
null
null
UVa/AOAPC_I/V1_Elementary_Problem_Solving/Maths_SimpleGeometry/10387.c
wh-acmer/minixalpha-acm
cb684ad70eaa61d42a445364cb3ee195b9e9302e
[ "MIT" ]
null
null
null
#include <stdio.h> #include <math.h> #define PI acos(-1) int main() { double a, b, s, m, n; double angle, velocity; while (scanf ("%lf%lf%lf%lf%lf", &a, &b, &s, &m, &n) != EOF) { if (a == 0 && b==0 && s==0 && m==0 && n==0) break; angle = atan( (b*n)/(a*m) ) * 180 / PI; velocity = sqrt(b*n*b*n+a*m*a*m) / s; printf ("%.2lf %.2lf\n", angle, velocity); } return 0; }
20.1
64
0.477612
3543bdc4750acb8c371c884bc66a87043481fd40
2,206
rs
Rust
src/errors.rs
OttoBos/gpx
e86ed781a0bd4aa2d2fc9744e129bc1693f85a07
[ "MIT" ]
null
null
null
src/errors.rs
OttoBos/gpx
e86ed781a0bd4aa2d2fc9744e129bc1693f85a07
[ "MIT" ]
null
null
null
src/errors.rs
OttoBos/gpx
e86ed781a0bd4aa2d2fc9744e129bc1693f85a07
[ "MIT" ]
null
null
null
//! errors provides error generics for the gpx parser. use std::num::{ParseFloatError, ParseIntError}; use thiserror::Error; pub(crate) type GpxResult<T> = Result<T, GpxError>; #[derive(Error, Debug)] #[non_exhaustive] /// Errors that can occur when reading or writing GPX files pub enum GpxError { #[error("error while casting to f64")] ParseFloatError(#[from] ParseFloatError), #[error("Could not convert value to u32")] ParseIntegerError(#[from] ParseIntError), #[error("invalid child element `{0}` in `{1}`")] InvalidChildElement(String, &'static str), #[error("invalid closing tag `{0}` in `{1}`")] InvalidClosingTag(String, &'static str), #[error("missing closing tag in `{0}`")] MissingClosingTag(&'static str), #[error("missing opening tag in `{0}`")] MissingOpeningTag(&'static str), #[error("invalid element, `{1}` lacks required attribute `{0}`")] InvalidElementLacksAttribute(&'static str, &'static str), #[error("minimum `{0}` larger than maximum `{0}`")] OutOfBounds(&'static str), #[error("error while parsing XML")] XmlParseError(#[from] xml::reader::Error), #[error("unknown GPX version: `{0}`")] UnknownVersionError(crate::types::GpxVersion), #[error("tag opened twice: `{0}`")] TagOpenedTwice(&'static str), #[error("error while parsing 'track' segment")] TrackSegmentError(), #[error("no string content")] NoStringContent, #[error("error while writing XML")] XmlWriteError(#[from] xml::writer::Error), #[error("missing `{0}` part in email")] MissingEmailPartError(&'static str), #[error("email contains multiple `@` symbols")] TooManyAtsError, #[error("error while parsing `{0}`")] EventParsingError(&'static str), #[error("error while parsing metadata")] MetadataParsingError(), #[error("invalid `{0}`: must be between `{1}`. Actual value: `{2}`")] LonLatOutOfBoundsError(&'static str, &'static str, f64), #[error("error trying to parse RFC3339 formatted date")] Rfc3339Error(#[from] time::error::Parse), #[error("error trying to write RFC3339 formatted date")] Rfc3339ErrorWriting(#[from] time::error::Format), }
40.109091
73
0.657752
feb34dd0d66a9884b9f38e9b6de1d387d0d47322
418
asm
Assembly
programs/oeis/004/A004446.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/004/A004446.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/004/A004446.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A004446: a(n) = Nimsum n + 5. ; 5,4,7,6,1,0,3,2,13,12,15,14,9,8,11,10,21,20,23,22,17,16,19,18,29,28,31,30,25,24,27,26,37,36,39,38,33,32,35,34,45,44,47,46,41,40,43,42,53,52,55,54,49,48,51,50,61,60,63,62,57,56,59,58,69,68,71,70,65,64,67,66,77,76,79,78,73,72,75,74,85,84,87,86,81,80,83,82,93,92,95,94,89,88,91,90,101,100,103,102 mov $2,$0 seq $0,244586 ; a(n) = n OR 4. div $0,2 add $0,10 mul $0,4 sub $0,$2 sub $0,43
38
295
0.619617
f780f7afc8254317a9c95564c63aa5ece9aed04d
370
rb
Ruby
lib/pallets/middleware/stack.rb
tombruijn/pallets
9052f989124c85462e8da2fd714e440e8fc59aa6
[ "MIT" ]
211
2018-10-01T13:53:10.000Z
2021-12-31T08:05:51.000Z
lib/pallets/middleware/stack.rb
tombruijn/pallets
9052f989124c85462e8da2fd714e440e8fc59aa6
[ "MIT" ]
10
2018-10-02T16:55:37.000Z
2021-09-10T07:36:29.000Z
lib/pallets/middleware/stack.rb
tombruijn/pallets
9052f989124c85462e8da2fd714e440e8fc59aa6
[ "MIT" ]
7
2018-10-01T13:53:13.000Z
2020-08-15T12:07:56.000Z
module Pallets module Middleware # Array-like class that acts like a stack and additionally provides the # means to wrap an operation with callable objects class Stack < Array def invoke(*args, &block) reverse.inject(block) do |memo, middleware| lambda { middleware.call(*args, &memo) } end.call end end end end
26.428571
75
0.654054
aa319733c52547cdf92aa3dcc4cdc1f1fb56a131
24,216
html
HTML
docs/_build/html/running.html
dondealban/coded
b6abfffbd173e507655e4989894442681e7b3da7
[ "MIT" ]
25
2018-06-06T18:42:32.000Z
2022-02-08T04:51:24.000Z
docs/_build/html/running.html
dondealban/coded
b6abfffbd173e507655e4989894442681e7b3da7
[ "MIT" ]
3
2019-05-23T18:30:11.000Z
2021-10-12T22:50:55.000Z
docs/_build/html/running.html
dondealban/coded
b6abfffbd173e507655e4989894442681e7b3da7
[ "MIT" ]
17
2018-12-07T21:12:45.000Z
2022-03-02T00:29:52.000Z
<!DOCTYPE html> <!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]--> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Running CODED &mdash; coded 0.2 documentation</title> <link rel="stylesheet" href="_static/css/theme.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <link rel="index" title="Index" href="genindex.html" /> <link rel="search" title="Search" href="search.html" /> <link rel="next" title="Utility Functions" href="dataFuncs.html" /> <link rel="prev" title="Parameters" href="module_parameters.html" /> <script src="_static/js/modernizr.min.js"></script> </head> <body class="wy-body-for-nav"> <div class="wy-grid-for-nav"> <nav data-toggle="wy-nav-shift" class="wy-nav-side"> <div class="wy-side-scroll"> <div class="wy-side-nav-search"> <a href="index.html" class="icon icon-home"> coded </a> <div class="version"> 0.2 </div> <div role="search"> <form id="rtd-search-form" class="wy-form" action="search.html" method="get"> <input type="text" name="q" placeholder="Search docs" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation"> <ul> <li class="toctree-l1"><a class="reference internal" href="background.html">Background and Motivation</a></li> <li class="toctree-l1"><a class="reference internal" href="definitions.html">Definitions</a></li> <li class="toctree-l1"><a class="reference internal" href="examples.html">Timeseries Examples</a></li> </ul> <ul class="current"> <li class="toctree-l1"><a class="reference internal" href="algorithm.html">Algorithm Description</a></li> <li class="toctree-l1"><a class="reference internal" href="training_data.html">Training Data</a></li> <li class="toctree-l1"><a class="reference internal" href="module_parameters.html">Parameters</a></li> <li class="toctree-l1 current"><a class="current reference internal" href="#">Running CODED</a></li> <li class="toctree-l1"><a class="reference internal" href="dataFuncs.html">Utility Functions</a></li> <li class="toctree-l1"><a class="reference internal" href="acre.html">Example: Acre, Brazil</a></li> </ul> <ul> <li class="toctree-l1"><a class="reference internal" href="drawing_sample.html">Sampling</a></li> <li class="toctree-l1"><a class="reference internal" href="interpretation.html">Interpretation</a></li> <li class="toctree-l1"><a class="reference internal" href="estimation.html">Accuracy and Estimation</a></li> </ul> </div> </div> </nav> <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"> <nav class="wy-nav-top" aria-label="top navigation"> <i data-toggle="wy-nav-top" class="fa fa-bars"></i> <a href="index.html">coded</a> </nav> <div class="wy-nav-content"> <div class="rst-content"> <div role="navigation" aria-label="breadcrumbs navigation"> <ul class="wy-breadcrumbs"> <li><a href="index.html">Docs</a> &raquo;</li> <li>Running CODED</li> <li class="wy-breadcrumbs-aside"> <a href="_sources/running.rst.txt" rel="nofollow"> View page source</a> </li> </ul> <hr/> </div> <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article"> <div itemprop="articleBody"> <div class="section" id="running-coded"> <h1>Running CODED<a class="headerlink" href="#running-coded" title="Permalink to this headline">¶</a></h1> <p><em>Instructions on running CODED.</em></p> <p>First, load the CODED module:</p> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><span class="kd">var</span> <span class="nx">codedUtils</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;users/bullocke/coded:v0.2/changeDetection&#39;</span><span class="p">)</span> </pre></div> </div> <p>Define the study area, with ‘region’ being an import or path to a feature.</p> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><span class="kd">var</span> <span class="nx">saveRegion</span> <span class="o">=</span> <span class="nx">ee</span><span class="p">.</span><span class="nx">FeatureCollection</span><span class="p">(</span><span class="nx">region</span><span class="p">)</span> </pre></div> </div> <p>Define the sample name and parameters:</p> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><span class="kd">var</span> <span class="nx">sampleName</span> <span class="o">=</span> <span class="nx">ee</span><span class="p">.</span><span class="nx">FeatureCollection</span><span class="p">(</span><span class="s1">&#39;users/bullockebu/amazon/samples/sample1&#39;</span><span class="p">)</span> <span class="kd">var</span> <span class="nx">params</span> <span class="o">=</span> <span class="nx">ee</span><span class="p">.</span><span class="nx">Dictionary</span><span class="p">({</span> <span class="s1">&#39;consec&#39;</span><span class="o">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;thresh&#39;</span><span class="o">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;start&#39;</span><span class="o">:</span> <span class="mi">1990</span><span class="p">,</span> <span class="s1">&#39;end&#39;</span><span class="o">:</span> <span class="mi">2018</span><span class="p">,</span> <span class="s1">&#39;trainDataEnd&#39;</span><span class="o">:</span> <span class="mi">2016</span><span class="p">,</span> <span class="s1">&#39;trainDataStart&#39;</span><span class="o">:</span> <span class="mi">2013</span><span class="p">,</span> <span class="s1">&#39;trainLength&#39;</span><span class="o">:</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;soil&#39;</span><span class="o">:</span> <span class="p">[</span><span class="mi">2000</span><span class="p">,</span> <span class="mi">3000</span><span class="p">,</span> <span class="mi">3400</span><span class="p">,</span> <span class="mi">5800</span><span class="p">,</span> <span class="mi">6000</span><span class="p">,</span> <span class="mi">5800</span><span class="p">],</span> <span class="s1">&#39;gv&#39;</span><span class="o">:</span> <span class="p">[</span><span class="mi">500</span><span class="p">,</span> <span class="mi">900</span><span class="p">,</span> <span class="mi">400</span><span class="p">,</span> <span class="mi">6100</span><span class="p">,</span> <span class="mi">3000</span><span class="p">,</span> <span class="mi">1000</span><span class="p">],</span> <span class="s1">&#39;npv&#39;</span><span class="o">:</span> <span class="p">[</span><span class="mi">1400</span><span class="p">,</span> <span class="mi">1700</span><span class="p">,</span> <span class="mi">2200</span><span class="p">,</span> <span class="mi">3000</span><span class="p">,</span> <span class="mi">5500</span><span class="p">,</span> <span class="mi">3000</span><span class="p">],</span> <span class="s1">&#39;shade&#39;</span><span class="o">:</span> <span class="p">[</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">],</span> <span class="s1">&#39;cloud&#39;</span><span class="o">:</span> <span class="p">[</span><span class="mi">9000</span><span class="p">,</span> <span class="mi">9600</span><span class="p">,</span> <span class="mi">8000</span><span class="p">,</span> <span class="mi">7800</span><span class="p">,</span> <span class="mi">7200</span><span class="p">,</span> <span class="mi">6500</span><span class="p">],</span> <span class="s1">&#39;cfThreshold&#39;</span><span class="o">:</span> <span class="mf">.05</span><span class="p">,</span> <span class="s1">&#39;forestLabel&#39;</span><span class="o">:</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;minYears&#39;</span><span class="o">:</span> <span class="mi">3</span> <span class="p">})</span> </pre></div> </div> <p>Call the main function of CODED to retrieve the results:</p> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><span class="kd">var</span> <span class="nx">results</span> <span class="o">=</span> <span class="nx">codedUtils</span><span class="p">.</span><span class="nx">submitCODED</span><span class="p">(</span><span class="nx">saveRegion</span><span class="p">,</span> <span class="nx">params</span><span class="p">,</span> <span class="nx">trainingData</span><span class="p">)</span> </pre></div> </div> <p>The output of the change detection is an <a class="reference external" href="https://developers.google.com/earth-engine/arrays_array_images">array image</a>. At every pixel location there is an array matrix, with a row for every year in the study period and the columns corresponding to the a change flag (1 = change, 0 = no change), change magnitude, post-change land cover, NDFI difference band, and a forest flag (1 = forest in training period).</p> <table border="1" class="docutils"> <colgroup> <col width="7%" /> <col width="7%" /> <col width="85%" /> </colgroup> <thead valign="bottom"> <tr class="row-odd"><th class="head">Column</th> <th class="head">Range</th> <th class="head">Description</th> </tr> </thead> <tbody valign="top"> <tr class="row-even"><td>1</td> <td>0-1</td> <td>Change flag with 1 indicating change</td> </tr> <tr class="row-odd"><td>2</td> <td>0-255</td> <td>Change magnitude with higher values representing higher magnitude</td> </tr> <tr class="row-even"><td>3</td> <td>1-#C</td> <td>Post-change land cover corrresponding to label in training data (1 - # of classes)</td> </tr> <tr class="row-odd"><td>4</td> <td>0-255</td> <td>Difference in NDFI expressed as percent NDFI magnitude after disturbance compared to before</td> </tr> <tr class="row-even"><td>5</td> <td>0-1</td> <td>Forest flag with 1 representing forest in training period</td> </tr> </tbody> </table> <p>The data array that CODED returns can not be saved as an output or asset. The array image needs to be projected as a saveable 3-D image (x, y, and band dimensions).</p> <p>First, it helps to define a function to create band names:</p> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><span class="kd">var</span> <span class="nx">makeBands</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">start</span><span class="p">,</span> <span class="nx">end</span><span class="p">,</span> <span class="nx">prefix</span><span class="p">)</span> <span class="p">{</span> <span class="kd">var</span> <span class="nx">bandSeq</span> <span class="o">=</span> <span class="nx">ee</span><span class="p">.</span><span class="nx">List</span><span class="p">.</span><span class="nx">sequence</span><span class="p">(</span><span class="nx">start</span><span class="p">,</span> <span class="nx">end</span><span class="p">)</span> <span class="kd">var</span> <span class="nx">bandList</span> <span class="o">=</span> <span class="nx">bandSeq</span><span class="p">.</span><span class="nx">map</span><span class="p">(</span><span class="kd">function</span><span class="p">(</span><span class="nx">i</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nx">ee</span><span class="p">.</span><span class="nb">String</span><span class="p">(</span><span class="nx">prefix</span><span class="p">).</span><span class="nx">cat</span><span class="p">(</span><span class="nx">ee</span><span class="p">.</span><span class="nb">String</span><span class="p">(</span><span class="nx">i</span><span class="p">).</span><span class="nx">slice</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span><span class="mi">4</span><span class="p">))</span> <span class="p">})</span> <span class="k">return</span> <span class="nx">bandList</span> <span class="p">}</span> </pre></div> </div> <p>Next, use a combination of arraySlice, arrayProject, and arrayFlatten to turn one column of the array image into a 3D image with one band for each year:</p> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><span class="kd">var</span> <span class="nx">makeImage</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">arrayImage</span><span class="p">,</span> <span class="nx">column</span><span class="p">,</span> <span class="nx">bandPrefix</span><span class="p">,</span> <span class="nx">start</span><span class="p">,</span> <span class="nx">end</span><span class="p">)</span> <span class="p">{</span> <span class="kd">var</span> <span class="nx">bandList</span> <span class="o">=</span> <span class="nx">makeBands</span><span class="p">(</span><span class="nx">start</span><span class="p">,</span> <span class="nx">end</span><span class="p">,</span> <span class="nx">bandPrefix</span><span class="p">)</span> <span class="k">return</span> <span class="nx">arrayImage</span><span class="p">.</span><span class="nx">arraySlice</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="nx">ee</span><span class="p">.</span><span class="nb">Number</span><span class="p">(</span><span class="nx">column</span><span class="p">),</span> <span class="nx">ee</span><span class="p">.</span><span class="nb">Number</span><span class="p">(</span><span class="nx">column</span><span class="p">).</span><span class="nx">add</span><span class="p">(</span><span class="mi">1</span><span class="p">))</span> <span class="p">.</span><span class="nx">arrayProject</span><span class="p">([</span><span class="mi">0</span><span class="p">])</span> <span class="p">.</span><span class="nx">arrayFlatten</span><span class="p">([</span><span class="nx">bandList</span><span class="p">])</span> <span class="p">}</span> <span class="kd">var</span> <span class="nx">column</span> <span class="o">=</span> <span class="mi">0</span> <span class="c1">// change flag</span> <span class="kd">var</span> <span class="nx">bandPrefix</span> <span class="o">=</span> <span class="s1">&#39;distFlag_&#39;</span> <span class="c1">// band prefix</span> <span class="kd">var</span> <span class="nx">start</span> <span class="o">=</span> <span class="nx">params</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="s1">&#39;start&#39;</span><span class="p">)</span> <span class="c1">// first year of study period</span> <span class="kd">var</span> <span class="nx">end</span> <span class="o">=</span> <span class="nx">params</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="s1">&#39;end&#39;</span><span class="p">)</span> <span class="c1">// last year of study period</span> <span class="kd">var</span> <span class="nx">distFlagImage</span> <span class="o">=</span> <span class="nx">makeImage</span><span class="p">(</span><span class="nx">results</span><span class="p">,</span> <span class="nx">column</span><span class="p">,</span> <span class="nx">bandPrefix</span><span class="p">,</span> <span class="nx">start</span><span class="p">,</span> <span class="nx">end</span><span class="p">)</span> </pre></div> </div> <p>If you create images of all the outputs the images will contain a lot of bands - likely not all of them are necessary. The dataUtils file contains a function to reduce the bands to 4 times the number of changes specified in the parameter dictionary. The output bands are the date of first change, magnitude of first change, the land cover after the first change, the difference in NDFI from before and after the change, the date of second change, and so on. In the following example the CODED output array is turned into 5 images, and then reduced to a smaller image while keeping all the forest flags and attaching the parameter dictionary to the image attributes.</p> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><span class="kd">var</span> <span class="nx">dataUtils</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;users/bullocke/coded:v0.2/dataUtils&#39;</span><span class="p">)</span> <span class="kd">var</span> <span class="nx">disturbances</span> <span class="o">=</span> <span class="nx">dataUtils</span><span class="p">.</span><span class="nx">makeImage</span><span class="p">(</span><span class="nx">results</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="s1">&#39;dist_&#39;</span><span class="p">,</span> <span class="nx">start</span><span class="p">,</span> <span class="nx">end</span><span class="p">)</span> <span class="kd">var</span> <span class="nx">magnitude</span> <span class="o">=</span> <span class="nx">dataUtils</span><span class="p">.</span><span class="nx">makeImage</span><span class="p">(</span><span class="nx">results</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="s1">&#39;mag_&#39;</span><span class="p">,</span> <span class="nx">start</span><span class="p">,</span> <span class="nx">end</span><span class="p">)</span> <span class="kd">var</span> <span class="nx">postChange</span> <span class="o">=</span> <span class="nx">dataUtils</span><span class="p">.</span><span class="nx">makeImage</span><span class="p">(</span><span class="nx">results</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="s1">&#39;post_&#39;</span><span class="p">,</span> <span class="nx">start</span><span class="p">,</span> <span class="nx">end</span><span class="p">)</span> <span class="kd">var</span> <span class="nx">difference</span> <span class="o">=</span> <span class="nx">dataUtils</span><span class="p">.</span><span class="nx">makeImage</span><span class="p">(</span><span class="nx">results</span><span class="p">,</span> <span class="mi">3</span><span class="p">,</span> <span class="s1">&#39;dif_&#39;</span><span class="p">,</span> <span class="nx">start</span><span class="p">,</span> <span class="nx">end</span><span class="p">)</span> <span class="kd">var</span> <span class="nx">forestFlag</span> <span class="o">=</span> <span class="nx">dataUtils</span><span class="p">.</span><span class="nx">makeImage</span><span class="p">(</span><span class="nx">results</span><span class="p">,</span> <span class="mi">4</span><span class="p">,</span> <span class="s1">&#39;forest_&#39;</span><span class="p">,</span> <span class="nx">start</span><span class="p">,</span> <span class="nx">end</span><span class="p">)</span> <span class="kd">var</span> <span class="nx">disturbanceBands</span> <span class="o">=</span> <span class="nx">disturbances</span><span class="p">.</span><span class="nx">addBands</span><span class="p">([</span><span class="nx">magnitude</span><span class="p">,</span> <span class="nx">postChange</span><span class="p">,</span> <span class="nx">difference</span><span class="p">])</span> <span class="kd">var</span> <span class="nx">saveOutput</span> <span class="o">=</span> <span class="nx">ee</span><span class="p">.</span><span class="nx">Image</span><span class="p">(</span><span class="nx">dataUtils</span><span class="p">.</span><span class="nx">reduceBands</span><span class="p">(</span><span class="nx">ee</span><span class="p">.</span><span class="nx">Image</span><span class="p">(</span><span class="nx">disturbanceBands</span><span class="p">),</span> <span class="nx">params</span><span class="p">)</span> <span class="p">.</span><span class="nx">setMulti</span><span class="p">(</span><span class="nx">params</span><span class="p">))</span> <span class="p">.</span><span class="nx">addBands</span><span class="p">(</span><span class="nx">forestFlag</span><span class="p">)</span> </pre></div> </div> <p>The results can then be submitted as a task:</p> <div class="highlight-javascript notranslate"><div class="highlight"><pre><span></span><span class="nx">Export</span><span class="p">.</span><span class="nx">image</span><span class="p">.</span><span class="nx">toAsset</span><span class="p">({</span> <span class="nx">image</span><span class="o">:</span> <span class="nx">saveOutput</span><span class="p">,</span> <span class="nx">description</span><span class="o">:</span> <span class="s1">&#39;imageDescription&#39;</span><span class="p">,</span> <span class="nx">assetId</span><span class="o">:</span> <span class="s1">&#39;path/imageDescription&#39;</span><span class="p">,</span> <span class="nx">maxPixels</span><span class="o">:</span> <span class="mi">1000000000000</span><span class="p">,</span> <span class="nx">scale</span><span class="o">:</span> <span class="mi">30</span><span class="p">,</span> <span class="nx">region</span><span class="o">:</span> <span class="nx">saveRegion</span><span class="p">.</span><span class="nx">geometry</span><span class="p">(),</span> <span class="p">})</span> </pre></div> </div> </div> </div> </div> <footer> <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation"> <a href="dataFuncs.html" class="btn btn-neutral float-right" title="Utility Functions" accesskey="n" rel="next">Next <span class="fa fa-arrow-circle-right"></span></a> <a href="module_parameters.html" class="btn btn-neutral" title="Parameters" accesskey="p" rel="prev"><span class="fa fa-arrow-circle-left"></span> Previous</a> </div> <hr/> <div role="contentinfo"> <p> &copy; Copyright 2018, Eric Bullock. </p> </div> Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. </footer> </div> </div> </section> </div> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT:'./', VERSION:'0.2', LANGUAGE:'None', COLLAPSE_INDEX:false, FILE_SUFFIX:'.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/javascript" src="_static/js/theme.js"></script> <script type="text/javascript"> jQuery(function () { SphinxRtdTheme.Navigation.enable(true); }); </script> </body> </html>
67.266667
672
0.62405
4962a9a2f44406ee882d7cfe6089ed8e2d0a12a5
433
dart
Dart
lib/src/utils/font.dart
mark8044/flutter-quill
a00b7fead108313ff3bd3f187b4c925abfad735f
[ "MIT" ]
null
null
null
lib/src/utils/font.dart
mark8044/flutter-quill
a00b7fead108313ff3bd3f187b4c925abfad735f
[ "MIT" ]
null
null
null
lib/src/utils/font.dart
mark8044/flutter-quill
a00b7fead108313ff3bd3f187b4c925abfad735f
[ "MIT" ]
null
null
null
dynamic getFontSize(dynamic sizeValue) { if (sizeValue is String && ['small', 'large', 'huge'].contains(sizeValue)) { return sizeValue; } if (sizeValue is double) { return sizeValue; } if (sizeValue is int) { return sizeValue.toDouble(); } assert(sizeValue is String); final fontSize = double.tryParse(sizeValue); if (fontSize == null) { throw 'Invalid size $sizeValue'; } return fontSize; }
20.619048
78
0.655889
daaf342119580101f5704c130794fa0451060e1b
1,461
php
PHP
views/site/search.php
Alexandr211/Funny-cook
7092d28ace0a799e8b46b9bceacc3b875b710534
[ "BSD-3-Clause" ]
null
null
null
views/site/search.php
Alexandr211/Funny-cook
7092d28ace0a799e8b46b9bceacc3b875b710534
[ "BSD-3-Clause" ]
null
null
null
views/site/search.php
Alexandr211/Funny-cook
7092d28ace0a799e8b46b9bceacc3b875b710534
[ "BSD-3-Clause" ]
null
null
null
<?php use yii\widgets\ActiveForm; use yii\helpers\Html; use yii\helpers\ArrayHelper; /* @var $this yii\web\View */ $this->title = 'Поиск в меню'; ?> <div> <?php $form = ActiveForm::begin(); // get all info from status table $ingredients = app\models\Ingredients::find()->all(); // use map ArrayHelper $ingredient = ArrayHelper::map($ingredients,'id','ingredient'); ?> <h2>Пожалуйста выберите не менее 2-х ингредиентов</h2> <div class="row"> <div class="col-xs-5"> <?= $form->field($items, 'ingredient1')->dropDownList($ingredient)->label('Ингредиент1') ?> </div> <div class="col-xs-5"> <?= $form->field($items, 'ingredient2')->dropDownList($ingredient)->label('Ингредиент2') ?> </div> <div class="col-xs-5"> <?= $form->field($items, 'ingredient3')->dropDownList($ingredient)->label('Ингредиент3') ?> </div> <div class="col-xs-5"> <?= $form->field($items, 'ingredient4')->dropDownList($ingredient)->label('Ингредиент4') ?> </div> <div class="col-xs-5"> <?= $form->field($items, 'ingredient5')->dropDownList($ingredient)->label('Ингредиент5') ?> </div> <div class="form-group"> <div class = "col-xs-11" align="left"> <?= Html::submitButton('Найти блюдо', ['class' => 'btn btn-primary']) ?> </div> </div> <?php ActiveForm::end(); ?> </div> </div>
31.085106
97
0.562628
da270e71e4c9bd55256b0c3f74c13a489258093d
6,576
php
PHP
rollpa/pages/cenik.php
glararan/begin
6be674e52e07a1ded02f66ab28a7c2d2b0df515d
[ "MIT" ]
null
null
null
rollpa/pages/cenik.php
glararan/begin
6be674e52e07a1ded02f66ab28a7c2d2b0df515d
[ "MIT" ]
null
null
null
rollpa/pages/cenik.php
glararan/begin
6be674e52e07a1ded02f66ab28a7c2d2b0df515d
[ "MIT" ]
null
null
null
<div class="wrapper cenik"> <div class="container_1"> <div class="largest_box"> <div class="f_left"> <h3>Police Rollpa</h3> <p>Lakované HDF a MDF desky, Barvy: bílá a přírodní (béžová), tapetované + 20%. <span>Cena je bez 21% DPH.</span></p> <table class="box1"> <tr> <td class="nadpis width_32p">Výrobek</td> <td class="nadpis width_45p">Rozměry</td> <td class="nadpis">Cena bez DPH</td> </tr> <tr> <td>Police/ZV</td> <td>30 x 10 cm</td> <td>8 Kč</td> </tr> <tr> <td>Police/ZV</td> <td>30 x 15 cm</td> <td>8 Kč</td> </tr> <tr> <td>Police/ZV</td> <td>30 x 30 cm</td> <td>8 Kč</td> </tr> <tr> <td>Police/ZV</td> <td>37 x 15 cm</td> <td>8 Kč</td> </tr> <tr> <td>Police/ZV</td> <td>37 x 30 cm</td> <td>8 Kč</td> </tr> <tr> <td>Police/ZV</td> <td>45 x 10 cm</td> <td>8 Kč</td> </tr> <tr> <td>Police/ZV</td> <td>45 x 15 cm</td> <td>8 Kč</td> </tr> <tr> <td>Police/ZV</td> <td>45 x 30 cm</td> <td>8 Kč</td> </tr> <tr> <td>Police/ZV</td> <td>60 x 15 cm</td> <td>8 Kč</td> </tr> <tr> <td>Police/ZV</td> <td>60 x 30 cm</td> <td>8 Kč</td> </tr> <tr> <td>Police/ZV</td> <td>60 x 45 cm</td> <td>8 Kč</td> </tr> <tr> <td>Police/ZV</td> <td>60 x 60 cm</td> <td>8 Kč</td> </tr> <tr> <td>Police/ZV</td> <td>atypický rozměr - 1 cm2</td> <td>0,03 Kč</td> </tr> </table> <a href="#" class="button">Prodejní katalogy</a> <a href="#" class="button">Fotografie</a> <a href="#" class="button">Stáhnout ceník</a> </div> <div class="f_right"> <h3>Trubky Rollpa (32/28mm)</h3> <p>Materiál - plast.</p> <table class="box1"> <tr> <td class="nadpis width_53p">Výrobek</td> <td class="nadpis">Cena bez 21% DPH</td> </tr> <tr> <td>Modul M60 cm - 568 mm</td> <td>8 Kč</td> </tr> <tr> <td>Modul M60 cm - 418 mm</td> <td>8 Kč</td> </tr> <tr> <td>Modul M60 cm - 338 mm</td> <td>8 Kč</td> </tr> <tr> <td>Modul M60 cm - 268 mm</td> <td>8 Kč</td> </tr> <tr> <td>Modul M60 cm - 238 mm</td> <td>8 Kč</td> </tr> <tr> <td>Modul M60 cm - 153 mm</td> <td>8 Kč</td> </tr> <tr> <td>Modul M60 cm - 118 mm</td> <td>8 Kč</td> </tr> <tr> <td>Modul M60 cm - 68 mm</td> <td>8 Kč</td> </tr> <tr> <td>Atypický rozměr - 1 cm</td> <td>8 Kč</td> </tr> <tr class="height_10px"><td></td><td></td></tr> <tr> <td class="nadpis">Barva</td> <td></td> </tr> <tr> <td><p>Trubky papírové: pouze výprodej, barvy po dohodě<br>Trubky plastové: černé a bílé,<br>Další barvy: etiketované trubky po dohodě +15%<br>Barva stříbrná - chromová na plastu + 20% k ceně</p></td> <td class="width_1p"></td> </tr> </table> <a href="#" class="button">Prodejní katalogy</a> <a href="#" class="button">Fotografie</a> <a href="#" class="button">Stáhnout ceník</a> </div> <div class="clear"></div> </div> </div> <div class="container_1"> <div class="largest_box"> <div class="f_left"> <h3>Typy spojek a příslušenství</h3> <p>Materiál - plast, barvy - černá a bílá.<br><span>Cena je bez 21% DPH.</span></p> <table class="box2"> <tr> <td class="nadpis width_78p">Výrobek</td> <td class="nadpis">Cena/Ks</td> </tr> <tr> <td>Spojka "L"</td> <td>16,90 Kč</td> </tr> <tr> <td>Spojka "T"</td> <td>16,90 Kč</td> </tr> <tr> <td>Spojka "X"</td> <td>16,90 Kč</td> </tr> <tr> <td>Spojka "3"</td> <td>16,90 Kč</td> </tr> <tr> <td>Spojka "4"</td> <td>16,90 Kč</td> </tr> <tr> <td>Spojka "5"</td> <td>16,90 Kč</td> </tr> <tr> <td>Spojka "6"</td> <td>16,90 Kč</td> </tr> <tr> <td>Zátka "Z"</td> <td>16,90 Kč</td> </tr> <tr> <td>Kolečko "K"</td> <td>16,90 Kč</td> </tr> <tr> <td>Přítlačný kroužek "PK"</td> <td>16,90 Kč</td> </tr> <tr> <td>Držák trubek "DT"</td> <td>16,90 Kč</td> </tr> </table> <a href="#" class="button">Prodejní katalogy</a> <a href="#" class="button">Fotografie</a> <div class="clear"></div> <a href="#" class="button">Stáhnout ceník</a> </div> <div class="f_right"> <h3>Korpusy, zásuvky a příslušenství</h3> <p>Materiály: kufrové a mikrovlnné lepenky.<span>Cena je bez 21% DPH</span></p> <table class="box3"> <tr> <td class="nadpis width_77p">Výrobek</td> <td class="nadpis">Cena bez 21% DPH</td> </tr> <tr> <td>Korpus 37 x 30 x 37 cm se 3 zásuvkami: bílými, přírodními</td> <td>16,90 Kč</td> </tr> <tr> <td>Korpus 37 x 30 x 37 cm se 3 zásuvkami: barevnými</td> <td>238,00 Kč</td> </tr> <tr> <td>Mikrovlnná zásuvka 30 x 30 x 6 cm</td> <td>31,00 Kč</td> </tr> <tr> <td>Police pod zásuvku 30 x 30 cm - přírodní</td> <td>10,00 Kč</td> </tr> <tr> <td>Palubka skládaná PM 30 - šíře 21mm - mikrovlna</td> <td>5,80 Kč</td> </tr> <tr> <td>Palubka skládaná PM 45 - šíře 21mm - mikrovlna</td> <td>9,10 Kč</td> </tr> <tr> <td>Palubka skládaná PM 30 - šíře 32mm - kufrová lepenka</td> <td>11,50 Kč</td> </tr> <tr> <td>Suchý zip 3M - plastový - obě části - 2 x 2,5 cm</td> <td>16,90 Kč</td> </tr> <tr> <td>Suchý zip 3M - textilní - obě části - 2 x 1,5 cm</td> <td>16,90 Kč</td> </tr> </table> <a href="#" class="button">Prodejní katalogy</a> <a href="#" class="button">Fotografie</a> <a href="#" class="button">Stáhnout ceník</a> </div> <div class="clear"></div> </div> </div> </div>
23.740072
207
0.450274
5f36e32e09b4dd69054d4dc98ae1795153d10e26
640
kt
Kotlin
compiler/tests-spec/testData/codegen/box/notLinked/annotations/type-annotations/neg/8.kt
Sathawale27/kotlin
9dd201aaf243cf9198cf129b22d3aa38fcff182c
[ "ECL-2.0", "Apache-2.0" ]
337
2020-05-14T00:40:10.000Z
2022-02-16T23:39:07.000Z
compiler/tests-spec/testData/codegen/box/notLinked/annotations/type-annotations/neg/8.kt
seanwallawalla-forks/kotlin
ed88aa43a4c2990ca10ebcb608dcbe797919b856
[ "ECL-2.0", "Apache-2.0" ]
92
2020-06-10T23:17:42.000Z
2020-09-25T10:50:13.000Z
compiler/tests-spec/testData/codegen/box/notLinked/annotations/type-annotations/neg/8.kt
seanwallawalla-forks/kotlin
ed88aa43a4c2990ca10ebcb608dcbe797919b856
[ "ECL-2.0", "Apache-2.0" ]
44
2020-05-17T10:11:11.000Z
2022-03-11T02:37:20.000Z
/* * KOTLIN CODEGEN BOX NOT LINKED SPEC TEST (NEGATIVE) * * SECTIONS: annotations, type-annotations * NUMBER: 8 * DESCRIPTION: Type annotations on a receiver type (for an extension property only), with unresolved reference in parameters. * ISSUES: KT-28424 */ @Target(AnnotationTarget.TYPE) annotation class Ann(val x: Int) val <T> @Ann(unresolved_reference) T.test // OK, error only in IDE but not in the compiler get() = 10 val @Ann(unresolved_reference) Int.test get() = 10 fun box(): String? { val x = 10.test val y = '.'.test if (x == null) return null if (y == null) return null return "OK" }
22.857143
126
0.671875
0a9ca52effbdc7b41073a831f3243fa7e85cef57
2,522
cshtml
C#
Factory/Views/Locations/Details.cshtml
JeffTerrell/Factory.Solution
6ae58e224e3a1bb369f93b3004a675e93e14ff22
[ "MIT" ]
null
null
null
Factory/Views/Locations/Details.cshtml
JeffTerrell/Factory.Solution
6ae58e224e3a1bb369f93b3004a675e93e14ff22
[ "MIT" ]
null
null
null
Factory/Views/Locations/Details.cshtml
JeffTerrell/Factory.Solution
6ae58e224e3a1bb369f93b3004a675e93e14ff22
[ "MIT" ]
null
null
null
@{ Layout = "_Layout"; } @model Factory.Models.Location <h2>Location Details</h2> <hr/> <h3>@Html.DisplayNameFor(model => model.Name): @Html.DisplayFor(model => model.Name)</h3> @if(@Model.JoinEntitiesMachine.Count == 0) { <p>This location has no machines.</p> <h4>Add a machine to this location:</h4> @using (Html.BeginForm("AddMachine", "Locations")) { @Html.HiddenFor(model => model.LocationId) @Html.Label("") @Html.DropDownList("MachineId") <input type="submit" value="Add Machine"/> } } else { <h4>Machines at this location:</h4> @foreach(var join in Model.JoinEntitiesMachine) { @Html.ActionLink($"{join.Machine.Name}", "Details", "Machines", new { id = join.Machine.MachineId }) @using (Html.BeginForm("DeleteMachine", "Locations")) { @Html.Hidden("joinId", @join.LocationMachineId) <input type="submit" value="Delete Machine"/> } } <br> <h6>Add a machine to this location:</h6> @using (Html.BeginForm("AddMachine", "Locations")) { @Html.HiddenFor(model => model.LocationId) @Html.Label("") @Html.DropDownList("MachineId") <br> <input type="submit" value="Add Machine"/> } } <br> @if(@Model.JoinEntitiesEngineer.Count == 0) { <p>This location has no engineers.</p> <h4>Add an engineer to this location:</h4> @using (Html.BeginForm("AddEngineer", "Locations")) { @Html.HiddenFor(model => model.LocationId) @Html.Label("") @Html.DropDownList("EngineerId") <br> <input type="submit" value="Add Engineer"/> } } else { <h4>Engineers assigned to this location:</h4> @foreach(var join in Model.JoinEntitiesEngineer) { @Html.ActionLink($"{join.Engineer.Name}", "Details", "Engineers", new { id = join.Engineer.EngineerId }) @using (Html.BeginForm("DeleteEngineer", "Locations")) { @Html.Hidden("joinId", @join.EngineerLocationId) <input type="submit" value="Delete Engineer"/> } } <br> <h6>Add an engineer to this location:</h6> @using (Html.BeginForm("AddEngineer", "Locations")) { @Html.HiddenFor(model => model.LocationId) @Html.Label("") @Html.DropDownList("EngineerId") <br> <input type="submit" value="Add Engineer"/> } } <br> <br> <p>@Html.ActionLink("Edit this location", "Edit", new { id = Model.LocationId })</p> <p>@Html.ActionLink("Delete this location", "Delete", new { id = Model.LocationId })</p> <p>@Html.ActionLink("View all locations", "Index")</p> <br> <p>@Html.ActionLink("Home", "Index", "Home")</p>
27.413043
108
0.642744
dbae1da616985f0d2aeb7af2234a9d600b6f7fda
2,084
php
PHP
web/core/modules/block/tests/src/Functional/BlockDemoTest.php
Tuyuyi99/Curso-Drupal
8bac2824ba9ff5a9a6c6ad90fee58671e41bccb5
[ "MIT" ]
4
2021-08-06T16:34:11.000Z
2022-02-12T07:08:16.000Z
web/core/modules/block/tests/src/Functional/BlockDemoTest.php
Tuyuyi99/Curso-Drupal
8bac2824ba9ff5a9a6c6ad90fee58671e41bccb5
[ "MIT" ]
36
2021-02-18T10:54:08.000Z
2022-01-21T00:02:10.000Z
web/core/modules/block/tests/src/Functional/BlockDemoTest.php
Tuyuyi99/Curso-Drupal
8bac2824ba9ff5a9a6c6ad90fee58671e41bccb5
[ "MIT" ]
4
2021-03-13T17:38:24.000Z
2022-03-15T09:43:09.000Z
<?php namespace Drupal\Tests\block\Functional; use Drupal\Tests\BrowserTestBase; /** * Tests the block demo page with admin themes. * * @group block */ class BlockDemoTest extends BrowserTestBase { /** * Modules to enable. * * @var array */ protected static $modules = ['block']; /** * {@inheritdoc} */ protected $defaultTheme = 'classy'; /** * Check for the accessibility of the admin block demo page. */ public function testBlockDemo() { // Create administrative user. $admin_user = $this->drupalCreateUser([ 'administer blocks', 'administer themes', ]); $this->drupalLogin($admin_user); // Confirm we have access to the block demo page for the default theme. $config = $this->container->get('config.factory')->get('system.theme'); $default_theme = $config->get('default'); $this->drupalGet('admin/structure/block/demo/' . $default_theme); $this->assertSession()->statusCodeEquals(200); $this->assertSession()->linkByHrefExists('admin/structure/block'); $this->assertSession()->linkByHrefNotExists('admin/structure/block/list/' . $default_theme); // All available themes in core. $available_themes = [ 'bartik', 'classy', 'seven', 'stark', ]; // All available themes minute minus the default theme. $themes = array_diff($available_themes, [$default_theme]); foreach ($themes as $theme) { // Install theme. $this->container->get('theme_installer')->install([$theme]); // Confirm access to the block demo page for the theme. $this->drupalGet('admin/structure/block/demo/' . $theme); $this->assertSession()->statusCodeEquals(200); // Confirm existence of link for "Exit block region demonstration". $this->assertSession()->linkByHrefExists('admin/structure/block/list/' . $theme); } // Confirm access to the block demo page is denied for an invalid theme. $this->drupalGet('admin/structure/block/demo/invalid_theme'); $this->assertSession()->statusCodeEquals(403); } }
28.944444
96
0.65595
93f7421259134713e61e706b3b5ae0aebbe47773
1,891
cs
C#
Net/Geocoding/StreetMapRoutingSample/CSharp/RoutingSample/DirectionsForm.cs
PrivadoTest/arcobjects-sdk-community-samples
2f83fa35d2818100ab6a93e44306d778665083df
[ "Apache-2.0" ]
111
2016-02-22T12:50:15.000Z
2022-03-31T10:10:19.000Z
Net/Geocoding/StreetMapRoutingSample/CSharp/RoutingSample/DirectionsForm.cs
PrivadoTest/arcobjects-sdk-community-samples
2f83fa35d2818100ab6a93e44306d778665083df
[ "Apache-2.0" ]
14
2016-03-01T12:38:46.000Z
2022-02-02T02:34:04.000Z
Net/Geocoding/StreetMapRoutingSample/CSharp/RoutingSample/DirectionsForm.cs
PrivadoTest/arcobjects-sdk-community-samples
2f83fa35d2818100ab6a93e44306d778665083df
[ "Apache-2.0" ]
201
2016-02-25T10:45:07.000Z
2022-03-25T16:13:15.000Z
/* Copyright 2019 Esri 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. */ using ESRI.ArcGIS.DataSourcesFile; namespace RoutingSample { public partial class DirectionsForm : System.Windows.Forms.Form { #region Windows Form Designer generated code public DirectionsForm() : base() { //This call is required by the Windows Form Designer. InitializeComponent(); } #endregion #region Public methods // Clears Directions text public void Init() { m_txtDirections.Text = ""; } // Fills text box public void Init(ISMDirections objDirections) { int nCount = objDirections.Count; string strText = null; // Totals strText = objDirections.TotalsText + System.Environment.NewLine + System.Environment.NewLine; // Add text for each Direction for (int i = 0; i < nCount; i++) { SMDirItem objItem = null; objItem = objDirections.get_Item(i); // Direction text strText = strText + objItem.Text + System.Environment.NewLine; // Drive text (length, time) if (objItem.DriveText.Length > 0) strText = strText + " " + objItem.DriveText + System.Environment.NewLine; strText = strText + System.Environment.NewLine; } // Set control text m_txtDirections.Text = strText; // deselect if was be selected m_txtDirections.Select(0, 0); } #endregion } } //end of root namespace
22.511905
96
0.699101
2c4b3f14664306c9b3b6cf64782c589c29277366
79
py
Python
indra/assemblers/english/__init__.py
zebulon2/indra
7727ddcab52ad8012eb6592635bfa114e904bd48
[ "BSD-2-Clause" ]
136
2016-02-11T22:06:37.000Z
2022-03-31T17:26:20.000Z
indra/assemblers/english/__init__.py
zebulon2/indra
7727ddcab52ad8012eb6592635bfa114e904bd48
[ "BSD-2-Clause" ]
748
2016-02-03T16:27:56.000Z
2022-03-09T14:27:54.000Z
indra/assemblers/english/__init__.py
zebulon2/indra
7727ddcab52ad8012eb6592635bfa114e904bd48
[ "BSD-2-Clause" ]
56
2015-08-28T14:03:44.000Z
2022-02-04T06:15:55.000Z
from .assembler import EnglishAssembler, AgentWithCoordinates, SentenceBuilder
39.5
78
0.886076
39a400091b6d43abadb42354681abd09ab9c7c0c
241
dart
Dart
lib/src/mock_meal_collection.dart
Italbytz/pub-adapters-meal-mock
7c41a433fb50d9268bb7c0eb6f11fce08886db68
[ "MIT" ]
null
null
null
lib/src/mock_meal_collection.dart
Italbytz/pub-adapters-meal-mock
7c41a433fb50d9268bb7c0eb6f11fce08886db68
[ "MIT" ]
null
null
null
lib/src/mock_meal_collection.dart
Italbytz/pub-adapters-meal-mock
7c41a433fb50d9268bb7c0eb6f11fce08886db68
[ "MIT" ]
null
null
null
import 'package:meal_ports/meal_ports.dart'; class MockMealCollection implements MealCollection { @override MealCategory category; @override List<Meal> meals; MockMealCollection({required this.category, required this.meals}); }
20.083333
68
0.780083
0a6ac59882fee6eb08399cb6ca507ca9127adbb3
412
cs
C#
Snittlistan.Queue/Config/QueueListenersElement.cs
dlidstrom/Snittlistan
8f2ebf5eb4c0d31b718fc6d5409a63518b510583
[ "MIT" ]
1
2020-12-24T07:47:45.000Z
2020-12-24T07:47:45.000Z
Snittlistan.Queue/Config/QueueListenersElement.cs
dlidstrom/Snittlistan
8f2ebf5eb4c0d31b718fc6d5409a63518b510583
[ "MIT" ]
323
2015-01-14T06:51:37.000Z
2022-03-28T04:20:49.000Z
Snittlistan.Queue/Config/QueueListenersElement.cs
dlidstrom/Snittlistan
8f2ebf5eb4c0d31b718fc6d5409a63518b510583
[ "MIT" ]
2
2020-04-08T08:23:06.000Z
2021-04-28T20:27:55.000Z
namespace Snittlistan.Queue.Config { using System.Configuration; public class QueueListenersElement : ConfigurationElement { [ConfigurationProperty("", IsRequired = true, IsDefaultCollection = true)] public QueueListenersCollection Listeners { get => (QueueListenersCollection)this[string.Empty]; set => this[string.Empty] = value; } } }
27.466667
82
0.652913
a46d12c5207464c9d0b11b4b5c65c0f5eac8e396
1,282
php
PHP
resources/views/groupware/zzz.schedule.bak/index.blade.php
IwataYoshifumi/freegroup
e3d20d3644ff0f6f403f44e11e1dee84a265611f
[ "MIT" ]
3
2021-02-28T08:39:47.000Z
2021-09-17T22:46:32.000Z
resources/views/groupware/zzz.schedule.bak/index.blade.php
IwataYoshifumi/freegroup
e3d20d3644ff0f6f403f44e11e1dee84a265611f
[ "MIT" ]
null
null
null
resources/views/groupware/zzz.schedule.bak/index.blade.php
IwataYoshifumi/freegroup
e3d20d3644ff0f6f403f44e11e1dee84a265611f
[ "MIT" ]
1
2021-08-30T11:13:47.000Z
2021-08-30T11:13:47.000Z
@php use App\myHttp\Schedule\Models\Schedule; @endphp@extends('layouts.app') @php use Illuminate\Support\Facades\Session; use Illuminate\Support\Facades\URL; use App\Http\Helpers\MyForm; use App\Http\Helpers\OutputCSV; use App\Models\Customer; #dump( Request::all() ); #dump( session( 'back_button' ) ); @endphp @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-12"> @include( 'groupware.schedule.menu_button' ) <div class="card"> <div class="card-header">{{ config( Route::currentRouteName() ) }}</div> <div class="card-body"> @include( 'layouts.flash_message' ) @include( 'layouts.error' ) <hr> <table> </table> <div class="w-100"></div> @php $inputs = [ 'find' => $find, 'show' => [ 'array' => $show, $find ]]; @endphp {{ OutputCSV::button( [ 'route_name' => 'customer.csv', 'inputs' => $inputs , 'method' => 'GET' ]) }} </div> </div> </div> </div> </div> @php @endphp @endsection
20.349206
121
0.49142
fa8625618391b436b5d3793376c4526443b27842
3,821
cpp
C++
scripts/da_shotgun.cpp
mpforums/RenSharp
5b3fb8bff2a1772a82a4148bcf3e1265a11aa097
[ "Apache-2.0" ]
1
2021-10-04T02:34:33.000Z
2021-10-04T02:34:33.000Z
scripts/da_shotgun.cpp
TheUnstoppable/RenSharp
2a123c6018c18f3fc73501737d600e291ac3afa7
[ "Apache-2.0" ]
9
2019-07-03T19:19:59.000Z
2020-03-02T22:00:21.000Z
scripts/da_shotgun.cpp
TheUnstoppable/RenSharp
2a123c6018c18f3fc73501737d600e291ac3afa7
[ "Apache-2.0" ]
2
2019-08-14T08:37:36.000Z
2020-09-29T06:44:26.000Z
/* Renegade Scripts.dll Dragonade Shotgun Wars Game Mode Copyright 2017 Whitedragon, Tiberian Technologies This file is part of the Renegade scripts.dll The Renegade scripts.dll is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. See the file COPYING for more details. In addition, an exemption is given to allow Run Time Dynamic Linking of this code with any closed source module that does not contain code covered by this licence. Only the source code to the module(s) containing the licenced code has to be released. */ #include "general.h" #include "scripts.h" #include "engine.h" #include "engine_DA.h" #include "da.h" #include "da_shotgun.h" void DAShotgunGameModeClass::Init() { Register_Event(DAEvent::ADDWEAPONREQUEST,INT_MAX); Register_Object_Event(DAObjectEvent::CREATED,DAObjectEvent::POWERUP | DAObjectEvent::BUILDING | DAObjectEvent::ARMED,INT_MAX); WeaponDefinitionClass *Shotgun = (WeaponDefinitionClass*)Find_Named_Definition("Weapon_Shotgun_Player"); WeaponDefinitionClass *Repair = (WeaponDefinitionClass*)Find_Named_Definition("Weapon_RepairGun_Player"); int ShotgunID = Shotgun->Get_ID(); Shotgun->MaxInventoryRounds = -1; int RepairID = Repair->Get_ID(); ArmorType LightArmor = ArmorWarheadManager::Get_Armor_Type("CNCVehicleLight"); for (SoldierGameObjDef *Def = (SoldierGameObjDef*)DefinitionMgrClass::Get_First(CID_Soldier);Def;Def = (SoldierGameObjDef*)DefinitionMgrClass::Get_Next(Def,CID_Soldier)) { Def->WeaponDefID = ShotgunID; Def->SecondaryWeaponDefID = RepairID; Def->WeaponRounds = -1; } for (VehicleGameObjDef *Def = (VehicleGameObjDef*)DefinitionMgrClass::Get_First(CID_Vehicle); Def; Def = (VehicleGameObjDef*)DefinitionMgrClass::Get_Next(Def, CID_Vehicle)) { if (Def->Get_Type() != VehicleType::VEHICLE_TYPE_TURRET) { Def->WeaponDefID = ShotgunID; Def->WeaponRounds = -1; } if (Def->DefenseObjectDef.ShieldType != ArmorType(1)) { Def->DefenseObjectDef.ShieldType = LightArmor; Def->DefenseObjectDef.Skin = LightArmor; } } } bool DAShotgunGameModeClass::Add_Weapon_Request_Event(cPlayer *Player,const WeaponDefinitionClass *Weapon) { if (_stricmp(Weapon->Get_Name(),"Weapon_Shotgun_Player") && _stricmp(Weapon->Get_Name(), "Weapon_RepairGun_Player")) { return false; } return true; } void DAShotgunGameModeClass::Object_Created_Event(GameObject *obj) { if (BuildingGameObj *Building = obj->As_BuildingGameObj()) { Building->Get_Defense_Object()->Set_Skin(ArmorWarheadManager::Get_Armor_Type("CNCVehicleMedium")); Building->Get_Defense_Object()->Set_Shield_Type(ArmorWarheadManager::Get_Armor_Type("CNCVehicleMedium")); const_cast<BuildingGameObjDef&>(Building->Get_Definition()).MCTSkin = ArmorWarheadManager::Get_Armor_Type("CNCVehicleLight"); } else if (VehicleGameObj *Vehicle = obj->As_VehicleGameObj()) { if (!_stricmp(Vehicle->Get_Weapon()->Get_Name(),"Weapon_Shotgun_Player")) { Update_Network_Object(Vehicle); Set_Position_Clip_Bullets(Vehicle,1,-1); } if (Vehicle->Get_Defense_Object()->Get_Shield_Type() != ArmorType(1)) { ArmorType LightArmor = ArmorWarheadManager::Get_Armor_Type("CNCVehicleLight"); Vehicle->Get_Defense_Object()->Set_Shield_Type(LightArmor); Vehicle->Get_Defense_Object()->Set_Skin(LightArmor); } } else if (SoldierGameObj *Soldier = obj->As_SoldierGameObj()) { if (Soldier->Get_Player()) { Update_Network_Object(Soldier->Get_Player()); } Update_Network_Object(Soldier); Set_Position_Clip_Bullets(Soldier,1,-1); } else if (((PowerUpGameObj*)obj)->Get_Definition().GrantWeapon) { obj->Set_Delete_Pending(); } } Register_Game_Mode(DAShotgunGameModeClass,"Shotgun","Shotgun Wars",0);
44.430233
175
0.772311
b0cf59f8df67638136293bd56b10563540f27d00
28,663
py
Python
main.py
kawinm/time-table-management-system
9eb4b635fac1848c024e11636c5bf59de271d0cb
[ "MIT" ]
4
2018-06-06T06:02:53.000Z
2019-12-17T04:58:17.000Z
main.py
kawinm/time-table-management-system
9eb4b635fac1848c024e11636c5bf59de271d0cb
[ "MIT" ]
null
null
null
main.py
kawinm/time-table-management-system
9eb4b635fac1848c024e11636c5bf59de271d0cb
[ "MIT" ]
null
null
null
"""Imports""" #++++++++++++++++++++++++++++++++++++++++++++ from datetime import datetime from tkinter import * import tkinter.ttk,tkinter.messagebox,tkinter.font,os from prettytable import PrettyTable #++++++++++++++++++++++++++++++++++++++++++++ #++++++++++++++++++++++++++++++++++++++++++++ """Creating the window, menubar and title""" class EventApp(): def __init__(self): #Creating instance self.root=Tk() self.root.title("Time Schedule") self.messagebox=tkinter.messagebox self.ttk=tkinter.ttk #Using prettytable to create the tables for timetable headerFormat = ["Period","1","2","3","4","5","6","7"] self.mains=PrettyTable(headerFormat) self.main1=PrettyTable(headerFormat) self.main2=PrettyTable(headerFormat) self.main3=PrettyTable(headerFormat) self.main4=PrettyTable(headerFormat) self.main5=PrettyTable(headerFormat) self.customFont = tkinter.font.Font(family="Helvetica", size=12) #initializing functions self.root.resizable(0,0) self.createMenu() self.MainTabs() self.TabContent() self.retrieveTab() self.deleteEvent() #++++++++++++++++++++++++++++++++++++++++++ #================================================================== #creating the menu bar def createMenu(self): self.menuBar=Menu(self.root) self.root.configure(menu= self.menuBar) ## self.FileMenu = Menu(self.menuBar,tearoff=0) self.FileMenu.add_command(label="New") self.FileMenu.add_command(label="Exit", command=self.root.destroy) self.HelpMenu= Menu(self.menuBar,tearoff=0) self.HelpMenu.add_command(label="About", command=self._msgBox) self.menuBar.add_cascade(label="File", menu=self.FileMenu) self.menuBar.add_cascade(label="Help", menu=self.HelpMenu) def _msgBox(self): self.messagebox.showinfo('About the App','This App is designed to create a schedule for the days of the week and the time with an hour between between the times.The schedule can be accessed by the days of the week') #===================================================================== #creating the tabs def MainTabs(self): """Adding tabs to make navigation easy""" self.AddingEventTab=tkinter.ttk.Notebook(self.root) self.tab1= tkinter.ttk.Frame(self.AddingEventTab) self.tab2= tkinter.ttk.Frame(self.AddingEventTab) self.tab3= tkinter.ttk.Frame(self.AddingEventTab) self.AddingEventTab.add(self.tab1, text="ADD TABLE") self.AddingEventTab.add(self.tab2, text="VIEW TABLE") self.AddingEventTab.add(self.tab3, text="DELETE TABLE") self.AddingEventTab.pack(expand=5,pady=7, fill="both") #********************************************************************************************************** """Adding content to the 'Add event tab'""" def TabContent(self): #first choosing day root1= tkinter.ttk.LabelFrame(self.tab1, text="Add TABLE") root1.grid(column=0, row=0,padx=8,pady=4,sticky="W") Day=tkinter.ttk.Label(root1, text="Please Choose the Department:").grid(column=0,row=0,sticky='W') self.dept=StringVar() self.year=StringVar() #Monday values self.ttval11=StringVar() self.ttval12=StringVar() self.ttval13=StringVar() self.ttval14=StringVar() self.ttval15=StringVar() self.ttval16=StringVar() self.ttval17=StringVar() #Tuesday values self.ttval21=StringVar() self.ttval22=StringVar() self.ttval23=StringVar() self.ttval24=StringVar() self.ttval25=StringVar() self.ttval26=StringVar() self.ttval27=StringVar() #Wednesday values self.ttval31=StringVar() self.ttval32=StringVar() self.ttval33=StringVar() self.ttval34=StringVar() self.ttval35=StringVar() self.ttval36=StringVar() self.ttval37=StringVar() #Thursday values self.ttval41=StringVar() self.ttval42=StringVar() self.ttval43=StringVar() self.ttval44=StringVar() self.ttval45=StringVar() self.ttval46=StringVar() self.ttval47=StringVar() #Friday values self.ttval51=StringVar() self.ttval52=StringVar() self.ttval53=StringVar() self.ttval54=StringVar() self.ttval55=StringVar() self.ttval56=StringVar() self.ttval57=StringVar() option1=self.ttk.Combobox(root1, width=20, textvariable=self.dept,state="readonly") option1['values']=("CSE","EEE","MECH","CIVIL","ECE") option1.grid(column=0,row=1,sticky='W') option1.current(0) #************************************************************************************************************** ###choosing start time Time=tkinter.ttk.Label(root1, text="Please Choose the Year").grid(column=0,row=2,sticky='W') startTime=tkinter.ttk.Label(root1, text="Year").grid(column=0,row=3,sticky='W') ###Drop down days of the week Timedrop=tkinter.ttk.Combobox(root1, width=20, textvariable=self.year,state="readonly") Timedrop['values']=("I","II","III","IV") Timedrop.grid(column=0,row=4,sticky='W') Timedrop.current(0) tkinter.ttk.Label(root1,text="Please enter the table").grid(column=0,row=6,pady=10,sticky='W') tkinter.ttk.Label(root1,text="Period").grid(column=0,row=7,sticky='W') tkinter.ttk.Label(root1,text="1").grid(column=1,row=7,sticky='W') tkinter.ttk.Label(root1,text="2").grid(column=2,row=7,sticky='W') tkinter.ttk.Label(root1,text="3").grid(column=3,row=7,sticky='W') tkinter.ttk.Label(root1,text="4").grid(column=4,row=7,sticky='W') tkinter.ttk.Label(root1,text="5").grid(column=5,row=7,sticky='W') tkinter.ttk.Label(root1,text="6").grid(column=6,row=7,sticky='W') tkinter.ttk.Label(root1,text="7").grid(column=7,row=7,sticky='W') #------------------------ Monday Entry ------------------------- tkinter.ttk.Label(root1,text="Monday").grid(column=0,row=8,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval11) self.Agenda.grid(column=1,row=8,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval12) self.Agenda.grid(column=2,row=8,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval13) self.Agenda.grid(column=3,row=8,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval14) self.Agenda.grid(column=4,row=8,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval15) self.Agenda.grid(column=5,row=8,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval16) self.Agenda.grid(column=6,row=8,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval17) self.Agenda.grid(column=7,row=8,sticky='W') #------------------------ Tuesday Entry ------------------------- tkinter.ttk.Label(root1,text="Tuesday").grid(column=0,row=9,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval21) self.Agenda.grid(column=1,row=9,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval22) self.Agenda.grid(column=2,row=9,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval23) self.Agenda.grid(column=3,row=9,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval24) self.Agenda.grid(column=4,row=9,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval25) self.Agenda.grid(column=5,row=9,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval26) self.Agenda.grid(column=6,row=9,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval27) self.Agenda.grid(column=7,row=9,sticky='W') #------------------------ Wednesday Entry ------------------------- tkinter.ttk.Label(root1,text="Wednesday").grid(column=0,row=10,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval31) self.Agenda.grid(column=1,row=10,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval32) self.Agenda.grid(column=2,row=10,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval33) self.Agenda.grid(column=3,row=10,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval34) self.Agenda.grid(column=4,row=10,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval35) self.Agenda.grid(column=5,row=10,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval36) self.Agenda.grid(column=6,row=10,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval37) self.Agenda.grid(column=7,row=10,sticky='W') #------------------------ Thursday Entry ------------------------- tkinter.ttk.Label(root1,text="Thursday").grid(column=0,row=11,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval41) self.Agenda.grid(column=1,row=11,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval42) self.Agenda.grid(column=2,row=11,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval43) self.Agenda.grid(column=3,row=11,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval44) self.Agenda.grid(column=4,row=11,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval45) self.Agenda.grid(column=5,row=11,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval46) self.Agenda.grid(column=6,row=11,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval47) self.Agenda.grid(column=7,row=11,sticky='W') #------------------------ Friday Entry ------------------------- tkinter.ttk.Label(root1,text="Friday").grid(column=0,row=12,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval51) self.Agenda.grid(column=1,row=12,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval52) self.Agenda.grid(column=2,row=12,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval53) self.Agenda.grid(column=3,row=12,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval54) self.Agenda.grid(column=4,row=12,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval55) self.Agenda.grid(column=5,row=12,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval56) self.Agenda.grid(column=6,row=12,sticky='W') self.Agenda=tkinter.ttk.Entry(root1,width=10,textvariable=self.ttval57) self.Agenda.grid(column=7,row=12,sticky='W') def viewPrint(): showbiz2.delete(1.0,END) self.messagebox.showinfo("View","The View button shows all the Events") if os.stat("text.txt").st_size==0: showbiz2.insert(INSERT,"No Event Found") else: with open ("text.txt","r")as file_new: contents=file_new.read() showbiz2.insert(INSERT,contents) showbiz2.see(INSERT) def clean(): showbiz2.delete(1.0,END) self.messagebox.showinfo("Clear","Please note that the clear button only cleans the display field but not the schedule. Please use 'DELETE EVENT' to delete any event") creat=Button(self.tab1,text="CREATE ",bg='#4d79ff',fg='white',font=("Helvetica",14),command=self.addElement).grid(column=0,ipadx=62,pady=5,row=10,sticky="W") view=Button(self.tab1, text="All Event",bg='#ff5050',fg='white',font=("Helvetica",14),command=viewPrint).grid(column=0,ipadx=70,row=11,pady=5,sticky="W") clear=Button(self.tab1,text="CLEAR ",bg='#ffc34d',fg='white',font=("Helvetica",14),command=clean).grid(column=0,ipadx=66,row=12,pady=5,sticky="W") def addElement(self): def allEvent(): self.messagebox.showinfo("Created","Event Created") self.Agenda.delete(0,'end') self.main1.add_row(["Monday",self.ttval11.get(),self.ttval12.get(),self.ttval13.get(),self.ttval14.get(),self.ttval15.get(),self.ttval16.get(),self.ttval17.get()]) self.main1.add_row(["Tuesday",self.ttval21.get(),self.ttval22.get(),self.ttval23.get(),self.ttval24.get(),self.ttval25.get(),self.ttval26.get(),self.ttval27.get()]) self.main1.add_row(["Wednesday",self.ttval31.get(),self.ttval32.get(),self.ttval33.get(),self.ttval34.get(),self.ttval35.get(),self.ttval36.get(),self.ttval37.get()]) self.main1.add_row(["Thursday",self.ttval41.get(),self.ttval42.get(),self.ttval43.get(),self.ttval44.get(),self.ttval45.get(),self.ttval46.get(),self.ttval47.get()]) self.main1.add_row(["Friday",self.ttval51.get(),self.ttval52.get(),self.ttval53.get(),self.ttval54.get(),self.ttval55.get(),self.ttval56.get(),self.ttval57.get()]) file_new=open("text.txt","a") file_new.write(str("Department: " + self.dept.get()+'\t'+"Year: " + self.year.get()+'\n')) if self.dept.get()=="CSE": file_new.write(str(self.main1)+'\n') elif self.dept.get()=="EEE": file_new.write(str(self.main2)+'\n') elif self.dept.get()=="MECH": file_new.write(str(self.main3)+'\n') elif self.dept.get()=="CIVIL": file_new.write(str(self.main4)+'\n') elif self.dept.get()=="ECE": file_new.write(str(self.main5)+'\n') file_new.close() def cse(): self.main1.add_row(["Monday",self.ttval11.get(),self.ttval12.get(),self.ttval13.get(),self.ttval14.get(),self.ttval15.get(),self.ttval16.get(),self.ttval17.get()]) self.main1.add_row(["Tuesday",self.ttval21.get(),self.ttval22.get(),self.ttval23.get(),self.ttval24.get(),self.ttval25.get(),self.ttval26.get(),self.ttval27.get()]) self.main1.add_row(["Wednesday",self.ttval31.get(),self.ttval32.get(),self.ttval33.get(),self.ttval34.get(),self.ttval35.get(),self.ttval36.get(),self.ttval37.get()]) self.main1.add_row(["Thursday",self.ttval41.get(),self.ttval42.get(),self.ttval43.get(),self.ttval44.get(),self.ttval45.get(),self.ttval46.get(),self.ttval47.get()]) self.main1.add_row(["Friday",self.ttval51.get(),self.ttval52.get(),self.ttval53.get(),self.ttval54.get(),self.ttval55.get(),self.ttval56.get(),self.ttval57.get()]) file_new=open("cse.txt","a") file_new.write(str('\n'+self.year.get()+'\n')) file_new.write(str(self.main1)) file_new.close() allEvent() def eee(): self.main2.add_row(["Monday",self.ttval11.get(),self.ttval12.get(),self.ttval13.get(),self.ttval14.get(),self.ttval15.get(),self.ttval16.get(),self.ttval17.get()]) self.main2.add_row(["Tuesday",self.ttval21.get(),self.ttval22.get(),self.ttval23.get(),self.ttval24.get(),self.ttval25.get(),self.ttval26.get(),self.ttval27.get()]) self.main2.add_row(["Wednesday",self.ttval31.get(),self.ttval32.get(),self.ttval33.get(),self.ttval34.get(),self.ttval35.get(),self.ttval36.get(),self.ttval37.get()]) self.main2.add_row(["Thursday",self.ttval41.get(),self.ttval42.get(),self.ttval43.get(),self.ttval44.get(),self.ttval45.get(),self.ttval46.get(),self.ttval47.get()]) self.main2.add_row(["Friday",self.ttval51.get(),self.ttval52.get(),self.ttval53.get(),self.ttval54.get(),self.ttval55.get(),self.ttval56.get(),self.ttval57.get()]) file_new=open("eee.txt","w") file_new.write(str('\n'+self.year.get()+'\n')) file_new.write(str(self.main2)) file_new.close() allEvent() def mech(): self.main3.add_row(["Monday",self.ttval11.get(),self.ttval12.get(),self.ttval13.get(),self.ttval14.get(),self.ttval15.get(),self.ttval16.get(),self.ttval17.get()]) self.main3.add_row(["Tuesday",self.ttval21.get(),self.ttval22.get(),self.ttval23.get(),self.ttval24.get(),self.ttval25.get(),self.ttval26.get(),self.ttval27.get()]) self.main3.add_row(["Wednesday",self.ttval31.get(),self.ttval32.get(),self.ttval33.get(),self.ttval34.get(),self.ttval35.get(),self.ttval36.get(),self.ttval37.get()]) self.main3.add_row(["Thursday",self.ttval41.get(),self.ttval42.get(),self.ttval43.get(),self.ttval44.get(),self.ttval45.get(),self.ttval46.get(),self.ttval47.get()]) self.main3.add_row(["Friday",self.ttval51.get(),self.ttval52.get(),self.ttval53.get(),self.ttval54.get(),self.ttval55.get(),self.ttval56.get(),self.ttval57.get()]) file_new=open("mech.txt","w") file_new.write(str('\n'+self.year.get()+'\n')) file_new.write(str(self.main3)) file_new.close() allEvent() def civil(): self.main4.add_row(["Monday",self.ttval11.get(),self.ttval12.get(),self.ttval13.get(),self.ttval14.get(),self.ttval15.get(),self.ttval16.get(),self.ttval17.get()]) self.main4.add_row(["Tuesday",self.ttval21.get(),self.ttval22.get(),self.ttval23.get(),self.ttval24.get(),self.ttval25.get(),self.ttval26.get(),self.ttval27.get()]) self.main4.add_row(["Wednesday",self.ttval31.get(),self.ttval32.get(),self.ttval33.get(),self.ttval34.get(),self.ttval35.get(),self.ttval36.get(),self.ttval37.get()]) self.main4.add_row(["Thursday",self.ttval41.get(),self.ttval42.get(),self.ttval43.get(),self.ttval44.get(),self.ttval45.get(),self.ttval46.get(),self.ttval47.get()]) self.main4.add_row(["Friday",self.ttval51.get(),self.ttval52.get(),self.ttval53.get(),self.ttval54.get(),self.ttval55.get(),self.ttval56.get(),self.ttval57.get()]) file_new=open("civil.txt","w") file_new.write(str('\n'+self.year.get()+'\n')) file_new.write(str(self.main4)) file_new.close() allEvent() def ece(): self.main5.add_row(["Monday",self.ttval11.get(),self.ttval12.get(),self.ttval13.get(),self.ttval14.get(),self.ttval15.get(),self.ttval16.get(),self.ttval17.get()]) self.main5.add_row(["Tuesday",self.ttval21.get(),self.ttval22.get(),self.ttval23.get(),self.ttval24.get(),self.ttval25.get(),self.ttval26.get(),self.ttval27.get()]) self.main5.add_row(["Wednesday",self.ttval31.get(),self.ttval32.get(),self.ttval33.get(),self.ttval34.get(),self.ttval35.get(),self.ttval36.get(),self.ttval37.get()]) self.main5.add_row(["Thursday",self.ttval41.get(),self.ttval42.get(),self.ttval43.get(),self.ttval44.get(),self.ttval45.get(),self.ttval46.get(),self.ttval47.get()]) self.main5.add_row(["Friday",self.ttval51.get(),self.ttval52.get(),self.ttval53.get(),self.ttval54.get(),self.ttval55.get(),self.ttval56.get(),self.ttval57.get()]) file_new=open("ece.txt","w") file_new.write(str('\n'+self.year.get()+'\n')) file_new.write(str(self.main5)) file_new.close() allEvent() if self.dept.get()=="CSE": cse() elif self.dept.get()=="EEE": eee() elif self.dept.get()=="MECH": mech() elif self.dept.get()=="CIVIL": civil() elif self.dept.get()=="ECE": ece() #************************************************************************************************************************ """Retrieving the Table""" def retrieveTab(self): root2=tkinter.ttk.LabelFrame(self.tab2, text="Retrieve") greetings=tkinter.ttk.Label(self.tab2,text="Please click on the department and year you want to retrieve",font=self.customFont) greetings.grid(column=0,row=0,pady=5) self.yearet=StringVar() def printAllEvent(): showbiz.delete(1.0,END) file_new=open("text.txt",'a') if os.stat("text.txt").st_size == 0: showbiz.insert(INSERT,"Sorry, No Event Found") else: with open ("text.txt","a")as file_new: file_new=open("text.txt") contents=file_new.read() showbiz.insert(INSERT,contents) showbiz.see(INSERT) def printCse(): showbiz.delete(1.0,END) file_new=open("cse.txt","a") if os.stat("cse.txt").st_size == 0: showbiz.insert(INSERT,"Sorry, CSE is Empty") else: with open ("cse.txt","a")as file_new: file_new=open("cse.txt") contents=file_new.read() showbiz.insert(INSERT,contents) showbiz.see(INSERT) def printEee(): showbiz.delete(1.0,END) file_new=open("eee.txt","a") if os.stat("eee.txt").st_size == 0: showbiz.insert(INSERT,"Sorry, EEE is Empty") else: with open ("eee.txt","a")as file_new: file_new=open("eee.txt") contents=file_new.read() showbiz.insert(INSERT,contents) showbiz.see(INSERT) def printMech(): showbiz.delete(1.0,END) file_new=open("mech.txt",'a') if os.stat("mech.txt").st_size == 0: showbiz.insert(INSERT,"Sorry, MECH is Empty") else: with open ("mech.txt","a")as file_new: file_new=open("mech.txt") contents=file_new.read() showbiz.insert(INSERT,contents) showbiz.see(INSERT) def printCivil(): showbiz.delete(1.0,END) file_new=open("civil.txt",'a') if os.stat("civil.txt").st_size == 0: showbiz.insert(INSERT,"Sorry, CIVIL is Empty") else: with open ("civil.txt","a")as file_new: file_new=open("civil.txt") contents=file_new.read() showbiz.insert(INSERT,contents) showbiz.see(INSERT) def printEce(): showbiz.delete(1.0,END) file_new=open("ece.txt",'a') if os.stat("ece.txt").st_size == 0: showbiz.insert(INSERT,"Sorry, ECE is Empty") else: with open ("ece.txt","a")as file_new: file_new=open("ece.txt") contents=file_new.read() showbiz.insert(INSERT,contents) showbiz.see(INSERT) cse=Button(self.tab2, text="CSE",bg="blue2",fg="white",font=("Helvetica",14),command=printCse).grid(column=0,row=2,ipadx=10,pady=5) cseyear=tkinter.ttk.Combobox(self.tab2, width=20, textvariable=self.yearet,state="readonly") cseyear['values']=("I","II","III","IV") cseyear.grid(column=1,row=2) cseyear.current(0) eee=Button(self.tab2, text="EEE",bg="#ff5050",fg="white",font=("Helvetica",14),command=printEee).grid(column=0,row=3,ipadx=10,pady=5) eeeyear=tkinter.ttk.Combobox(self.tab2, width=20, textvariable=self.yearet,state="readonly") eeeyear['values']=("I","II","III","IV") eeeyear.grid(column=1,row=3) eeeyear.current(0) mech=Button(self.tab2, text="MECH",bg="#ffc34d",fg="white",font=("Helvetica",14),command=printMech).grid(column=0,row=4,pady=5) mechyear=tkinter.ttk.Combobox(self.tab2, width=20, textvariable=self.yearet,state="readonly") mechyear['values']=("I","II","III","IV") mechyear.grid(column=1,row=4,sticky='W') mechyear.current(0) civil=Button(self.tab2, text="CIVIL",bg="#4d79ff",fg="white",font=("Helvetica",14),command=printCivil).grid(column=0,row=5,ipadx=10,pady=5) civilyear=tkinter.ttk.Combobox(self.tab2, width=20, textvariable=self.yearet,state="readonly") civilyear['values']=("I","II","III","IV") civilyear.grid(column=1,row=5,sticky='W') civilyear.current(0) ece=Button(self.tab2, text="ECE",bg="#009900",fg="white",font=("Helvetica",14),command=printEce).grid(column=0,row=6,pady=5,ipadx=24) eceyear=tkinter.ttk.Combobox(self.tab2, width=20, textvariable=self.yearet,state="readonly") eceyear['values']=("I","II","III","IV") eceyear.grid(column=1,row=6,sticky='W') eceyear.current(0) showbiz=Text(self.tab2,width=97,height=22) showbiz.grid(columnspan=3) allEvent=Button(self.tab2, text="All Events",bg="orange",fg="white",font=("Helvetica",14),command=printAllEvent).grid(column=1,row=7,ipadx=8,pady=5) #*********************************************************************************************************************** def deleteEvent(self): def deleteCse(): result=self.messagebox.askyesno("delete","Are you sure you want to delete CSE timetable ?") if result is True: file_new=open("cse.txt","w").close() self.messagebox.showinfo("Deleted","CSE timetable Deleted") def deleteEee(): result=self.messagebox.askyesno("delete","Are you sure you want to delete CSE timetable ?") if result is True: file_new=open("eee.txt","w").close() self.messagebox.showinfo("Deleted","EEE timetable Deleted") def deleteMech(): result=self.messagebox.askyesno("delete","Are you sure you want to delete CSE timetable ?") if result is True: file_new=open("mech.txt","w").close() tkMessageBox.showinfo("Deleted","MECH timetable Deleted") def deleteCivil(): result=tkMessageBox.askyesno("delete","Are you sure you want to delete CSE timetable ?") if result is True: file_new=open("civil.txt","w").close() tkMessageBox.showinfo("Deleted","CIVIL timetable Deleted") def deleteEce(): result=tkMessageBox.askyesno("delete","Are you sure you want to delete CSE timetable ?") if result is True: file_new=open("ece.txt","w").close() tkMessageBox.showinfo("Deleted","ECE timetable Deleted") def deleteAllEvent(): result=tkMessageBox.askyesno("delete","Are you sure you want to delete All Time table?") files = ["text.txt", "cse.txt", "eee.txt", "ece.txt","mech.txt","civil.txt" ] if result is True: for file_name in files: file_new=open(file_name,"w").close() tkMessageBox.showinfo("Deleted","All timetable Deleted") monday=Button(self.tab3, text="Delete CSE",bg='#4d79ff',fg='white',font=("Helvetica",14),command=deleteCse).pack(fill=X,padx=100,ipady=10,pady=10) tuesday=Button(self.tab3, text="Delete EEE",bg='#ff5050',fg='white',font=("Helvetica",14),command=deleteEee).pack(fill=X,padx=100,ipady=10,pady=10) wednesday=Button(self.tab3, text="Delete MECH",bg='#ffc34d',fg='white',font=("Helvetica",14),command=deleteMech).pack(fill=X,padx=100,ipady=10,pady=10) thursday=Button(self.tab3, text="Delete CIVIL",bg='#4d79ff',fg='white',font=("Helvetica",14),command=deleteCivil).pack(fill=X,padx=100,ipady=10,pady=10) friday=Button(self.tab3, text="Delete ECE",bg='#009900',fg='white',font=("Helvetica",14),command=deleteEce).pack(fill=X,padx=100,ipady=10,pady=10) allEvent=Button(self.tab3, text="Delete all Time table",bg='orange',fg='white',font=("Helvetica",14),command=deleteAllEvent).pack(fill=X,padx=100,ipady=10,pady=10) app= EventApp() app.root.mainloop()
57.440882
223
0.601333
38d2cede91744e4c56fa3462345adf653fce24ed
661
php
PHP
resources/views/admin/layouts/partial/topbar.blade.php
ahmadmirlan/sion-laravel
f017f3b1e825a77b989c5a40ea89a7f554bacd9e
[ "MIT" ]
null
null
null
resources/views/admin/layouts/partial/topbar.blade.php
ahmadmirlan/sion-laravel
f017f3b1e825a77b989c5a40ea89a7f554bacd9e
[ "MIT" ]
null
null
null
resources/views/admin/layouts/partial/topbar.blade.php
ahmadmirlan/sion-laravel
f017f3b1e825a77b989c5a40ea89a7f554bacd9e
[ "MIT" ]
null
null
null
<!-- Topbar --> <header class="topbar"> <div class="topbar-left"> <span class="topbar-btn sidebar-toggler"><i>&#9776;</i></span> </div> <div class="topbar-right"> <ul class="topbar-btns"> <li class="dropdown"> <span class="topbar-btn" data-toggle="dropdown"><img class="avatar" src="/assets/img/avatar/1.jpg" alt="..."></span> <div class="dropdown-menu dropdown-menu-right"> <a class="dropdown-item" href="{{route('admin.logout')}}"><i class="ti-power-off"></i> Logout</a> </div> </li> </ul> </div> </header> <!-- END Topbar -->
36.722222
132
0.514372
20b015ca2ec71f522ae39dc4b9569a815437dcb8
4,701
cshtml
C#
BugPoint.Solution/BugPoint.Application/Views/MyAccount/Changepassword.cshtml
saineshwar/Bugpoint
eaff316d840fe70efbc39ca5bb93baab9092f191
[ "MIT" ]
28
2021-12-13T05:16:04.000Z
2022-02-14T08:14:57.000Z
BugPoint.Solution/BugPoint.Application/Views/MyAccount/Changepassword.cshtml
kritulrathod/Bugpoint
5098be1d78b27b5c43142e88de6bb794736d3663
[ "MIT" ]
null
null
null
BugPoint.Solution/BugPoint.Application/Views/MyAccount/Changepassword.cshtml
kritulrathod/Bugpoint
5098be1d78b27b5c43142e88de6bb794736d3663
[ "MIT" ]
12
2021-12-13T05:43:14.000Z
2022-03-17T10:17:13.000Z
@model BugPoint.ViewModel.Login.ChangePasswordViewModel @{ ViewBag.PageName = "Authentication"; } <form autocomplete="off" asp-controller="MyAccount" asp-antiforgery="true" id="frmchangepassword" asp-action="Changepassword" method="post"> <div class="col-md-3"> <div class="card card-cyan card-outline"> <div class="card-header"> <h3 class="card-title">Change Password</h3> </div> <!-- /.card-header --> <!-- form start --> <div class="card-body"> <div class="text-danger" asp-validation-summary="ModelOnly"></div> <div class="form-group"> <label class="mandatory" asp-for="OldPassword"></label> <input asp-for="OldPassword" maxlength="64" placeholder="Enter Old Password" type="password" class="form-control" /> <span class="text-danger" asp-validation-for="OldPassword"></span> </div> <div class="form-group"> <label class="mandatory" asp-for="NewPassword"></label> <input asp-for="NewPassword" maxlength="64" placeholder="Enter New Password" type="password" class="form-control" /> <span class="text-danger" asp-validation-for="NewPassword"></span> </div> <div class="form-group"> <label class="mandatory" asp-for="ConfirmPassword"></label> <input asp-for="ConfirmPassword" maxlength="64" placeholder="Enter Confirm Password" type="password" class="form-control" /> <span class="text-danger" asp-validation-for="ConfirmPassword"></span> </div> </div> <div class="card-footer"> <button type="button" id="btnsubmit" class="btn btn-success">Update Password</button> <a asp-area="" class="btn btn-danger" asp-controller="MyAccount" asp-action="Changepassword">Clear</a> </div> </div> </div> </form> <script src="~/scripts/sha256.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#btnsubmit").click(function () { var oldPassword = $('#OldPassword').val(); var newPassword = $('#NewPassword').val(); var confirmPassword = $('#ConfirmPassword').val(); if (oldPassword == '') { $.alert("Please Enter Old Password"); $('#OldPassword').focus(); } else if (newPassword == '') { $.alert("Please Enter New Password"); $('#NewPassword').focus(); } else if (confirmPassword == '') { $.alert("Please Enter Confirm Password"); $('#ConfirmPassword').focus(); } else if (validatePassword($('#NewPassword').val()) == false) { $.alert('New Password Must Have Minimum 7 characters at least 1 Alphabet, 1 Number and 1 Special Character !'); return false; } else if (newPassword != confirmPassword) { $.alert("Please Enter Valid Confirm Password"); $('#ConfirmPassword').focus(); } else { var oldPasswordhash = Sha256.hash(oldPassword, false); $('#OldPassword').val(oldPasswordhash); var newPasswordhash = Sha256.hash(newPassword, false); $('#NewPassword').val(newPasswordhash); var confirmPasswordhash = Sha256.hash(confirmPassword, false); $('#ConfirmPassword').val(confirmPasswordhash); $("#frmchangepassword").submit(); } }); $("#NewPassword").blur(function (event) { if ($("#NewPassword").val()!="") { if (validatePassword($("#NewPassword").val()) == false) { alert('New Password Must Have Minimum 7 characters at least 1 Alphabet, 1 Number and 1 Special Character !'); $("#NewPassword").val(''); } var data = $("#NewPassword").val().length; if (data > 20) { alert('Maximum 20 character password is Allowed!'); $("#NewPassword").val(''); } } }); }); function validatePassword(password) { var reg = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@@$!%*#?&])[A-Za-z\d$@@$!%*#?&]{7,}$/; if (reg.test(password)) { return true; } else { return false; } } </script>
37.608
144
0.508615
0ae86f24e751a92c3d2da5d9138ad07b30468fa9
1,631
cs
C#
src/Comformation/Generated/Athena/WorkGroup/EncryptionConfiguration.cs
stanb/Comformation
0a7d3bbdf035fa06885202493a7427bf96d72baa
[ "MIT" ]
17
2018-05-27T07:34:39.000Z
2021-11-25T10:30:34.000Z
src/Comformation/Generated/Athena/WorkGroup/EncryptionConfiguration.cs
stanb/Comformation
0a7d3bbdf035fa06885202493a7427bf96d72baa
[ "MIT" ]
2
2019-01-16T14:19:20.000Z
2019-12-11T23:42:44.000Z
src/Comformation/Generated/Athena/WorkGroup/EncryptionConfiguration.cs
stanb/Comformation
0a7d3bbdf035fa06885202493a7427bf96d72baa
[ "MIT" ]
3
2018-05-28T08:30:25.000Z
2021-03-14T23:37:18.000Z
using System; using System.Collections.Generic; using Newtonsoft.Json; using Comformation.IntrinsicFunctions; namespace Comformation.Athena.WorkGroup { /// <summary> /// AWS::Athena::WorkGroup EncryptionConfiguration /// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-athena-workgroup-encryptionconfiguration.html /// </summary> public class EncryptionConfiguration { /// <summary> /// EncryptionOption /// Indicates whether Amazon S3 server-side encryption with Amazon S3-managed keys (SSE-S3), server-side /// encryption with KMS-managed keys (SSE-KMS), or client-side encryption with KMS-managed keys /// (CSE-KMS) is used. /// If a query runs in a workgroup and the workgroup overrides client-side settings, then the /// workgroup&#39;s setting for encryption is used. It specifies whether query results must be encrypted, /// for all queries that run in this workgroup. /// Required: Yes /// Type: String /// Allowed values: CSE_KMS | SSE_KMS | SSE_S3 /// Update requires: No interruption /// </summary> [JsonProperty("EncryptionOption")] public Union<string, IntrinsicFunction> EncryptionOption { get; set; } /// <summary> /// KmsKey /// For SSE-KMS and CSE-KMS, this is the KMS key ARN or ID. /// Required: No /// Type: String /// Update requires: No interruption /// </summary> [JsonProperty("KmsKey")] public Union<string, IntrinsicFunction> KmsKey { get; set; } } }
37.930233
131
0.646229
0a6b05629840ea901a911377025bb4dcfba07354
1,538
cs
C#
MOE.CommonTests/Models/InMemoryRegionRepository.cs
AndreRSanchez/ATSPM
dd282d98148818ff7ac44edce1f26efae27f7ea4
[ "Apache-2.0" ]
51
2017-08-29T18:14:16.000Z
2022-02-23T18:28:35.000Z
MOE.CommonTests/Models/InMemoryRegionRepository.cs
AndreRSanchez/ATSPM
dd282d98148818ff7ac44edce1f26efae27f7ea4
[ "Apache-2.0" ]
91
2017-08-31T18:38:59.000Z
2022-03-23T18:42:54.000Z
MOE.CommonTests/Models/InMemoryRegionRepository.cs
avenueconsultants/ATSPM
ee89c4b2d880cdc96c0a111d772a5e036bb7ecea
[ "Apache-2.0" ]
40
2017-08-29T22:35:38.000Z
2022-03-28T17:46:58.000Z
using System; using System.Collections.Generic; using MOE.Common.Models; using MOE.Common.Models.Repositories; namespace MOE.CommonTests.Models { public class InMemoryRegionRepository : IRegionsRepository { public InMemoryMOEDatabase _db; public InMemoryRegionRepository() { _db = new InMemoryMOEDatabase(); } public InMemoryRegionRepository(InMemoryMOEDatabase context) { _db = context; } public void Add(Region newRegion) { _db.Regions.Add(newRegion); } public void DeleteByID(int regionID) { Region region = _db.Regions.Find(r => r.ID == regionID); _db.Regions.Remove(region); } public List<Region> GetAllRegions() { List<Region> regions = _db.Regions; return regions; } public Region GetRegionByID(int regionID) { Region region = _db.Regions.Find(r => r.ID == regionID); return region; } //public void Update(Region region) //{ // var checkRegion = _db.Regions.Find(r => r.ID == region.ID); // if (checkRegion != null) // { // checkRegion.RegionName = region.RegionName; // if (region.RegionSignals != null) // { // checkRegion.RegionSignals = region.RegionSignals; // } // } //} } }
23.30303
73
0.526008
e21d9a2af08e2ef1921a9301a9f64f43882805c7
8,995
py
Python
Code/board.py
zutn/King_of_the_Hill
fdec5022a5456e3cdec58e5688a1e560e2cd7801
[ "Apache-2.0" ]
1
2016-11-05T21:39:10.000Z
2016-11-05T21:39:10.000Z
Code/board.py
zutn/King-of-the-Hill
fdec5022a5456e3cdec58e5688a1e560e2cd7801
[ "Apache-2.0" ]
14
2016-08-04T16:37:40.000Z
2016-09-13T08:23:28.000Z
Code/board.py
zutn/King-of-the-Hill
fdec5022a5456e3cdec58e5688a1e560e2cd7801
[ "Apache-2.0" ]
2
2016-08-04T15:14:45.000Z
2016-09-04T13:01:05.000Z
# -*- coding: utf-8 -*- """ Created on Wed Aug 3 10:43:16 2016 @author: Florian Jehn """ import pygame as pg import math import random import copy import circular_arc as ca class Board(): """ draws all the things needed to start and play the game """ # Define the colors we will use in RGB format as class attributes black = ( 0, 0, 0) white = (255, 255, 255) light_ter = ( 0, 255, 0) # green normal_ter = (255,255,0) # yellow diff_ter = (255, 0, 0) # red col_play_1 = ( 0, 0, 255) # blue col_play_2 = (186, 143, 43) # brown col_play_3 = (150, 43, 186) # purple col_play_4 = (177, 171, 179) # grey # order the colors for easier access tile_colors = [black, light_ter, normal_ter, diff_ter] player_colors = [col_play_1, col_play_2, col_play_4, col_play_4] # prepare the tiles list of list for all tiles # explanation of order in __init__ tiles = [] for section in range(6): tiles.append([]) # define additional class attributes width = 800 height = 800 center_rad = (height//7//2) ring_width = center_rad num_players = 4 num_rings = 4 tiles_per_ring = 7 def __init__(self): """ define and call the screen for the game """ pg.init() global width, height # initialize the screen self.screen = pg.display.set_mode((self.width, self.height)) pg.display.set_caption("King of the Hill") # initialize pygame clock self.clock = pg.time.Clock() # write something here that creates all tiles for the first time # and sorts them into a list of list that represent all tile # sorted by the ring their in # Order of tiles in the tiles list of lists # tiles [0] = most inward ring # tiles [1] = second most inward ring # tiles [2] = third most inward ring # tiles [3] = outer ring # tiles [4] = center piece # tiles [5] = starting areas # reshuffle the terrain for each ring terrains = self.shuffle_terrain() # add all ring tiles for ring in range(self.num_rings): for tile in range(self.tiles_per_ring): # calculate distance of the rectangle of the arc (tile) from the center distance = (ring*self.ring_width)+ 0.5*self.ring_width + self.center_rad rect_x = 0.5*self.width-distance rect_y = 0.5*self.height-distance rect_height = distance * 2 rect_width = distance * 2 # each arc is 2*pi/7 wide radi_start = tile*(2*math.pi/7) radi_end = (tile*(2*math.pi/7))+2*math.pi/7 terrain = terrains[ring][tile] ring_width = int(self.ring_width*0.5) self.tiles[ring].append(Tile(rect_x, rect_y, rect_height, rect_width, radi_start, radi_end, terrain, ring_width)) # add center self.tiles[4].append(Center_Piece(self.width//2, self.height//2, self.center_rad-20)) # add starting areas # self.tiles[5].append(Starting_Area()) def shuffle_terrain(self): """ creates and returns a list of list which contains the randomized terrain for all tiles of a ring """ terrains = [] ring = [1,1,1,2,2,3,3] for ring_num in range(4): ring_copy = copy.copy(ring) random.shuffle(ring_copy) # shuffle it, so that the starting order of terrains is random for every ring terrains.append(ring_copy) return terrains def draw_board(self): """ calls all method which draw the seperate pieces of the board """ self.draw_center() for ring in range(self.num_rings): self.draw_ring(ring) for player_num in range(self.num_players): self.draw_counter(player_num) self.draw_start_area(player_num) def draw_center(self): """ draws the center piece """ # - 20 to adjust it in size pg.draw.circle(self.screen, self.black, [self.tiles[4][0].x, self.tiles[4][0].y], self.tiles[4][0].rad) def draw_ring(self, ring): """ draws the outer rings """ # draw all tiles for tile in range(self.tiles_per_ring): self.draw_tile(tile, ring) def draw_tile(self, tile, ring): """ draws one arc tile of a ring depending on the number of players and the size of the screen """ pg.draw.arc(self.screen, self.tile_colors[self.tiles[ring][tile].terrain], [self.tiles[ring][tile].rect_x, self.tiles[ring][tile].rect_y, self.tiles[ring][tile].rect_width, self.tiles[ring][tile].rect_height], self.tiles[ring][tile].radi_start, self.tiles[ring][tile].radi_end, self.tiles[ring][tile].ring_width) def draw_counter(self, player_num): """ draws the counters for the score of each player """ pass def draw_start_area(self, player_num): """ draws the starting area for each player """ pass def rotate_ring_right(self, ring_num): """ rotates a ring one field to the right """ # to accomplish this save the pos of the first tile in the ring # in a temporary variable, then interchange clockwise the position data # of all tiles pass def rotate_ring_left(self, ring_num): """ rotates a ring one field to the right """ pass class Tile: """ class for the instances of the tiles on the board """ # Somehow the units must be asociated with a given tile # define the terrains ter_names = ["center", "light", "normal", "difficult"] def __init__(self, rect_x = 0, rect_y = 0 ,rect_height = 0, rect_width = 0, radi_start = 0, radi_end = 0, terrain = 0, ring_width = 0, units = None): """ defines the instance attributes for every tile on call """ # terrain 0 = black (center), 1 = light/green, 2 normal/yellow, 3 difficult/red self.rect_x = rect_x self.rect_y = rect_y self.radi_start = radi_start self.radi_end = radi_end self.terrain = terrain self.rect_width = rect_width self.rect_height = rect_height self.ring_width = ring_width if units == None: self.units = [] else: self.units = units def __str__(self): """ string output for the class """ pass def change_terrain(self, new_ter): """changes the terrain""" self.terrain = new_ter def change_pos(self, new_radi_start, new_radi_end): """ changes the position of a tile """ self.radi_start = new_radi_start self.radi_end = new_radi_end def add_unit(self, unit): """ adds a unit to the tile """ pass def del_unit(self, unit): """ deletes a unit from a tile """ pass class Center_Piece: """ class for the instance of the center piece """ def __init__(self,x = 0, y = 0, rad = 0, col = 0): """ defines the instance attributes """ self.x = x self.y = y self.rad = rad self.col = col class Counter: """ class for the instances of the counters """ def __init__(self, x = 0, y = 0, player = None, points = 0): """ defines the instance attributes for every counter on call """ self.x = x self.y = y self.player = player self.points = points def increment(self): """increments the points by one""" self.points += 1 class Start_Area: """ class for the instances of the starting areas """ def __init__(self, rect_x = 0, rect_y = 0, radi_start = 0, radi_end = 0, player = None): """ defines the instance attributes for every start area on call """ self.rect_x = rect_x self.rect_y = rect_y self.radi_start = radi_start self.radi_end = radi_end self.player = player def change_pos(self, new_radi_start, new_radi_end): """ changes the position of the start are """ self.radi_start = new_radi_start self.radi_end = new_radi_end class Unit: # 0 = runner, 1 = warrior, 2 = blocker # define the units unit_names = ["runner", "warrior", "blocker"] pass
30.083612
323
0.558644
6da0097fec0154e31536f300a1b8d358dc61b6c6
1,583
h
C
System/Library/PrivateFrameworks/IDS.framework/identityservicesd.app/IDSKeychainWrapper.h
lechium/tvOS130Headers
6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd
[ "MIT" ]
11
2019-11-06T04:48:48.000Z
2022-02-09T17:48:15.000Z
System/Library/PrivateFrameworks/IDS.framework/identityservicesd.app/IDSKeychainWrapper.h
lechium/tvOS130Headers
6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd
[ "MIT" ]
1
2020-04-16T01:41:56.000Z
2020-04-16T04:32:00.000Z
System/Library/PrivateFrameworks/IDS.framework/identityservicesd.app/IDSKeychainWrapper.h
lechium/tvOS130Headers
6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd
[ "MIT" ]
3
2019-12-22T20:17:53.000Z
2021-01-25T09:47:49.000Z
/* * This header is generated by classdump-dyld 1.0 * on Tuesday, November 5, 2019 at 2:41:53 AM Mountain Standard Time * Operating System: Version 13.0 (Build 17J586) * Image Source: /System/Library/PrivateFrameworks/IDS.framework/identityservicesd.app/identityservicesd * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ @interface IDSKeychainWrapper : NSObject +(BOOL)isItemNotFoundError:(id)arg1 ; +(id)shortDescriptionForDataProtectionClass:(long long)arg1 ; +(BOOL)isUpgradePendingError:(id)arg1 ; +(BOOL)isInteractionNotAllowedError:(id)arg1 ; +(long long)idsKeychainWrapperDataProtectionClassFromIMDataProtectionClass:(unsigned)arg1 ; +(unsigned)imDataProtectionClassFromDataProtectionClass:(long long)arg1 ; +(BOOL)_isKeychainError:(id)arg1 withOSStatus:(int)arg2 ; +(id)descriptionForDataProtectionClass:(long long)arg1 ; -(id)dataForIdentifier:(id)arg1 error:(id*)arg2 ; -(BOOL)saveData:(id)arg1 forIdentifier:(id)arg2 allowSync:(BOOL)arg3 dataProtectionClass:(long long)arg4 error:(id*)arg5 ; -(BOOL)removeDataForIdentifier:(id)arg1 dataProtectionClass:(long long)arg2 error:(id*)arg3 ; -(id)_keychainAccountFromBaseIdentifier:(id)arg1 ; -(BOOL)saveData:(id)arg1 forIdentifier:(id)arg2 allowSync:(BOOL)arg3 allowBackup:(BOOL)arg4 dataProtectionClass:(long long)arg5 error:(id*)arg6 ; -(long long)cloudCircleStatusError:(id*)arg1 ; -(id)dataForIdentifier:(id)arg1 ; -(void)saveData:(id)arg1 forIdentifier:(id)arg2 dataProtectionClass:(long long)arg3 withCompletion:(/*^block*/id)arg4 ; -(BOOL)isInCloudCircleWithError:(id*)arg1 ; @end
52.766667
145
0.794062
77ae50a506f0014d668f576632566c1cf89c8f92
1,285
h
C
src/misc.h
alertflex/altprobe
1c9f256ef8aa4a015cac1b1c5f990f4c177c8b3d
[ "Apache-2.0" ]
31
2020-10-08T13:16:17.000Z
2022-03-18T06:38:31.000Z
src/misc.h
olegzhr/altprobe
da9597efcf0463f31ea38bf715ed8d5453dfc0e5
[ "Apache-2.0" ]
2
2020-09-17T15:54:58.000Z
2021-02-26T07:58:01.000Z
src/misc.h
alertflex/altprobe
1c9f256ef8aa4a015cac1b1c5f990f4c177c8b3d
[ "Apache-2.0" ]
8
2020-11-25T21:29:00.000Z
2022-02-21T01:37:20.000Z
/* * Copyright 2021 Oleg Zharkov * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #ifndef MISC_H #define MISC_H #include "source.h" using namespace std; namespace bpt = boost::property_tree; class Misc : public Source { public: bpt::ptree pt; stringstream ss; Misc (string skey) : Source(skey) { ClearRecords(); ResetStream(); } void ResetStream() { ss.str(""); ss.clear(); } void ResetJsontree() { pt.clear(); } int Open(); void Close(); int Go(); int ParsJson (char* redis_payload); void ClearRecords() { ResetJsontree(); jsonPayload.clear(); } }; extern boost::lockfree::spsc_queue<string> q_logs_misc; #endif /* MISC_H */
20.396825
78
0.611673
de3c61deaf06afb84197d6fff857606df10eca50
438
css
CSS
src/components/article-preview.module.css
sleeepysquid/DoingLifeWithYou
76c4139b5ac387852abd94cd3076604ab892171a
[ "MIT" ]
null
null
null
src/components/article-preview.module.css
sleeepysquid/DoingLifeWithYou
76c4139b5ac387852abd94cd3076604ab892171a
[ "MIT" ]
11
2019-05-02T03:50:11.000Z
2021-02-02T17:19:40.000Z
src/components/article-preview.module.css
sleeepysquid/DoingLifeWithYou
76c4139b5ac387852abd94cd3076604ab892171a
[ "MIT" ]
null
null
null
.previewTitle { font-size: 1.2em; background-color: #000000b8; color: #fff; display: inline; text-align: center; margin: 10px !important; padding: 5px; -webkit-box-decoration-break: clone; box-decoration-break: clone; } .tag { color: #A0A0A0; text-decoration: none; display: inline-block; padding: .33333rem .5rem; line-height: 1; border-radius: 2px; border: 1px solid #A0A0A0; margin-right: .5em; }
19.043478
38
0.66895
1bd1d59ecf4d18636ef619f2a6b45da1cea56b5b
752
rb
Ruby
lib/fantasydata/api/player_details.rb
kohactive/fantasydata
8dd9cf73697c51d54c8337651976d4b3ec75a16e
[ "MIT" ]
null
null
null
lib/fantasydata/api/player_details.rb
kohactive/fantasydata
8dd9cf73697c51d54c8337651976d4b3ec75a16e
[ "MIT" ]
null
null
null
lib/fantasydata/api/player_details.rb
kohactive/fantasydata
8dd9cf73697c51d54c8337651976d4b3ec75a16e
[ "MIT" ]
2
2017-11-08T06:37:02.000Z
2019-01-05T03:15:46.000Z
require 'fantasydata/api/utils' module Fantasydata module API module PlayerDetails include Fantasydata::API::Utils def player_details_available sport=:nfl objects_from_response(Fantasydata::PlayerDetail, :get, "/#{sport}/v2/JSON/Players") end def player_details_free_agents objects_from_response(Fantasydata::PlayerDetail, :get, "/nfl/v2/JSON/FreeAgents") end def player_details_by_team(team_name) objects_from_response(Fantasydata::PlayerDetail, :get, "/nfl/v2/JSON/Players/#{team_name}") end def player_details_by_player_id(player_id) object_from_response(Fantasydata::PlayerDetail, :get, "/nfl/v2/JSON/Player/#{player_id.to_s}") end end end end
27.851852
102
0.707447
38868ea0e27ff11ef7171295ed1b8ceb8f5d26b1
4,722
php
PHP
ppdb.man2/simplex/database/drivers/pdo/PdoUtil.php
Bladefidz/ppdb
4d8f05bfe6ac983e5e59b4ef75a898407d3d61c8
[ "Apache-2.0" ]
null
null
null
ppdb.man2/simplex/database/drivers/pdo/PdoUtil.php
Bladefidz/ppdb
4d8f05bfe6ac983e5e59b4ef75a898407d3d61c8
[ "Apache-2.0" ]
null
null
null
ppdb.man2/simplex/database/drivers/pdo/PdoUtil.php
Bladefidz/ppdb
4d8f05bfe6ac983e5e59b4ef75a898407d3d61c8
[ "Apache-2.0" ]
1
2019-02-09T03:57:05.000Z
2019-02-09T03:57:05.000Z
<?php namespace Database\Driver; require_once __DIR__.'/PdoDb.php'; /** * PdoUtil class. */ class PdoUtil extends \Database\Driver\PdoDb { /** * Getter and setter variable. * * @var array */ public $variables; /** * Table name. * * @var string */ public $table; /** * Table primary key. * * @var string */ public $pk; public function __construct($dsn, $username, $password, $log, $data = array()) { parent::__construct($dsn, $username, $password, $log); $this->variables = $data; } public function __set($name, $value) { if (strtolower($name) === $this->pk) { $this->variables[$this->pk] = $value; } else { $this->variables[$name] = $value; } } public function __get($name) { if (is_array($this->variables)) { if (array_key_exists($name, $this->variables)) { return $this->variables[$name]; } } $trace = debug_backtrace(); trigger_error( 'Undefined property via __get(): '.$name. ' in '.$trace[0]['file']. ' on line '.$trace[0]['line'], E_USER_NOTICE ); return; } public function from($tableName) { $this->table = $tableName; } public function into($tableName) { $this->table = $tableName; } public function where($value) { $this->variables[$name] = $value; } public function save($id = '0') { $this->variables[$this->pk] = (empty($this->variables[$this->pk])) ? $id : $this->variables[$this->pk]; $fieldsvals = ''; $columns = array_keys($this->variables); foreach ($columns as $column) { if ($column !== $this->pk) { $fieldsvals .= $column.' = :'.$column.','; } } $fieldsvals = substr_replace($fieldsvals, '', -1); if (count($columns) > 1) { $sql = 'UPDATE '.$this->table.' SET '.$fieldsvals.' WHERE '.$this->pk.'= :'.$this->pk; return $this->query($sql, $this->variables); } } public function create() { $bindings = $this->variables; if (!empty($bindings)) { $fields = array_keys($bindings); $fieldsvals = array(implode(',', $fields),':'.implode(',:', $fields)); $sql = 'INSERT INTO '.$this->table.' ('.$fieldsvals[0].') VALUES ('.$fieldsvals[1].')'; } else { $sql = 'INSERT INTO '.$this->table.' () VALUES ()'; } return $this->query($sql, $bindings); } public function delete($id = '') { $id = (empty($this->variables[$this->pk])) ? $id : $this->variables[$this->pk]; if (!empty($id)) { $sql = 'DELETE FROM '.$this->table.' WHERE '.$this->pk.'= :'.$this->pk.' LIMIT 1'; return $this->query($sql, array($this->pk => $id)); } } public function find($id = '') { $id = (empty($this->variables[$this->pk])) ? $id : $this->variables[$this->pk]; if (!empty($id)) { $sql = 'SELECT * FROM '.$this->table.' WHERE '.$this->pk.'= :'.$this->pk.' LIMIT 1'; $this->variables = $this->row($sql, array($this->pk => $id)); } } public function get($limit = null) { if ($limit === null) { return $this->query('SELECT * FROM '.$this->table); } else { return $this->query('SELECT * FROM '.$this->table.' LIMIT '.$limit); } } public function all() { return $this->query('SELECT * FROM '.$this->table); } public function min($field) { if ($field) { return $this->single('SELECT min('.$field.')'.' FROM '.$this->table); } } public function max($field) { if ($field) { return $this->single('SELECT max('.$field.')'.' FROM '.$this->table); } } public function avg($field) { if ($field) { return $this->single('SELECT avg('.$field.')'.' FROM '.$this->table); } } public function sum($field) { if ($field) { return $this->single('SELECT sum('.$field.')'.' FROM '.$this->table); } } public function count($field) { if ($field) { return $this->single('SELECT count('.$field.')'.' FROM '.$this->table); } } public function countRows() { return $this->lastQuery->rowCount(); } public function countColumn() { return $this->lastQuery->columnCount(); } }
23.61
111
0.479034
5e61b3b26ef4fbb2a69069a9694b51cefb2bd60e
11,830
swift
Swift
24-core-location/projects/final/Meetup Finder/Meetup Finder Watch Extension/InterfaceController.swift
raywenderlich/w2t-materials
9de746b0140e15cbcc5648d167c55846529d4b35
[ "Apache-2.0" ]
1
2021-04-29T01:19:56.000Z
2021-04-29T01:19:56.000Z
24-core-location/projects/final/Meetup Finder/Meetup Finder Watch Extension/InterfaceController.swift
raywenderlich/w2t-materials
9de746b0140e15cbcc5648d167c55846529d4b35
[ "Apache-2.0" ]
null
null
null
24-core-location/projects/final/Meetup Finder/Meetup Finder Watch Extension/InterfaceController.swift
raywenderlich/w2t-materials
9de746b0140e15cbcc5648d167c55846529d4b35
[ "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2017 Razeware LLC * * 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. * * Notwithstanding the foregoing, you may not use, copy, modify, merge, publish, * distribute, sublicense, create a derivative work, and/or sell copies of the * Software in any work that is designed, intended, or marketed for pedagogical or * instructional purposes related to programming, coding, application development, * or information technology. Permission for such use, copying, modification, * merger, publication, distribution, sublicensing, creation of derivative works, * or sale is expressly withheld. * * 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. */ import WatchKit import Foundation import CoreLocation import WatchConnectivity class InterfaceController: WKInterfaceController { private let locationAccessUnauthorizedMessage = "Locations Disabled\n\nEnable locations for this app via the Settings in your iPhone to see meetups near you!" private let pendingAccessMessage = "Grant location access to Meetup Finder on your iPhone to see meetup groups in your vicinity." /// The WKInterfaceGroup that's displayed when there's no content and instead /// you want to display a message to user, e.g. "No Meetups found", or /// "Location service is disabled", etc. @IBOutlet private var messageContentGroup: WKInterfaceGroup! @IBOutlet private var messageLabel: WKInterfaceLabel! /// The WKInterfaceGroup that's displayed when there're meetups. It contains the WKInterfaceTable. @IBOutlet private var meetupsContentGroup: WKInterfaceGroup! @IBOutlet private var interfaceTable: WKInterfaceTable! private let interfaceModel = MainInterfaceModel() private let meetupRequestManager = MeetupRequestManager() private let locationManager = CLLocationManager() private var session: WCSession? private var lastQueriedLocation: CLLocation? override func awake(withContext context: Any?) { super.awake(withContext: context) startSession() locationManager.allowsBackgroundLocationUpdates = true locationManager.delegate = self } override func willActivate() { super.willActivate() // Then ask location manager to give you an updated location. // If the new location is significantly different, you'll dispatch // another request. let authorizationStatus = CLLocationManager.authorizationStatus() handleLocationServicesAuthorizationStatus(authorizationStatus) // If there is a valid last known location - usually set either via // session(_:, didReceiveApplicationContext:) of WCSessionDelegate, // query data for that. if let lastQueriedLocation = lastQueriedLocation { queryMeetupsForLocation(lastQueriedLocation) } } func handleLocationServicesAuthorizationStatus(_ status: CLAuthorizationStatus) { switch status { case .notDetermined: print("handleLocationServicesAuthorizationStatus: .undetermined") handleLocationServicesStateNotDetermined() case .restricted, .denied: print("handleLocationServicesAuthorizationStatus: .restricted, .denied") handleLocationServicesStateUnavailable() case .authorizedAlways, .authorizedWhenInUse: print("handleLocationServicesAuthorizationStatus: .authorizedAlways, .authorizedWhenInUse") handleLocationServicesStateAvailable(status) } } func handleLocationServicesStateNotDetermined() { updateVisibilityOfInterfaceGroups() messageLabel.setText(pendingAccessMessage) locationManager.requestWhenInUseAuthorization() } func handleLocationServicesStateUnavailable() { interfaceModel.state = MainInterfaceState.notAuthorized updateVisibilityOfInterfaceGroups() messageLabel.setText(locationAccessUnauthorizedMessage) } func handleLocationServicesStateAvailable(_ status: CLAuthorizationStatus) { updateVisibilityOfInterfaceGroups() showLoadingMessageIfApplicable() switch status { case .authorizedAlways: locationManager.startUpdatingLocation() case .authorizedWhenInUse: locationManager.requestLocation() default: break } } override func didDeactivate() { super.didDeactivate() } override func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) { let meetup = interfaceModel.meetups[rowIndex] pushController(withName: "DetailInterfaceController", context: meetup) } // MARK: Helper private func updateInterfaceWithMeetups(_ meetups: [Meetup]) { // Initialize, add or remove rows from the Interface Table // based on current number of meetups and the new count of meetups. let currentCount = interfaceModel.meetups.count let newCount = meetups.count let rowType = "MeetupRowController" // Not all conditions may require the following values. // They're here to refactor common code. let diff = newCount - currentCount let range = Range(uncheckedBounds:(lower: currentCount, upper: currentCount + diff)) let indexSet = IndexSet(integersIn: range) // Update row count of the table. performBlock { () -> Void in if currentCount == 0 { // Initialize table. self.interfaceTable.setNumberOfRows(newCount, withRowType: rowType) } else if currentCount > newCount { // Add new rows. self.interfaceTable.insertRows(at: indexSet, withRowType: rowType) } else if currentCount < newCount { // Remove extra rows. self.interfaceTable.removeRows(at: indexSet) } // Update content of rows. self.performBlock { () -> Void in for (index, meetup) in meetups.enumerated() { guard let rowController = self.interfaceTable.rowController(at: index) as? MeetupRowController else { continue } rowController.meetupGroupNameLabel.setText(meetup.group.name) rowController.meetupLocationLabel.setText(meetup.location.city + ", " + meetup.location.state) rowController.meetupMembersLabel.setText("\(meetup.group.numberOfMembers)") rowController.containerGroup.setBackgroundColor(meetup.group.color) } } } // Update interface model. interfaceModel.meetups = meetups if newCount == 0 { interfaceModel.state = .noContent messageLabel.setText("No Meetup groups\nare found ;[") } else { interfaceModel.state = .meetupContent } performBlock { () -> Void in self.updateVisibilityOfInterfaceGroups() } } /// Show 'Loading...' in the message label if applicable. That's there's been no /// content before, now the controller is loading content. /// Otherwise does nothing, e.g. a refresh or reload. private func showLoadingMessageIfApplicable() { switch interfaceModel.state { case .error: fallthrough case .noContent: fallthrough case .notAuthorized: messageLabel.setText("Loading...") default: break } } /// Toggles appearance of top-level interface elements private func updateVisibilityOfInterfaceGroups() { switch self.interfaceModel.state { case .error: fallthrough case .noContent: messageContentGroup.setHidden(false) meetupsContentGroup.setHidden(true) case .notAuthorized: messageContentGroup.setHidden(false) meetupsContentGroup.setHidden(true) case .meetupContent: messageContentGroup.setHidden(true) meetupsContentGroup.setHidden(false) } } private func queryMeetupsForLocation(_ location: CLLocation) { // Early termination. Don't query backend if location hasn't changed significantly. let isSignificantChange = isLocationChangedSignificantly(location) if isSignificantChange == false { print("New query to meetups ignored because current location hasn't changed significantly.") return } lastQueriedLocation = location interfaceModel.loading = true showLoadingMessageIfApplicable() let coordinate = location.coordinate let lon = Double(coordinate.longitude) let lat = Double(coordinate.latitude) let requestModel = MeetupGroupRequestModel(latitude: lat, longitude: lon, radius: MeetupQueryRadius, pages: MeetupQueryPages, searchText: "iOS") weak var weakSelf = self meetupRequestManager.fetchMeetupGroupsWithModel(model: requestModel) { (meetups, error) -> Void in var nonnilMeetups = [Meetup]() if let meetups = meetups { nonnilMeetups = meetups } weakSelf?.interfaceModel.loading = false weakSelf?.updateInterfaceWithMeetups(nonnilMeetups) } } func isLocationChangedSignificantly(_ updatedLocation: CLLocation) -> Bool { guard let lastQueriedLocation = lastQueriedLocation else { return true } let distance = lastQueriedLocation.distance(from: updatedLocation) return distance > CLLocationDistance(MeetupSignificantDistanceChange) } } // MARK: WCSessionDelegate extension InterfaceController: WCSessionDelegate { private func startSession() { session = WCSession.default session?.delegate = self session?.activate() } func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { let description = error?.localizedDescription ?? "nil" print("Activation did complete: \(activationState), error: \(description)") } func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any]) { print("Received application context: (applicationContext)") guard let data = applicationContext["lastQueriedLocation"] as? Data else { return } guard let location = NSKeyedUnarchiver.unarchiveObject(with: data) as? CLLocation else { return } queryMeetupsForLocation(location) } } // MARK: CoreLocation extension InterfaceController: CLLocationManagerDelegate { // MARK: Delegate callbacks func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { handleLocationServicesAuthorizationStatus(status) } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { print("Did update locations: \(locations)") guard let mostRecentLocation = locations.last else { return } queryMeetupsForLocation(mostRecentLocation) } func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { print("CL failed: \(error)") if interfaceModel.loading == false || interfaceModel.state != .meetupContent { interfaceModel.state = .error updateVisibilityOfInterfaceGroups() messageLabel.setText("Failed to get a valid location.") } else { print("CL failed but ignore the error because interface controlelr is already loading data with a valid location.") } } }
39.83165
160
0.738377
cdfaff5616595c76f8b778d30e2e57db9f00770e
674
cs
C#
Havit.Data.EntityFrameworkCore.BusinessLayer/Metadata/Conventions/CharColumnTypeForCharPropertyConventionPlugin.cs
havit/HavitFramework
cc23bd0070a4becb2ce990e696022eb62662973a
[ "MIT" ]
23
2019-05-08T07:15:12.000Z
2022-01-27T06:44:25.000Z
Havit.Data.EntityFrameworkCore.BusinessLayer/Metadata/Conventions/CharColumnTypeForCharPropertyConventionPlugin.cs
havit/HavitFramework
cc23bd0070a4becb2ce990e696022eb62662973a
[ "MIT" ]
null
null
null
Havit.Data.EntityFrameworkCore.BusinessLayer/Metadata/Conventions/CharColumnTypeForCharPropertyConventionPlugin.cs
havit/HavitFramework
cc23bd0070a4becb2ce990e696022eb62662973a
[ "MIT" ]
2
2021-10-15T06:36:51.000Z
2022-01-25T22:23:10.000Z
using Microsoft.EntityFrameworkCore.Metadata.Conventions; using Microsoft.EntityFrameworkCore.Metadata.Conventions.Infrastructure; using System; using System.Collections.Generic; using System.Text; namespace Havit.Data.EntityFrameworkCore.BusinessLayer.Metadata.Conventions { /// <summary> /// Registruje CharColumnTypeForCharPropertyConvention do ConventionSetu. /// </summary> internal class CharColumnTypeForCharPropertyConventionPlugin : IConventionSetPlugin { public ConventionSet ModifyConventions(ConventionSet conventionSet) { conventionSet.PropertyAddedConventions.Add(new CharColumnTypeForCharPropertyConvention()); return conventionSet; } } }
32.095238
93
0.833828
0750a03172aecbf520f5ac22a841f45f6ce3b8fb
1,264
kt
Kotlin
vk-api/src/main/kotlin/name/alatushkin/api/vk/api/executeManyMethodsAtOnce.kt
alatushkin/kotlin-vk-api
123bd61b24be70f9bbf044328b98a3901523cb1b
[ "MIT" ]
10
2018-11-27T09:44:37.000Z
2020-01-18T11:00:40.000Z
vk-api/src/main/kotlin/name/alatushkin/api/vk/api/executeManyMethodsAtOnce.kt
alatushkin/kotlin-vk-api
123bd61b24be70f9bbf044328b98a3901523cb1b
[ "MIT" ]
4
2018-11-30T09:45:24.000Z
2018-12-10T16:14:29.000Z
vk-api/src/main/kotlin/name/alatushkin/api/vk/api/executeManyMethodsAtOnce.kt
alatushkin/kotlin-vk-api
123bd61b24be70f9bbf044328b98a3901523cb1b
[ "MIT" ]
3
2018-11-30T09:39:21.000Z
2020-05-13T19:09:23.000Z
package name.alatushkin.api.vk.api import com.fasterxml.jackson.databind.JavaType import name.alatushkin.api.vk.MethodExecutor import name.alatushkin.api.vk.MethodExecutorWithException import name.alatushkin.api.vk.VkMethod import name.alatushkin.api.vk.api.methods.ExecuteMethod suspend inline operator fun <reified T, M : VkMethod<T>> MethodExecutor.invoke(methods: List<M>): VkResponse<Array<T>> { val methodToCall = makeVkScriptToCall(methods) return this(methodToCall) } suspend inline operator fun <reified T, M : VkMethod<T>> MethodExecutorWithException.invoke(methods: List<M>): Array<T> { val methodToCall = makeVkScriptToCall(methods) return this(methodToCall) } inline fun <M : VkMethod<T>, reified T> makeVkScriptToCall(methods: List<M>): ExecuteMethod<Array<T>> { assert(methods.size <= 25) { "Maximum 25 call at one allowed by api" } val mapper = ExecuteMethod.mapper val code = methods.joinToString(", ", prefix = "return [", postfix = "];") { method -> val argsJson = mapper.writeValueAsString(method.toJsonObject()) "API." + method.apiMethodName + "($argsJson)" } val arrayType: JavaType = mapper.typeFactory.constructArrayType(T::class.java) return ExecuteMethod(code, arrayType) }
42.133333
121
0.738133
cf3689b283022665e5cb06a12a3ab5d0b0a2afff
3,878
php
PHP
system/src/Grav/Common/Backup/ZipBackup.php
antunes145/antunes145.github.io
e3734a79075a7b7d4bb78203de54e9b8732a9ef8
[ "MIT" ]
1
2019-01-18T10:09:21.000Z
2019-01-18T10:09:21.000Z
system/src/Grav/Common/Backup/ZipBackup.php
antunes145/antunes145.github.io
e3734a79075a7b7d4bb78203de54e9b8732a9ef8
[ "MIT" ]
null
null
null
system/src/Grav/Common/Backup/ZipBackup.php
antunes145/antunes145.github.io
e3734a79075a7b7d4bb78203de54e9b8732a9ef8
[ "MIT" ]
null
null
null
<?php namespace Grav\Common\Backup; use Grav\Common\GravTrait; use Grav\Common\Filesystem\Folder; use Grav\Common\Inflector; /** * The ZipBackup class lets you create simple zip-backups of a grav site * * @author RocketTheme * @license MIT */ class ZipBackup { use GravTrait; protected static $ignorePaths = [ 'backup', 'cache', 'images', 'logs' ]; protected static $ignoreFolders = [ '.git', '.svn', '.hg', '.idea' ]; public static function backup($destination = null, callable $messager = null) { if (!$destination) { $destination = self::getGrav()['locator']->findResource('backup://', true); if (!$destination) throw new \RuntimeException('The backup folder is missing.'); Folder::mkdir($destination); } $name = self::getGrav()['config']->get('site.title', basename(GRAV_ROOT)); $inflector = new Inflector(); if (is_dir($destination)) { $date = date('YmdHis', time()); $filename = trim($inflector->hyphenize($name), '-') . '-' . $date . '.zip'; $destination = rtrim($destination, DS) . DS . $filename; } $messager && $messager([ 'type' => 'message', 'level' => 'info', 'message' => 'Creating new Backup "' . $destination . '"' ]); $messager && $messager([ 'type' => 'message', 'level' => 'info', 'message' => '' ]); $zip = new \ZipArchive(); $zip->open($destination, \ZipArchive::CREATE); $max_execution_time = ini_set('max_execution_time', 600); static::folderToZip(GRAV_ROOT, $zip, strlen(rtrim(GRAV_ROOT, DS) . DS), $messager); $messager && $messager([ 'type' => 'progress', 'percentage' => false, 'complete' => true ]); $messager && $messager([ 'type' => 'message', 'level' => 'info', 'message' => '' ]); $messager && $messager([ 'type' => 'message', 'level' => 'info', 'message' => 'Saving and compressing archive...' ]); $zip->close(); if ($max_execution_time !== false) { ini_set('max_execution_time', $max_execution_time); } return $destination; } /** * @param $folder * @param $zipFile * @param $exclusiveLength * @param $messager */ private static function folderToZip($folder, \ZipArchive &$zipFile, $exclusiveLength, callable $messager = null) { $handle = opendir($folder); while (false !== $f = readdir($handle)) { if ($f != '.' && $f != '..') { $filePath = "$folder/$f"; // Remove prefix from file path before add to zip. $localPath = substr($filePath, $exclusiveLength); if (in_array($f, static::$ignoreFolders)) { continue; } elseif (in_array($localPath, static::$ignorePaths)) { $zipFile->addEmptyDir($f); continue; } if (is_file($filePath)) { $zipFile->addFile($filePath, $localPath); $messager && $messager([ 'type' => 'progress', 'percentage' => false, 'complete' => false ]); } elseif (is_dir($filePath)) { // Add sub-directory. $zipFile->addEmptyDir($localPath); static::folderToZip($filePath, $zipFile, $exclusiveLength, $messager); } } } closedir($handle); } }
28.306569
116
0.47705
b1090c9092b025ed42f8b74624c0ef7329fe91a2
510
lua
Lua
src/ServerScriptService/Main/SelectionBoxHandler.server.lua
INWNMTheBossM/minershaven
3be28d1f2a95ba5578629c36b4581a066b1cc34f
[ "Apache-2.0" ]
113
2019-09-16T14:38:12.000Z
2022-03-29T04:56:36.000Z
src/ServerScriptService/Main/SelectionBoxHandler.server.lua
INWNMTheBossM/minershaven
3be28d1f2a95ba5578629c36b4581a066b1cc34f
[ "Apache-2.0" ]
2
2021-06-24T01:40:07.000Z
2022-03-26T20:57:48.000Z
src/ServerScriptService/Main/SelectionBoxHandler.server.lua
INWNMTheBossM/minershaven
3be28d1f2a95ba5578629c36b4581a066b1cc34f
[ "Apache-2.0" ]
64
2019-09-16T15:04:06.000Z
2022-02-23T01:04:44.000Z
game.ReplicatedStorage:WaitForChild("Items") for i,v in pairs(game.ReplicatedStorage.Items:GetChildren()) do local SelBox = Instance.new("SelectionBox",v) SelBox.Name = "SelectionBox" SelBox.Adornee = v.Hitbox SelBox.Visible = false --[[ if v.Tier.Value == 20 then SelBox.Color3 = Color3.new(172/255, 167/255, 15/255) elseif v.Tier.Value == 30 then SelBox.Color3 = Color3.new(172/255, 29/255, 153/255) elseif v.Tier.Value == 40 then SelBox.Color3 = Color3.new(0/255, 161/255, 34/255) end ]] end
31.875
63
0.713725
e778bd2256061a88b94d69eeb560612b00c584c8
1,879
php
PHP
resources/views/test/pdf.blade.php
askate741/openshift
abc20a68ba62a08e8e35f3cef4fed9cb0e4cffff
[ "MIT" ]
null
null
null
resources/views/test/pdf.blade.php
askate741/openshift
abc20a68ba62a08e8e35f3cef4fed9cb0e4cffff
[ "MIT" ]
null
null
null
resources/views/test/pdf.blade.php
askate741/openshift
abc20a68ba62a08e8e35f3cef4fed9cb0e4cffff
[ "MIT" ]
null
null
null
<script> /** * @return {string} */ function Chinese(str) { str = str.replace(/,/g, ""); var AU = []; var ans = ""; var chi = "零壹貳參肆伍陸柒捌玖"; for (var i = 0; i < str.length; i++) ans += chi.charAt(parseInt(str.charAt(i))); for (var i = ans.length; i > 0; i--) { var U = ""; var k = i; while ((k - 13) >= 0) { k -= 12; U += "兆"; } while ((k - 9) >= 0) { k -= 8; U += "億"; } while ((k - 5) >= 0) { k -= 4; U += "萬"; } if (k > 1) U = ""; while ((k - 4) >= 0) { k -= 3; U += "仟"; } while ((k - 3) >= 0) { k -= 2; U += "佰"; } while ((k - 2) >= 0) { k -= 1; U += "拾"; } var tU = ""; var r = U.length; while (r-- > 0) tU = tU + U.charAt(r); if (tU != "") AU.push(tU); } AU.push(""); var final = ""; for (i = 0; i < ans.length; i++) { final += ans.charAt(i) + AU[i]; } while (final.match(/零[仟佰拾]零/)) final = final.replace(/零[仟佰拾]零/g, "零"); final = final.replace(/零[仟佰拾]/g, "零").replace(/零兆/g, '兆').replace(/零億/g, '億').replace(/零萬/g, '萬'); final = final.replace(/兆[仟佰拾億萬][兆億萬仟佰拾]*/g, '兆零').replace(/億[仟佰拾萬][兆億萬仟佰拾]*/g, '億零').replace(/萬[仟佰拾][兆億萬仟佰拾]*/g, '萬零'); final = final.replace(/^壹拾/, "拾"); while (final.match(/零$/)) final = final.replace(/零$/, ""); return final; } </script> <form onsubmit="alert(Chinese(this.numb.value))"> <input name=numb size=50> <br><input type="submit"> </form>
29.359375
127
0.345396
ce444bb924d004649fc13d9e8fb5195a0eaccaf8
808
swift
Swift
Tests/BigIntTests/ShiftTest.swift
agouin/BigInt
2e5a43c9cfd56b18ceddf609f3780716dcf567a9
[ "MIT" ]
null
null
null
Tests/BigIntTests/ShiftTest.swift
agouin/BigInt
2e5a43c9cfd56b18ceddf609f3780716dcf567a9
[ "MIT" ]
null
null
null
Tests/BigIntTests/ShiftTest.swift
agouin/BigInt
2e5a43c9cfd56b18ceddf609f3780716dcf567a9
[ "MIT" ]
null
null
null
// // ShiftTest.swift // XBigIntegerTests // // Created by Leif Ibsen on 11/12/2018. // import XCTest class ShiftTest: XCTestCase { override func 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. } func test1() { let x1 = BInt(bitWidth: 200) XCTAssertEqual(x1, (x1 << 3) >> 3) XCTAssertEqual(x1 << -3, x1 >> 3) XCTAssertEqual(x1 << 3, x1 >> -3) let x2 = BInt("1234567890")! XCTAssertEqual(x2, (x2 << 200) / (BInt.ONE << 200)) var x3 = x2 x3 <<= 1 XCTAssertEqual(x3, BInt("2469135780")!) } }
23.764706
111
0.581683
dddd57aad2239a81445e223d7c51d923147a226c
930
java
Java
project/server/accountManagementService/src/main/java/ntut/csie/accountManagementService/adapter/presenter/user/ModifyPersonalInformationPresenter.java
xtc841113/Medical-Service-System
0c1ea91b4b878766c918b7161b85f829afa15922
[ "Apache-2.0" ]
null
null
null
project/server/accountManagementService/src/main/java/ntut/csie/accountManagementService/adapter/presenter/user/ModifyPersonalInformationPresenter.java
xtc841113/Medical-Service-System
0c1ea91b4b878766c918b7161b85f829afa15922
[ "Apache-2.0" ]
null
null
null
project/server/accountManagementService/src/main/java/ntut/csie/accountManagementService/adapter/presenter/user/ModifyPersonalInformationPresenter.java
xtc841113/Medical-Service-System
0c1ea91b4b878766c918b7161b85f829afa15922
[ "Apache-2.0" ]
null
null
null
package ntut.csie.accountManagementService.adapter.presenter.user; import ntut.csie.accountManagementService.adapter.presenter.Presenter; import ntut.csie.accountManagementService.useCase.modifyPersonalInformation.ModifyPersonalInformationOutput; public class ModifyPersonalInformationPresenter implements Presenter<ModifyPersonalInformationOutput, ModifyPersonalInformationViewModel>, ModifyPersonalInformationOutput { private String outputMessage; @Override public ModifyPersonalInformationViewModel buildViewModel() { ModifyPersonalInformationViewModel viewModel = new ModifyPersonalInformationViewModel(); viewModel.setOutputMessage(outputMessage); return viewModel; } @Override public String getOutputMessage() { return outputMessage; } @Override public void setOutputMessage(String outputMessage) { this.outputMessage = outputMessage; } }
35.769231
172
0.797849
da61f928c89c1942d8074a8b38921a85327caadc
2,384
php
PHP
app/Http/Controllers/CommentController.php
drenja1994/bobby-guchi
49c865d6f22b6af99548bb2438c57248244c8205
[ "MIT" ]
1
2021-02-12T08:46:24.000Z
2021-02-12T08:46:24.000Z
app/Http/Controllers/CommentController.php
drenja1994/bobby-guchi
49c865d6f22b6af99548bb2438c57248244c8205
[ "MIT" ]
null
null
null
app/Http/Controllers/CommentController.php
drenja1994/bobby-guchi
49c865d6f22b6af99548bb2438c57248244c8205
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers; use Validator; use App\Models\Menu; use App\Models\Post; use App\Models\Slika; use App\Models\Comment; use Illuminate\Http\Request; use Illuminate\Support\Facades\File; use Illuminate\Support\Facades\DB; class CommentController extends Controller { //put your code here private $data = []; public function __construct() { // Zadatak 1 - prikaz stavki menija // Pre svega - .env podesiti parametre za pristup bazi $menu = new Menu(); $this->data['menus'] = $menu->getAll(); // var_dump($this->data['menus']); } public function index(){ $komentar = new Komentar(); $this->data['komentari'] = $komentar->getAll(); return view('pages.radKomentari', $this->data); } public function store($id, Request $request){ $ident=$id; $kident= \session()->get('user')->id; try { $komentar = new Comment(); $komentar->user_id = $kident; $komentar->post_id = $ident; $komentar->text = $request->get('commentText'); $rez = $komentar->save(); if($rez == 1){ return redirect( asset('/posts/'.$ident) )->with('message','You have succesfuly added a comment, it will show on page if admins verify it!'); } else { return redirect('/')->with('message','Error upon entering comment!'); } } catch (\Exception $ex){ \Log::error('Error: '.$ex->getMessage()); } } public function destroy($id){ $ident = $id; $komentar=new Komentar(); $rez = DB::table('komentar') ->select('*') ->where('id',$ident) ->delete(); if($rez == 1){ return redirect('/komentari')->with('message','Uspešno ste obrisali komentar!'); } else { return redirect('/komentari')->with('message','Greška pri brisanju!'); } } public function update($id) { $komentar = new Komentar(); $komentar->id = $id; $rez = $komentar->prihvatanje(); if($rez == 1){ return redirect('/komentari')->with('message','Prikaz komentara je odobren!'); } else { return redirect('/komentari')->with('message','Greška!'); } } }
22.923077
146
0.537332
b366f83191f70953314cc94597cd93d243fc16d3
1,136
py
Python
tests/test_spoc.py
canorbal/SPOC
7dd83c86bd0ac4d406d1c6cf6ce63d579a71feaf
[ "MIT" ]
3
2020-04-02T09:50:48.000Z
2021-11-27T13:23:56.000Z
tests/test_spoc.py
canorbal/SPOC
7dd83c86bd0ac4d406d1c6cf6ce63d579a71feaf
[ "MIT" ]
null
null
null
tests/test_spoc.py
canorbal/SPOC
7dd83c86bd0ac4d406d1c6cf6ce63d579a71feaf
[ "MIT" ]
1
2020-04-03T11:09:13.000Z
2020-04-03T11:09:13.000Z
import pytest from spoc import spoc, generate_spoc_model @pytest.fixture() def get_A(): n_nodes = 300 n_clusters = 5 pure_nodes = 10 A, _, _ = generate_spoc_model.generate_a(n_nodes, n_clusters, pure_nodes) return A def test_simple(): A = get_A() spoc_obj = spoc.SPOC() theta, b = spoc_obj.fit(A, 5) assert theta.shape == (300, 5) assert b.shape == (5, 5) def test_ellipsoid(): A = get_A() spoc_obj = spoc.SPOC(use_ellipsoid=True) theta, b = spoc_obj.fit(A, 5) assert theta.shape == (300, 5) assert b.shape == (5, 5) def test_use_cvxpy(): A = get_A() spoc_obj = spoc.SPOC(use_cvxpy=True) theta, b = spoc_obj.fit(A, 5) assert theta.shape == (300, 5) assert b.shape == (5, 5) def test_use_convex_hull(): A = get_A() spoc_obj = spoc.SPOC(use_convex_hull=True) theta, b = spoc_obj.fit(A, 5) assert theta.shape == (300, 5) assert b.shape == (5, 5) def test_bootstrap(): A = get_A() spoc_obj = spoc.SPOC(use_bootstrap=True) theta, b = spoc_obj.fit(A, 5) assert theta.shape == (300, 5) assert b.shape == (5, 5)
21.846154
77
0.614437
df12e13454d934667daea2baa6c2527d4bf04e54
511
rb
Ruby
test/automated/handler/input_message_is_already_applied.rb
obsidian-btc/data-aggregation-accumulator
c9fed33efdaf6647f2c1b0ced97113a7eccd13c6
[ "MIT" ]
null
null
null
test/automated/handler/input_message_is_already_applied.rb
obsidian-btc/data-aggregation-accumulator
c9fed33efdaf6647f2c1b0ced97113a7eccd13c6
[ "MIT" ]
null
null
null
test/automated/handler/input_message_is_already_applied.rb
obsidian-btc/data-aggregation-accumulator
c9fed33efdaf6647f2c1b0ced97113a7eccd13c6
[ "MIT" ]
1
2019-10-16T10:23:29.000Z
2019-10-16T10:23:29.000Z
require_relative '../automated_init' context "Accumulate Handles Input Message that Has Already Been Applied" do input_message = Controls::Messages::Input::Initial.example accumulate = Controls::Accumulate.example write = SubstAttr::Substitute.(:write, accumulate) accumulate.accumulate input_message test "Nothing is written to output stream" do refute write do written? end end test "Nothing is stored in cache" do refute accumulate.cache do put? end end end
21.291667
75
0.729941
6414b2bb81f916f42d0de106b6b344bee2274d8c
67
py
Python
epson_projector/version.py
xWizard360/epson_projector
059cfa77b04cc31da6b191facf594788304ffaeb
[ "MIT" ]
null
null
null
epson_projector/version.py
xWizard360/epson_projector
059cfa77b04cc31da6b191facf594788304ffaeb
[ "MIT" ]
null
null
null
epson_projector/version.py
xWizard360/epson_projector
059cfa77b04cc31da6b191facf594788304ffaeb
[ "MIT" ]
null
null
null
"""Version of Epson projector module.""" __version__ = '0.2.3.500'
22.333333
40
0.686567
448220a84bd89d97b3a7842070073f389ae0093b
1,494
py
Python
src/get_data.py
sukilsiva/ML-WorkFlow
a66b9c2b8ccab5cdc800a1c00133cb5fc5629792
[ "MIT" ]
null
null
null
src/get_data.py
sukilsiva/ML-WorkFlow
a66b9c2b8ccab5cdc800a1c00133cb5fc5629792
[ "MIT" ]
null
null
null
src/get_data.py
sukilsiva/ML-WorkFlow
a66b9c2b8ccab5cdc800a1c00133cb5fc5629792
[ "MIT" ]
null
null
null
from numpy.core.numeric import flatnonzero import pandas as pd from pandas.core.indexes.base import Index import sqlalchemy import argparse import yaml pd.pandas.set_option("display.max_columns", None) def read_params(config_path): with open(config_path) as yaml_file: config = yaml.safe_load(yaml_file) return config def get_input_data(config_path): config = read_params(config_path) #print(config) data_path=config["data_source"]["sql_source"] db = yaml.full_load(open('database.yaml')) username = db['mysql_user'] password = db['mysql_password'] host = db['mysql_host'] dbname = db['mysql_db'] #print(username, password, host, dbname) #print("mysql+pymysql://"+username+":"+password+"@"+host+"/"+dbname) engine = sqlalchemy.create_engine("mysql+pymysql://"+username+":"+password+"@"+host+"/"+dbname) original_data = pd.read_sql_table("customerdata",engine, index_col=0) app_data = pd.read_sql_table("webappdata",engine, index_col=0) #print(original_data.head()) #print(app_data.head()) data = pd.concat([original_data, app_data],axis=0) data.reset_index(drop=True, inplace=True) #print(data.tail()) data.to_csv(data_path,sep=",",encoding="utf-8", index=False) return data if __name__ == "__main__": args = argparse.ArgumentParser() args.add_argument("--config",default="params.yaml") parsed_args = args.parse_args() results=get_input_data(config_path=parsed_args.config)
35.571429
99
0.707497
e0530d7ef5eab3ea060b93540550ff6d65dd99c4
6,150
h
C
OpenSim/Tools/InverseKinematicsTool.h
mcx/opensim-core
c109f8cec3a81c732f335cd39752da6ae573b604
[ "Apache-2.0" ]
532
2015-03-13T18:51:10.000Z
2022-03-27T08:08:29.000Z
OpenSim/Tools/InverseKinematicsTool.h
mcx/opensim-core
c109f8cec3a81c732f335cd39752da6ae573b604
[ "Apache-2.0" ]
2,701
2015-01-03T21:33:34.000Z
2022-03-30T07:13:41.000Z
OpenSim/Tools/InverseKinematicsTool.h
mcx/opensim-core
c109f8cec3a81c732f335cd39752da6ae573b604
[ "Apache-2.0" ]
271
2015-02-16T23:25:29.000Z
2022-03-30T20:12:17.000Z
#ifndef OPENSIM_INVERSE_KINEMATICS_TOOL_H_ #define OPENSIM_INVERSE_KINEMATICS_TOOL_H_ /* -------------------------------------------------------------------------- * * OpenSim: InverseKinematicsTool.h * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2017 Stanford University and the Authors * * Author(s): Ajay Seth * * * * Licensed under the Apache License, Version 2.0 (the "License"); you may * * not use this file except in compliance with the License. You may obtain a * * copy of the License at http://www.apache.org/licenses/LICENSE-2.0. * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * -------------------------------------------------------------------------- */ #include "osimToolsDLL.h" #include <OpenSim/Common/Object.h> #include <OpenSim/Tools/IKTaskSet.h> #include <OpenSim/Tools/InverseKinematicsToolBase.h> namespace OpenSim { class Model; class MarkersReference; class CoordinateReference; //============================================================================= //============================================================================= /** * A Tool that performs an Inverse Kinematics analysis with a given model. * Inverse kinematics is the solution of internal coordinates that poses * the model such that the landmark locations (markers), affixed to the model, * minimize the weighted least-squares error with observations of markers * in spatial coordinates. Observations of coordinates can also be included. * * @author Ajay Seth * @version 1.0 */ class OSIMTOOLS_API InverseKinematicsTool : public InverseKinematicsToolBase { OpenSim_DECLARE_CONCRETE_OBJECT(InverseKinematicsTool, InverseKinematicsToolBase); public: OpenSim_DECLARE_UNNAMED_PROPERTY( IKTaskSet, "Markers and coordinates to be considered (tasks) and their weightings. " "The sum of weighted-squared task errors composes the cost function."); OpenSim_DECLARE_PROPERTY(marker_file, std::string, "TRC file (.trc) containing the time history of observations of marker " "positions obtained during a motion capture experiment. Markers in this " "file that have a corresponding task and model marker are included."); OpenSim_DECLARE_PROPERTY(coordinate_file, std::string, "The name of the storage (.sto or .mot) file containing the time " "history of coordinate observations. Coordinate values from this file are " "included if there is a corresponding model coordinate and task. "); OpenSim_DECLARE_PROPERTY(report_marker_locations, bool, "Flag indicating whether or not to report model marker locations. " "Note, model marker locations are expressed in Ground."); //============================================================================= // METHODS //============================================================================= //-------------------------------------------------------------------------- // CONSTRUCTION //-------------------------------------------------------------------------- public: virtual ~InverseKinematicsTool(); InverseKinematicsTool(); InverseKinematicsTool(const std::string &aFileName, bool aLoadModel=true) SWIG_DECLARE_EXCEPTION; /* Handle reading older formats/Versioning */ void updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber=-1) override; //---- Setters and getters for various attributes void setMarkerDataFileName(const std::string& markerDataFileName) { upd_marker_file() = markerDataFileName; }; const std::string& getMarkerDataFileName() const { return get_marker_file(); }; void setCoordinateFileName(const std::string& coordDataFileName) { upd_coordinate_file() = coordDataFileName; }; const std::string& getCoordinateFileName() const { return get_coordinate_file(); }; IKTaskSet& getIKTaskSet() { return upd_IKTaskSet(); } //-------------------------------------------------------------------------- // INTERFACE //-------------------------------------------------------------------------- bool run() override SWIG_DECLARE_EXCEPTION; #ifndef SWIG /** @cond **/ // hide from Doxygen #endif // For testing/debugging it is necessary to know exactly what are the // MarkersReference (set of marker trajectories and their weights) and // CoordinateReferences that are being used by the InverseKinematicsSolver. void populateReferences(MarkersReference& markersReference, SimTK::Array_<CoordinateReference>&coordinateReferences) const; #ifndef SWIG /** @endcond **/ #endif private: void constructProperties(); //============================================================================= }; // END of class InverseKinematicsTool //============================================================================= } // namespace #endif // OPENSIM_INVERSE_KINEMATICS_TOOL_H_
47.674419
101
0.551545
23ff249346b8b301345d554859c5a79d8672b697
1,323
js
JavaScript
src/components/GIF.js
grantreighard/ghr-eaze-front-end-project
3ca5d019cbdeb55134c73be61fabb248ab111ecc
[ "MIT" ]
null
null
null
src/components/GIF.js
grantreighard/ghr-eaze-front-end-project
3ca5d019cbdeb55134c73be61fabb248ab111ecc
[ "MIT" ]
null
null
null
src/components/GIF.js
grantreighard/ghr-eaze-front-end-project
3ca5d019cbdeb55134c73be61fabb248ab111ecc
[ "MIT" ]
null
null
null
import React, { Component } from 'react'; import AOS from 'aos'; import './aos.css'; class GIF extends Component { constructor(props) { super(props); this.state = { showDetails: false } } toggleShow = () => { this.setState({showDetails: this.state.showDetails ? false : true}) } componentDidMount = () => { AOS.init({duration: 2000}); } render () { return( <div className="GIFcontainer"> <img src={`https://media.giphy.com/media/${this.props.gif.id}/giphy.gif`} alt={this.props.gif.slug} onClick={this.toggleShow} width="400" className="GIFpic" data-aos="flip-up"/> <ul> {this.state.showDetails ? this.props.gif.title ? <li>{this.props.gif.title}</li> : null : null} {this.state.showDetails ? this.props.gif.username ? <li>By: {this.props.gif.username}</li> : null : null} {this.state.showDetails ? this.props.gif.rating ? <li>Rating: {this.props.gif.rating.toUpperCase()}</li> : null : null} {this.state.showDetails ? this.props.gif.source_post_url ? <li><a href={this.props.gif.source_post_url}>Source</a></li> : null : null} </ul> </div> ) } } export default GIF;
36.75
193
0.558579
28d4d497f78bd1d77c31b05e233b43565a8c733d
1,021
dart
Dart
lib/screens/preprocess/cubit/preprocess_state.dart
1998apoorvmalik/teachable_image_classifier
353e683f903927c3c9bd48702cee31a09ee33fe9
[ "MIT" ]
null
null
null
lib/screens/preprocess/cubit/preprocess_state.dart
1998apoorvmalik/teachable_image_classifier
353e683f903927c3c9bd48702cee31a09ee33fe9
[ "MIT" ]
null
null
null
lib/screens/preprocess/cubit/preprocess_state.dart
1998apoorvmalik/teachable_image_classifier
353e683f903927c3c9bd48702cee31a09ee33fe9
[ "MIT" ]
1
2022-01-10T02:41:48.000Z
2022-01-10T02:41:48.000Z
part of 'preprocess_cubit.dart'; class PreprocessState extends Equatable { PreprocessState({ this.selectedImagePath, this.processedImagePath, this.selectedTool, this.findContours = false, }); final PreprocessTool? selectedTool; final String? selectedImagePath; final String? processedImagePath; final bool findContours; factory PreprocessState.initial() => PreprocessState(); @override List<Object?> get props => [selectedTool, selectedImagePath, processedImagePath, findContours]; @override bool get stringify => true; PreprocessState copyWith({ PreprocessTool? selectedTool, String? selectedImagePath, String? processedImagePath, bool? findContours, }) { return PreprocessState( selectedTool: selectedTool ?? this.selectedTool, selectedImagePath: selectedImagePath ?? this.selectedImagePath, processedImagePath: processedImagePath ?? this.processedImagePath, findContours: findContours ?? this.findContours, ); } }
26.179487
74
0.733595
54cce77dd4ffa51254c802306916d5f517d36f14
3,105
rb
Ruby
dashboard/app/models/levels/bounce.rb
yinyuecheng1/code-org
a689bc502b3cd490cce0e8cc60b59d5656c22b88
[ "Apache-2.0" ]
null
null
null
dashboard/app/models/levels/bounce.rb
yinyuecheng1/code-org
a689bc502b3cd490cce0e8cc60b59d5656c22b88
[ "Apache-2.0" ]
null
null
null
dashboard/app/models/levels/bounce.rb
yinyuecheng1/code-org
a689bc502b3cd490cce0e8cc60b59d5656c22b88
[ "Apache-2.0" ]
null
null
null
# == Schema Information # # Table name: levels # # id :integer not null, primary key # game_id :integer # name :string(255) not null # created_at :datetime # updated_at :datetime # level_num :string(255) # ideal_level_source_id :integer # user_id :integer # properties :text(65535) # type :string(255) # md5 :string(255) # published :boolean default(FALSE), not null # notes :text(65535) # audit_log :text(65535) # # Indexes # # index_levels_on_game_id (game_id) # index_levels_on_name (name) # class Bounce < Grid serialized_attrs %w( ball_direction fail_on_ball_exit failure_condition goal min_workspace_height scale soft_buttons success_condition theme timeout_failure_tick use_flag_goal free_play ) validate :validate_skin_and_theme def validate_skin_and_theme return unless skin && theme # the sports skin can have any theme except retro sport_skin_non_sport_theme = ( skin === "sports" && theme === "retro" ) # the bounce and basketball skins can only have retro or basketball themes sport_theme_non_sport_skin = ( %(bounce basketball).include?(skin) && !%(retro basketball).include?(theme) ) errors.add(:theme, "#{skin} skin and #{theme} theme are incompatible") if sport_skin_non_sport_theme || sport_theme_non_sport_skin end def self.soft_buttons %w( leftButton rightButton downButton upButton ) end def self.themes ["", "retro", "basketball", "soccer", "hockey", "football"] end # List of possible skins, the first is used as a default. def self.skins %w(bounce basketball sports) end def self.create_from_level_builder(params, level_params) puts params puts level_params create!( level_params.merge( user: params[:user], game: Game.bounce, level_num: 'custom', ) ) end def self.parse_maze(maze_json, _ = nil) maze_json = maze_json.to_json if maze_json.is_a? Array {'maze' => JSON.parse(maze_json).map {|row| row.map {|cell| Integer(cell['tileType'])}}.to_json} end def toolbox(type) <<-XML.strip_heredoc.chomp <block type="bounce_moveLeft"></block> <block type="bounce_moveRight"></block> <block type="bounce_bounceBall"></block> <block type="bounce_playSound"></block> <block type="bounce_incrementPlayerScore"></block> <block type="bounce_incrementOpponentScore"></block> <block type="bounce_launchBall"></block> <block type="bounce_setTeam"></block> <block type="bounce_setPaddleSpeed"></block> <block type="bounce_setPaddleDropdown"></block> <block type="bounce_setBackground"></block> <block type="bounce_setBall"></block> <block type="bounce_setPaddle"></block> <block type="bounce_setBallSpeed"></block> XML end end
27
100
0.625443
af96d1e10d7aaff8d25288ea80abcc1f1559e666
1,382
py
Python
app.py
Tobolov/HorizonTology
1dfade48e7a9d4c7b9142a3c4a85b3c2906c14ae
[ "MIT" ]
null
null
null
app.py
Tobolov/HorizonTology
1dfade48e7a9d4c7b9142a3c4a85b3c2906c14ae
[ "MIT" ]
null
null
null
app.py
Tobolov/HorizonTology
1dfade48e7a9d4c7b9142a3c4a85b3c2906c14ae
[ "MIT" ]
null
null
null
from flask import Flask, render_template, request from python.dotmapgenerator import * app = Flask(__name__) app.config['DEBUG'] = True app.config['TEMPLATES_AUTO_RELOAD'] = True @app.route('/') def index(): return render_template('index.html') METHOD_AUTOSIZE = 1 METHOD_REPEAT = 2 @app.route('/app.html') def process(): error = lambda: render_template('process.html', generated_text="ERROR") if len(request.args) != 0: inner = request.args.get("text[main]") if not inner: return error() outer = request.args.get("text[wrapper]") if not outer: return error() method = request.args.get("options[method]") if not method: return error() font = request.args.get("options[font]") if not font: return error() method = int(method) if method == METHOD_AUTOSIZE: error() elif int(method) == METHOD_REPEAT: size = request.args.get("options[size]") if not size: return error() text = wrap_text_in_text_repeat(inner, outer, font, size) else: error() return render_template('process.html', generated_text=text) else: return render_template('app.html') if __name__ == '__main__': generate_font_paths(app) app.run()
21.936508
75
0.592619
dc722604390903427d178c5dca6780bce4917e26
5,300
tsx
TypeScript
x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.tsx
Raven283/kibana
cec09af7370f88f6669f537cc3940cd3248a0e0a
[ "Apache-2.0" ]
null
null
null
x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.tsx
Raven283/kibana
cec09af7370f88f6669f537cc3940cd3248a0e0a
[ "Apache-2.0" ]
null
null
null
x-pack/plugins/security_solution/public/detections/components/value_lists_management_modal/modal.tsx
Raven283/kibana
cec09af7370f88f6669f537cc3940cd3248a0e0a
[ "Apache-2.0" ]
null
null
null
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ import React, { useCallback, useEffect, useState } from 'react'; import { EuiButton, EuiModal, EuiModalBody, EuiModalFooter, EuiModalHeader, EuiModalHeaderTitle, EuiOverlayMask, EuiSpacer, } from '@elastic/eui'; import { ListSchema, exportList, useFindLists, useDeleteList, useCursor, } from '../../../shared_imports'; import { useKibana } from '../../../common/lib/kibana'; import { useAppToasts } from '../../../common/hooks/use_app_toasts'; import { GenericDownloader } from '../../../common/components/generic_downloader'; import * as i18n from './translations'; import { ValueListsTable } from './table'; import { ValueListsForm } from './form'; interface ValueListsModalProps { onClose: () => void; showModal: boolean; } export const ValueListsModalComponent: React.FC<ValueListsModalProps> = ({ onClose, showModal, }) => { const [pageIndex, setPageIndex] = useState(0); const [pageSize, setPageSize] = useState(5); const [cursor, setCursor] = useCursor({ pageIndex, pageSize }); const { http } = useKibana().services; const { start: findLists, ...lists } = useFindLists(); const { start: deleteList, result: deleteResult } = useDeleteList(); const [exportListId, setExportListId] = useState<string>(); const [deletingListIds, setDeletingListIds] = useState<string[]>([]); const { addError, addSuccess } = useAppToasts(); const fetchLists = useCallback(() => { findLists({ cursor, http, pageIndex: pageIndex + 1, pageSize }); }, [cursor, http, findLists, pageIndex, pageSize]); const handleDelete = useCallback( ({ id }: { id: string }) => { setDeletingListIds([...deletingListIds, id]); deleteList({ http, id }); }, [deleteList, deletingListIds, http] ); useEffect(() => { if (deleteResult != null && deletingListIds.length > 0) { setDeletingListIds([...deletingListIds.filter((id) => id !== deleteResult.id)]); fetchLists(); } }, [deleteResult, deletingListIds, fetchLists]); const handleExport = useCallback( async ({ ids }: { ids: string[] }) => exportList({ http, listId: ids[0], signal: new AbortController().signal }), [http] ); const handleExportClick = useCallback(({ id }: { id: string }) => setExportListId(id), []); const handleExportComplete = useCallback(() => setExportListId(undefined), []); const handleTableChange = useCallback( ({ page: { index, size } }: { page: { index: number; size: number } }) => { setPageIndex(index); setPageSize(size); }, [setPageIndex, setPageSize] ); const handleUploadError = useCallback( (error: Error) => { if (error.name !== 'AbortError') { addError(error, { title: i18n.UPLOAD_ERROR }); } }, [addError] ); const handleUploadSuccess = useCallback( (response: ListSchema) => { addSuccess({ text: i18n.uploadSuccessMessage(response.name), title: i18n.UPLOAD_SUCCESS_TITLE, }); fetchLists(); }, // eslint-disable-next-line react-hooks/exhaustive-deps [addSuccess] ); useEffect(() => { if (showModal) { fetchLists(); } }, [showModal, fetchLists]); useEffect(() => { if (!lists.loading && lists.result?.cursor) { setCursor(lists.result.cursor); } }, [lists.loading, lists.result, setCursor]); if (!showModal) { return null; } const tableItems = (lists.result?.data ?? []).map((item) => ({ ...item, isExporting: item.id === exportListId, isDeleting: deletingListIds.includes(item.id), })); const pagination = { pageIndex, pageSize, totalItemCount: lists.result?.total ?? 0, hidePerPageOptions: true, }; return ( <EuiOverlayMask onClick={onClose}> <EuiModal onClose={onClose} maxWidth={800}> <EuiModalHeader> <EuiModalHeaderTitle>{i18n.MODAL_TITLE}</EuiModalHeaderTitle> </EuiModalHeader> <EuiModalBody> <ValueListsForm onSuccess={handleUploadSuccess} onError={handleUploadError} /> <EuiSpacer /> <ValueListsTable items={tableItems} loading={lists.loading} onDelete={handleDelete} onExport={handleExportClick} onChange={handleTableChange} pagination={pagination} /> </EuiModalBody> <EuiModalFooter> <EuiButton data-test-subj="value-lists-modal-close-action" onClick={onClose}> {i18n.CLOSE_BUTTON} </EuiButton> </EuiModalFooter> </EuiModal> <GenericDownloader filename={exportListId ?? 'download.txt'} ids={exportListId != null ? [exportListId] : undefined} onExportSuccess={handleExportComplete} onExportFailure={handleExportComplete} exportSelectedData={handleExport} /> </EuiOverlayMask> ); }; ValueListsModalComponent.displayName = 'ValueListsModalComponent'; export const ValueListsModal = React.memo(ValueListsModalComponent); ValueListsModal.displayName = 'ValueListsModal';
30.285714
93
0.644151
239cf6b4ceee20660176a831cdf4a1767094b104
256
js
JavaScript
src/assets/scripts/scrollto.js
abitofjoey/auff_unna_de
2b615d043e6817fcaf8e7a8a0535afb9e5307cd5
[ "MIT" ]
null
null
null
src/assets/scripts/scrollto.js
abitofjoey/auff_unna_de
2b615d043e6817fcaf8e7a8a0535afb9e5307cd5
[ "MIT" ]
16
2020-09-07T14:10:18.000Z
2022-02-26T18:55:36.000Z
src/assets/scripts/scrollto.js
abitofjoey/auff_unna_de
2b615d043e6817fcaf8e7a8a0535afb9e5307cd5
[ "MIT" ]
1
2019-10-13T08:58:37.000Z
2019-10-13T08:58:37.000Z
$( document ).ready(function() { $(".scrollto").click(function() { let a_href = $(this).attr('href'); $([document.documentElement, document.body]).animate({ scrollTop: $(a_href).offset().top }, 1000); }); });
21.333333
62
0.519531
0a4f6eaded3e075a5c417819bc6b57bc0b4a96cd
4,724
cs
C#
Healthcare/ProcedureCheckIn.cs
econmed/ImageServer20
2339c32e5fee68458c1c0bd8c638f964b3bc8b8a
[ "Apache-2.0" ]
1
2017-06-08T21:47:22.000Z
2017-06-08T21:47:22.000Z
Healthcare/ProcedureCheckIn.cs
econmed/ImageServer20
2339c32e5fee68458c1c0bd8c638f964b3bc8b8a
[ "Apache-2.0" ]
null
null
null
Healthcare/ProcedureCheckIn.cs
econmed/ImageServer20
2339c32e5fee68458c1c0bd8c638f964b3bc8b8a
[ "Apache-2.0" ]
2
2017-06-08T21:47:22.000Z
2020-01-01T04:37:44.000Z
#region License // Copyright (c) 2009, ClearCanvas Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of ClearCanvas Inc. 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 OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY // OF SUCH DAMAGE. #endregion using System; using System.Collections; using System.Text; using ClearCanvas.Common; using ClearCanvas.Enterprise.Core; using ClearCanvas.Workflow; namespace ClearCanvas.Healthcare { /// <summary> /// ProcedureCheckIn entity /// </summary> public partial class ProcedureCheckIn : ClearCanvas.Enterprise.Core.Entity { /// <summary> /// This method is called from the constructor. Use this method to implement any custom /// object initialization. /// </summary> private void CustomInitialize() { } #region Public Operations /// <summary> /// Check in the procedure, optionally specifying a check-in time. If not specified, /// the current time is assumed. /// </summary> public virtual void CheckIn(DateTime? checkInTime) { if (_checkInTime != null) throw new WorkflowException("Procedure already checked-in."); _checkInTime = checkInTime ?? Platform.Time; } /// <summary> /// Check out the procedure, optionally specifying a check-out time. If not specified, /// the current time is assumed. /// </summary> public virtual void CheckOut(DateTime? checkOutTime) { if (_checkOutTime != null) throw new WorkflowException("Procedure already checked-out."); _checkOutTime = checkOutTime ?? Platform.Time; } /// <summary> /// Returns true if this procedure is pre check-in (patient has not yet checked-in). /// </summary> public virtual bool IsPreCheckIn { get { return _checkInTime == null; } } /// <summary> /// Returns true if the patient is currently checked-in for this procedure. /// </summary> public virtual bool IsCheckedIn { get { return !IsPreCheckIn && !IsCheckedOut; } } /// <summary> /// Returns true if the patient has checked-out for this procedure. /// </summary> public virtual bool IsCheckedOut { get { return _checkOutTime != null; } } #endregion /// <summary> /// Reverts Check-In status if not already checked out /// </summary> public virtual void RevertCheckIn() { if (!IsCheckedOut) _checkInTime = null; else throw new WorkflowException("Cannot revert check-in status of a procedure already checked-out."); } /// <summary> /// Shifts the object in time by the specified number of days, which may be negative or positive. /// </summary> /// <remarks> /// The method is not intended for production use, but is provided for the purpose /// of generating back-dated data for demos and load-testing. /// </remarks> /// <param name="minutes"></param> protected internal virtual void TimeShift(int minutes) { _checkInTime = _checkInTime.HasValue ? _checkInTime.Value.AddMinutes(minutes) : _checkInTime; _checkOutTime = _checkOutTime.HasValue ? _checkOutTime.Value.AddMinutes(minutes) : _checkOutTime; } } }
35.518797
114
0.672312
b02f77c76168ec6de1eb6736f7ad197a6775b213
2,439
py
Python
soc/python/modifyDBFiles.py
idea-fasoc/fasoc
5a1fc8cf980b24a48b17f4447f13fb50d49e366a
[ "MIT" ]
48
2019-09-16T09:49:54.000Z
2022-02-09T20:59:10.000Z
soc/python/modifyDBFiles.py
idea-fasoc/fasoc
5a1fc8cf980b24a48b17f4447f13fb50d49e366a
[ "MIT" ]
18
2019-10-15T04:17:35.000Z
2021-05-25T00:12:52.000Z
soc/python/modifyDBFiles.py
idea-fasoc/fasoc
5a1fc8cf980b24a48b17f4447f13fb50d49e366a
[ "MIT" ]
8
2019-10-15T17:27:41.000Z
2022-01-26T20:42:07.000Z
#!/usr/bin/env python3 # MIT License # Copyright (c) 2018 The University of Michigan # 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. import os import json def modifyDBFiles(file,postfix,new_module_name,old_module_name): if postfix != '.db' and postfix != '.gds.gz': if postfix == '.json': with open(file, "r") as f: fdata = json.load(f) fdata["module_name"] = new_module_name with open(file, "w") as f: json.dump(fdata, f, indent = True) else: with open (file,'r') as f: fdata=f.read() if postfix == '.lef': fdata = fdata.replace('MACRO ' + old_module_name, 'MACRO ' + new_module_name) fdata = fdata.replace('FOREIGN ' + old_module_name, 'FOREIGN ' + new_module_name) fdata = fdata.replace('END ' + old_module_name, 'END ' + new_module_name) elif postfix == '.lib': fdata = fdata.replace('library("' + old_module_name, 'library("' + new_module_name) fdata = fdata.replace('cell( ' + old_module_name, 'cell( ' + new_module_name) elif postfix == '.spi' or postfix == '.cdl': fdata = fdata.replace('.SUBCKT ' + old_module_name + ' ', '.SUBCKT ' + new_module_name + ' ') elif postfix == '.v' or postfix == '.lvs.v': fdata = fdata.replace('module ' + old_module_name, 'module ' + new_module_name) fdata = fdata.replace('# Design: ' + old_module_name, '# Design: ' + new_module_name) with open(file, 'w') as f: f.write(fdata)
42.789474
113
0.697827
1098486a6c369adc29b98b37d05f8db82a2fa008
240
lua
Lua
Police_Base_1.lua
xVoid-xyz/Roblox-Scripts
7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2
[ "BSD-3-Clause" ]
70
2021-02-09T17:21:32.000Z
2022-03-28T12:41:42.000Z
Police_Base_1.lua
xVoid-xyz/Roblox-Scripts
7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2
[ "BSD-3-Clause" ]
4
2021-08-19T22:05:58.000Z
2022-03-19T18:58:01.000Z
Police_Base_1.lua
xVoid-xyz/Roblox-Scripts
7eb176fa654f2ea5fbc6bcccced1b15df7ed82c2
[ "BSD-3-Clause" ]
325
2021-02-26T22:23:41.000Z
2022-03-31T19:36:12.000Z
getglobal game getfield -1 Players getfield -1 LocalPlayer getfield -1 Character getfield -1 HumanoidRootPart getglobal CFrame getfield -1 new pushnumber -1130.11426 pushnumber 17.950058 pushnumber -1593.09766 pcall 3 1 0 setfield -3 CFrame
20
28
0.825
6d8bbb86b5ac26f7a7b7f718e6564c48321e1c8c
7,560
h
C
src/list.h
kasymovga/taisei
8aad971114186b0679ac5447381c427d7319fe21
[ "CC-BY-4.0" ]
null
null
null
src/list.h
kasymovga/taisei
8aad971114186b0679ac5447381c427d7319fe21
[ "CC-BY-4.0" ]
null
null
null
src/list.h
kasymovga/taisei
8aad971114186b0679ac5447381c427d7319fe21
[ "CC-BY-4.0" ]
null
null
null
/* * This software is licensed under the terms of the MIT License. * See COPYING for further information. * --- * Copyright (c) 2011-2019, Lukas Weber <laochailan@web.de>. * Copyright (c) 2012-2019, Andrei Alexeyev <akari@taisei-project.org>. */ #ifndef IGUARD_list_h #define IGUARD_list_h #include "taisei.h" #if TAISEI_BUILDCONF_MALLOC_ALIGNMENT < 16 #define LIST_ALIGN alignas(TAISEI_BUILDCONF_MALLOC_ALIGNMENT) #else #define LIST_ALIGN alignas(16) #endif typedef struct ListInterface ListInterface; typedef struct List List; typedef struct ListAnchorInterface ListAnchorInterface; typedef struct ListAnchor ListAnchor; typedef struct ListContainer ListContainer; #define LIST_INTERFACE_BASE(typename) struct { \ typename *next; \ typename *prev; \ } #define LIST_INTERFACE(typename) union { \ LIST_ALIGN ListInterface list_interface; \ LIST_INTERFACE_BASE(typename); \ } struct ListInterface { LIST_INTERFACE_BASE(ListInterface); }; struct List { LIST_INTERFACE(List); }; #define LIST_ANCHOR_INTERFACE_BASE(typename) struct { \ typename *first; \ typename *last; \ } #define LIST_ANCHOR_INTERFACE(typename) union { \ ListAnchorInterface list_anchor_interface; \ LIST_ANCHOR_INTERFACE_BASE(typename); \ } #define LIST_ANCHOR(typename) struct { \ LIST_ANCHOR_INTERFACE(typename); \ } struct ListAnchorInterface { LIST_ANCHOR_INTERFACE_BASE(ListInterface); }; struct ListAnchor { LIST_ANCHOR_INTERFACE(List); }; struct ListContainer { LIST_INTERFACE(ListContainer); void *data; }; typedef void* (*ListForeachCallback)(List **head, List *elem, void *arg); typedef void* (*ListAnchorForeachCallback)(ListAnchor *list, List *elem, void *arg); typedef List* (*ListInsertionRule)(List **dest, List *elem); typedef List* (*ListAnchorInsertionRule)(ListAnchor *dest, List *elem); typedef int (*ListPriorityFunc)(List *elem); List* list_insert(List **dest, List *elem) attr_nonnull(1, 2); List* list_push(List **dest, List *elem) attr_nonnull(1, 2); List* list_append(List **dest, List *elem) attr_nonnull(1, 2); List* list_insert_at_priority_head(List **dest, List *elem, int prio, ListPriorityFunc prio_func) attr_hot attr_nonnull(1, 2, 4); List* list_insert_at_priority_tail(List **dest, List *elem, int prio, ListPriorityFunc prio_func) attr_hot attr_nonnull(1, 2, 4); List* list_pop(List **dest) attr_nonnull(1); List* list_unlink(List **dest, List *elem) attr_nonnull(1, 2); void* list_foreach(List **dest, ListForeachCallback callback, void *arg) attr_nonnull(1, 2); void* list_callback_free_element(List **dest, List *elem, void *arg); void list_free_all(List **dest) attr_nonnull(1); List* alist_insert(ListAnchor *list, List *ref, List *elem) attr_nonnull(1, 3); List* alist_push(ListAnchor *list, List *elem) attr_nonnull(1, 2); List* alist_append(ListAnchor *list, List *elem) attr_nonnull(1, 2); List* alist_insert_at_priority_head(ListAnchor *list, List *elem, int prio, ListPriorityFunc prio_func) attr_hot attr_nonnull(1, 2, 4); List* alist_insert_at_priority_tail(ListAnchor *list, List *elem, int prio, ListPriorityFunc prio_func) attr_hot attr_nonnull(1, 2, 4); List* alist_pop(ListAnchor *list) attr_nonnull(1); List* alist_unlink(ListAnchor *list, List *elem) attr_nonnull(1, 2); void* alist_foreach(ListAnchor *list, ListAnchorForeachCallback callback, void *arg) attr_nonnull(1, 2); void* alist_callback_free_element(ListAnchor *list, List *elem, void *arg); void alist_free_all(ListAnchor *list) attr_nonnull(1); ListContainer* list_wrap_container(void *data) attr_returns_allocated; // type-generic macros #ifdef USE_GNU_EXTENSIONS // thorough safeguard #define LIST_CAST(expr) (__extension__ ({ \ static_assert(__builtin_types_compatible_p(ListInterface, __typeof__((*(expr)).list_interface)), \ "struct must implement ListInterface (use the LIST_INTERFACE macro)"); \ static_assert(__builtin_offsetof(__typeof__(*(expr)), list_interface) == 0, \ "list_interface must be the first member in struct"); \ CASTPTR_ASSUME_ALIGNED((expr), List); \ })) #define LIST_CAST_2(expr) (__extension__ ({ \ static_assert(__builtin_types_compatible_p(ListInterface, __typeof__((**(expr)).list_interface)), \ "struct must implement ListInterface (use the LIST_INTERFACE macro)"); \ static_assert(__builtin_offsetof(__typeof__(**(expr)), list_interface) == 0, \ "list_interface must be the first member in struct"); \ (void)ASSUME_ALIGNED(*(expr), alignof(List)); \ (List**)(expr); \ })) #define LIST_ANCHOR_CAST(expr) (__extension__ ({ \ static_assert(__builtin_types_compatible_p(ListAnchorInterface, __typeof__((*(expr)).list_anchor_interface)), \ "struct must implement ListAnchorInterface (use the LIST_ANCHOR_INTERFACE macro)"); \ static_assert(__builtin_offsetof(__typeof__(*(expr)), list_anchor_interface) == 0, \ "list_anchor_interface must be the first member in struct"); \ CASTPTR_ASSUME_ALIGNED((expr), ListAnchor); \ })) #define LIST_CAST_RETURN(e_typekey, e_return) CASTPTR_ASSUME_ALIGNED((e_return), __typeof__(*(e_typekey))) #else // basic safeguard #define LIST_CAST(expr) ((void)sizeof((*(expr)).list_interface), (List*)(expr)) #define LIST_CAST_2(expr) ((void)sizeof((**(expr)).list_interface), (List**)(expr)) #define LIST_ANCHOR_CAST(expr) ((void)sizeof((*(expr)).list_anchor_interface), (ListAnchor*)(expr)) #define LIST_CAST_RETURN(e_typekey, e_return) (void*)(e_return) #endif #define list_insert(dest,elem) \ (LIST_CAST_RETURN(elem, list_insert(LIST_CAST_2(dest), LIST_CAST(elem)))) #define alist_insert(dest,ref,elem) \ (LIST_CAST_RETURN(elem, alist_insert(LIST_ANCHOR_CAST(dest), LIST_CAST(ref), LIST_CAST(elem)))) #define list_push(dest,elem) \ (LIST_CAST_RETURN(elem, list_push(LIST_CAST_2(dest), LIST_CAST(elem)))) #define alist_push(dest,elem) \ (LIST_CAST_RETURN(elem, alist_push(LIST_ANCHOR_CAST(dest), LIST_CAST(elem)))) #define list_append(dest,elem) \ (LIST_CAST_RETURN(elem, list_append(LIST_CAST_2(dest), LIST_CAST(elem)))) #define alist_append(dest,elem) \ (LIST_CAST_RETURN(elem, alist_append(LIST_ANCHOR_CAST(dest), LIST_CAST(elem)))) #define list_insert_at_priority_head(dest,elem,prio,prio_func) \ (LIST_CAST_RETURN(elem, list_insert_at_priority_head(LIST_CAST_2(dest), LIST_CAST(elem), prio, prio_func))) #define alist_insert_at_priority_head(dest,elem,prio,prio_func) \ (LIST_CAST_RETURN(elem, alist_insert_at_priority_head(LIST_ANCHOR_CAST(dest), LIST_CAST(elem), prio, prio_func))) #define list_insert_at_priority_tail(dest,elem,prio,prio_func) \ (LIST_CAST_RETURN(elem, list_insert_at_priority_tail(LIST_CAST_2(dest), LIST_CAST(elem), prio, prio_func))) #define alist_insert_at_priority_tail(dest,elem,prio,prio_func) \ (LIST_CAST_RETURN(elem, alist_insert_at_priority_tail(LIST_ANCHOR_CAST(dest), LIST_CAST(elem), prio, prio_func))) #define list_pop(dest) \ (LIST_CAST_RETURN(*(dest), list_pop(LIST_CAST_2(dest)))) #define alist_pop(dest) \ (LIST_CAST_RETURN((dest)->first, alist_pop(LIST_ANCHOR_CAST(dest)))) #define list_unlink(dest,elem) \ (LIST_CAST_RETURN(elem, list_unlink(LIST_CAST_2(dest), LIST_CAST(elem)))) #define alist_unlink(dest,elem) \ (LIST_CAST_RETURN(elem, alist_unlink(LIST_ANCHOR_CAST(dest), LIST_CAST(elem)))) #define list_foreach(dest,callback,arg) \ list_foreach(LIST_CAST_2(dest), callback, arg) #define alist_foreach(dest,callback,arg) \ alist_foreach(LIST_ANCHOR_CAST(dest), callback, arg) #define list_free_all(dest) \ list_free_all(LIST_CAST_2(dest)) #define alist_free_all(dest) \ alist_free_all(LIST_ANCHOR_CAST(dest)) #endif // IGUARD_list_h
38.769231
135
0.770767
cdaf8327af1e2180506e1e00c48be8297261853f
478
cs
C#
src/Datory/DataType.cs
siteserver/Datory
e17899dd44cac941af56054ea32accbd392610c9
[ "MIT" ]
17
2019-04-12T16:41:04.000Z
2022-03-20T11:58:55.000Z
src/Datory/DataType.cs
siteserver/Datory
e17899dd44cac941af56054ea32accbd392610c9
[ "MIT" ]
1
2020-04-16T10:29:35.000Z
2020-04-16T10:29:35.000Z
src/Datory/DataType.cs
siteserver/Datory
e17899dd44cac941af56054ea32accbd392610c9
[ "MIT" ]
10
2019-04-04T02:25:05.000Z
2021-11-20T01:27:01.000Z
using Datory.Annotations; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Datory { [JsonConverter(typeof(StringEnumConverter))] public enum DataType { [DataEnum(DisplayName = "布尔值")] Boolean, [DataEnum(DisplayName = "日期")] DateTime, [DataEnum(DisplayName = "小数")] Decimal, [DataEnum(DisplayName = "整数")] Integer, [DataEnum(DisplayName = "备注")] Text, [DataEnum(DisplayName = "字符串")] VarChar } }
28.117647
48
0.646444
af57a83f0eb088afcab7e1110461e42ea2c0d52e
136
py
Python
ast-transformations-core/src/test/resources/org/jetbrains/research/ml/ast/transformations/comparisonUnification/data/in_1_comparison.py
JetBrains-Research/ast-transformations
0ab408af3275b520cc87a473f418c4b4dfcb0284
[ "MIT" ]
8
2021-01-19T21:15:54.000Z
2022-02-23T19:16:25.000Z
ast-transformations-core/src/test/resources/org/jetbrains/research/ml/ast/transformations/comparisonUnification/data/in_1_comparison.py
JetBrains-Research/ast-transformations
0ab408af3275b520cc87a473f418c4b4dfcb0284
[ "MIT" ]
4
2020-11-17T14:28:25.000Z
2022-02-24T07:54:28.000Z
ast-transformations-core/src/test/resources/org/jetbrains/research/ml/ast/transformations/comparisonUnification/data/in_1_comparison.py
nbirillo/ast-transformations
717706765a2da29087a0de768fc851698886dd65
[ "MIT" ]
1
2022-02-23T19:16:30.000Z
2022-02-23T19:16:30.000Z
_ = 1 < 3 _ = 1 <= 3 _ = 1 < input() and input() > 3 _ = 1 < input() and input() >= 3 _ = 1 < input() and 1 <= input() and input() >= 3
22.666667
49
0.463235
c6e7ebccf14c7b96152d3a433c512bb7da0df8b9
410
rb
Ruby
spec/range_value_spec.rb
northwoodspd/UIA.Extensions
f1bad5372c0d8642163ad0dc8ae6e394df17186e
[ "MIT" ]
4
2015-12-08T07:38:20.000Z
2017-02-27T21:17:51.000Z
spec/range_value_spec.rb
northwoodspd/UIA.Extensions
f1bad5372c0d8642163ad0dc8ae6e394df17186e
[ "MIT" ]
4
2015-07-09T18:04:05.000Z
2022-02-28T15:45:40.000Z
spec/range_value_spec.rb
northwoodspd/UIA.Extensions
f1bad5372c0d8642163ad0dc8ae6e394df17186e
[ "MIT" ]
5
2015-12-09T16:51:32.000Z
2021-10-30T06:04:13.000Z
require 'spec_helper' describe 'range valuing' do Given(:screen) { on(MainScreen) } context 'getting / setting' do When { screen.range_value = 57.2 } Then { screen.range_value == 57.2 } end context 'incrementing and decrementing' do Given { 4.times { screen.increment_range_value } } When { 2.times { screen.decrement_range_value } } Then { screen.range_value == 2 } end end
21.578947
54
0.673171
79fee04b35973b9489d8ac069667501076a6f2cd
2,689
rb
Ruby
giternal_helper.rb
thewoolleyman/giternal
e4bd4e9d627ee1b3c5b4a160d6f95111afa10b98
[ "MIT" ]
2
2015-12-25T11:43:19.000Z
2016-05-08T17:10:50.000Z
giternal_helper.rb
thewoolleyman/giternal
e4bd4e9d627ee1b3c5b4a160d6f95111afa10b98
[ "MIT" ]
null
null
null
giternal_helper.rb
thewoolleyman/giternal
e4bd4e9d627ee1b3c5b4a160d6f95111afa10b98
[ "MIT" ]
null
null
null
class GiternalHelper @@giternal_base = File.expand_path(File.dirname(__FILE__)) def self.create_main_repo FileUtils.mkdir_p tmp_path Dir.chdir(tmp_path) do FileUtils.mkdir "main_repo" Dir.chdir('main_repo') do `git init` `echo 'first content' > starter_repo` `git add starter_repo` `git commit -m "starter repo"` end end end def self.wipe_repos FileUtils.rm_r(tmp_path) if File.directory?(tmp_path) end def self.tmp_path "/tmp/giternal_test" end def self.giternal_base @@giternal_base end def self.base_project_dir tmp_path + '/main_repo' end def self.run(*args) `#{giternal_base}/bin/giternal #{args.join(' ')}` end def self.create_repo(repo_name) Dir.chdir(tmp_path) do FileUtils.mkdir_p "externals/#{repo_name}" `cd externals/#{repo_name} && git init` end add_content repo_name add_to_config_file repo_name end def self.add_to_config_file(repo_name) config_dir = tmp_path + '/main_repo/config' FileUtils.mkdir(config_dir) unless File.directory?(config_dir) Dir.chdir(config_dir) do `echo #{repo_name}: >> giternal.yml` `echo ' repo: #{external_path(repo_name)}' >> giternal.yml` `echo ' path: dependencies' >> giternal.yml` end end def self.add_content(repo_name, content=repo_name) Dir.chdir(tmp_path + "/externals/#{repo_name}") do `echo #{content} >> #{content} && git add #{content}` `git commit #{content} -m "added content to #{content}"` end end def self.external_path(repo_name) File.expand_path(tmp_path + "/externals/#{repo_name}") end def self.checked_out_path(repo_name) File.expand_path(tmp_path + "/main_repo/dependencies/#{repo_name}") end def self.clean! FileUtils.rm_rf tmp_path end def self.update_externals Dir.chdir(tmp_path + '/main_repo') do GiternalHelper.run('update') end end def self.freeze_externals Dir.chdir(tmp_path + '/main_repo') do GiternalHelper.run('freeze') end end def self.unfreeze_externals Dir.chdir(tmp_path + '/main_repo') do GiternalHelper.run('unfreeze') end end def self.repo_contents(path) Dir.chdir(path) do contents = `git cat-file -p HEAD` unless contents.include?('tree') && contents.include?('author') raise "something is wrong with the repo, output doesn't contain expected git elements:\n\n #{contents}" end contents end end def self.add_external_to_ignore(repo_name) Dir.chdir(tmp_path + '/main_repo') do `echo 'dependencies/#{repo_name}' >> .gitignore` end end end
24.669725
111
0.664931
a39e125a2ee62d0464ed2be1dddc414314363db5
1,259
ts
TypeScript
megabot_client/megabot/src/userManagement/service/groupService.ts
azjaehyun/crm-react
364563b313bf492a29afc747404fcecc5f63241f
[ "MIT" ]
null
null
null
megabot_client/megabot/src/userManagement/service/groupService.ts
azjaehyun/crm-react
364563b313bf492a29afc747404fcecc5f63241f
[ "MIT" ]
null
null
null
megabot_client/megabot/src/userManagement/service/groupService.ts
azjaehyun/crm-react
364563b313bf492a29afc747404fcecc5f63241f
[ "MIT" ]
null
null
null
import {Status} from './type'; import {DataProvider} from 'ra-core'; import {Method} from 'ra-data-simple-rest/lib'; import {UserEntity} from './userService'; export type GroupState = Status; export interface GroupEntity { id: number; name: string; description: string; users: Array<UserEntity> } export interface GroupDto { name: string; description: string; status: Status; } export interface GroupData {[key: string]: GroupEntity} export default class groupService { static getListGroup = (dataProvider: DataProvider) => dataProvider.execute({ method: Method.GET, resource: `group/filter` }).then((res:any)=>(res.data.list)) static createGroup = (dataProvider: DataProvider, groupDto: GroupDto)=> dataProvider.create('group', {data: groupDto}) static deleteGroup = (dataProvider: DataProvider, groupId: number)=> /** * Uncaught (in promise) Error: {"message":"The group (Id: 6) has been removed"} * validateResponseFormat validateResponseFormat.js:12 */ //dataProvider.delete("group", {id: groupId}) dataProvider.execute({ method: Method.DELETE, resource: `group/${groupId}` }) }
29.97619
88
0.643368
1c6136ed26d45bcc6c0f97d0b3a6985fd9dd8a19
509
rb
Ruby
spec/features/users/profile_view_spec.rb
cyberplanner/Devine
114416d542714ee6d435b7749a35f586d79ce19a
[ "FSFAP" ]
null
null
null
spec/features/users/profile_view_spec.rb
cyberplanner/Devine
114416d542714ee6d435b7749a35f586d79ce19a
[ "FSFAP" ]
null
null
null
spec/features/users/profile_view_spec.rb
cyberplanner/Devine
114416d542714ee6d435b7749a35f586d79ce19a
[ "FSFAP" ]
null
null
null
require 'rails_helper' feature 'View Profiles'do scenario 'user can view projects of other users in devs' do User.create!(:id => 5, :name => 'Bob') Project.create!(:repo_id => 11111111, :name => "new project", :description => "DELETE", :user_id => 5) visit '/' signin click_link 'DEVS' click_link 'Bob' expect(page).to have_selector("ul#projects") click_link 'new project' expect(page).to have_content('new project') expect(page).to have_content('DELETE') end end
29.941176
106
0.662083
e051d95f0d5ffc8313681750870aaeba410cc170
424
asm
Assembly
oeis/347/A347501.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/347/A347501.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/347/A347501.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A347501: Number of dominating sets in the n-alkane graph. ; 17,81,405,2025,10125,50625,253125,1265625,6328125,31640625,158203125,791015625,3955078125,19775390625,98876953125,494384765625,2471923828125,12359619140625,61798095703125,308990478515625,1544952392578125,7724761962890625 seq $0,199214 ; 3*5^n+1. mov $3,$0 add $3,2 mul $3,9 add $2,$3 div $2,2 mul $3,2 div $3,10 sub $2,$3 mov $0,$2 sub $0,17 mul $0,2 add $0,17
24.941176
222
0.759434
32dd982683b190b6ed9e63d3d17ae7d93471b93d
12,815
kt
Kotlin
buildSrc/src/main/kotlin/idea/DistModelBuilder.kt
tnorbye/kotlin
b6be6a4919cd7f37426d1e8780509a22fa49e1b1
[ "Apache-2.0" ]
2
2019-01-08T01:50:40.000Z
2021-06-16T20:56:26.000Z
buildSrc/src/main/kotlin/idea/DistModelBuilder.kt
tnorbye/kotlin
b6be6a4919cd7f37426d1e8780509a22fa49e1b1
[ "Apache-2.0" ]
null
null
null
buildSrc/src/main/kotlin/idea/DistModelBuilder.kt
tnorbye/kotlin
b6be6a4919cd7f37426d1e8780509a22fa49e1b1
[ "Apache-2.0" ]
3
2019-06-17T03:29:49.000Z
2021-06-07T04:20:41.000Z
/* * Copyright 2010-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/LICENSE.txt file. */ package org.jetbrains.kotlin.buildUtils.idea import IntelliJInstrumentCodeTask import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar import idea.DistCopyDetailsMock import idea.DistModelBuildContext import org.codehaus.groovy.runtime.GStringImpl import org.gradle.api.Project import org.gradle.api.Task import org.gradle.api.artifacts.Configuration import org.gradle.api.file.FileCollection import org.gradle.api.file.FileVisitDetails import org.gradle.api.file.FileVisitor import org.gradle.api.file.SourceDirectorySet import org.gradle.api.internal.file.* import org.gradle.api.internal.file.archive.ZipFileTree import org.gradle.api.internal.file.collections.* import org.gradle.api.internal.file.copy.CopySpecInternal import org.gradle.api.internal.file.copy.DefaultCopySpec import org.gradle.api.internal.file.copy.DestinationRootCopySpec import org.gradle.api.internal.file.copy.SingleParentCopySpec import org.gradle.api.tasks.AbstractCopyTask import org.gradle.api.tasks.Copy import org.gradle.api.tasks.SourceSetOutput import org.gradle.api.tasks.Sync import org.gradle.api.tasks.bundling.AbstractArchiveTask import org.gradle.api.tasks.compile.AbstractCompile import org.gradle.internal.file.PathToFileResolver import org.gradle.jvm.tasks.Jar import java.io.File import java.io.PrintWriter import java.util.concurrent.Callable open class DistModelBuilder(val rootProject: Project, pw: PrintWriter) { val rootCtx = DistModelBuildContext(null, "ROOT", "dist", pw) val visited = mutableMapOf<Task, DistModelBuildContext>() val vfsRoot = DistVFile(null, "<root>", File("")) val refs = mutableSetOf<DistVFile>() fun visitInstrumentTask(it: IntelliJInstrumentCodeTask): DistModelBuildContext = visited.getOrPut(it) { val ctx = rootCtx.child("INSTRUMENT", it.path) ctx.setDest(it.output!!.path) processSourcePath(it.originalClassesDirs, ctx) val dest = ctx.destination if (dest != null) { DistModuleOutput(dest, it.project.path) } ctx } fun visitCompileTask(it: AbstractCompile): DistModelBuildContext = visited.getOrPut(it) { val ctx = rootCtx.child("COMPILE", it.path) ctx.setDest(it.destinationDir.path) val dest = ctx.destination if (dest != null) DistModuleOutput(dest, it.project.path) else ctx.logUnsupported("Cannot add contents: destination is unknown", it) ctx } fun visitCopyTask( copy: AbstractCopyTask, shade: Boolean = false ): DistModelBuildContext = visited.getOrPut(copy) { val context = rootCtx.child("COPY", copy.path, shade) val rootSpec = copy.rootSpec when (copy) { is Copy -> context.setDest(copy.destinationDir.path) is Sync -> context.setDest(copy.destinationDir.path) is AbstractArchiveTask -> context.setDest(copy.archivePath.path) } when (copy) { is ShadowJar -> copy.configurations.forEach { processSourcePath(it, context) } } processCopySpec(rootSpec, context) context } fun processCopySpec(spec: CopySpecInternal, ctx: DistModelBuildContext) { spec.children.forEach { when (it) { is DestinationRootCopySpec -> ctx.child("DESTINATION ROOT COPY SPEC") { newCtx -> newCtx.setDest(getRelativePath(it.destinationDir.path)) processCopySpec(it, newCtx) } is DefaultCopySpec -> ctx.child("DEFAULT COPY SPEC") { newCtx -> val buildRootResolver = it.buildRootResolver() ctx.addCopyActions(buildRootResolver.allCopyActions) newCtx.setDest(buildRootResolver.destPath.getFile(ctx.destination!!.file).path) processCopySpec(it, newCtx) it.includes newCtx.child("SINGE PARENT COPY SPEC") { child -> it.sourcePaths.forEach { processSourcePath(it, child) } } } is SingleParentCopySpec -> ctx.child("OTHER SINGE PARENT COPY SPEC") { child -> it.sourcePaths.forEach { processSourcePath(it, child) } } is CopySpecInternal -> processCopySpec(it, ctx) else -> ctx.logUnsupported("CopySpec", spec) } } } fun processSourcePath(sourcePath: Any?, ctx: DistModelBuildContext) { when { sourcePath == null -> Unit sourcePath is Jar -> ctx.child("JAR") { child -> child.addCopyOf(sourcePath.archivePath.path) } sourcePath is SourceSetOutput -> ctx.child("COMPILE") { child -> sourcePath.classesDirs.files.forEach { child.addCopyOf(it.path) } } sourcePath is Configuration -> { ctx.child("CONFIGURATION") { child -> sourcePath.resolve().forEach { child.addCopyOf(it.path) } } } sourcePath is SourceDirectorySet -> { ctx.child("SOURCES") { child -> sourcePath.srcDirs.forEach { child.addCopyOf(it.path) } } } sourcePath is MinimalFileSet -> ctx.child("MINIMAL FILE SET (${sourcePath.javaClass.simpleName})") { child -> sourcePath.files.forEach { processSourcePath(it, child) } } sourcePath is MinimalFileTree -> ctx.child("MINIMAL FILE TREE (${sourcePath.javaClass.simpleName})") { child -> sourcePath.visit(object : FileVisitor { override fun visitDir(dirDetails: FileVisitDetails) { processSourcePath(dirDetails.file, child) } override fun visitFile(fileDetails: FileVisitDetails) { processSourcePath(fileDetails.file, child) } }) } sourcePath is FileTreeAdapter && sourcePath.tree is MapFileTree -> ctx.child("FILE TREE ADAPTER OF MAP FILE TREE (${sourcePath.javaClass.simpleName})") { child -> sourcePath.visitContents(object : FileCollectionResolveContext { override fun add(element: Any): FileCollectionResolveContext { processSourcePath(element, child) return this } override fun newContext(): ResolvableFileCollectionResolveContext { error("not supported") } override fun push(fileResolver: PathToFileResolver): FileCollectionResolveContext { return this } }) } sourcePath is CompositeFileCollection -> ctx.child("COMPOSITE FILE COLLECTION") { child -> sourcePath.visitRootElements(object : FileCollectionVisitor { override fun visitDirectoryTree(directoryTree: DirectoryFileTree) { child.child("DIR TREE") { it.addCopyOf(directoryTree.dir.path) } } override fun visitTree(fileTree: FileTreeInternal) { child.child("TREE") { processSourcePath(fileTree, it) } } override fun visitCollection(fileCollection: FileCollectionInternal) { processSourcePath(fileCollection, child) } }) } sourcePath is FileTreeAdapter && sourcePath.tree is ZipFileTree -> ctx.child("ZIP FILE TREE ADAPTER") { child -> val tree = sourcePath.tree val field = tree.javaClass.declaredFields.find { it.name == "zipFile" }!! field.isAccessible = true val zipFile = field.get(tree) as File child.addCopyOf(zipFile.path) } sourcePath is FileTreeInternal -> ctx.child("FILE TREE INTERNAL") { child -> // todo: preserve or warn about filtering sourcePath.visitTreeOrBackingFile(object : FileVisitor { override fun visitFile(fileDetails: FileVisitDetails) { child.addCopyOf(fileDetails.file.path) } override fun visitDir(dirDetails: FileVisitDetails) { child.addCopyOf(dirDetails.file.path) } }) } sourcePath is FileCollection -> ctx.child("OTHER FILE COLLECTION (${sourcePath.javaClass})") { child -> try { sourcePath.files.forEach { child.addCopyOf(it.path) } } catch (t: Throwable) { child.logUnsupported("FILE COLLECTION (${t.message})", sourcePath) } } sourcePath is String || sourcePath is GStringImpl -> ctx.child("STRING") { child -> child.addCopyOf(sourcePath.toString()) } sourcePath is Callable<*> -> ctx.child("CALLABLE") { child -> processSourcePath(sourcePath.call(), child) } sourcePath is Collection<*> -> ctx.child("COLLECTION") { child -> sourcePath.forEach { processSourcePath(it, child) } } sourcePath is Copy -> ctx.child("COPY OUTPUT") { child -> val src = visitCopyTask(sourcePath).destination if (src != null) child.addCopyOf(src) // else it is added to `it`, because destination is inhereted by context } sourcePath is File -> ctx.child("FILE ${sourcePath.path}") { child -> child.addCopyOf(sourcePath.path) } else -> ctx.logUnsupported("SOURCE PATH", sourcePath) } } inline fun DistModelBuildContext.addCopyOf( src: String, body: (src: DistVFile, target: DistVFile) -> Unit = { _, _ -> Unit } ) { addCopyOf(requirePath(src), body) } fun DistModelBuildContext.transformName(srcName: String): String? { val detailsMock = DistCopyDetailsMock(this, srcName) allCopyActions.forEach { detailsMock.lastAction = it try { it.execute(detailsMock) } catch (t: DistCopyDetailsMock.E) { // skip } } val name1 = detailsMock.relativePath.lastName return if (name1.endsWith(".jar")) transformJarName(name1) else name1 } // todo: investigate why allCopyActions not working open fun transformJarName(name: String): String = name inline fun DistModelBuildContext.addCopyOf( src: DistVFile, body: (src: DistVFile, target: DistVFile) -> Unit = { _, _ -> Unit } ) { val destination = destination if (destination != null) { body(src, destination) val customTargetName = transformName(src.name) DistCopy(destination, src, customTargetName) log("+DistCopy", "${getRelativePath(src.file.path)} -> ${getRelativePath(destination.file.path)}/$customTargetName") } else logUnsupported("Cannot add copy of `$src`: destination is unknown") } fun DistModelBuildContext.setDest(path: String) { destination = vfsRoot.relativePath(path) log("INTO", getRelativePath(path)) } fun checkRefs() { refs.forEach { if (!it.hasContents && it.contents.isEmpty() && it.file.path.contains("${File.pathSeparator}build${File.pathSeparator}")) { logger.error("UNRESOLVED ${it.file}") it.contents.forEach { logger.error("+ ${it}") } } } } fun getRelativePath(path: String) = path.replace(rootProject.projectDir.path, "$") fun requirePath(targetPath: String): DistVFile { val target = vfsRoot.relativePath(targetPath) if (!File(targetPath).exists()) refs.add(target) return target } }
40.812102
174
0.575575
12e4ebbad368dfea1f289070a0989e9576a229eb
4,010
cs
C#
TestService/TestService.cs
Mallekoppie/netCorePOC
a3f643bf21933916b55ad226e1772d93c75dc41b
[ "Apache-2.0" ]
1
2018-08-13T17:27:14.000Z
2018-08-13T17:27:14.000Z
TestService/TestService.cs
Mallekoppie/netCorePOC
a3f643bf21933916b55ad226e1772d93c75dc41b
[ "Apache-2.0" ]
null
null
null
TestService/TestService.cs
Mallekoppie/netCorePOC
a3f643bf21933916b55ad226e1772d93c75dc41b
[ "Apache-2.0" ]
null
null
null
using Microsoft.AspNetCore.Mvc; using PlatformContracts; using PlatformPOC.PlatformContracts; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace TestService { [Produces("application/json")] [Route("api/Test")]// Should be in format Subsystem/Service/Version public class TestService : Controller, IServiceMethod { IPlatform _platform; IPlatformLogger _logger; IPlatformMetrics _metrics; public TestService(IPlatform platform) { _platform = platform; _logger = platform.GetLogger(typeof(TestService)); _metrics = _platform.GetMetrics(); } [HttpGet("/config")] public string GetConfig() { return $"Config retrieved: {_platform.GetConfigurarion("CustomConfigSection:SomeConfiguration")}"; } [HttpGet("claims", Name = "GetClaims")] public IEnumerable<string> GetClaims() { // Theere must be a better way var authorizationHeader = HttpContext.Request.Headers.FirstOrDefault(c => c.Key.ToLower() == "authorization"); var claims = _platform.GetTokenClaims(authorizationHeader.Value); List<String> claimTypes = new List<string>(); return claims.Select(c=> c.Type).ToList(); } // GET: api/Test [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET: api/Test/5 [HttpGet("id/{id}", Name = "GetId")] public string Get(int id) { if (id == 2) { _logger.LogInformation("Calling platform for testValue"); return _platform.GetValueForTesting(); } else { return "value"; } } [HttpGet("model", Name = "GetModel")] public JsonResult GetModel() { var model = new TestModel { Name = "test name", Surname = "Barnard" }; return new JsonResult(model); } // POST: api/Test [HttpPost] public void Post([FromBody]string value) { _logger.LogInformation("Entered Post"); } // PUT: api/Test/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { _logger.LogInformation("Entered Put"); } // DELETE: api/ApiWithActions/5 [HttpDelete("{id}")] public void Delete(int id) { _logger.LogInformation("Entered Delete"); } [HttpGet("error")] public void CreateErrorToTrackMetrics() { throw new Exception("Test exception"); } [HttpGet("remote")] public async Task<string> CallRemote() { using (HttpClient client = new HttpClient()) { String textResponse = ""; await _metrics.TrackSlaRemote("testServer", async () => { var result = await client.GetAsync("http://localhost:10000/returnjsonBody"); textResponse = await result.Content.ReadAsStringAsync(); }); return textResponse; } } public bool Authorise(string token) { if (token.Contains("deny")) { return false; } else { return true; } } public bool ValidateRequestSchema(string token, string request) { if (!String.IsNullOrWhiteSpace(token) && !String.IsNullOrWhiteSpace(request)) { return true; } else { return false; } } } }
27.465753
122
0.514464
c6a3497b86548c17dfe1e61cbf77fc27331c8a4e
11,339
py
Python
tubes.py
salmank255/ROADSlowFast
e939d8f79fe3eb6f3dd32e967a34530d00f45c8e
[ "Apache-2.0" ]
null
null
null
tubes.py
salmank255/ROADSlowFast
e939d8f79fe3eb6f3dd32e967a34530d00f45c8e
[ "Apache-2.0" ]
null
null
null
tubes.py
salmank255/ROADSlowFast
e939d8f79fe3eb6f3dd32e967a34530d00f45c8e
[ "Apache-2.0" ]
null
null
null
""" Build tubes and evaluate """ import os import time, json import datetime import numpy as np import torch import pdb import pickle import copy import torch.utils.data as data_utils from modules import utils from modules.evaluation import evaluate_tubes from modules.box_utils import decode, nms from data import custum_collate, get_gt_video_list from modules.tube_helper import nms3dt import modules.gen_agent_paths as gen_paths #update_agent_paths, copy_live_to_dead, from modules.tube_helper import trim_tubes logger = utils.get_logger(__name__) def build_eval_tubes(args, val_dataset): for epoch in args.EVAL_EPOCHS: args.det_itr = epoch logger.info('Building tubes at ' + str(epoch)) log_file = open("{pt:s}/tubeing-{it:02d}-{sq:02d}.log".format(pt=args.SAVE_ROOT, it=epoch, sq=args.TEST_SEQ_LEN), "w", 10) args.det_save_dir = args.det_save_dir = os.path.join(args.SAVE_ROOT, "detections-{it:02d}-{sq:02d}-{n:d}/".format(it=epoch, sq=args.TEST_SEQ_LEN, n=int(100*args.GEN_NMS))) args.tube_save_dir = "{pt:s}/tubes-{it:02d}-{sq:02d}-{n:d}-{tk:d}-{s:s}-{io:d}-{jp:d}/".format(pt=args.SAVE_ROOT, it=epoch, sq=args.TEST_SEQ_LEN, n=int(100*args.GEN_NMS), tk=args.TOPK, s=args.PATHS_COST_TYPE, io=int(args.PATHS_IOUTH*100), jp=args.PATHS_JUMP_GAP) tube_file = args.tube_save_dir+ 'tubes_{}_{:d}.pkl'.format(args.TRIM_METHOD, int(args.TUBES_ALPHA*10)) if args.JOINT_4M_MARGINALS: tube_file = args.tube_save_dir+ 'tubes_{}_{:d}-j4m.pkl'.format(args.TRIM_METHOD, int(args.TUBES_ALPHA*10)) log_file = open("{pt:s}/tubeing-{it:02d}-{sq:02d}-j4m.log".format(pt=args.SAVE_ROOT, it=epoch, sq=args.TEST_SEQ_LEN), "w", 10) if not os.path.isdir(args.tube_save_dir): os.makedirs(args.tube_save_dir) assert os.path.isdir(args.det_save_dir), args.det_save_dir + ' detection directory does not exists ' log_file.write(args.exp_name + '\n') tt0 = time.perf_counter() log_file.write('Building tubes......\n') paths = perform_building(args, val_dataset.video_list, epoch) childs = [] if args.JOINT_4M_MARGINALS: childs = val_dataset.childs make_tubes(args, paths, val_dataset.video_list, childs, tube_file) # torch.cuda.synchronize() logger.info('Computation time {:0.2f}'.format(time.perf_counter() - tt0)) # result_file = args.SAVE_ROOT + '/video-map-results.json' results = {} table = '\n|class' map_line = ['|mAP |' for _ in range(len(args.SUBSETS)*len(args.label_types[1:]))] metric_types = ['stiou'] #['tiou','siou','stiou'] for metric_type in metric_types: for TUBES_EVAL_THRESH in args.TUBES_EVAL_THRESHS: table += '|{:s} {:0.02f}'.format(metric_type, TUBES_EVAL_THRESH) result_file = "{pt:s}/video-ap-results-{tm:s}-{a:d}-{th:d}-{m:s}.json".format(tm=args.TRIM_METHOD, a=int(args.TUBES_ALPHA*10), pt=args.tube_save_dir, th=int(TUBES_EVAL_THRESH*100), m=metric_type) if args.JOINT_4M_MARGINALS: result_file = "{pt:s}/video-ap-results-{tm:s}-{a:d}-{th:d}-{m:s}-j4m.json".format(tm=args.TRIM_METHOD, a=int(args.TUBES_ALPHA*10), pt=args.tube_save_dir, th=int(TUBES_EVAL_THRESH*100), m=metric_type) mcount =0 for subset in args.SUBSETS: if len(subset)<2: continue sresults = evaluate_tubes(val_dataset.anno_file, tube_file, dataset=args.DATASET, subset=subset, iou_thresh=TUBES_EVAL_THRESH, metric_type=metric_type) for _, label_type in enumerate(args.label_types[1:]): name = subset + ' & ' + label_type rstr = '\n\nResults for {:s} @ {:0.02f} {:s}\n'.format(name, TUBES_EVAL_THRESH, metric_type) logger.info(rstr) log_file.write(rstr+'\n') results[name] = {'mAP': sresults[label_type]['mAP'], 'APs': sresults[label_type]['ap_all'], 'mR':sresults[label_type]['mR'], 'Recalls': sresults[label_type]['recalls'], 'ap_strs': sresults[label_type]['ap_strs']} map_line[mcount] += '{:0.1f}/{:0.01f}|'.format(sresults[label_type]['mAP'],sresults[label_type]['mR']) mcount += 1 for ap_str in sresults[label_type]['ap_strs']: logger.info(ap_str) log_file.write(ap_str+'\n') with open(result_file, 'w') as f: json.dump(results, f) mcount = 0 for subset in args.SUBSETS: if len(subset)<2: continue for nlt, label_type in enumerate(args.label_types[1:]): name = subset + ' & ' + label_type print(args.label_types, len(args.all_classes)) table += '|\n' table += '|:-:|:-:|:-:|:-:|:-:|:-:|:-:|\n' + map_line[mcount] + '\n' mcount += 1 for c, cls in enumerate(args.all_classes[nlt+1]): table += '|{:s}'.format(cls) for metric_type in metric_types: for TUBES_EVAL_THRESH in args.TUBES_EVAL_THRESHS: result_file = "{pt:s}/video-ap-results-{tm:s}-{a:d}-{th:d}-{m:s}.json".format(tm=args.TRIM_METHOD, a=int(args.TUBES_ALPHA*10), pt=args.tube_save_dir, th=int(TUBES_EVAL_THRESH*100), m=metric_type) if args.JOINT_4M_MARGINALS: result_file = "{pt:s}/video-ap-results-{tm:s}-{a:d}-{th:d}-{m:s}-j4m.json".format(tm=args.TRIM_METHOD, a=int(args.TUBES_ALPHA*10), pt=args.tube_save_dir, th=int(TUBES_EVAL_THRESH*100), m=metric_type) with open(result_file, 'r') as f: results = json.load(f) table += '|{:0.01f}/{:0.01f}'.format(results[name]['APs'][c],results[name]['Recalls'][c]) table += '|\n' logger.info(table) log_file.close() def perform_building(args, video_list, epoch): """Build agent-level tube or called paths""" all_paths = {} for videoname in video_list: total_dets = 0 video_dir = args.det_save_dir + videoname + '/' assert os.path.isdir( video_dir), 'Detection should exist @ ' + video_dir if args.DATASET == 'ucf24': dirname = args.tube_save_dir + videoname.split('/')[0] if not os.path.isdir(dirname): os.makedirs(dirname) agent_path_save_name = args.tube_save_dir + videoname + '_paths.pkl'.format() if args.COMPUTE_PATHS or not os.path.isfile(agent_path_save_name): frames_names = os.listdir(video_dir) frame_ids = [int(fn.split('.')[0]) for fn in frames_names if fn.endswith('.pkl')] num_classes_to_use = args.num_classes_list[0] + args.num_classes_list[1] t1 = time.perf_counter() live_paths = [] dead_paths = [] for frame_num in sorted(frame_ids): save_name = '{:s}/{:05d}.pkl'.format(video_dir, frame_num) with open(save_name, 'rb') as f: det_boxes = pickle.load(f) det_boxes = det_boxes['main'] pickn = min(args.TOPK, det_boxes.shape[0]) det_boxes = det_boxes[:args.TOPK,:] det_boxes = det_boxes[det_boxes[:,4]>args.CONF_THRESH,:] num_dets = 0 if det_boxes.shape[0]>0: frame = {} frame['boxes'] = det_boxes[:,:4] frame['scores'] = det_boxes[:,4] frame['allScores'] = det_boxes[:,4:] num_dets = det_boxes.shape[0] live_paths, dead_paths = gen_paths.update_agent_paths(live_paths, dead_paths, frame, num_classes_to_use, iouth=args.PATHS_IOUTH, time_stamp=frame_num, costtype=args.PATHS_COST_TYPE, jumpgap=args.PATHS_JUMP_GAP, min_len=args.PATHS_MIN_LEN) total_dets += num_dets if frame_num % 600 == 0 and frame_num>1: logger.info('Time taken at fn {:d}, num dets {:d}, num live_paths {:d} time {:0.02f}'.format(frame_num, num_dets, len(live_paths), time.perf_counter() - t1)) t1 = time.perf_counter() paths = gen_paths.copy_live_to_dead(live_paths, dead_paths,args.PATHS_MIN_LEN) paths = gen_paths.fill_gaps( paths, min_len_with_gaps=args.PATHS_MIN_LEN, minscore=args.PATHS_MINSCORE) ## dump agent paths to disk with open(agent_path_save_name,'wb') as f: pickle.dump(paths, f) else: with open(agent_path_save_name, 'rb') as f: paths = pickle.load(f) all_paths[videoname] = paths return all_paths def apply_labelwise_nms(all_tubes): labelwise_tubes = {} for tube in all_tubes: label = 'l'+str(tube['label_id']) if label not in labelwise_tubes: labelwise_tubes[label] = [tube] else: labelwise_tubes[label].append(tube) det_tubes = [] for label, ltubes in labelwise_tubes.items(): ltubes = nms3dt(ltubes) for tube in ltubes: det_tubes.append(tube) return det_tubes def make_tubes(args, paths, video_list, childs, tube_file): """Make tubes from paths and dump in tube_file""" if args.COMPUTE_TUBES or not os.path.isfile(tube_file): # logger.info('building agent tubes') detection_tubes = {} for ltype in args.label_types[1:]: detection_tubes[ltype] = {} for vid, videoname in enumerate(video_list): start_id = 1 for nlt, ltype in enumerate(args.label_types[1:]): logger.info('building tubes for '+ ltype) # print(args.num_classes_list, args.label_types) numc = args.num_classes_list[nlt+1] all_tubes = trim_tubes(start_id, numc, copy.deepcopy(paths[videoname]), childs, args.num_classes_list, topk=args.TUBES_TOPK, alpha=args.TUBES_ALPHA, min_len=args.TUBES_MINLEN, trim_method=args.TRIM_METHOD) # det_tubes = apply_labelwise_nms(all_tubes) detection_tubes[ltype][videoname] = all_tubes start_id += numc logger.info(str(vid+1) + '/'+ str(len(video_list)) + ' '+ str(len(detection_tubes[ltype][videoname])) +' tubes built for '+ ltype+' '+ videoname) with open(tube_file, 'wb') as f: pickle.dump(detection_tubes, f)
51.076577
231
0.563718
b6b702e40b2423892ae56816f33ddd73ff285860
419
rb
Ruby
recipes/default.rb
ifeltsweet/chef-disable-thp
6226595f4971e50c065c1164c005b2b0de7e0054
[ "Apache-2.0" ]
null
null
null
recipes/default.rb
ifeltsweet/chef-disable-thp
6226595f4971e50c065c1164c005b2b0de7e0054
[ "Apache-2.0" ]
null
null
null
recipes/default.rb
ifeltsweet/chef-disable-thp
6226595f4971e50c065c1164c005b2b0de7e0054
[ "Apache-2.0" ]
null
null
null
template '/etc/systemd/system/disable-thp.service' do source 'disable-thp.service.erb' owner 'root' group 'root' mode '0644' notifies :reload, 'service[disable-thp]', :delayed end template '/usr/bin/disable-thp' do source 'disable-thp.erb' owner 'root' group 'root' mode '0755' notifies :reload, 'service[disable-thp]', :delayed end service 'disable-thp' do action [:enable, :start] end
20.95
54
0.684964
b31c0364d3b3c6f0e6157e9a4d623e77515058ce
26
py
Python
yaraa/__init__.py
Te-k/yaraa
b5a1be88419fbd4ea5e0a1f5e6dbedca8ff77b36
[ "MIT" ]
3
2019-12-18T03:14:56.000Z
2021-01-15T13:23:09.000Z
yaraa/__init__.py
Te-k/yaraa
b5a1be88419fbd4ea5e0a1f5e6dbedca8ff77b36
[ "MIT" ]
1
2019-12-17T15:13:39.000Z
2019-12-17T15:13:39.000Z
yaraa/__init__.py
Te-k/yaraa
b5a1be88419fbd4ea5e0a1f5e6dbedca8ff77b36
[ "MIT" ]
null
null
null
from .yaraa import lookup
13
25
0.807692
3149f72afbc0c26ce124fcb2a878ccfbb8e09d20
2,364
rb
Ruby
spec/integration/drain_spec.rb
pmenglund/bosh
ede389a2e112e1b4f2dbc4495c08977da4439483
[ "Ruby", "Apache-2.0" ]
null
null
null
spec/integration/drain_spec.rb
pmenglund/bosh
ede389a2e112e1b4f2dbc4495c08977da4439483
[ "Ruby", "Apache-2.0" ]
null
null
null
spec/integration/drain_spec.rb
pmenglund/bosh
ede389a2e112e1b4f2dbc4495c08977da4439483
[ "Ruby", "Apache-2.0" ]
null
null
null
require 'spec_helper' describe 'drain', type: :integration do describe 'static drain' do with_reset_sandbox_before_all before(:all) do cloud_config_hash = Bosh::Spec::Deployments.simple_cloud_config cloud_config_hash['resource_pools'].first['size'] = 1 manifest_hash = Bosh::Spec::Deployments.simple_manifest manifest_hash['releases'].first['version'] = 'latest' manifest_hash['jobs'][0]['instances'] = 1 deploy_from_scratch(cloud_config_hash: cloud_config_hash, manifest_hash: manifest_hash) manifest_hash['jobs'][0]['persistent_disk'] = 100 manifest_hash['properties'] ||= {} manifest_hash['properties']['test_property'] = 0 deploy_simple_manifest(manifest_hash: manifest_hash) end it 'runs the drain script on a job if drain script is present' do drain_log = director.vm('foobar/0').read_file('drain-test.log') expect(drain_log).to eq("job_shutdown hash_unchanged\n1\n") end it 'sets BOSH_JOB_STATE and BOSH_JOB_NEXT_STATE env vars with changed values' do drain_log = director.vm('foobar/0').read_file('drain-job-state.log') expect(drain_log).to include('BOSH_JOB_STATE={"persistent_disk":0}') expect(drain_log).to include('BOSH_JOB_NEXT_STATE={"persistent_disk":100}') end end describe 'dynamic drain' do with_reset_sandbox_before_all before(:all) do cloud_config_hash = Bosh::Spec::Deployments.simple_cloud_config cloud_config_hash['resource_pools'].first['size'] = 1 manifest_hash = Bosh::Spec::Deployments.simple_manifest manifest_hash['releases'].first['version'] = 'latest' manifest_hash['jobs'][0]['instances'] = 1 manifest_hash['properties'] ||= {} manifest_hash['properties']['drain_type'] = 'dynamic' deploy_from_scratch(cloud_config_hash: cloud_config_hash, manifest_hash: manifest_hash) manifest_hash['properties']['test_property'] = 0 deploy_simple_manifest(manifest_hash: manifest_hash) end it 'retries after the appropriate amount of time' do drain_log = director.vm('foobar/0').read_file('drain-test.log') drain_times = drain_log.split.map(&:to_i) expect(drain_times.size).to eq(3) expect(drain_times[1] - drain_times[0]).to be >= 3 expect(drain_times[2] - drain_times[1]).to be >= 2 end end end
37.52381
93
0.702623
ed74b01cd1048da82621ea3c11c4d9dc141ed402
18,092
c
C
PlibC/src/strptime.c
orynider/php-5.6.3x4VC9
47f9765b797279061c364e004153a0919895b23e
[ "BSD-2-Clause" ]
1
2021-02-24T13:01:00.000Z
2021-02-24T13:01:00.000Z
PlibC/src/strptime.c
orynider/php-5.6.3x4VC9
47f9765b797279061c364e004153a0919895b23e
[ "BSD-2-Clause" ]
null
null
null
PlibC/src/strptime.c
orynider/php-5.6.3x4VC9
47f9765b797279061c364e004153a0919895b23e
[ "BSD-2-Clause" ]
null
null
null
/* Convert a string representation of time to a time value. Copyright (C) 1996, 1997, 1998, 1999, 2000 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper <drepper@cygnus.com>, 1996. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The GNU C Library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with the GNU C Library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /** * @file src/strptime.c * @brief This is a slightly modified version by the "R Project" * <http://www.r-project.org/> with locale support removed. * Support for Windows locales added by Nils Durner for PlibC */ #include "plibc_private.h" void get_locale_strings(void); /* XXX This version of the implementation is not really complete. Some of the fields cannot add information alone. But if seeing some of them in the same format (such as year, week and weekday) this is enough information for determining the date. */ #include <ctype.h> #include <limits.h> #include <string.h> #include <time.h> #define match_char(ch1, ch2) if (ch1 != ch2) return NULL #ifndef Macintosh #if defined __GNUC__ && __GNUC__ >= 2 # define match_string(cs1, s2) \ ({ size_t len = strlen (cs1); \ int result = strncasecmp ((cs1), (s2), len) == 0; \ if (result) (s2) += len; \ result; }) #else /* Oh come on. Get a reasonable compiler. */ # define match_string(cs1, s2) \ (strncasecmp ((cs1), (s2), strlen (cs1)) ? 0 : ((s2) += strlen (cs1), 1)) #endif #else # define match_string(cs1, s2) \ (strncmp ((cs1), (s2), strlen (cs1)) ? 0 : ((s2) += strlen (cs1), 1)) #endif /* mac */ /* We intentionally do not use isdigit() for testing because this will lead to problems with the wide character version. */ #define get_number(from, to, n) \ do { \ int __n = n; \ val = 0; \ while (*rp == ' ') \ ++rp; \ if (*rp < '0' || *rp > '9') \ return NULL; \ do { \ val *= 10; \ val += *rp++ - '0'; \ } while (--__n > 0 && val * 10 <= to && *rp >= '0' && *rp <= '9'); \ if (val < from || val > to) \ return NULL; \ } while (0) # define get_alt_number(from, to, n) \ /* We don't have the alternate representation. */ \ get_number(from, to, n) #define recursive(new_fmt) \ (*(new_fmt) != '\0' \ && (rp = strptime_internal (rp, (new_fmt), tm, decided)) != NULL) /* This version: may overwrite these with versions for the locale */ static char weekday_name[][20] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; static char ab_weekday_name[][10] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static char month_name[][20] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; static char ab_month_name[][10] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; static char am_pm[][4] = {"AM", "PM"}; static int have_used_strptime = 0; static const unsigned short int __mon_yday[2][13] = { /* Normal years. */ { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }, /* Leap years. */ { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 } }; /* Status of lookup: do we use the locale data or the raw data? */ enum locale_status { not, loc, raw }; # define __isleap(year) \ ((year) % 4 == 0 && ((year) % 100 != 0 || (year) % 400 == 0)) /* Convert Windows date picture to POSIX style. The converted format string may not mach exactly. */ void conv_winpic(char *win, char **posix) { char *src, *dst; src = win; *posix = dst = malloc(strlen(src) * 2 + 1); while(*src) { if (src[0] == 'y') if (src[1] == 'y') if (src[2] == 'y') if (src[3] == 'y') { strcpy(dst, "%Y"); if (src[4] == 'y') src += 5; // yyyyy else src += 4; // yyyy dst += 2; } else // yyy { // undefined strcpy(dst, "yyy"); dst += 3; src += 3; } else // yy { strcpy(dst, "%y"); dst += 2; src += 2; } else // y { // impossible to convert properly strcpy(dst, "%y"); dst += 2; src++; } else if (src[0] == 'M') { if (src[1] == 'M') if (src[2] == 'M') if (src[3] == 'M') // MMMM { strcpy(dst, "%b"); src += 4; } else // MMM { // impossible to convert properly strcpy(dst, "%m"); src += 3; } else // MM { strcpy(dst, "%m"); src += 2; } else // M { strcpy(dst, "%m"); src += 1; } dst += 2; } else if (src[0] == 'd') { if (src[1] == 'd') if (src[2] == 'd') if (src[3] == 'd') // dddd { strcpy(dst, "%a"); src += 4; } else // ddd { // impossible to convert properly strcpy(dst, "%d"); src += 3; } else // dd { strcpy(dst, "%d"); src += 2; } else // d { strcpy(dst, "%d"); src++; } dst += 2; } else if (src[0] == 'g' && src[1] == 'g') // impossible to convert src += 2; else if (src[0] == 'h') { strcpy(dst, "%I"); dst += 2; if (src[1] == 'h') src += 2; else src += 1; } else if (src[0] == 'H') { strcpy(dst, "%H"); dst += 2; if (src[1] == 'H') src += 2; else src += 1; } else if (src[0] == 'm') { strcpy(dst, "%M"); dst += 2; if (src[1] == 'm') src += 2; else src += 1; } else if (src[0] == 's') { strcpy(dst, "%S"); dst += 2; if (src[1] == 's') src += 2; else src += 1; } else if (src[0] == 't') { strcpy(dst, "%p"); dst += 2; if (src[1] == 't') src += 2; else src += 1; } else { *dst = *src; dst++; src++; } } dst[0] = 0; } /* Compute the day of the week. */ void day_of_the_week (struct tm *tm) { /* We know that January 1st 1970 was a Thursday (= 4). Compute the the difference between this data in the one on TM and so determine the weekday. */ int corr_year = 1900 + tm->tm_year - (tm->tm_mon < 2); int wday = (-473 + (365 * (tm->tm_year - 70)) + (corr_year / 4) - ((corr_year / 4) / 25) + ((corr_year / 4) % 25 < 0) + (((corr_year / 4) / 25) / 4) + __mon_yday[0][tm->tm_mon] + tm->tm_mday - 1); tm->tm_wday = ((wday % 7) + 7) % 7; } /* Compute the day of the year. */ void day_of_the_year (struct tm *tm) { tm->tm_yday = (__mon_yday[__isleap (1900 + tm->tm_year)][tm->tm_mon] + (tm->tm_mday - 1)); } char * strptime_internal (const char *rp, const char *fmt, struct tm *tm, enum locale_status *decided) { const char *rp_backup; int cnt; size_t val; int have_I, is_pm; int century, want_century; int have_wday, want_xday; int have_yday; int have_mon, have_mday; have_I = is_pm = 0; century = -1; want_century = 0; have_wday = want_xday = have_yday = have_mon = have_mday = 0; while (*fmt != '\0') { /* A white space in the format string matches 0 more or white space in the input string. */ if (isspace (*fmt)) { while (isspace (*rp)) ++rp; ++fmt; continue; } /* Any character but `%' must be matched by the same character in the iput string. */ if (*fmt != '%') { match_char (*fmt++, *rp++); continue; } ++fmt; /* We need this for handling the `E' modifier. */ start_over: /* Make back up of current processing pointer. */ rp_backup = rp; switch (*fmt++) { case '%': /* Match the `%' character itself. */ match_char ('%', *rp++); break; case 'a': case 'A': /* Match day of week. */ for (cnt = 0; cnt < 7; ++cnt) { if (*decided != loc && (match_string (weekday_name[cnt], rp) || match_string (ab_weekday_name[cnt], rp))) { *decided = raw; break; } } if (cnt == 7) /* Does not match a weekday name. */ return NULL; tm->tm_wday = cnt; have_wday = 1; break; case 'b': case 'B': case 'h': /* Match month name. */ for (cnt = 0; cnt < 12; ++cnt) { if (match_string (month_name[cnt], rp) || match_string (ab_month_name[cnt], rp)) { *decided = raw; break; } } if (cnt == 12) /* Does not match a month name. */ return NULL; tm->tm_mon = cnt; want_xday = 1; break; case 'c': /* Match locale's date and time format. */ return strptime_internal (rp, "%x %X", tm, decided); break; case 'C': /* Match century number. */ get_number (0, 99, 2); century = val; want_xday = 1; break; case 'd': case 'e': /* Match day of month. */ get_number (1, 31, 2); tm->tm_mday = val; have_mday = 1; want_xday = 1; break; case 'F': if (!recursive ("%Y-%m-%d")) return NULL; want_xday = 1; break; case 'x': { char *pic; unsigned int loc; char winpic[100]; int ret; loc = GetThreadLocale(); GetLocaleInfo(loc, LOCALE_SSHORTDATE, winpic, 100); conv_winpic(winpic, &pic); ret = recursive(pic); free(pic); if (!ret) return NULL; want_xday = 1; } break; case 'D': /* Match standard day format. */ if (!recursive ("%m/%d/%y")) return NULL; want_xday = 1; break; case 'k': case 'H': /* Match hour in 24-hour clock. */ get_number (0, 23, 2); tm->tm_hour = val; have_I = 0; break; case 'I': /* Match hour in 12-hour clock. */ get_number (1, 12, 2); tm->tm_hour = val % 12; have_I = 1; break; case 'j': /* Match day number of year. */ get_number (1, 366, 3); tm->tm_yday = val - 1; have_yday = 1; break; case 'm': /* Match number of month. */ get_number (1, 12, 2); tm->tm_mon = val - 1; have_mon = 1; want_xday = 1; break; case 'M': /* Match minute. */ get_number (0, 59, 2); tm->tm_min = val; break; case 'n': case 't': /* Match any white space. */ while (isspace (*rp)) ++rp; break; case 'p': /* Match locale's equivalent of AM/PM. */ if (!match_string (am_pm[0], rp)) if (match_string (am_pm[1], rp)) is_pm = 1; else return NULL; break; case 'r': return strptime_internal (rp, "%x %X", tm, decided); break; case 'R': if (!recursive ("%H:%M")) return NULL; break; case 's': { /* The number of seconds may be very high so we cannot use the `get_number' macro. Instead read the number character for character and construct the result while doing this. */ time_t secs = 0; if (*rp < '0' || *rp > '9') /* We need at least one digit. */ return NULL; do { secs *= 10; secs += *rp++ - '0'; } while (*rp >= '0' && *rp <= '9'); if ((tm = localtime (&secs)) == NULL) /* Error in function. */ return NULL; } break; case 'S': get_number (0, 61, 2); tm->tm_sec = val; break; case 'X': { char *pic; unsigned int loc; char winpic[100]; int ret; loc = GetThreadLocale(); GetLocaleInfo(loc, LOCALE_STIMEFORMAT, winpic, 100); conv_winpic(winpic, &pic); ret = recursive(pic); free(pic); if (!ret) return NULL; } break; case 'T': return strptime_internal (rp, "%H:%M:%S", tm, decided); break; case 'u': get_number (1, 7, 1); tm->tm_wday = val % 7; have_wday = 1; break; case 'g': get_number (0, 99, 2); /* XXX This cannot determine any field in TM. */ break; case 'G': if (*rp < '0' || *rp > '9') return NULL; /* XXX Ignore the number since we would need some more information to compute a real date. */ do ++rp; while (*rp >= '0' && *rp <= '9'); break; case 'U': case 'V': case 'W': get_number (0, 53, 2); /* XXX This cannot determine any field in TM without some information. */ break; case 'w': /* Match number of weekday. */ get_number (0, 6, 1); tm->tm_wday = val; have_wday = 1; break; case 'y': /* Match year within century. */ get_number (0, 99, 2); /* The "Year 2000: The Millennium Rollover" paper suggests that values in the range 69-99 refer to the twentieth century. */ tm->tm_year = val >= 69 ? val : val + 100; /* Indicate that we want to use the century, if specified. */ want_century = 1; want_xday = 1; break; case 'Y': /* Match year including century number. */ get_number (0, 9999, 4); tm->tm_year = val - 1900; want_century = 0; want_xday = 1; break; case 'Z': /* XXX How to handle this? */ break; case 'E': /* We have no information about the era format. Just use the normal format. */ if (*fmt != 'c' && *fmt != 'C' && *fmt != 'y' && *fmt != 'Y' && *fmt != 'x' && *fmt != 'X') /* This is an invalid format. */ return NULL; goto start_over; case 'O': switch (*fmt++) { case 'd': case 'e': /* Match day of month using alternate numeric symbols. */ get_alt_number (1, 31, 2); tm->tm_mday = val; have_mday = 1; want_xday = 1; break; case 'H': /* Match hour in 24-hour clock using alternate numeric symbols. */ get_alt_number (0, 23, 2); tm->tm_hour = val; have_I = 0; break; case 'I': /* Match hour in 12-hour clock using alternate numeric symbols. */ get_alt_number (1, 12, 2); tm->tm_hour = val - 1; have_I = 1; break; case 'm': /* Match month using alternate numeric symbols. */ get_alt_number (1, 12, 2); tm->tm_mon = val - 1; have_mon = 1; want_xday = 1; break; case 'M': /* Match minutes using alternate numeric symbols. */ get_alt_number (0, 59, 2); tm->tm_min = val; break; case 'S': /* Match seconds using alternate numeric symbols. */ get_alt_number (0, 61, 2); tm->tm_sec = val; break; case 'U': case 'V': case 'W': get_alt_number (0, 53, 2); /* XXX This cannot determine any field in TM without further information. */ break; case 'w': /* Match number of weekday using alternate numeric symbols. */ get_alt_number (0, 6, 1); tm->tm_wday = val; have_wday = 1; break; case 'y': /* Match year within century using alternate numeric symbols. */ get_alt_number (0, 99, 2); tm->tm_year = val >= 69 ? val : val + 100; want_xday = 1; break; default: return NULL; } break; default: return NULL; } } if (have_I && is_pm) tm->tm_hour += 12; if (century != -1) { if (want_century) tm->tm_year = tm->tm_year % 100 + (century - 19) * 100; else /* Only the century, but not the year. Strange, but so be it. */ tm->tm_year = (century - 19) * 100; } if (want_xday && !have_wday) { if ( !(have_mon && have_mday) && have_yday) { /* we don't have tm_mon and/or tm_mday, compute them */ int t_mon = 0; while (__mon_yday[__isleap(1900 + tm->tm_year)][t_mon] <= tm->tm_yday) t_mon++; if (!have_mon) tm->tm_mon = t_mon - 1; if (!have_mday) tm->tm_mday = tm->tm_yday - __mon_yday[__isleap(1900 + tm->tm_year)][t_mon - 1] + 1; } day_of_the_week (tm); } if (want_xday && !have_yday) day_of_the_year (tm); return (char *) rp; } char * strptime (const char *buf, const char *format, struct tm *tm) { enum locale_status decided; #ifdef HAVE_LOCALE_H if(!have_used_strptime) { get_locale_strings(); /* have_used_strptime = 1; might change locale during session */ } #endif decided = raw; return strptime_internal (buf, format, tm, &decided); } #ifdef HAVE_LOCALE_H void get_locale_strings(void) { int i; struct tm tm; char buff[4]; tm.tm_sec = tm.tm_min = tm.tm_hour = tm.tm_mday = tm.tm_mon = tm.tm_isdst = 0; tm.tm_year = 30; for(i = 0; i < 12; i++) { tm.tm_mon = i; strftime(ab_month_name[i], 10, "%b", &tm); strftime(month_name[i], 20, "%B", &tm); } tm.tm_mon = 0; for(i = 0; i < 7; i++) { tm.tm_mday = tm.tm_yday = i+1; /* 2000-1-2 was a Sunday */ tm.tm_wday = i; strftime(ab_weekday_name[i], 10, "%a", &tm); strftime(weekday_name[i], 20, "%A", &tm); } tm.tm_hour = 1; /* in locales where these are unused, they may be empty: better not to reset them then */ strftime(buff, 4, "%p", &tm); if(strlen(buff)) strcpy(am_pm[0], buff); tm.tm_hour = 13; strftime(buff, 4, "%p", &tm); if(strlen(buff)) strcpy(am_pm[1], buff); } #endif
24.058511
100
0.520396
212cc6e0bd3521a1257015e3b7d6eefaea54cc79
7,018
dart
Dart
nyxx_lavalink/lib/src/node/Node.dart
abitofevrything/nyxx
24d45b97631f62a878d4d4e65e27ac163351d51d
[ "Apache-2.0" ]
161
2018-06-18T15:24:32.000Z
2021-07-11T16:47:15.000Z
nyxx_lavalink/lib/src/node/Node.dart
abitofevrything/nyxx
24d45b97631f62a878d4d4e65e27ac163351d51d
[ "Apache-2.0" ]
108
2018-08-24T13:12:05.000Z
2021-07-26T20:25:05.000Z
nyxx_lavalink/lib/src/node/Node.dart
abitofevrything/nyxx
24d45b97631f62a878d4d4e65e27ac163351d51d
[ "Apache-2.0" ]
53
2018-08-03T09:40:30.000Z
2021-07-22T19:48:38.000Z
part of nyxx_lavalink; /// Represents an active and running lavalink node class Node { /// Node options, such as host, port, etc.. NodeOptions options; /// A map with guild ids as keys and players as values final Map<Snowflake, GuildPlayer> _players = {}; /// Returns a map with all the players the node currently has UnmodifiableMapView<Snowflake, GuildPlayer> get players => UnmodifiableMapView(this._players); /// Last stats received by this node StatsEvent? _stats; /// Returns the last stats received by this node StatsEvent? get stats => this._stats; /// Http client used with this node final Client _httpClient = Client(); final SendPort _nodeSendPort; late String _httpUri; late Map<String, String> _defaultHeaders; final Cluster _cluster; /// A regular expression to avoid searching when a link is provided final RegExp _urlRegex = RegExp(r"https?://(?:www\.)?.+"); /// Build a new Node Node._fromOptions(this._cluster, this.options, this._nodeSendPort) { this._httpUri = options.ssl ? "https://${options.host}:${options.port}" : "http://${options.host}:${options.port}"; this._defaultHeaders = { "Authorization": options.password, "Num-Shards": options.shards.toString(), "User-Id": options.clientId.toString() }; } void _sendPayload(String op, Snowflake guildId, [Map<String, dynamic>? data]) async { if (data == null) { _nodeSendPort.send({"cmd": "SEND", "data": { "op": op, "guildId": guildId.toString(), }}); } else { _nodeSendPort.send({"cmd": "SEND", "data": { "op": op, "guildId": guildId.toString(), ...data }}); } } void _playNext(Snowflake guildId) async { final player = this._players[guildId]; if (player == null) { return; } final track = player.queue.first; player.nowPlaying = track; if (track.endTime == null) { this._sendPayload("play", guildId, { "track": track.track.track, "noReplace": false, "startTime": track.startTime.inMilliseconds, }); } else { this._sendPayload("play", guildId, { "track": track.track.track, "noReplace": false, "startTime": track.startTime.inMilliseconds, "endTime": track.endTime!.inMilliseconds }); } } void _handleTrackEnd(TrackEndEvent event) { if(!(event.reason == "FINISHED")) { return; } final player = this._players[event.guildId]; if (player == null) { return; } player.queue.removeAt(0); player.nowPlaying = null; if (player.queue.isEmpty) { return; } _playNext(event.guildId); } /// Destroys a player void destroy(Snowflake guildId) { _sendPayload("destroy", guildId); // delete the actual player this._players.remove(guildId); // delete the relationship between this node and the player so // if this guild creates a new player, it can be assigned to other node this._cluster._nodeLocations.remove(guildId); } /// Stops a player void stop(Snowflake guildId) { final player = this._players[guildId]; if (player == null) { return; } player.queue.clear(); player.nowPlaying = null; _sendPayload("stop", guildId); } /// Skips a track, starting the next one if available or stopping the player if not void skip(Snowflake guildId) { final player = this._players[guildId]; if (player == null) { return; } if (player.queue.isEmpty) { return; } else if (player.queue.length == 1) { stop(guildId); return; } else { player.queue.removeAt(0); this._playNext(guildId); } } /// Set the pause state of a player /// /// this method is internally used by [resume] and [pause] void setPause(Snowflake guildId, bool pauseState) { _sendPayload("pause", guildId, {"pause": pauseState}); } /// Seeks for a given time at the currently playing track void seek(Snowflake guildId, Duration time) { _sendPayload("seek", guildId, { "position": time.inMilliseconds }); } /// Sets the volume for a guild player, [volume] should be a number between 1 to 1000 void volume(Snowflake guildId, int volume) { final trimmed = volume.clamp(0, 1000); _sendPayload("volume", guildId, { "volume": trimmed }); } /// Pauses a guild player void pause(Snowflake guildId) { setPause(guildId, true); } /// Resumes the track playback of a guild player void resume(Snowflake guildId) { setPause(guildId, false); } /// Searches a given query over the lavalink api and returns the results Future<Tracks> searchTracks(String query) async { final response = await _httpClient.get(Uri.parse( "${this._httpUri}/loadtracks?identifier=$query"), headers: this._defaultHeaders ); if (!(response.statusCode == 200)) { throw HttpException._new(response.statusCode); } return Tracks._fromJson(jsonDecode(response.body) as Map<String, dynamic>); } /// Searches a provided query on selected platform (YouTube by default), /// if the query is a link it's searched directly by the link Future<Tracks> autoSearch( String query, { SearchPlatform platform = SearchPlatform.youtube, }) async { if (this._urlRegex.hasMatch(query)) { return searchTracks(query); } return searchTracks("${platform.value}:$query"); } /// Get the [PlayParameters] object for a specific track PlayParameters play(Snowflake guildId, Track track, { bool replace = false, Duration startTime = const Duration(), Duration? endTime, Snowflake? requester, Snowflake? channelId }) => PlayParameters( this, track, guildId, replace, startTime, endTime, requester, channelId ); /// Shuts down the node void shutdown() { this._nodeSendPort.send({"cmd": "SHUTDOWN"}); } /// Create a new player for a specific guild GuildPlayer createPlayer(Snowflake guildId) { final player = GuildPlayer._new(this, guildId); this._players[guildId] = player; _cluster._nodeLocations[guildId] = this.options.nodeId; return player; } /// Updates the [NodeOptions] property of the node, also reconnects the /// websocket to the new options void updateOptions(NodeOptions newOptions) { // Set the node id and client id before sending it to the isolate newOptions.clientId = this.options.clientId; newOptions.nodeId = this.options.nodeId; _nodeSendPort.send({"cmd": "UPDATE", "data": newOptions._toJson()}); this.options = newOptions; } /// Tells the node to disconnect from lavalink server void disconnect() { _nodeSendPort.send({"cmd": "DISCONNECT"}); } /// Tells the node to reconnect to lavalink server void reconnect() { _nodeSendPort.send({"cmd": "RECONNECT"}); } @override String toString() => "Node ${this.options.nodeId}"; }
25.992593
96
0.646623
be59d190429040b4b8b40ec2377acf209a44cb6e
4,292
ts
TypeScript
index.ts
apioo/fusio-worker-javascript
10a510f5d11166aa3b83801dff19d7ad20b5481d
[ "MIT" ]
null
null
null
index.ts
apioo/fusio-worker-javascript
10a510f5d11166aa3b83801dff19d7ad20b5481d
[ "MIT" ]
null
null
null
index.ts
apioo/fusio-worker-javascript
10a510f5d11166aa3b83801dff19d7ad20b5481d
[ "MIT" ]
1
2021-10-11T02:27:01.000Z
2021-10-11T02:27:01.000Z
import * as fs from "fs"; import Thrift from "thrift"; import {Config, Connector} from "./src/Connector"; import {HttpResponse, Response} from "./src/Response"; import {Dispatcher} from "./src/Dispatcher"; import {Logger} from "./src/Logger"; import {Action, Connection, Execute, Message, Result} from "./generated/worker_types"; import {Processor} from "./generated/Worker"; const PORT = 9091; const ACTION_DIR = './actions'; var connections: Record<string, Config>|null = null; var actions: Record<string, Promise<Function>> = {}; interface WorkerHandler { setConnection(connection: Connection, result: Function): void; setAction(action: Action, result: Function): void; executeAction(execute: Execute, result: Function): void; } var handler : WorkerHandler = { setConnection: function(connection: Connection, result: Function): void { if (!fs.existsSync(ACTION_DIR)){ fs.mkdirSync(ACTION_DIR); } let data = readConnections(); if (!connection.name) { result(null, new Message({success: false, message: 'Provided no connection name'})); } data[connection.name] = { type: connection.type, config: connection.config, }; fs.writeFileSync(ACTION_DIR + '/connections.json', JSON.stringify(data)); // reset connections connections = null; console.debug('Update connection ' + connection.name); result(null, new Message({success: true, message: 'Connection successful updated'})); }, setAction: function(action: Action, result: Function): void { if (!fs.existsSync(ACTION_DIR)){ fs.mkdirSync(ACTION_DIR); } if (!action.name) { result(null, new Message({success: false, message: 'Provided no action name'})); } const file = ACTION_DIR + '/' + action.name + '.js'; fs.writeFileSync(file, action.code); if (actions.hasOwnProperty(action.name)) { delete actions[action.name]; } // delete require cache delete require.cache[require.resolve(file)]; console.debug('Update action ' + action.name); result(null, new Message({success: true, message: 'Action successful updated'})); }, executeAction: function(execute: Execute, result: Function): void { const connector = new Connector(readConnections()); const dispatcher = new Dispatcher(); const logger = new Logger(); const response = new Response((response: HttpResponse) => { result(null, new Result({ response: response, events: dispatcher.getEvents(), logs: logger.getLogs(), })); }); if (!execute.action) { return; } console.debug('Execute action ' + execute.action); if (!actions.hasOwnProperty(execute.action)) { actions[execute.action] = Promise.resolve(require(ACTION_DIR + '/' + execute.action + '.js')); } try { actions[execute.action] .then(function(callback){ callback(execute.request, execute.context, connector, response, dispatcher, logger) }) .catch(function(error){ result(null, newError(error)); }); } catch (error) { result(null, newError(error)); } }, }; var server = Thrift.createServer<Processor, WorkerHandler>(Processor, handler); server.listen(PORT); console.log('Fusio Worker started'); function readConnections(): Record<string, Config> { if (connections !== null) { return connections; } const file = ACTION_DIR + '/connections.json'; if (fs.existsSync(file)) { connections = JSON.parse(fs.readFileSync(file, 'utf8')) } return connections !== null ? connections : {}; } function newError(error: any): Result { return new Result({ response: { statusCode: 500, headers: {}, body: JSON.stringify({ success: false, message: 'An error occurred at the worker: ' + error }) }, events: [], logs: [] }); }
30.439716
106
0.587838
cdcd010e5d8a2d66ce76ae1bf360cfb05ab24e58
1,878
cs
C#
test/Annex.Test/Collections/CollectionExtensions_AddRangeTest.cs
gtbuchanan/annex-net
814d82ab98f2472b7efd8740b84ca77448a11281
[ "MIT" ]
1
2018-10-24T02:02:33.000Z
2018-10-24T02:02:33.000Z
test/Annex.Test/Collections/CollectionExtensions_AddRangeTest.cs
gtbuchanan/annex-net
814d82ab98f2472b7efd8740b84ca77448a11281
[ "MIT" ]
null
null
null
test/Annex.Test/Collections/CollectionExtensions_AddRangeTest.cs
gtbuchanan/annex-net
814d82ab98f2472b7efd8740b84ca77448a11281
[ "MIT" ]
1
2021-09-01T07:31:19.000Z
2021-09-01T07:31:19.000Z
using Annex.Collections; using AutoFixture.AutoNSubstitute; using NSubstitute; using NUnit.Framework; using Shouldly; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; namespace Annex.Test.Collections { public sealed class CollectionExtensions_AddRangeTest { [Test, AutoDomainData] [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] public void NullThisThrowsArgumentNullException(IEnumerable<object> expectedValues) => Should.Throw<ArgumentNullException>(() => ((ICollection<object>)null).AddRange(expectedValues)); [Test, AutoDomainData] [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] public void NullCollectionThrowsArgumentNullException([Substitute]ICollection<object> sut) => Should.Throw<ArgumentNullException>(() => sut.AddRange(null)); [Test, AutoDomainData] [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] public void CollectionInvokesAdd([Substitute]ICollection<object> sut, IEnumerable<object> expectedValues) { var values = new List<object>(); sut.Add(Arg.Do<object>(values.Add)); sut.AddRange(expectedValues); values.ShouldBe(expectedValues); } [Test, AutoDomainData] [SuppressMessage("ReSharper", "PossibleMultipleEnumeration")] public void ListInvokesAddRange(IEnumerable<object> expectedValues) { var values = Substitute.For<List<object>, ICollection<object>>(); var sut = (ICollection<object>)values; sut.AddRange(expectedValues); // Since List.AddRange isn't virtual, this is the best we can do sut.DidNotReceive().Add(Arg.Any<object>()); values.ToArray().ShouldBe(expectedValues); } } }
36.115385
113
0.681044
6b81f16abecb95e402f4cf562e4b26fba622a63a
6,433
js
JavaScript
Backend/birras-service/services/geoLocationService.js
ftobares/MeetupDemo
ed88d2084df217cada87d6748046469fe43df635
[ "MIT" ]
null
null
null
Backend/birras-service/services/geoLocationService.js
ftobares/MeetupDemo
ed88d2084df217cada87d6748046469fe43df635
[ "MIT" ]
null
null
null
Backend/birras-service/services/geoLocationService.js
ftobares/MeetupDemo
ed88d2084df217cada87d6748046469fe43df635
[ "MIT" ]
null
null
null
// Database pool const poolDB = require('@config/database.config') // Logger & Properties const logger = require('@config/logger.config') const props = require('@config/properties') const schema = props.databaseSchema // Import dependencies const ResponseModel = require('@models/ResponseModel').ResponseModel const CountryModel = require('@models/CountryModel').CountryModel const StateModel = require('@models/StateModel').StateModel const CityModel = require('@models/CityModel').CityModel const getCountries = async () => { const client = await poolDB.connect(); let resp = new ResponseModel(); try{ const res = await client.query('SELECT country_id, ' + ' name ' + 'FROM '+schema+'.countries' ); if(res.rows.length > 0){ logger.warn("Countries fetched"); let countriesArray = res.rows.map((country) => { return new CountryModel( country.country_id, country.name ); }); resp.code = 200 resp.message = countriesArray }else{ logger.warn("Error fetching countries") resp.code = 200 resp.message = [] } }catch(exception){ resp.code = 500, resp.message = 'Unexpected error: '+exception return resp; } finally { client.release(); } return resp; } const getStates = async (countryId) => { const client = await poolDB.connect(); let resp = new ResponseModel(); try{ const res = await client.query('SELECT state_id, ' + ' name ' + 'FROM '+schema+'.states '+ 'WHERE country_id = $1', [ countryId ] ); if(res.rows.length > 0){ logger.warn("States fetched"); let statesArray = res.rows.map((state) => { return new StateModel( state.state_id, state.name, countryId ); }); resp.code = 200 resp.message = statesArray }else{ logger.warn("Error fetching states") resp.code = 200 resp.message = [] } }catch(exception){ resp.code = 500, resp.message = 'Unexpected error: '+exception return resp; } finally { client.release(); } return resp; } const getCities = async (stateId) => { const client = await poolDB.connect(); let resp = new ResponseModel(); try{ const res = await client.query('SELECT city_id, ' + ' name, ' + ' latitud, ' + ' longuitud ' + 'FROM '+schema+'.cities '+ 'WHERE state_id = $1', [ stateId ] ); if(res.rows.length > 0){ logger.warn("Cities fetched"); let citiesArray = res.rows.map((city) => { return new CityModel( city.city_id, city.name, stateId, city.latitud, city.longuitud ); }); resp.code = 200 resp.message = citiesArray }else{ logger.warn("Error fetching Cities") resp.code = 200 resp.message = [] } }catch(exception){ resp.code = 500, resp.message = 'Unexpected error: '+exception return resp; } finally { client.release(); } return resp; } const getCity = async (cityId) => { const client = await poolDB.connect(); let resp = new ResponseModel(); try{ const res = await client.query('SELECT city_id, ' + ' name, ' + ' state_id, ' + ' latitud, ' + ' longuitud ' + 'FROM '+schema+'.cities '+ 'WHERE city_id = $1', [ cityId ] ); if(res.rows.length > 0){ logger.warn("City fetched"); resp.code = 200 resp.message = new CityModel( res.rows[0].city_id, res.rows[0].name, res.rows[0].state_id, res.rows[0].latitud, res.rows[0].longuitud ); }else{ logger.warn("Error fetching City") resp.code = 200 resp.message = [] } }catch(exception){ resp.code = 500, resp.message = 'Unexpected error: '+exception return resp; } finally { client.release(); } return resp; } module.exports = { getCountries, getStates, getCities, getCity };
35.541436
121
0.364216
701018df461dad2def917ed536b3fb928f370ade
4,820
cpp
C++
src/plugins/azoth/plugins/xoox/xep0232handler.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
1
2017-01-12T07:05:45.000Z
2017-01-12T07:05:45.000Z
src/plugins/azoth/plugins/xoox/xep0232handler.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
src/plugins/azoth/plugins/xoox/xep0232handler.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #include "xep0232handler.h" #include <algorithm> #include <QtDebug> #include <QXmppDataForm.h> namespace LeechCraft { namespace Azoth { namespace Xoox { namespace XEP0232Handler { const QString SWInfoFormType = "urn:xmpp:dataforms:softwareinfo"; bool SoftwareInformation::IsNull () const { return OS_.isEmpty () && OSVer_.isEmpty () && Software_.isEmpty () && SoftwareVer_.isEmpty (); } SoftwareInformation FromDataForm (const QXmppDataForm& form) { if (form.isNull ()) return SoftwareInformation (); const auto& fields = form.fields (); auto pos = std::find_if (fields.begin (), fields.end (), [] (decltype (fields.front ()) field) { return field.key () == "FORM_TYPE"; }); if (pos == fields.end ()) { qWarning () << Q_FUNC_INFO << "no FORM_TYPE" << form.title (); return SoftwareInformation (); } if (pos->value () != SWInfoFormType) return SoftwareInformation (); SoftwareInformation si; Q_FOREACH (const QXmppDataForm::Field& f, fields) { const auto& var = f.key (); if (var == "icon") { const auto& media = f.media (); si.IconWidth_ = media.width (); si.IconHeight_ = media.height (); Q_FOREACH (const auto& pair, media.uris ()) if (pair.second.startsWith ("http")) { si.IconURL_ = QUrl::fromEncoded (pair.second.toLatin1 ()); si.IconType_ = pair.first; } else if (pair.second.startsWith ("cid")) si.IconCID_ = pair.second; } else if (var == "os") si.OS_ = f.value ().toString (); else if (var == "os_version") si.OSVer_ = f.value ().toString (); else if (var == "software") si.Software_ = f.value ().toString (); else if (var == "software_version") si.SoftwareVer_ = f.value ().toString (); else if (var != "FORM_TYPE") qWarning () << Q_FUNC_INFO << "unknown field" << var << f.value (); } return si; } QXmppDataForm ToDataForm (const SoftwareInformation& si) { QList<QXmppDataForm::Field> fields; QXmppDataForm::Field typeField (QXmppDataForm::Field::HiddenField); typeField.setKey ("FORM_TYPE"); typeField.setValue (SWInfoFormType); fields << typeField; if (si.IconURL_.isValid ()) { QXmppDataForm::Field iconField; iconField.setKey ("icon"); QXmppDataForm::Media media; media.setWidth (si.IconHeight_); media.setHeight (si.IconWidth_); QList<QPair<QString, QString>> uris; if (!si.IconCID_.isEmpty ()) uris << qMakePair (si.IconType_, si.IconCID_); uris << qMakePair (si.IconType_, QString (si.IconURL_.toEncoded ())); media.setUris (uris); iconField.setMedia (media); iconField.setValue (si.IconURL_.toEncoded ()); fields << iconField; } auto setStr = [&fields] (const QString& key, const QString& val) { if (!val.isEmpty ()) { QXmppDataForm::Field field; field.setKey (key); field.setValue (val); fields << field; } }; setStr ("os", si.OS_); setStr ("os_version", si.OSVer_); setStr ("software", si.Software_); setStr ("software_version", si.SoftwareVer_); QXmppDataForm form (QXmppDataForm::Result); form.setFields (fields); return form; } } } } }
31.096774
83
0.660788
e77fa7de91b31325d1aa0cb4aa6bdfb61abcce5c
3,884
php
PHP
index.php
robefosa/capiros_windows
25526018e3b77f2bbfae7fbbb9edfcf8be755dd9
[ "MIT" ]
null
null
null
index.php
robefosa/capiros_windows
25526018e3b77f2bbfae7fbbb9edfcf8be755dd9
[ "MIT" ]
null
null
null
index.php
robefosa/capiros_windows
25526018e3b77f2bbfae7fbbb9edfcf8be755dd9
[ "MIT" ]
null
null
null
<?php include_once 'header.php'; include_once 'functions/get_images.php'; $images = get_images($slide_thumbs_location); $num_elements = count($images); ?> <section id="slideshow" class="container"> <div class="bg-faded p-4 my-4"> <!-- Image Carousel --> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> <?php for($i = 1; $i < $num_elements; $i++) {?> <li data-target="#carouselExampleIndicators" data-slide-to="<?php echo $i;?>"></li> <?php } ?> </ol> <div class="carousel-inner" role="listbox"> <?php foreach ($images as $it => $va) { if($it == 0){?> <div class="carousel-item active"> <img class="d-block img-fluid w-100" src="<?php echo $slide_thumbs_location . '/' . $va;?>" alt=""> </div> <?php } else {?> <div class="carousel-item"> <img class="d-block img-fluid w-100" src="<?php echo $slide_thumbs_location . '/' . $va;?>" alt=""> </div> <?php } } ?> </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> <!-- Welcome Message --> <div class="text-center mt-4"> <div class="text-heading text-muted text-lg">Become a client of</div> <h2 class="my-2">Capiro´s Windows</h1> <a class="text-heading text-muted text-lg" href="contact.php">Request a free estimate now</a> </div> </div> </section> <section id="who_we_are" class="bg-faded p-4 my-4"> <hr class="divider"> <h2 class="text-center text-lg text-uppercase my-0"><strong>Who we are</strong></h2> <hr class="divider"> <p class="home text-center">Capiro’s Windows Corporation is a growing company who deliver a customize service, focused on the quality, safety and satisfaction of our clients expectation.</p> </section> <section id="who_we_are" class="bg-faded p-4 my-4"> <hr class="divider"> <h2 class="text-center text-lg text-uppercase my-0"><strong>Why to hire us?</strong></h2> <hr class="divider"> <p class="home text-center">We offer high quality products and a fast and efficient service, focused on solving client demands. We make homes more secure, ready to face natural disasters. Your home will be beautiful and made to last long, which increase the property value. Say bye to high electricity bills. Reduces the frequency of common repairs. You may contact us for free estimates. </p> </section> <?php include_once 'footer.php';
36.990476
136
0.496653
df91519e5429cf34bed2e0fb5946ccea78d8af1b
217
cs
C#
GISShare.Controls.WinForm/WFNew/View/Interface/IVisibleViewItem.cs
llzzhh/GISShare.Controls.WinForm
34e6c7325dc1eb9adffe871848729518ec4090d1
[ "MIT" ]
6
2019-01-15T00:32:42.000Z
2021-01-19T06:43:36.000Z
GISShare.Controls.WinForm/WFNew/View/Interface/IVisibleViewItem.cs
llzzhh/GISShare.Controls.WinForm
34e6c7325dc1eb9adffe871848729518ec4090d1
[ "MIT" ]
null
null
null
GISShare.Controls.WinForm/WFNew/View/Interface/IVisibleViewItem.cs
llzzhh/GISShare.Controls.WinForm
34e6c7325dc1eb9adffe871848729518ec4090d1
[ "MIT" ]
5
2019-03-28T07:31:16.000Z
2021-09-06T13:33:09.000Z
using System; using System.Collections.Generic; using System.Text; namespace GISShare.Controls.WinForm.WFNew.View { public interface IVisibleViewItem : IViewItem { bool Visible { get; set; } } }
18.083333
49
0.705069
ca0a29acc4ae49a18e4e400a1225464a1cdd4fdd
180
sh
Shell
deploy.sh
callum-p/callumpember.com
86964b771fe3e8ec181c28f3c810109856f2ebdf
[ "MIT" ]
null
null
null
deploy.sh
callum-p/callumpember.com
86964b771fe3e8ec181c28f3c810109856f2ebdf
[ "MIT" ]
1
2022-02-10T15:50:14.000Z
2022-02-10T15:50:14.000Z
deploy.sh
callum-p/callumpember.com
86964b771fe3e8ec181c28f3c810109856f2ebdf
[ "MIT" ]
null
null
null
#!/bin/sh -e docker-compose run --rm build aws s3 cp ./_site/ s3://callumpember.com/ --recursive aws cloudfront create-invalidation --distribution-id E20KVYOK8HW59W --paths '/*'
25.714286
80
0.727778
6f6793887206f4472499e4ed46943ce2870544df
662
php
PHP
resources/views/livewire/status/like.blade.php
Rafi1112/friendster-livewire
80a211e7331c9b584f9eccc62501383eb2c52a60
[ "MIT" ]
null
null
null
resources/views/livewire/status/like.blade.php
Rafi1112/friendster-livewire
80a211e7331c9b584f9eccc62501383eb2c52a60
[ "MIT" ]
null
null
null
resources/views/livewire/status/like.blade.php
Rafi1112/friendster-livewire
80a211e7331c9b584f9eccc62501383eb2c52a60
[ "MIT" ]
null
null
null
<div class="flex items-center mx-4"> {{-- Success is as dangerous as failure. --}} <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1 {{ $status->isLiked() ? 'text-red-600' : '' }}" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" /> </svg> {{ $status->likes()->count() }} &nbsp; <button class="focus:outline-none" wire:click="like"> {{ Str::plural('Like', $status->likes()->count()) }} </button> </div>
55.166667
208
0.598187
06cbc6a4f4e7f41d13747c7c70778ce7bce497cd
31,983
py
Python
packages/w3af/w3af/plugins/output/xml_file.py
ZooAtmosphereGroup/HelloPackages
0ccffd33bf927b13d28c8f715ed35004c33465d9
[ "Apache-2.0" ]
null
null
null
packages/w3af/w3af/plugins/output/xml_file.py
ZooAtmosphereGroup/HelloPackages
0ccffd33bf927b13d28c8f715ed35004c33465d9
[ "Apache-2.0" ]
null
null
null
packages/w3af/w3af/plugins/output/xml_file.py
ZooAtmosphereGroup/HelloPackages
0ccffd33bf927b13d28c8f715ed35004c33465d9
[ "Apache-2.0" ]
null
null
null
""" xml_file.py Copyright 2006 Andres Riancho This file is part of w3af, http://w3af.org/ . w3af 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 version 2 of the License. w3af is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with w3af; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ import os import sys import time import base64 import jinja2 import subprocess32 as subprocess import lz4.frame from jinja2 import Environment, FileSystemLoader, StrictUndefined from unicodedata import category from tempfile import NamedTemporaryFile from functools import wraps import w3af.core.data.kb.config as cf import w3af.core.data.kb.knowledge_base as kb import w3af.core.controllers.output_manager as om from w3af import ROOT_PATH from w3af.core.controllers.plugins.output_plugin import OutputPlugin from w3af.core.controllers.misc import get_w3af_version from w3af.core.controllers.exceptions import DBException from w3af.core.controllers.misc.temp_dir import get_temp_dir from w3af.core.data.db.url_tree import URLTree from w3af.core.data.db.history import HistoryItem, TraceReadException from w3af.core.data.db.disk_list import DiskList from w3af.core.data.options.opt_factory import opt_factory from w3af.core.data.options.option_types import OUTPUT_FILE from w3af.core.data.options.option_list import OptionList from w3af.core.data.misc.encoding import smart_str_ignore, smart_unicode from w3af.core.data.misc.dotdict import dotdict from w3af.core.data.constants.encodings import DEFAULT_ENCODING TIME_FORMAT = '%a %b %d %H:%M:%S %Y' TEMPLATE_ROOT = os.path.join(ROOT_PATH, 'plugins/output/xml_file/') def took(func): """ A decorator that will print how long a function was running to the debug output. This is useful for measuring performance in production. """ @wraps(func) def func_wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) spent = time.time() - start # Log things which take more than 0.5 seconds if spent > 0.5: msg = '[xml_file.flush()] %s took %.2f seconds to run.' function_name = func.__name__ args = (function_name, spent) om.out.debug(msg % args) return result return func_wrapper class xml_file(OutputPlugin): """ Print all messages to a xml file. :author: Andres Riancho (andres.riancho@gmail.com) """ XML_OUTPUT_VERSION = '2.8' def __init__(self): OutputPlugin.__init__(self) # User configured parameters self._file_name = '~/report.xml' self._timestamp = str(int(time.time())) self._long_timestamp = str(time.strftime(TIME_FORMAT, time.localtime())) # Set defaults for scan metadata self._plugins_dict = {} self._options_dict = {} self._scan_targets = None # Keep internal state self._is_working = False self._jinja2_env = self._get_jinja2_env() # List with additional xml elements self._errors = DiskList() def do_nothing(self, *args, **kwds): pass debug = information = vulnerability = console = log_http = do_nothing def error(self, message, new_line=True): """ This method is called from the output object. The output object was called from a plugin or from the framework. This method should take an action for error messages. """ # # Note that while the call to "get_caller()" is costly, it only happens # when an error occurs, so it shouldn't impact performance # error_data = (message, self.get_caller()) self._errors.append(error_data) def set_options(self, option_list): """ Sets the Options given on the OptionList to self. The options are the result of a user entering some data on a window that was constructed using the XML Options that was retrieved from the plugin using get_options() This method MUST be implemented on every plugin. :return: No value is returned. """ self._file_name = option_list['output_file'].get_value() def get_options(self): """ :return: A list of option objects for this plugin. """ ol = OptionList() d = 'Output file name where to write the XML data' o = opt_factory('output_file', self._file_name, d, OUTPUT_FILE) ol.add(o) return ol def log_enabled_plugins(self, plugins_dict, options_dict): """ This method is called from the output manager object. This method should take an action for the enabled plugins and their configuration. Usually, write the info to a file or print it somewhere. :param plugins_dict: A dict with all the plugin types and the enabled plugins for that type of plugin. :param options_dict: A dict with the options for every plugin. """ # See doc for _log_enabled_plugins_to_xml to understand why we don't write # to the XML just now. self._plugins_dict = plugins_dict self._options_dict = options_dict def end(self): """ This method is called when the scan has finished. """ self.flush() # Free some memory and disk space self._plugins_dict = {} self._options_dict = {} self._scan_targets = None self._errors.cleanup() self._jinja2_env = None def flush(self): """ Write the XML to the output file :return: None """ # Create the cache path CachedXMLNode.create_cache_path() FindingsCache.create_cache_path() # Create the context context = dotdict({}) try: self._add_scan_status_to_context(context) except RuntimeError, rte: # In some very strange scenarios we get this error: # # Can NOT call get_run_time before start() # # Just "ignore" this call to flush and write the XML in the next call msg = 'xml_file.flush() failed to add scan status to context: "%s"' om.out.debug(msg % rte) return self._add_root_info_to_context(context) self._add_scan_info_to_context(context) self._add_findings_to_context(context) self._add_errors_to_context(context) # Write to file self._write_context_to_file(context) @took def _add_root_info_to_context(self, context): context.start_timestamp = self._timestamp context.start_time_long = self._long_timestamp context.xml_version = self.XML_OUTPUT_VERSION context.w3af_version = get_w3af_version.get_w3af_version() @took def _add_scan_info_to_context(self, context): if self._scan_targets is None: self._scan_targets = ','.join([t.url_string for t in cf.cf.get('targets')]) scan_info = ScanInfo(self._jinja2_env, self._scan_targets, self._plugins_dict, self._options_dict) context.scan_info = scan_info.to_string() @took def _add_scan_status_to_context(self, context): om.out.debug('[xml_file.flush()] _add_scan_status_to_context() start') status = self.get_w3af_core().status.get_status_as_dict() om.out.debug('[xml_file.flush()] _add_scan_status_to_context() read status') all_known_urls = kb.kb.get_all_known_urls() total_urls = len(all_known_urls) om.out.debug('[xml_file.flush()] _add_scan_status_to_context() read total_urls') known_urls = self._get_known_urls(all_known_urls) om.out.debug('[xml_file.flush()] _add_scan_status_to_context() read generated URLTree') scan_status = ScanStatus(self._jinja2_env, status, total_urls, known_urls) context.scan_status = scan_status.to_string() om.out.debug('[xml_file.flush()] _add_scan_status_to_context() rendered') def _get_known_urls(self, all_known_urls): """ This method calls kb.get_all_known_urls() to retrieve the URLs, then it structures them into a tree which has some helper methods to allow us to easily print them using jinja2 templates. :return: A URLTree instance """ url_tree = URLTree() for url in all_known_urls: url_tree.add_url(url) return url_tree @took def _add_errors_to_context(self, context): context.errors = self._errors def findings(self): """ A small generator that queries the findings cache and yields all the findings so they get written to the XML. :yield: Strings representing the findings as XML """ cache = FindingsCache() cached_nodes = cache.list() processed_uniq_ids = [] om.out.debug('[xml_file.flush()] Starting findings()') start = time.time() # # This for loop is a performance improvement which should yield # really good results, taking into account that get_all_uniq_ids_iter # will only query the DB and yield IDs, without doing any of the # CPU-intensive cPickle.loads() done in get_all_findings_iter() # which we do below. # # Ideally, we're only doing a cPickle.loads() once for each finding # the rest of the calls to flush() will load the finding from the # cache in this loop, and use the exclude_ids to prevent cached # entries from being queried # # What this for loop also guarantees is that we're not simply # reading all the items from the cache and putting them into the XML, # which would be incorrect because some items are modified in the # KB (which changes their uniq id) # for uniq_id in kb.kb.get_all_uniq_ids_iter(include_ids=cached_nodes): node = cache.get_node_from_cache(uniq_id) # cached_nodes can be (), this means that get_all_uniq_ids_iter() # will return *all* findings, some might not be in the cache. When # that happens, the cache returns None if node is not None: yield node processed_uniq_ids.append(uniq_id) msg = '[xml_file.flush()] findings() processed %s cached nodes in %.2f seconds' spent = time.time() - start args = (len(processed_uniq_ids), spent) om.out.debug(msg % args) start = time.time() # # This for loop is getting all the new findings that w3af has found # In this context "new" means that the findings are not in the cache # new_findings = 0 for finding in kb.kb.get_all_findings_iter(exclude_ids=cached_nodes): uniq_id = finding.get_uniq_id() processed_uniq_ids.append(uniq_id) node = Finding(self._jinja2_env, finding).to_string() cache.save_finding_to_cache(uniq_id, node) new_findings += 1 yield node msg = '[xml_file.flush()] findings() processed %s new findings in %.2f seconds' spent = time.time() - start args = (new_findings, spent) om.out.debug(msg % args) start = time.time() # # Now that we've finished processing all the new findings we can # evict the findings that were removed from the KB from the cache # evicted_findings = 0 for cached_finding in cached_nodes: if cached_finding not in processed_uniq_ids: cache.evict_from_cache(cached_finding) evicted_findings += 1 msg = '[xml_file.flush()] findings() evicted %s findings from cache in %.2f seconds' spent = time.time() - start args = (evicted_findings, spent) om.out.debug(msg % args) @took def _add_findings_to_context(self, context): context.findings = (f for f in self.findings()) def _get_jinja2_env(self): """ Creates the jinja2 environment which will be used to render all templates The same environment is used in order to take advantage of jinja's template cache. :return: A jinja2 environment """ env_config = {'undefined': StrictUndefined, 'trim_blocks': True, 'autoescape': True, 'lstrip_blocks': True} jinja2_env = Environment(**env_config) jinja2_env.loader = FileSystemLoader(TEMPLATE_ROOT) jinja2_env.filters['escape_attr'] = jinja2_attr_value_escape_filter jinja2_env.filters['escape_text'] = jinja2_text_value_escape_filter return jinja2_env @took def _write_context_to_file(self, context): """ Write xml report to the file by rendering the context :return: None """ om.out.debug('[xml_file.flush()] Starting _write_context_to_file()') template = self._jinja2_env.get_template('root.tpl') # We use streaming as explained here: # # http://flask.pocoo.org/docs/0.12/patterns/streaming/ # # To prevent having the whole XML in memory # pylint: disable=E1101 report_stream = template.stream(context) report_stream.enable_buffering(3) # pylint: enable=E1101 # Write everything to a temp file, this is useful in two cases: # # * An external tool will always see a valid XML in the output, # and not just a partially written XML document. # # * If w3af is killed in the middle of writing the XML report, # the report file will still be valid -- if xml_file.flush() was # run successfully at least once tempfh = NamedTemporaryFile(delete=False, prefix='w3af-xml-output', suffix='.xml') om.out.debug('[xml_file.flush()] write_context_to_file() created' ' template.stream and NamedTemporaryFile') try: # Write each report section to the temp file for report_section in report_stream: tempfh.write(report_section.encode(DEFAULT_ENCODING)) except Exception: # No exception handling is done here, we just raise the exception # so that the core can handle it properly raise else: # Close the temp file so all the content is flushed tempfh.close() om.out.debug('[xml_file.flush()] write_context_to_file() starting to' ' copy temp file to destination') # Copy to the real output file report_file_name = os.path.expanduser(self._file_name) cmd = 'cp %s %s' % (tempfh.name, report_file_name) subprocess.call(cmd, shell=True) om.out.debug('[xml_file.flush()] write_context_to_file() finished copy' ' operation.') stat_info = os.stat(report_file_name) om.out.debug('The XML output file size is %s bytes.' % stat_info.st_size) finally: os.remove(tempfh.name) om.out.debug('[xml_file.flush()] write_context_to_file() finished') def get_long_desc(self): """ :return: A DETAILED description of the plugin functions and features. """ return """ This plugin creates an XML file containing all of w3af's findings. One configurable parameter exists: - output_file When using the contents of the XML file it's important to notice that the long-description and fix-guidance tags contain text in markdown format. The generated XML file validates against the report.xsd file which is distributed with the plugin. Some vulnerabilities require special characters to be triggered, those special characters might not be valid according to the XML specification, in order to be able to write these to the report, tags like the following are used: <character code="hhhh"/> Where "hhhh" is the hex representation of the character. The XML parser should handle these tags and show the real character to the user, encoded as expected in the final format. """ class FindingsCache(object): COMPRESSION_LEVEL = 2 @staticmethod def create_cache_path(): cache_path = FindingsCache.get_cache_path() if not os.path.exists(cache_path): os.makedirs(cache_path) @staticmethod def get_cache_path(): return os.path.join(get_temp_dir(), 'xml_file', 'findings') def get_filename_from_uniq_id(self, uniq_id): return os.path.join(FindingsCache.get_cache_path(), uniq_id) def get_node_from_cache(self, uniq_id): filename = self.get_filename_from_uniq_id(uniq_id) try: node = lz4.frame.decompress(open(filename, 'rb').read()) except (IOError, RuntimeError): return None return node.decode('utf-8') def save_finding_to_cache(self, uniq_id, node): filename = self.get_filename_from_uniq_id(uniq_id) node = node.encode('utf-8') open(filename, 'wb').write(lz4.frame.compress(node)) def evict_from_cache(self, uniq_id): filename = self.get_filename_from_uniq_id(uniq_id) if os.path.exists(filename): os.remove(filename) def list(self): return os.listdir(FindingsCache.get_cache_path()) class XMLNode(object): TEMPLATE = None TEMPLATE_INST = None def __init__(self, jinja2_env): """ :param jinja2_env: The jinja2 environment to use for rendering """ self._jinja2_env = jinja2_env def get_template(self, template_name): return self._jinja2_env.get_template(template_name) class CachedXMLNode(XMLNode): COMPRESSION_LEVEL = 2 @staticmethod def create_cache_path(): cache_path = CachedXMLNode.get_cache_path() if not os.path.exists(cache_path): os.makedirs(cache_path) @staticmethod def get_cache_path(): return os.path.join(get_temp_dir(), 'xml_file') def get_cache_key(self): raise NotImplementedError def get_filename(self): return os.path.join(CachedXMLNode.get_cache_path(), self.get_cache_key()) def get_node_from_cache(self): filename = self.get_filename() try: node = lz4.frame.decompress(open(filename, 'rb').read()) except (IOError, RuntimeError): return None return node.decode('utf-8') def save_node_to_cache(self, node): filename = self.get_filename() node = node.encode('utf-8') open(filename, 'wb').write(lz4.frame.compress(node)) class HTTPTransaction(CachedXMLNode): TEMPLATE = 'http_transaction.tpl' def __init__(self, jinja2_env, _id): """ :param _id: The HTTP request / response ID from w3af. This is is used to query the history and get the information. In most cases we'll get the information from the cache and return the XML node. """ super(HTTPTransaction, self).__init__(jinja2_env) self._id = _id def get_cache_key(self): return 'http-transaction-%s.data' % self._id def to_string(self): """ :return: An xml node (as a string) representing the HTTP request / response. <http-transaction id="..."> <http-request> <status></status> <headers> <header> <field></field> <content></content> </header> </headers> <body content-encoding="base64"></body> </http-request> <http-response> <status></status> <headers> <header> <field></field> <content></content> </header> </headers> <body content-encoding="base64"></body> </http-response> </http-transaction> One of the differences this class has with the previous implementation is that the body is always encoded, no matter the content-type. This helps prevent encoding issues. """ # Get the data from the cache node = self.get_node_from_cache() if node is not None: return node # HistoryItem to get requests/responses req_history = HistoryItem() # This might raise a DBException in some cases (which I still # need to identify and fix). When an exception is raised here # the caller needs to handle it by ignoring this part of the # HTTP transaction request, response = req_history.load_from_file(self._id) data = request.get_data() or '' b64_encoded_request_body = base64.encodestring(smart_str_ignore(data)) body = response.get_body() or '' b64_encoded_response_body = base64.encodestring(smart_str_ignore(body)) context = {'id': self._id, 'request': {'status': request.get_request_line().strip(), 'headers': request.get_headers(), 'body': b64_encoded_request_body}, 'response': {'status': response.get_status_line().strip(), 'headers': response.get_headers(), 'body': b64_encoded_response_body}} context = dotdict(context) template = self.get_template(self.TEMPLATE) transaction = template.render(context) self.save_node_to_cache(transaction) return transaction class ScanInfo(CachedXMLNode): TEMPLATE = 'scan_info.tpl' def __init__(self, jinja2_env, scan_target, plugins_dict, options_dict): """ Represents the w3af scan information :param plugins_dict: The plugins which were enabled :param options_dict: The options for each plugin """ super(ScanInfo, self).__init__(jinja2_env) self._scan_target = scan_target self._plugins_dict = plugins_dict self._options_dict = options_dict def get_cache_key(self): return 'scan-info.data' def to_string(self): # Get the data from the cache node = self.get_node_from_cache() if node is not None: return node context = {'enabled_plugins': self._plugins_dict, 'plugin_options': self._options_dict, 'scan_target': self._scan_target} template = self.get_template(self.TEMPLATE) transaction = template.render(context) self.save_node_to_cache(transaction) return transaction class ScanStatus(XMLNode): TEMPLATE = 'scan_status.tpl' def __init__(self, jinja2_env, status, total_urls, known_urls): """ Represents the current w3af scan status :param status: The w3af status as reported by the w3af core :param total_urls: The number of identified URLs """ super(ScanStatus, self).__init__(jinja2_env) self._status = status self._total_urls = total_urls self._known_urls = known_urls def to_string(self): context = dotdict({}) context.status = self._status['status'] context.is_paused = self._status['is_paused'] context.is_running = self._status['is_running'] context.active_crawl_plugin = self._status['active_plugin']['crawl'] context.active_audit_plugin = self._status['active_plugin']['audit'] context.current_crawl_request = self._status['current_request']['crawl'] context.current_audit_request = self._status['current_request']['audit'] context.crawl_input_speed = self._status['queues']['crawl']['input_speed'] context.crawl_output_speed = self._status['queues']['crawl']['output_speed'] context.crawl_queue_length = self._status['queues']['crawl']['length'] context.crawl_queue_processed_tasks = self._status['queues']['crawl']['processed_tasks'] context.audit_input_speed = self._status['queues']['audit']['input_speed'] context.audit_output_speed = self._status['queues']['audit']['output_speed'] context.audit_queue_length = self._status['queues']['audit']['length'] context.audit_queue_processed_tasks = self._status['queues']['audit']['processed_tasks'] context.grep_input_speed = self._status['queues']['grep']['input_speed'] context.grep_output_speed = self._status['queues']['grep']['output_speed'] context.grep_queue_length = self._status['queues']['grep']['length'] context.grep_queue_processed_tasks = self._status['queues']['grep']['processed_tasks'] context.crawl_eta = self._status['eta']['crawl'] context.audit_eta = self._status['eta']['audit'] context.grep_eta = self._status['eta']['grep'] context.all_eta = self._status['eta']['all'] context.rpm = self._status['rpm'] context.sent_request_count = self._status['sent_request_count'] context.progress = self._status['progress'] context.total_urls = self._total_urls context.known_urls = self._known_urls template = self.get_template(self.TEMPLATE) transaction = template.render(context) return transaction class Finding(XMLNode): TEMPLATE = 'finding.tpl' def __init__(self, jinja2_env, info): """ Represents a finding in the w3af framework, which will be serialized as an XML node """ super(Finding, self).__init__(jinja2_env) self._info = info def to_string(self): info = self._info context = dotdict({}) context.id_list = info.get_id() context.http_method = info.get_method() context.name = info.get_name() context.plugin_name = info.get_plugin_name() context.severity = info.get_severity() context.url = info.get_url().url_string if info.get_url() is not None else None context.var = info.get_token_name() context.description = info.get_desc(with_id=False) # # Add the information from the vuln db (if any) # context.long_description = None if info.has_db_details(): context.long_description = info.get_long_description() context.fix_guidance = info.get_fix_guidance() context.fix_effort = info.get_fix_effort() context.references = info.get_references() # # Add the HTTP transactions # context.http_transactions = [] for transaction in info.get_id(): try: xml = HTTPTransaction(self._jinja2_env, transaction).to_string() except (DBException, TraceReadException) as e: msg = ('Failed to retrieve request with id %s from DB: "%s".' ' The "%s" vulnerability will have an incomplete HTTP' ' transaction list.') args = (transaction, e, context.name) om.out.error(msg % args) continue else: context.http_transactions.append(xml) template = self.get_template(self.TEMPLATE) transaction = template.render(context) return transaction def is_unicode_escape(i): return category(unichr(i)).startswith('C') ATTR_VALUE_ESCAPES = { u'"': u'&quot;', u'&': u'&amp;', u'<': u'&lt;', u'>': u'&gt;', # Note that here we replace tabs with 4-spaces, like in python ;-) # but it makes sense for easy parsing and showing to users u'\t': u' ', } ATTR_VALUE_ESCAPES.update(dict((unichr(i), '&lt;character code=&quot;%04x&quot;/&gt;' % i) for i in xrange(sys.maxunicode) if is_unicode_escape(i))) ATTR_VALUE_ESCAPES_IGNORE = {'\n', '\r'} def jinja2_attr_value_escape_filter(value): """ This method is used to escape attribute values: <tag attribute="value"> The objective is to escape all the special characters which can not be printed in that context. We also implement something very specific for special characters. We're replacing the XML invalid characters with: <character code="%04x"/> The parser should handle that and replace these tags with the real char (if it can be handled by the reader). Something to note is that when escaping special characters we print the HTML-encoded (< replaced by &lt; and so on) version of the `character` tag. We do that because it is invalid to print < inside the attribute value. :param value: The value to escape :return: The escaped string """ if not isinstance(value, basestring): return value # Fix some encoding errors which are triggered when the value is not an # unicode string value = smart_unicode(value) retval = u'' for letter in value: if letter in ATTR_VALUE_ESCAPES_IGNORE: retval += letter continue escape = ATTR_VALUE_ESCAPES.get(letter, None) if escape is not None: retval += escape else: retval += letter return jinja2.Markup(retval) TEXT_VALUE_ESCAPES = { u'"': u'&quot;', u'&': u'&amp;', u'<': u'&lt;', u'>': u'&gt;', # Note that here we replace tabs with 4-spaces, like in python ;-) # but it makes sense for easy parsing and showing to users u'\t': u' ', } TEXT_VALUE_ESCAPES.update(dict((unichr(i), '<character code="%04x"/>' % i) for i in xrange(sys.maxunicode) if is_unicode_escape(i))) TEXT_VALUE_ESCAPES_IGNORE = {'\n', '\r'} def jinja2_text_value_escape_filter(value): """ This method is used to escape text values: <tag>text</tag> The objective is to escape all the special characters which can not be printed in that context, and the special characters which might be in the input and we want to escape to avoid "xml injection". We also implement something very specific for special characters. We're replacing the XML invalid characters with: <character code="%04x"/> The parser should handle that and replace these tags with the real char (if it can be handled by the reader). :param value: The value to escape :return: The escaped string """ if not isinstance(value, basestring): return value # Fix some encoding errors which are triggered when the value is not an # unicode string value = smart_unicode(value) retval = u'' for letter in value: if letter in TEXT_VALUE_ESCAPES_IGNORE: retval += letter continue escape = TEXT_VALUE_ESCAPES.get(letter, None) if escape is not None: retval += escape else: retval += letter return jinja2.Markup(retval)
33.98831
96
0.629522