text
stringlengths
27
775k
// Copyright (c) 2020 Google LLC All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #![deny(missing_docs)] use { crate::{content::*, error::*, options::*}, std::cell::RefCell, std::collections::HashMap, std::collections::HashSet, std::rc::Rc, }; pub(crate) struct SubpathOptions { /// Options for the matching property name, including subpath-options for nested containers. /// If matched, these options apply exclusively; the `options_for_next_level` will not apply. subpath_options_by_name: HashMap<String, Rc<RefCell<SubpathOptions>>>, /// Options for nested containers under any array item, or any property not matching a property /// name in `subpath_options_by_name`. unnamed_subpath_options: Option<Rc<RefCell<SubpathOptions>>>, /// The options that override the default FormatOptions (those passed to `with_options()`) for /// the matched path. pub options: FormatOptions, /// A map of property names to priority values, for sorting properties at the matched path. property_name_priorities: HashMap<&'static str, usize>, } impl SubpathOptions { /// Properties without an explicit priority will be sorted after prioritized properties and /// retain their original order with respect to any other unpriorized properties. const NO_PRIORITY: usize = std::usize::MAX; pub fn new(default_options: &FormatOptions) -> Self { Self { subpath_options_by_name: HashMap::new(), unnamed_subpath_options: None, options: default_options.clone(), property_name_priorities: HashMap::new(), } } pub fn override_default_options(&mut self, path_options: &HashSet<PathOption>) { for path_option in path_options.iter() { use PathOption::*; match path_option { TrailingCommas(path_value) => self.options.trailing_commas = *path_value, CollapseContainersOfOne(path_value) => { self.options.collapse_containers_of_one = *path_value } SortArrayItems(path_value) => self.options.sort_array_items = *path_value, PropertyNameOrder(property_names) => { for (index, property_name) in property_names.iter().enumerate() { self.property_name_priorities.insert(property_name, index); } } } } } pub fn get_or_create_subpath_options( &mut self, path: &[&str], default_options: &FormatOptions, ) -> Rc<RefCell<SubpathOptions>> { let name_or_star = path[0]; let remaining_path = &path[1..]; let subpath_options_ref = if name_or_star == "*" { self.unnamed_subpath_options.as_ref() } else { self.subpath_options_by_name.get(name_or_star) }; let subpath_options = match subpath_options_ref { Some(existing_options) => existing_options.clone(), None => { let new_options = Rc::new(RefCell::new(SubpathOptions::new(default_options))); if name_or_star == "*" { self.unnamed_subpath_options = Some(new_options.clone()); } else { self.subpath_options_by_name .insert(name_or_star.to_string(), new_options.clone()); } new_options } }; if remaining_path.len() == 0 { subpath_options } else { (*subpath_options.borrow_mut()) .get_or_create_subpath_options(remaining_path, default_options) } } fn get_subpath_options(&self, path: &[&str]) -> Option<Rc<RefCell<SubpathOptions>>> { let name_or_star = path[0]; let remaining_path = &path[1..]; let subpath_options_ref = if name_or_star == "*" { self.unnamed_subpath_options.as_ref() } else { self.subpath_options_by_name.get(name_or_star) }; if let Some(subpath_options) = subpath_options_ref { if remaining_path.len() == 0 { Some(subpath_options.clone()) } else { (*subpath_options.borrow()).get_subpath_options(remaining_path) } } else { None } } fn get_options_for(&self, name_or_star: &str) -> Option<Rc<RefCell<SubpathOptions>>> { self.get_subpath_options(&[name_or_star]) } pub fn get_property_priority(&self, property_name: &str) -> usize { match self.property_name_priorities.get(property_name) { Some(priority) => *priority, None => SubpathOptions::NO_PRIORITY, } } fn debug_format( &self, formatter: &mut std::fmt::Formatter<'_>, indent: &str, ) -> std::fmt::Result { writeln!(formatter, "{{")?; let next_indent = indent.to_owned() + " "; writeln!(formatter, "{}options = {:?}", &next_indent, self.options)?; writeln!( formatter, "{}property_name_priorities = {:?}", &next_indent, self.property_name_priorities )?; if let Some(unnamed_subpath_options) = &self.unnamed_subpath_options { write!(formatter, "{}* = ", &next_indent)?; (*unnamed_subpath_options.borrow()).debug_format(formatter, &next_indent)?; writeln!(formatter)?; } for (property_name, subpath_options) in self.subpath_options_by_name.iter() { write!(formatter, "{}{} = ", &next_indent, property_name)?; (*subpath_options.borrow()).debug_format(formatter, &next_indent)?; writeln!(formatter)?; } writeln!(formatter, "{}}}", &indent) } } impl std::fmt::Debug for SubpathOptions { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.debug_format(formatter, "") } } /// A JSON5 formatter that produces formatted JSON5 document content from a JSON5 `ParsedDocument`. pub(crate) struct Formatter { /// The current depth of the partially-generated document while formatting. Each nexted array or /// object increases the depth by 1. After the formatted array or object has been generated, the /// depth decreases by 1. depth: usize, /// The next value to be written should be indented. pending_indent: bool, /// The UTF-8 bytes of the output document as it is being generated. bytes: Vec<u8>, /// The 1-based column number of the next character to be appended. column: usize, /// While generating the formatted document, these are the options to be applied at each nesting /// depth and path, from the document root to the object or array currently being generated. If /// the current path has no explicit options, the value at the top of the stack is None. subpath_options_stack: Vec<Option<Rc<RefCell<SubpathOptions>>>>, /// Options that alter how the formatter generates the formatted output. This instance of /// FormatOptions is a subset of the FormatOptions passed to the `with_options` constructor. /// The `options_by_path` are first removed, and then used to initialize the SubpathOptions /// hierarchy rooted at the `document_root_options_ref`. default_options: FormatOptions, } impl Formatter { /// Create and return a Formatter, with the given options to be applied to the /// [Json5Format::to_utf8()](struct.Json5Format.html#method.to_utf8) operation. pub fn new( default_options: FormatOptions, document_root_options_ref: Rc<RefCell<SubpathOptions>>, ) -> Self { Formatter { depth: 0, pending_indent: false, bytes: vec![], column: 1, subpath_options_stack: vec![Some(document_root_options_ref)], default_options, } } pub fn increase_indent(&mut self) -> Result<&mut Formatter, Error> { self.depth += 1; Ok(self) } pub fn decrease_indent(&mut self) -> Result<&mut Formatter, Error> { self.depth -= 1; Ok(self) } /// Appends the given string, indenting if required. pub fn append(&mut self, content: &str) -> Result<&mut Formatter, Error> { if self.pending_indent && !content.starts_with("\n") { let spaces = self.depth * self.default_options.indent_by; self.bytes.extend_from_slice(" ".repeat(spaces).as_bytes()); self.column = spaces + 1; self.pending_indent = false; } if content.ends_with("\n") { self.column = 1; self.bytes.extend_from_slice(content.as_bytes()); } else { let mut first = true; for line in content.lines() { if !first { self.bytes.extend_from_slice("\n".as_bytes()); self.column = 1; } self.bytes.extend_from_slice(line.as_bytes()); self.column += line.len(); first = false; } } Ok(self) } pub fn append_newline(&mut self) -> Result<&mut Formatter, Error> { self.append("\n") } /// Outputs a newline (unless this is the first line), and sets the `pending_indent` flag to /// indicate the next non-blank line should be indented. pub fn start_next_line(&mut self) -> Result<&mut Formatter, Error> { if self.bytes.len() > 0 { self.append_newline()?; } self.pending_indent = true; Ok(self) } fn format_content<F>(&mut self, content_fn: F) -> Result<&mut Formatter, Error> where F: FnOnce(&mut Formatter) -> Result<&mut Formatter, Error>, { content_fn(self) } pub fn format_container<F>( &mut self, left_brace: &str, right_brace: &str, content_fn: F, ) -> Result<&mut Formatter, Error> where F: FnOnce(&mut Formatter) -> Result<&mut Formatter, Error>, { self.append(left_brace)? .increase_indent()? .format_content(content_fn)? .decrease_indent()? .append(right_brace) } fn format_comments_internal( &mut self, comments: &Vec<Comment>, leading_blank_line: bool, ) -> Result<&mut Formatter, Error> { let mut previous: Option<&Comment> = None; for comment in comments.iter() { match previous { Some(previous) => { if comment.is_block() || previous.is_block() { // Separate block comments and contiguous line comments. // Use append_newline() instead of start_next_line() because block comment // lines after the first line append their own indentation spaces. self.append_newline()?; } } None => { if leading_blank_line { self.start_next_line()?; } } } comment.format(self)?; previous = Some(comment) } Ok(self) } pub fn format_comments( &mut self, comments: &Vec<Comment>, is_first: bool, ) -> Result<&mut Formatter, Error> { self.format_comments_internal(comments, !is_first) } pub fn format_trailing_comments( &mut self, comments: &Vec<Comment>, ) -> Result<&mut Formatter, Error> { self.format_comments_internal(comments, true) } pub fn get_current_subpath_options(&self) -> Option<&Rc<RefCell<SubpathOptions>>> { self.subpath_options_stack.last().unwrap().as_ref() } fn enter_scope(&mut self, name_or_star: &str) { let mut subpath_options_to_push = None; if let Some(current_subpath_options_ref) = self.get_current_subpath_options() { let current_subpath_options = &*current_subpath_options_ref.borrow(); if let Some(next_subpath_options_ref) = current_subpath_options.get_options_for(name_or_star) { // SubpathOptions were explicitly provided for: // * the given property name in the current object; or // * all array items within the current array (as indicated by "*") subpath_options_to_push = Some(next_subpath_options_ref.clone()); } else if name_or_star != "*" { if let Some(next_subpath_options_ref) = current_subpath_options.get_options_for("*") { // `name_or_star` was a property name, and SubpathOptions for this path were // _not_ explicitly defined for this name. In this case, a Subpath defined with // "*" at this Subpath location, if provided, matches any property name in the // current object (like a wildcard). subpath_options_to_push = Some(next_subpath_options_ref.clone()); } } } self.subpath_options_stack.push(subpath_options_to_push); } fn exit_scope(&mut self) { self.subpath_options_stack.pop(); } fn format_scoped_value( &mut self, name: Option<&str>, value: &mut Value, is_first: bool, is_last: bool, container_has_pending_comments: bool, ) -> Result<&mut Formatter, Error> { let collapsed = is_first && is_last && value.is_primitive() && !value.has_comments() && !container_has_pending_comments && self.options_in_scope().collapse_containers_of_one; match name { // Above the enter_scope(...), the container's SubpathOptions affect formatting // and below, formatting is affected by named property or item SubpathOptions. // vvvvvvvvvvv Some(name) => self.enter_scope(name), None => self.enter_scope("*"), } if collapsed { self.append(" ")?; } else { if is_first { self.start_next_line()?; } self.format_comments(&value.comments().before_value(), is_first)?; } if let Some(name) = name { self.append(&format!("{}: ", name))?; } value.format(self)?; self.exit_scope(); // ^^^^^^^^^^ // Named property or item SubpathOptions affect Formatting above exit_scope(...) // and below, formatting is affected by the container's SubpathOptions. if collapsed { self.append(" ")?; } else { self.append_comma(is_last)? .append_end_of_line_comment(value.comments().end_of_line())? .start_next_line()?; } Ok(self) } pub fn format_item( &mut self, item: &Rc<RefCell<Value>>, is_first: bool, is_last: bool, container_has_pending_comments: bool, ) -> Result<&mut Formatter, Error> { self.format_scoped_value( None, &mut *item.borrow_mut(), is_first, is_last, container_has_pending_comments, ) } pub fn format_property( &mut self, property: &Property, is_first: bool, is_last: bool, container_has_pending_comments: bool, ) -> Result<&mut Formatter, Error> { self.format_scoped_value( Some(&property.name), &mut *property.value.borrow_mut(), is_first, is_last, container_has_pending_comments, ) } pub fn options_in_scope(&self) -> FormatOptions { match self.get_current_subpath_options() { Some(subpath_options) => (*subpath_options.borrow()).options.clone(), None => self.default_options.clone(), } } fn append_comma(&mut self, is_last: bool) -> Result<&mut Formatter, Error> { if !is_last || self.options_in_scope().trailing_commas { self.append(",")?; } Ok(self) } /// Outputs the value's end-of-line comment. If the comment has multiple lines, the first line /// is written from the current position and all subsequent lines are written on their own line, /// left-aligned directly under the first comment. fn append_end_of_line_comment( &mut self, comment: &Option<String>, ) -> Result<&mut Formatter, Error> { if let Some(comment) = comment { let start_column = self.column; let mut first = true; for line in comment.lines() { if !first { self.append_newline()?; self.append(&" ".repeat(start_column - 1))?; } self.append(&format!(" //{}", line))?; first = false; } } Ok(self) } /// Formats the given document into the returned UTF8 byte buffer, consuming self. pub fn format(mut self, parsed_document: &ParsedDocument) -> Result<Vec<u8>, Error> { parsed_document.content.format_content(&mut self)?; Ok(self.bytes) } }
require 'spec_helper' describe RspecApiDocumentation::Curl do let(:host) { "http://example.com" } let(:curl) { RspecApiDocumentation::Curl.new(method, path, data, headers) } subject { curl.output(host, ["Host", "Cookies"]) } describe "POST" do let(:method) { "POST" } let(:path) { "/orders" } let(:data) { "order%5Bsize%5D=large&order%5Btype%5D=cart" } let(:headers) do { "HTTP_ACCEPT" => "application/json", "HTTP_X_HEADER" => "header", "HTTP_AUTHORIZATION" => %{Token token="mytoken"}, "HTTP_DEVICE-ID" => "header", "HTTP_HOST" => "example.org", "HTTP_COOKIES" => "", "HTTP_SERVER" => nil } end it { should =~ /^curl/ } it { should =~ /http:\/\/example\.com\/orders/ } it { should =~ /-d 'order%5Bsize%5D=large&order%5Btype%5D=cart'/ } it { should =~ /-X POST/ } it { should =~ /-H "Accept: application\/json"/ } it { should =~ /-H "X-Header: header"/ } it { should =~ /-H "Device-Id: header"/ } it { should =~ /-H "Authorization: Token token=\\"mytoken\\""/ } it { should =~ /-H "Server: "/ } it { should_not =~ /-H "Host: example\.org"/ } it { should_not =~ /-H "Cookies: "/ } it "should call post" do expect(curl).to receive(:post) curl.output(host) end end describe "GET" do let(:method) { "GET" } let(:path) { "/orders" } let(:data) { "size=large" } let(:headers) do { "HTTP_ACCEPT" => "application/json", "HTTP_X_HEADER" => "header", "HTTP_HOST" => "example.org", "HTTP_COOKIES" => "" } end it { should =~ /^curl/ } it { should =~ /http:\/\/example\.com\/orders\?size=large/ } it { should =~ /-X GET/ } it { should =~ /-H "Accept: application\/json"/ } it { should =~ /-H "X-Header: header"/ } it { should_not =~ /-H "Host: example\.org"/ } it { should_not =~ /-H "Cookies: "/ } it "should call get" do expect(curl).to receive(:get) curl.output(host) end end describe "PUT" do let(:method) { "PUT" } let(:path) { "/orders/1" } let(:data) { "size=large" } let(:headers) do { "HTTP_ACCEPT" => "application/json", "HTTP_X_HEADER" => "header", "HTTP_HOST" => "example.org", "HTTP_COOKIES" => "" } end it { should =~ /^curl/ } it { should =~ /http:\/\/example\.com\/orders\/1/ } it { should =~ /-d 'size=large'/ } it { should =~ /-X PUT/ } it { should =~ /-H "Accept: application\/json"/ } it { should =~ /-H "X-Header: header"/ } it { should_not =~ /-H "Host: example\.org"/ } it { should_not =~ /-H "Cookies: "/ } it "should call put" do expect(curl).to receive(:put) curl.output(host) end end describe "DELETE" do let(:method) { "DELETE" } let(:path) { "/orders/1" } let(:data) { } let(:headers) do { "HTTP_ACCEPT" => "application/json", "HTTP_X_HEADER" => "header", "HTTP_HOST" => "example.org", "HTTP_COOKIES" => "" } end it { should =~ /^curl/ } it { should =~ /http:\/\/example\.com\/orders\/1/ } it { should =~ /-X DELETE/ } it { should =~ /-H "Accept: application\/json"/ } it { should =~ /-H "X-Header: header"/ } it { should_not =~ /-H "Host: example\.org"/ } it { should_not =~ /-H "Cookies: "/ } it "should call delete" do expect(curl).to receive(:delete) curl.output(host) end end describe "HEAD" do let(:method) { "HEAD" } let(:path) { "/orders" } let(:data) { "size=large" } let(:headers) do { "HTTP_ACCEPT" => "application/json", "HTTP_X_HEADER" => "header", "HTTP_HOST" => "example.org", "HTTP_COOKIES" => "" } end it { should =~ /^curl/ } it { should =~ /http:\/\/example\.com\/orders\?size=large/ } it { should =~ /-X HEAD/ } it { should =~ /-H "Accept: application\/json"/ } it { should =~ /-H "X-Header: header"/ } it { should_not =~ /-H "Host: example\.org"/ } it { should_not =~ /-H "Cookies: "/ } it "should call get" do expect(curl).to receive(:head) curl.output(host) end end describe "PATCH" do let(:method) { "PATCH" } let(:path) { "/orders/1" } let(:data) { "size=large" } let(:headers) do { "HTTP_ACCEPT" => "application/json", "HTTP_X_HEADER" => "header", "HTTP_HOST" => "example.org", "HTTP_COOKIES" => "" } end it { should =~ /^curl/ } it { should =~ /http:\/\/example\.com\/orders\/1/ } it { should =~ /-d 'size=large'/ } it { should =~ /-X PATCH/ } it { should =~ /-H "Accept: application\/json"/ } it { should =~ /-H "X-Header: header"/ } it { should_not =~ /-H "Host: example\.org"/ } it { should_not =~ /-H "Cookies: "/ } it "should call put" do expect(curl).to receive(:patch) curl.output(host) end end describe "Basic Authentication" do let(:method) { "GET" } let(:path) { "/" } let(:data) { "" } let(:headers) do { "HTTP_AUTHORIZATION" => %{Basic dXNlckBleGFtcGxlLm9yZzpwYXNzd29yZA==}, } end it { should_not =~ /-H "Authorization: Basic dXNlckBleGFtcGxlLm9yZzpwYXNzd29yZA=="/ } it { should =~ /-u user@example\.org:password/ } end end
# digitalocean-paas-static Simple static site to automatic deploy DigitalOcean PaaS (Platform as a Service) Static Site # live url https://digitalocean-paas-static-x4s8t.ondigitalocean.app/
# Copyright (C) 2011, Kevin Polulak <[email protected]>. # Copyright (C) 2015-2016 The Perl6 Community. # TODO Define Test::Builder::Exception # TODO Replace die() with fail() =begin pod =head1 NAME Test::Builder - flexible framework for building TAP test libraries =head1 SYNOPSIS =begin code my $tb = Test::Builder.new; $tb.plan(2); $tb.ok(1, 'This is a test'); $tb.ok(1, 'This is another test'); $tb.done; =end code =head1 DESCRIPTION C<Test::Builder> is meant to serve as a generic backend for test libraries. Put differently, it provides the basic "building blocks" and generic functionality needed for building your own application-specific TAP test libraries. C<Test::Builder> conforms to the Test Anything Protocol (TAP) specification. =head1 USE =head2 Object Initialization =over 4 =item B<new()> Returns the C<Test::Builder> singleton object. The C<new()> method only returns a new object the first time that it's called. If called again, it simply returns the same object. This allows multiple modules to share the global information about the TAP harness's state. Alternatively, if a singleton object is too limiting, you can use the C<create()> method instead. =item B<create()> Returns a new C<Test::Builder> instance. The C<create()> method should only be used under certain circumstances. For instance, when testing C<Test::Builder>-based modules. In all other cases, it is recommended that you stick to using C<new()> instead. =back =head2 Implementing Tests The following methods are responsible for performing the actual tests. All methods take an optional string argument describing the nature of the test. =over 4 =item B<plan(Int $tests)> Declares how many tests are going to be run. If called as C<.plan(*)>, then a plan will not be set. However, it is your job to call C<done()> when all tests have been run. =item B<ok(Mu $test, Str $description)> Evaluates C<$test> in a boolean context. The test will pass if the expression evaluates to C<Bool::True> and fail otherwise. =item B<nok(Mu $test, Str $description)> The antithesis of C<ok()>. Evaluates C<$test> in a boolean context. The test will pass if the expression evaluates to C<Bool::False> and fail otherwise. =back =head2 Modifying Test Behavior =over 4 =item B<todo(Str $reason, Int $count)> Marks the next C<$count> tests as failures but ignores the fact. Test execution will continue after displaying the message in C<$reason>. It's important to note that even though the tests are marked as failures, they will still be evaluated. If a test marked with C<todo()> in fact passes, a warning message will be displayed. # TODO The todo() method doesn't actually does this yet but I want it to =back =head1 SEE ALSO L<http://testanything.org> =head1 ACKNOWLEDGEMENTS C<Test::Builder> was largely inspired by chromatic's work on the old C<Test::Builder> module for Pugs. Additionally, C<Test::Builder> is based on the Perl 5 module of the same name also written by chromatic <[email protected]> and Michael G. Schwern <[email protected]>. =head1 COPYRIGHT Copyright (C) 2011, Kevin Polulak <[email protected]>. Copyright (C) 2015-2016 The Perl6 Community. This program is distributed under the terms of the Artistic License 2.0. For further information, please see LICENSE or visit <http://www.perlfoundation.org/attachment/legal/artistic-2_0.txt>. =end pod use Test::Builder::Test; use Test::Builder::Plan; use Test::Builder::Output; class Test::Builder { ... }; #= Global Test::Builder singleton object my Test::Builder $TEST_BUILDER; class Test::Builder:auth<soh_cah_toa>:ver<0.0.1> { #= Stack containing results of each test has @!results; #= Sets up number of tests to run has Test::Builder::Plan::Generic $!plan; #= Handles all output operations has Test::Builder::Output $!output handles 'diag'; #= Specifies whether or not .done() has been called has Bool $.done_testing is rw; #= Returns the Test::Builder singleton object method new() { return $TEST_BUILDER //= self.create; } #= Returns a new Test::Builder instance method create() { return $?CLASS.bless; } submethod BUILD(Test::Builder::Plan $!plan?, Test::Builder::Output $!output = Test::Builder::Output.new) { } #= Declares that no more tests need to be run method done() { $.done_testing = True; # "Cannot look up attributes in a type object" error check. my $footer = $!plan.footer(+@!results) if ?$!plan; $!output.write($footer) if $footer; } #= Declares the number of tests to run multi method plan(Int $tests) { die 'Plan already set!' if $!plan; $!plan = Test::Builder::Plan.new(:expected($tests)); } #= Declares that the number of tests is unknown multi method plan(Whatever $tests) { die 'Plan already set!' if $!plan; $!plan = Test::Builder::NoPlan.new; } # TODO Implement skip_all and no_plan multi method plan(Str $explanation) { ... } #= Default candidate for arguments of the wrong type multi method plan(Any $any) { die 'Unknown plan!'; } #= Tests the first argument for boolean truth method ok(Mu $test, Str $description= '') { self!report_test(Test::Builder::Test.new(:number(self!get_test_number), :passed(?$test), :description($description))); return $test; } #= Tests the first argument for boolean false method nok(Mu $test, Str $description= '') { self!report_test(Test::Builder::Test.new(:number(self!get_test_number), :passed(!$test), :description($description))); return $test; } #= Verifies that the first two arguments are equal method is(Mu $got, Mu $expected, Str $description= '') { my Bool $test = ?($got eq $expected); # Display verbose report unless test passed if $test { self!report_test(Test::Builder::Test.new( :number(self!get_test_number), :passed($test), :description($description))); } else { self!report_test(Test::Builder::Test.new( :number(self!get_test_number), :passed($test), :description($description)), :verbose({ got => $got, expected => $expected })); } return $test; } #= Verifies that the first two arguments are not equal method isnt(Mu $got, Mu $expected, Str $description= '') { my Bool $test = ?($got ne $expected); # Display verbose report unless test passed if $test { self!report_test(Test::Builder::Test.new( :number(self!get_test_number), :passed($test), :description($description))); } else { self!report_test(Test::Builder::Test.new( :number(self!get_test_number), :passed($test), :description($description)), :verbose({ got => $got, expected => $expected })); } return $test; } #= Marks a given number of tests as failures method todo(Mu $todo, Str $description = '', Str $reason = '') { self!report_test(Test::Builder::Test.new(:todo(Bool::True), :number(self!get_test_number), :reason($reason), :description($description))); return $todo; } #= Displays the results of the given test method !report_test(Test::Builder::Test::Generic $test, :%verbose) { die 'No plan set!' unless $!plan; @!results.push($test); $!output.write($test.report); $!output.diag($test.verbose_report(%verbose)) if %verbose; } #= Returns the current test number method !get_test_number() { return +@!results + 1; } } END { $TEST_BUILDER.done if $TEST_BUILDER.defined && !$TEST_BUILDER.done_testing } # vim: ft=perl6
(function main() { 'use strict'; var sidebarShouldOpen = window.matchMedia('(min-width: 50em)'); function handleSidebarToggle(event) { if (event.matches) { document.querySelector('.main-navigation details').open = true; } else { document.querySelector('.main-navigation details').open = false; } } sidebarShouldOpen.addListener(handleSidebarToggle); handleSidebarToggle(sidebarShouldOpen); })();
## ![](https://raw.githubusercontent.com/JackJiang2011/beautyeye/master/screenshots/beautyeye_logo_h.png) :cn: [点击进入简体中文版](https://github.com/JackJiang2011/beautyeye/blob/master/README.md) :bulb: BeautyEye has migrated from [Google Code](https://code.google.com/p/beautyeye/) since 2015-01-30. BeautyEye is a cross platform Java Swing look and feel;<br> Benefit from basic GUI technology of Android, BeautyEye is so different from other look and feel.<br> BeautyEye is open source and free. ## Source code online Click here: [http://www.52im.net/thread-112-1-1.html](http://www.52im.net/thread-112-1-1.html)。 ## Latest Release #### :page_facing_up: v3.7 release note Release time: `2015-11-13 17:23`<br> 1. Resolved text components can not edit on JPopupMenu; <br> 2. Resolved issue that JFormattedTextField has not ui. <br> > BeautyEye first code since 2012-05, v3.0 released date is 2012-09-11, latest version released date is 2015-11-13. [More release notes](https://github.com/JackJiang2011/beautyeye/wiki/BeautyEye-release-notes) ## Compatibility BeautyEye can be run at java 1.5,1.6,1.7 and 1.8 or later. [See compatibility test](https://github.com/JackJiang2011/beautyeye/wiki/Compatibility_test_results). ## Feature * Cross-platform; * Main ui style; * Better compatibility. ## Demos <b>Tip:</b> Ensure has install JRE(java1.5+). * :paperclip: [Download demo jar\(Swingsets2\)](https://raw.githubusercontent.com/JackJiang2011/beautyeye/master/demo/excute_jar/SwingSets2\(BeautyEyeLNFDemo\).jar) * :paperclip: [Download demo jar\(Swingsets3\)](https://raw.githubusercontent.com/JackJiang2011/beautyeye/master/demo2/SwingSets3(BeautyEyeLNFDemo).jar) <font color="#FF6600"> \[Recommend:thumbsup:\]</font> ## Download :paperclip: .zip package:[Download now!](https://github.com/JackJiang2011/beautyeye/archive/v3.6.zip) (included demos, api docs , dist jar and so on). ## Development Guide #### :triangular_flag_on_post: First step: Import *`beautyeye_lnf.jar`* you can found dist jar *`beautyeye_lnf.jar`* at *“`/dist/`”*。 #### :triangular_flag_on_post: Second step: Code like this: ```Java public static void main(String[] args) { try { org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF(); } catch(Exception e) { //TODO exception } ..................... Your code ......................... ..................... Your code ......................... } ``` :green_book: Introduction:[BeautyEye L&F brief introduction](https://github.com/JackJiang2011/beautyeye/wiki/BeautyEye-L&F%E7%AE%80%E6%98%8E%E5%BC%80%E5%8F%91%E8%80%85%E6%8C%87%E5%8D%97). ## License Open source and free. ## Contact * Issues mail to :love_letter: `[email protected]`; </li> * Welcome to Java Swing QQ:`259448663` <a target="_blank" href="http://shang.qq.com/wpa/qunwpa?idkey=9971fb1d1845edc87bdec92ad03f329c1d1f280b1cfe73b6d03c13b0f7f8aba1"><img border="0" src="http://pub.idqqimg.com/wpa/images/group.png" alt="Java Swing技术交流" title="Java Swing技术交流"></a>; * [Twitter](https://twitter.com/JackJiang2011/). ## About Author ![](https://raw.githubusercontent.com/JackJiang2011/beautyeye/master/screenshots/js2.png) ## Preview #### :triangular_flag_on_post: Part 1/2:[Original image](https://raw.githubusercontent.com/JackJiang2011/beautyeye/master/preview/be_lnf_preview_36.png) ![](https://raw.githubusercontent.com/JackJiang2011/beautyeye/master/preview/be_lnf_preview_36.png) #### :triangular_flag_on_post: Part 2/2:[Original image](https://raw.githubusercontent.com/JackJiang2011/beautyeye/master/preview/be_lnf_preview2_36.png) ![](https://raw.githubusercontent.com/JackJiang2011/beautyeye/master/preview/be_lnf_preview2_36.png) ## More Screenshots #### :triangular_flag_on_post: Case :one::SwingSets2 :point_right: [See more](https://github.com/JackJiang2011/beautyeye/wiki/Screenshots-all-in-one) #### :triangular_flag_on_post: Case :two::SwingSets3 ![](https://raw.githubusercontent.com/JackJiang2011/beautyeye/master/screenshots/swingsets3/swingsets3_beautyeye.png) :paperclip: [download jar\(Swingsets3\)](https://raw.githubusercontent.com/JackJiang2011/beautyeye/master/demo2/SwingSets3(BeautyEyeLNFDemo).jar) #### :triangular_flag_on_post: Case :three::DriodUIBuilder ![](https://raw.githubusercontent.com/JackJiang2011/beautyeye/master/screenshots/drioduiduilder/drioduiduilder_beautyeye.png) :point_right: DroidUIBuilder: [see more](https://github.com/JackJiang2011/DroidUIBuilder) #### :triangular_flag_on_post: Sace :four::Draw9patch ![](https://raw.githubusercontent.com/JackJiang2011/beautyeye/master/screenshots/draw9patch/draw9patch1_beautyeye.png) ![](https://raw.githubusercontent.com/JackJiang2011/beautyeye/master/screenshots/draw9patch/draw9patch2_beautyeye.png) ## Wiki :notebook_with_decorative_cover: [See more](https://github.com/JackJiang2011/beautyeye/wiki) ## Other projects * **DroidUIBuilder**:一款开源Android GUI设计工具(已于2012年底停止开发),[:octocat: see more](https://github.com/JackJiang2011/DroidUIBuilder)。<br> * **Swing9patch**:一组很酷的Java Swing可重用组件或UI效果,[:octocat: see more](https://github.com/JackJiang2011/Swing9patch)。<br>
from SceneGenerator import * import math scene = generateScene('ClothScene', camPosition=[0,15,30], camLookat=[0,0,0]) addParameters(scene, h=0.005, contactTolerance=0.05) friction = 0.1 restitution = 0.2 addRigidBody(scene, '../models/cube.obj', 2, coScale=[100, 1, 100], scale=[100, 1, 100], dynamic=0) addRigidBody(scene, '../models/torus.obj', 4, coScale=[2, 1, 2], scale=[2, 2, 2], translation=[0,5,0], friction=friction, rest = restitution, dynamic=0) addTriangleModel(scene, '../models/plane_50x50.obj', translation=[0, 10, 0], scale=[10,10,10], friction=friction, rest = restitution, staticParticles=[]) writeScene(scene, 'ClothScene.json')
// Copyright 2021 Praetorian Security, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package auditors defines an interface for all auditors. // This package provides a registration mechanism similar to // database/sql. In order to use a particular auditor, add a // "blank import" for its package. // // import ( // "github.com/praetorian-inc/snowcat/auditors" // "github.com/praetorian-inc/snowcat/pkg/types" // // _ "github.com/praetorian-inc/snowcat/auditors/authz" // _ "github.com/praetorian-inc/snowcat/auditors/peerauth" // ) // // auditors, err := auditors.New(types.Config{}) // if err != nil { // // handle error // } // for _, auditor := range auditors { // res, err := auditor.Audit(disco, resources) // ... // } // // See https://golang.org/doc/effective_go.html#blank_import for more // information on "blank imports". package auditors import ( "fmt" "sync" "github.com/praetorian-inc/snowcat/pkg/types" ) // Register makes an auditor available with the provided name. If register is // called twice or if the driver is nil, if panics. Register() is typically // called in the auditor implementation's init() function to allow for easy // importing of each auditor. func Register(auditor types.Auditor) { registryMu.Lock() defer registryMu.Unlock() if auditor == nil { panic("Registered auditor is nil") } name := auditor.Name() if _, ok := registry[name]; ok { panic(fmt.Errorf("auditor %s already registered", name)) } registry[name] = auditor } // All returns a list of all auditors. func All() []types.Auditor { registryMu.Lock() defer registryMu.Unlock() var auditors []types.Auditor for _, v := range registry { auditors = append(auditors, v) } return auditors } var ( registry = make(map[string]types.Auditor) registryMu sync.RWMutex )
(function(name, context){ function gogo(){ console.info(name); } return { go:gogo }; })
module Options.Harg.Pretty ( ppHelp, ppSourceRunErrors, ) where import Control.Applicative ((<|>)) import Data.List (intercalate) import Data.Maybe (fromMaybe) import Options.Harg.Sources.Types import Options.Harg.Types ppHelp :: Opt a -> Maybe String ppHelp Opt {..} = (<> ppEnvVar _optEnvVar) <$> _optHelp ppSourceRunErrors :: [SourceRunError] -> String ppSourceRunErrors = intercalate "\n\n" . map ppSourceRunError where ppSourceRunError :: SourceRunError -> String ppSourceRunError (SourceRunError Nothing src desc) = "error: " <> desc <> "\n\t" <> ppSource src ppSourceRunError (SourceRunError (Just (SomeOpt opt)) src desc) = "option " <> optId opt <> ": " <> desc <> "\n\t" <> ppSource src <> ppEnvVar (_optEnvVar opt) optId Opt {..} = fromMaybe "<no name available>" $ _optLong <|> (pure <$> _optShort) <|> _optMetavar ppSource :: String -> String ppSource s = " (source: " <> s <> ")" ppEnvVar :: Maybe String -> String ppEnvVar = maybe "" $ \s -> " (env var: " <> s <> ")"
using System; using System.Collections.Generic; using System.Text; namespace SSRD.IdentityUI.Admin.Models.Group { public class GroupUserTableModel { public long Id { get; set; } public string UserId { get; set; } public string Username { get; set; } public string Email { get; set; } public string GroupRoleId { get; set; } public string GroupRoleName { get; set; } public GroupUserTableModel(long id, string userId, string username, string email, string groupRoleId, string groupRoleName) { Id = id; UserId = userId; Username = username; Email = email; GroupRoleId = groupRoleId; GroupRoleName = groupRoleName; } } }
-module(my_client_v2_benchmark_initiator). -export([start/0, run_clients/0]). -include("my_client_v2.hrl"). start() -> NumberOfClients = get_val(number_of_clients), TimeBetweenBenchmarks = get_val(time_between_benchmarks), _ = [begin ?LOG_INFO("Initiating requests from ~p clients", [N]), [spawn(?MODULE, run_clients, []) || _ <- lists:seq(1, N)], timer:sleep(TimeBetweenBenchmarks) end || N <- NumberOfClients], ok. run_clients() -> my_client_v2_jactor:start(). get_val(Key) -> my_client_v2_config:get(Key).
use std::borrow::Cow; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PunctuatorToken { CurlyOpen, // { CurlyClose, // } ParenOpen, // ( ParenClose, // ) SquareOpen, // [ SquareClose, // ] Semicolon, // ; Comma, // , Tilde, // ~ Question, // ? Colon, // : Period, // . Ellipsis, // ... LAngle, // < LAngleEq, // <= LAngleAngle, // << LAngleAngleEq, // <<= LAngleExclamDashDash, // <!-- RAngle, // > RAngleEq, // >= RAngleAngle, // >> RAngleAngleEq, // >>= RAngleAngleAngle, // >>> RAngleAngleAngleEq, // >>>= Exclam, // ! ExclamEq, // != ExclamEqEq, // !== Eq, // = Arrow, // => EqEq, // == EqEqEq, // === Plus, // + PlusEq, // += PlusPlus, // ++ Minus, // - MinusEq, // -= MinusMinus, // -- MinusMinusAngle, // --> Percent, // % PercentEq, // %= Star, // * StarEq, // *= StarStar, // ** StarStarEq, // **= Slash, // / SlashEq, // /= Amp, // & AmpAmp, // && AmpEq, // &= Bar, // | BarBar, // || BarEq, // |= Caret, // ^ CaretEq, // ^= } impl From<PunctuatorToken> for Token<'static> { fn from(t: PunctuatorToken) -> Self { Token::Punctuator(t) } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CommentFormat { Line, Block, HTMLOpen, HTMLClose, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct CommentToken<'a> { pub format: CommentFormat, pub value: Cow<'a, str>, } impl<'a> From<CommentToken<'a>> for Token<'a> { fn from<'b>(t: CommentToken<'b>) -> Token<'b> { Token::Comment(t) } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct WhitespaceToken {} impl From<WhitespaceToken> for Token<'static> { fn from(t: WhitespaceToken) -> Self { Token::Whitespace(t) } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct LineTerminatorToken {} impl From<LineTerminatorToken> for Token<'static> { fn from(t: LineTerminatorToken) -> Self { Token::LineTerminator(t) } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct RegularExpressionLiteralToken<'a> { pub pattern: Cow<'a, str>, pub flags: Cow<'a, str>, } impl<'a> From<RegularExpressionLiteralToken<'a>> for Token<'a> { fn from<'b>(t: RegularExpressionLiteralToken<'b>) -> Token<'b> { Token::RegularExpressionLiteral(t) } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct IdentifierNameToken<'a> { // pub raw: Cow<'a, str>, pub name: Cow<'a, str>, } impl<'a> From<IdentifierNameToken<'a>> for Token<'a> { fn from<'b>(t: IdentifierNameToken<'b>) -> Token<'b> { Token::IdentifierName(t) } } #[derive(Debug, Clone, PartialEq)] pub struct NumericLiteralToken { pub value: f64, } impl From<NumericLiteralToken> for Token<'static> { fn from(t: NumericLiteralToken) -> Self { Token::NumericLiteral(t) } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct StringLiteralToken<'a> { pub value: Cow<'a, str>, } impl<'a> From<StringLiteralToken<'a>> for Token<'a> { fn from<'b>(t: StringLiteralToken<'b>) -> Token<'b> { Token::StringLiteral(t) } } #[derive(Debug, Clone, PartialEq, Eq)] pub enum TemplateFormat { // `foo` NoSubstitution, // `foo${ Head, // }foo${ Middle, // }foo` Tail, } #[derive(Debug, Clone, PartialEq, Eq)] pub struct TemplateToken<'a> { pub format: TemplateFormat, pub cooked: Cow<'a, str>, pub raw: Cow<'a, str>, } impl<'a> From<TemplateToken<'a>> for Token<'a> { fn from<'b>(t: TemplateToken<'b>) -> Token<'b> { Token::Template(t) } } #[derive(Debug, Clone, PartialEq)] pub struct EOFToken { } impl From<EOFToken> for Token<'static> { fn from(t: EOFToken) -> Self { Token::EOF(t) } } #[derive(Clone, Debug, PartialEq)] pub enum Token<'a> { Punctuator(PunctuatorToken), Comment(CommentToken<'a>), Whitespace(WhitespaceToken), LineTerminator(LineTerminatorToken), RegularExpressionLiteral(RegularExpressionLiteralToken<'a>), IdentifierName(IdentifierNameToken<'a>), NumericLiteral(NumericLiteralToken), StringLiteral(StringLiteralToken<'a>), Template(TemplateToken<'a>), EOF(EOFToken), // Boxed so we can jam in helpful info without making the overall token // structure larger than it needs to be. // Invalid(Box<InvalidToken>), } impl<'a> Default for Token<'a> { fn default() -> Token<'a> { EOFToken {}.into() } } // #[derive(Clone, Debug, PartialEq, Eq)] // pub enum InvalidToken { // Codepoints(InvalidCodepoints), // String(InvalidString), // Template(InvalidTemplate), // Numeric(InvalidNumeric), // RegularExpression(InvalidRegularExpression), // } // // Has random unknown code points // #[derive(Clone, Debug, PartialEq, Eq)] // pub struct InvalidCodepoints {} // // Has a newline or unknown escape? // #[derive(Clone, Debug, PartialEq, Eq)] // pub struct InvalidString {} // // Has unknown escape // #[derive(Clone, Debug, PartialEq, Eq)] // pub struct InvalidTemplate {} // // Has unknown number format or trailing decimal // #[derive(Clone, Debug, PartialEq, Eq)] // pub struct InvalidNumeric {} // // Has a newline or escape in flags // #[derive(Clone, Debug, PartialEq, Eq)] // pub struct InvalidRegularExpression {}
import React from "react"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import { UserData } from "react-oidc"; class AuthenticatedApp extends React.Component<any, any> { constructor(props: any) { super(props); this.state = {}; } static contextType = UserData; componentDidMount() {} render() { return ( <Router> <div className="App"> <main> <Switch> <Route path="/"> <h1>Welcome</h1> </Route> </Switch> </main> </div> </Router> ); } } export default AuthenticatedApp;
import { DirectionalProperty, Properties, Property, PropName, } from './properties'; import { CSSObject } from './system'; import { SafeLookup, SafeMapKey, WeakRecord } from './utils'; /** Theme Shape */ type BaseTheme = Readonly<{ readonly [key: string]: any; }>; export type AbstractTheme = BaseTheme & { breakpoints?: { xs: string; sm: string; md: string; lg: string; xl: string; }; }; /** Property Scales */ export type DefaultPropScale< Config extends AbstractPropertyConfig > = Properties[Config['propName']]['defaultScale']; export type ScaleArray = Readonly<unknown[]>; export type ScaleMap = Readonly<Record<string | number, unknown>>; export type ScaleAlias = Readonly<string>; export type AnyScale = ScaleArray | ScaleMap | ScaleAlias; export type AnyThematicScale<Theme extends AbstractTheme> = | ScaleArray | ScaleMap | Readonly<keyof Theme>; export type ThematicScaleValue< Theme extends AbstractTheme, Config extends PropertyConfig<Theme> > = Config['scale'] extends AnyThematicScale<Theme> ? | SafeLookup<Theme[Extract<Config, { scale: string }>['scale']]> | SafeMapKey<Theme[Extract<Config, { scale: string }>['scale']]> | SafeMapKey<Extract<Config, { scale: ScaleMap }>['scale']> | Extract<Config, { scale: ScaleArray }>['scale'][number] : DefaultPropScale<Config>; /** Property Configurations */ export type AbstractPropertyConfig = { propName: PropName; property?: Property; dependentProps?: Readonly<string[]>; type?: 'standard' | 'directional'; scale?: AnyScale; transformValue?: (value: any) => string | number; }; export type PropertyConfig< Theme extends AbstractTheme > = AbstractPropertyConfig & { scale?: AnyThematicScale<Theme>; }; /** Responsive Props */ export type MediaQueryArray<Value> = [ Value?, Value?, Value?, Value?, Value?, Value? ]; export type MediaQueryMap<Value> = { base?: Value; xs?: Value; sm?: Value; md?: Value; lg?: Value; xl?: Value; }; export type ResponsiveProp<Value> = | Value | MediaQueryArray<Value> | MediaQueryMap<Value>; /** Prop Shapes */ export type AbstractProps = Record<string, unknown>; export type ThematicProps< Theme extends AbstractTheme, Config extends PropertyConfig<Theme> > = WeakRecord< Config['propName'] extends DirectionalProperty ? Properties[Config['propName']]['dependentProps'] | Config['propName'] : Config['propName'], ResponsiveProp<ThematicScaleValue<Theme, Config>> > & { theme?: Theme }; /** Style Functions */ export type StyleTemplate<Props extends AbstractProps> = ( props: Props ) => CSSObject | undefined; export type HandlerMeta<Props extends AbstractProps> = { propNames: Exclude<keyof Props, 'theme'>[]; styleTemplates: WeakRecord<keyof Props, StyleTemplate<Props>>; }; export type Handler<Props extends AbstractProps> = HandlerMeta<Props> & ((props: Props) => CSSObject); export type HandlerProps< HandlerFn extends (props: AbstractProps) => CSSObject > = Parameters<HandlerFn>[0];
#!/bin/bash # $Id: edit_changelog.sh,v 1.7 2005/03/16 13:39:50 jenst Exp $ esc=`echo -en "\033"` tab="${esc}[5G" clear if [ -z $1 ] ; then echo -e "\nusage :" echo "sh update_po_files.sh -all for all .po file" echo -e "or sh update_po_files.sh -po <language_COUNTRY> for only one. e.g. sh update_po_files.sh -po de_DE \n" exit fi if [ $1 != "-all" ] && [ ! -e ../locale/$2 ]; then echo -e "\n$2 does not exist or your paramater was wrong" echo -e "\nusage :" echo -e "sh update_po_files.sh -po <language_COUNTRY> for only one. e.g. sh update_po_files.sh -po de_DE \n" exit fi ACTUALPATH=${0%/*} cd $ACTUALPATH #find all .po files or use only one echo -n "checking for Changelog files ...." find ../locale/ -iname "??_??*Changelog" >/dev/null 2>/dev/null || { echo $rc_failed echo "$tab No valid Changelog files found" exit 0 } if [ $1 = "-all" ] ; then Cfiles=$(find ../locale/ -iname "??_??*Changelog") else Cfiles=$(find ../locale/$2 -iname "??_??*Changelog") fi for all_CF in $Cfiles ; do echo -e "\nFound : $all_CF" lang1=${all_CF%-*} lang=${lang1##*/} echo "$tab Language = $lang" echo "$tab Updating ..." echo "" >> $all_CF echo "===============================================================================" >> $all_CF echo "2005-03-10 Jens Tkotz <jens AT peino DOT de>" >> $all_CF echo "" >> $all_CF echo " * Release of Gallery 1.5-RC2 langpack" >> $all_CF echo "===============================================================================" >> $all_CF echo "" >> $all_CF #read trash done find ../locale/ -iname "*~" -exec rm {} \;
import { contracts } from '../services/contracts' export default async function isRecoveryMode(): Promise<boolean> { try { const isMissedCheckpointSubmission = await contracts.checkMissedCheckpointSubmission() return isMissedCheckpointSubmission } catch (e) { return Promise.reject(e) } }
using GLAA.Domain.Models; namespace GLAA.ViewModels { public class LicenceIndustryViewModel { public virtual Licence Licence { get; set; } public virtual Industry Industry { get; set; } } }
package com.edwin.randompicture.data.repository.session import com.edwin.randompicture.data.model.SessionEntity import io.reactivex.Completable import io.reactivex.Single interface SessionRemote { fun setSession(token: String?): Completable fun doRegister(email: String, name: String, password: String): Single<SessionEntity> fun doLogin(email: String, password: String): Single<SessionEntity> }
<?php namespace WebsiteAnalyzer; use WebsiteAnalyzer\Metrics\MetricsInterface; class Result { const ERR_INVALID_METRIC = 'Requested metric [%s] does not exist'; protected $metrics; protected $uri; protected $body; protected $headers; protected $status; public function __construct($data = []) { $defaults = $this->getDefaults(); $data = array_merge($defaults, $data); foreach ($data as $key => $value) { $this->{$key} = $value; } } protected function getDefaults() { return [ 'body' => '', 'headers' => [], 'status' => '', 'metrics' => '', 'uri' => '', ]; } public function getMetrics() { return $this->metrics; } public function getMetric($type) { $metrics = $this->getMetrics(); if (!array_key_exists($type, $metrics)) { throw new RuntimeException(sprintf(self::ERR_INVALID_METRIC, $type)); } return $metrics[$type]; } public function getUri() { return $this->uri; } public function getBody() { return $this->body; } public function getHeaders() { return $this->headers; } public function getStatus() { return $this->status; } public function addMetric(MetricsInterface $metric) { $type = $metric->getType(); $this->metrics[$type] = $metric; return $this; } public function __debugInfo() { return [ 'uri' => $this->uri, 'body' => substr($this->body, 0, 200), 'headers' => $this->headers, 'status' => $this->status, 'metrics' => $this->metrics, ]; } }
TODO: =================== - Learning ERB, try used it for make elegant ruby code and compress usage html. - Added a work with sqlite, for example - Added a markdown - Make a class Page, for make page framework fast. - Added a registration etc - Make @name and #tags, also optionally - markdown in message
import 'package:Indo_News/api/news_api.dart'; import 'package:Indo_News/models/articles.dart'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:share/share.dart'; class MainPage extends StatefulWidget { @override _MainPageState createState() => _MainPageState(); } class _MainPageState extends State<MainPage> { NewsApi newsApi = NewsApi(); Future<Articles> futureArticles; @override void initState() { super.initState(); futureArticles = newsApi.fetchTopHeadlines(); } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.blueGrey[200], appBar: AppBar( leading: Icon(FontAwesomeIcons.solidNewspaper), title: Text('Indo News'), actions: <Widget>[ IconButton( icon: Icon( Icons.info_outline, color: Colors.white, ), onPressed: () { Navigator.pushNamed(context, '/info'); }, ) ], ), body: FutureBuilder( future: futureArticles, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator()); } else { if (snapshot.hasError) { return Center(child: Text('Error: ${snapshot.error}')); } else { print(snapshot.data); return NewsList(articles: snapshot.data.articles); } } }, ), ); } } class NewsList extends StatefulWidget { final List<Article> articles; const NewsList({Key key, this.articles}) : super(key: key); @override _NewsListState createState() => _NewsListState(); } class _NewsListState extends State<NewsList> { @override Widget build(BuildContext context) { return ListView.builder( itemCount: widget.articles.length, itemBuilder: (BuildContext context, int index) { final title = widget.articles[index].title; // final description = widget.articles[index].description; final url = widget.articles[index].url; final urlToImage = widget.articles[index].urlToImage; return Padding( padding: EdgeInsets.only(left: 8.0, right: 8.0, top: 8.0), child: GestureDetector( onTap: () => Navigator.pushNamed( context, '/detail', arguments: Article(url: url, title: title), ), child: Card( color: Colors.blueGrey[50], child: Column( children: <Widget>[ Image.network('$urlToImage'), ListTile( title: Container( margin: EdgeInsets.only(top: 8.0, bottom: 8.0), child: Text('$title'), ), // subtitle: Container( // child: Text('$description'), // margin: EdgeInsets.only(bottom: 8.0), // ), trailing: IconButton( icon: Icon(Icons.share), onPressed: () { Share.share( '$title\nlink: $url', subject: 'Berita dari Indo News', ); }, ), ), ], ), ), ), ); }, ); } }
// -------------------------------------------------- // UnityInjector - ConsoleEncoding.cs // Copyright (c) Usagirei 2015 - 2015 // -------------------------------------------------- using System; using System.Text; namespace UnityInjector.ConsoleUtil { // -------------------------------------------------- // Code ported from // https://gist.github.com/asm256/9bfb88336a1433e2328a // Which in turn was seemingly ported from // http://jonskeet.uk/csharp/ebcdic/ // using only safe (managed) code // -------------------------------------------------- internal partial class ConsoleEncoding : Encoding { private readonly uint _codePage; public override int CodePage => (int)_codePage; public static uint ConsoleCodePage { get { return GetConsoleOutputCP(); } set { SetConsoleOutputCP(value); } } public static uint GetActiveCodePage() { return GetACP(); } private ConsoleEncoding(uint codePage) { _codePage = codePage; } public static ConsoleEncoding GetEncoding(uint codePage) { return new ConsoleEncoding(codePage); } public override int GetByteCount(char[] chars, int index, int count) { WriteCharBuffer(chars, index, count); int result = WideCharToMultiByte(_codePage, 0, _charBuffer, count, _zeroByte, 0, IntPtr.Zero, IntPtr.Zero); return result; } public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { var byteCount = GetMaxByteCount(charCount); WriteCharBuffer(chars, charIndex, charCount); ExpandByteBuffer(byteCount); int result = WideCharToMultiByte(_codePage, 0, chars, charCount, _byteBuffer, byteCount, IntPtr.Zero, IntPtr.Zero); ReadByteBuffer(bytes, byteIndex, byteCount); return result; } public override int GetCharCount(byte[] bytes, int index, int count) { WriteByteBuffer(bytes, index, count); int result = MultiByteToWideChar(_codePage, 0, bytes, count, _zeroChar, 0); return result; } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { var charCount = GetMaxCharCount(byteCount); WriteByteBuffer(bytes, byteIndex, byteCount); ExpandCharBuffer(charCount); int result = MultiByteToWideChar(_codePage, 0, bytes, byteCount, _charBuffer, charCount); ReadCharBuffer(chars, charIndex, charCount); return result; } public override int GetMaxByteCount(int charCount) => charCount * 2; public override int GetMaxCharCount(int byteCount) => byteCount; } }
import React, { Component } from "react" import styled from "styled-components" import { Link } from "gatsby" import Social from "./Social" import { primaryFont } from "./../theme/theme" const Navigation = styled.div` display: flex; flex-direction: column; font-family: ${primaryFont}; background: #171717; height: 100vh; text-align: left; padding: 7rem 0 0 2.5rem; position: absolute; top: 0; right: -100; overflow-x: hidden; overflow-y: hidden; transition: transform 0.5s ease-in-out; z-index: 99; width: 40%; transform: ${({ open }) => (open ? "translateX(150%)" : "translateX(250%)")}; @media (max-width: 768px) { width: 96%; transform: ${({ open }) => (open ? "translateX(0%)" : "translateX(-100%)")}; } ` const NavLink = styled(Link)` text-decoration: none; color: #dedede; font-size: 1.5rem; padding: 2.5rem 0rem; font-weight: bold; letter-spacing: 0.1rem; transition: color 0.3s linear; @media only screen and (min-width: 768px) { padding: 2rem 0rem; } &:hover { color: cyan; } &.isOpen { animation-name: animateIn; animation-duration: 500ms; animation-delay: calc((${props => props.animateOrder}) * 170ms); animation-fill-mode: both; animation-timing-function: ease-in-out; @keyframes animateIn { 0% { opacity: 0; transform: translate(3em, 0); } 100% { opacity: 1; } } } ` const Hamburger = styled.div` -webkit-transition: margin 600ms; -moz-transition: margin 600ms; transition: margin 600ms; cursor: pointer; position: absolute; margin: 5px; right: 1px; top: 10px; padding: 5px; z-index: 200; span { display: block; width: 2.8em; height: 2px; margin: 0.7em; border-right: 1.8em solid cyan; border-left: 0.6em solid grey; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; -webkit-transition-property: -webkit-transform, margin, border-right-color, box-shadow; -moz-transition-property: -moz-transform, margin, border-right-color, box-shadow; transition-property: transform, margin, border-right-color, box-shadow; -webkit-transition-duration: 600ms; -moz-transition-duration: 600ms; transition-duration: 600ms; } &.pushed ${Navigation} { margin: 0; } &.pushed span:nth-of-type(1) { margin-left: 1.4em; -webkit-transform: rotate(-137deg) translateY(-0.2em); -moz-transform: rotate(-137deg) translateY(-0.2em); -ms-transform: rotate(-137deg) translateY(-0.2em); -o-transform: rotate(-137deg) translateY(-0.2em); transform: rotate(-137deg) translateY(-0.2em); } &.pushed span:nth-of-type(2) { margin-left: 0.5em; -webkit-transform: rotate(-42deg) translateX(1em); -moz-transform: rotate(-42deg) translateX(1em); -ms-transform: rotate(-42deg) translateX(1em); -o-transform: rotate(-42deg) translateX(1em); transform: rotate(-42deg) translateX(1em); } @media only screen and (min-width: 768px) { right: 70px; margin: 10px; padding: 20px; } ` const SocialAccounts = styled.div` display: flex; flex: 1; align-items: flex-end; padding-bottom: 50px; } ` class Menu extends Component { state = { active: false, } constructor(props) { super(props) this.wrapperRef = React.createRef() } hamburger = () => { this.setState({ slideOpen: !this.state.slideOpen }) } state = { slideOpen: false, } render() { return ( <> <Hamburger onClick={this.hamburger} className={this.state.slideOpen ? "pushed" : ""} style={{ zIndex: "999" }} > <span className="bar"></span> <span className="bar"></span> </Hamburger> <Navigation open={this.state.slideOpen}> <NavLink to="/" onClick={this.hamburger} className={this.state.slideOpen ? "isOpen" : ""} animateOrder={1} > home </NavLink> <NavLink to="/projects" onClick={this.hamburger} className={this.state.slideOpen ? "isOpen" : ""} animateOrder={2} > projects </NavLink> <NavLink to="/blogs" onClick={this.hamburger} className={this.state.slideOpen ? "isOpen" : ""} animateOrder={3} > blogs </NavLink> <SocialAccounts> <Social></Social> </SocialAccounts> </Navigation> </> ) } } export default Menu
--- nav: title: Components path: /components group: title: 数据 path: /data --- ### Layout 布局 Demo: ```tsx import React from 'react'; import { Layout, Content, Header, Footer, Aside } from 'volute-ui'; import './demo.less'; export default function() { return ( <div className="x-layout-demo"> <h1>1</h1> <Layout> <Header className="x-layout-demo-header">header</Header> <Content className="x-layout-demo-content">content</Content> <Footer className="x-layout-demo-footer">footer</Footer> </Layout> <h1>2</h1> <Layout> <Header className="x-layout-demo-header">Header</Header> <Layout> <Aside className="x-layout-demo-aside">aside</Aside> <Content className="x-layout-demo-content">Content</Content> </Layout> <Footer className="x-layout-demo-footer">Footer</Footer> </Layout> <h1>3</h1> <Layout> <Aside className="x-layout-demo-aside">aside</Aside> <Layout> <Header className="x-layout-demo-header">Header</Header> <Content className="x-layout-demo-content">Content</Content> <Footer className="x-layout-demo-footer">Footer</Footer> </Layout> </Layout> </div> ); } ```
// Copyright (c) 2017 Xidorn Quan <[email protected]> // Copyright (c) 2017 Martijn Rijkeboer <[email protected]> // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. /// The thread mode used to perform the hashing. #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum ThreadMode { /// Run in one thread. Sequential, /// Run in the same number of threads as the number of lanes. Parallel, } impl ThreadMode { /// Create a thread mode from the threads count. pub fn from_threads(threads: u32) -> ThreadMode { if threads > 1 { ThreadMode::Parallel } else { ThreadMode::Sequential } } } impl Default for ThreadMode { fn default() -> ThreadMode { ThreadMode::Sequential } } #[cfg(test)] mod tests { use crate::thread_mode::ThreadMode; #[test] fn default_returns_correct_thread_mode() { assert_eq!(ThreadMode::default(), ThreadMode::Sequential); } #[test] fn from_threads_returns_correct_thread_mode() { assert_eq!(ThreadMode::from_threads(0), ThreadMode::Sequential); assert_eq!(ThreadMode::from_threads(1), ThreadMode::Sequential); assert_eq!(ThreadMode::from_threads(2), ThreadMode::Parallel); assert_eq!(ThreadMode::from_threads(10), ThreadMode::Parallel); assert_eq!(ThreadMode::from_threads(100), ThreadMode::Parallel); } }
<?php class Article { public $id; public $title; public $created_date; public $summary; public $body; public function __construct($id, $title, $created_date, $summary, $body) { $this->id = $id; $this->title = $title; $this->created_date = $created_date; $this->summary = $summary; $this->body = $body; } public function toArray(): array { return [ $this->id, $this->title, $this->created_date, $this->summary, $this->body ]; } } class BlogData { public array $articles = []; private const ARTICLE_COLUMN_SIZE = 5; private const DB_FILE = './data/database.csv'; public function load() { $file = new SplFileObject(self::DB_FILE, "r"); $file->setFlags(SplFileObject::READ_CSV); foreach ($file as $line) { if (count($line) == self::ARTICLE_COLUMN_SIZE) { $this->articles[] = new Article( $line[0], $line[1], $line[2], $line[3], $line[4] ); } } $file = null; } public function getArticleById($id): Article { foreach ($this->articles as $article) { if ($article->id === $id) { return $article; } } } public function addArticle($title, $created_date, $summary, $body) { $new_id = count($this->articles); array_unshift($this->articles, new Article($new_id, $title, $created_date, $summary, $body)); $file = new SplFileObject(self::DB_FILE, "c+"); $file->setFlags(SplFileObject::READ_CSV); $file->fseek(0); foreach ($this->articles as $v) { $file->fputcsv($v->toArray()); } $file = null; } public function updateArticle($id, $title, $summary, $body) { foreach ($this->articles as $article) { if ($article->id === $id) { $article->title = $title; $article->summary = $summary; $article->body = $body; } } $file = new SplFileObject(self::DB_FILE, "c+"); $file->setFlags(SplFileObject::READ_CSV); $file->fseek(0); foreach ($this->articles as $article) { $file->fputcsv($article->toArray()); } $file = null; } }
using Content.Server.Fluids.EntitySystems; using Content.Shared.Chemistry.Reagent; using Content.Shared.FixedPoint; using Robust.Shared.Analyzers; using Robust.Shared.GameObjects; using Robust.Shared.Serialization.Manager.Attributes; namespace Content.Server.Fluids.Components { [RegisterComponent] [Friend(typeof(EvaporationSystem))] public sealed class EvaporationComponent : Component { /// <summary> /// The time that it will take this puddle to lose one fixed unit of solution, in seconds. /// </summary> [DataField("evaporateTime")] public float EvaporateTime { get; set; } = 5f; /// <summary> /// Name of referenced solution. Defaults to <see cref="PuddleComponent.DefaultSolutionName"/> /// </summary> [DataField("solution")] public string SolutionName { get; set; } = PuddleComponent.DefaultSolutionName; /// <summary> /// Lower limit below which puddle won't evaporate. Useful when wanting to leave a stain. /// Defaults to evaporate completely. /// </summary> [DataField("lowerLimit")] public FixedPoint2 LowerLimit = FixedPoint2.Zero; /// <summary> /// Upper limit below which puddle won't evaporate. Useful when wanting to make sure large puddle will /// remain forever. Defaults to <see cref="PuddleComponent.DefaultOverflowVolume"/>. /// </summary> [DataField("upperLimit")] public FixedPoint2 UpperLimit = PuddleComponent.DefaultOverflowVolume; /// <summary> /// The time accumulated since the start. /// </summary> public float Accumulator = 0f; } }
package org.map import org.scalatest.{BeforeAndAfter, FunSuite, Matchers} class MapTests extends FunSuite with Matchers with BeforeAndAfter { var map: Map = Nil before { map = new Map } test("create a new empty map") { map.size shouldBe 0 map.isEmpty shouldBe true } test("size of map should increase when put into it") { val oldSize = map.size map.put(1, 1) map.isEmpty shouldBe false map.size shouldBe oldSize + 1 } test("size of map should decrease when remove from it") { map.put(1, 1) val oldSize = map.size map.remove(1) map.size shouldBe oldSize - 1 } test("find put value inside map") { map.put(1, 1) map.contains(1) shouldBe true map.put(2, 2) map.contains(2) shouldBe true } test("map should contains all put key into it") { map.put(1, 1) map.put(2, 1) map.put(3, 1) map.contains(1) shouldBe true map.contains(2) shouldBe true map.contains(3) shouldBe true } test("get put value into map") { map.put(1, 1) map.get(1) shouldBe Some(1) map.get(3) shouldBe None } }
package typingsSlinky.officeUiFabricReact.mod import typingsSlinky.uifabricUtilities.fabricPerformanceMod.IPerfSummary import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} @JSImport("office-ui-fabric-react", "FabricPerformance") @js.native class FabricPerformance () extends typingsSlinky.officeUiFabricReact.utilitiesMod.FabricPerformance /* static members */ object FabricPerformance { @JSImport("office-ui-fabric-react", "FabricPerformance") @js.native val ^ : js.Any = js.native @JSImport("office-ui-fabric-react", "FabricPerformance._timeoutId") @js.native def _timeoutId: js.Any = js.native @scala.inline def _timeoutId_=(x: js.Any): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("_timeoutId")(x.asInstanceOf[js.Any]) /** * Measures execution time of the given syncronous function. If the same logic is executed multiple times, * each individual measurement will be collected as well the overall numbers. * @param name - The name of this measurement * @param func - The logic to be measured for execution time */ @JSImport("office-ui-fabric-react", "FabricPerformance.measure") @js.native def measure(name: String, func: js.Function0[Unit]): Unit = js.native @JSImport("office-ui-fabric-react", "FabricPerformance.reset") @js.native def reset(): Unit = js.native @JSImport("office-ui-fabric-react", "FabricPerformance.setPeriodicReset") @js.native def setPeriodicReset(): Unit = js.native @JSImport("office-ui-fabric-react", "FabricPerformance.summary") @js.native def summary: IPerfSummary = js.native @scala.inline def summary_=(x: IPerfSummary): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("summary")(x.asInstanceOf[js.Any]) }
--- layout: post category: scala date: 2015-02-04 22:11:38 UTC title: Scala基础之try...catch...finally tags: [异常处理, 字节] permalink: /scala/try-catch/ key: 9fc1d12984edc4fbd228195de9084ada # for SEO description: "一般异常处理的try..catch..finally总是会在finally中进行一些收尾的处理,本文研究了如果在finally中出现return语句以及异常会得到什么结果" keywords: [异常处理, Return语句, 流程控制] --- 不论是在Java还是在Scala中,`try..catch`块的`finally`都是做一些收尾处理的,比如资源关闭等。如果在`finally`语句中如果添加了返回语句,将会发生什么呢? ```scala def getResult: Int = try { println("try执行了吗?") return 1 } finally { println("finally执行了吗?") return 3 } ``` 运行之后,发现`getResult`的返回值是3,反编译后可以看到如下代码: ```java public int getResult() { try { Predef..MODULE$.println("try 执行了吗?"); return 3; } finally { Predef..MODULE$.println("finally 执行了吗?"); } return 3; } ``` 显然,finally中的代码已经改变了原来方法的执行流程。 ```scala try { b } catch e1 finally e2 ``` 在Scala中,b的类型是try表达式的期望类型, e1实际上是一个偏函数: `scala.PartialFunction[scala.Throwable, pt], pt <: b`, 而e2的类型则是Unit。 上例,finally中的return语句使控制流程又回到了try块中,同时会将finally中的'返回值'作为最终返回值。 下面针对不同情况下,`try...catch...finally`的执行进行解释(finally中的代码无论如何都会执行): (1) 计算b的过程中没有异常 如果在计算表达式e1的过程中抛出异常,那么整个表达式会中止,并且抛出异常(e1表达式中包含的异常) 如果在计算表达式的e1的过程中没有抛出异常,那么b就是整个表达式的返回值 (2) 计算b的过程中有异常(e1中的表达式仍然会被计算) 如果e1的计算过程也抛出异常,那么表达式会中止并且e1过程中的异常被抛出 如果e1的计算过程中没有抛出异常,那么原来b中的异常会在e1计算完成之后再次抛出。 <b style="color:red">但就像前面提到的,如果在finally中添加返回语句,执行流程发生改变。最终结果则为返回的内容,看上去就好像异常没有被抛出。 </b> ```scala def getResult: Int = try { throw new RuntimeException } finally { return 3 } ``` 所以,上面这段代码还是会返回3,通过字节码可以更清晰的了解原因。 ```java public int getResult() { // Byte code: // 0: new 12 java/lang/RuntimeException // 3: dup // 4: invokespecial 16 java/lang/RuntimeException:<init> ()V // 7: athrow // 8: astore_1 // 9: iconst_3 // 10: ireturn // // Exception table: // from to target type // 0 8 8 finally } ``` ## 参考 \> [JLS 14.17 Return语句](http://docs.oracle.com/javase/specs/jls/se5.0/html/statements.html#14.17)
package io.mspencer.krunch abstract class Lexer<T : Token>(val source: CharSequence) : CharParsers() { abstract val tokens: Parser<CharReader, T> val parsedTokens = mutableListOf<Pair<T, CharReader>>() var atEnd: Boolean = false fun tokenAt(index: Int): T? { if (index < parsedTokens.size) { return parsedTokens[index].first } else if (index == parsedTokens.size) { if (atEnd) return null return parseNextToken() } else { throw IllegalStateException("Can only get the next token or a previously parsed token") } } private fun parseNextToken(): T? { val input = parsedTokens.lastOrNull()?.second ?: CharReader(source) val result = (tokens or endOfFile).apply(input) when (result) { is Result.Ok -> { if (result.matched is Unit) { atEnd = true return null } @Suppress("UNCHECKED_CAST") val matched = result.matched as T parsedTokens.add(Pair(matched, result.remainder)) return matched } is Result.Error -> throw Exception("ERROR: Unable to parse token: ${result.message}") is Result.Failure -> throw Exception("FAILURE: Unable to parse token: ${result.message}") } } fun atEnd(index: Int): Boolean { return index >= parsedTokens.size && atEnd } }
package com.platform.code; public class CodeConfig { private String entityModel = "flash-core"; private String daoModel = "flash-core"; private String serviceModel = "flash-core"; private String controllerModel = "flash-api"; private String viewModel = "flash-vue-admin"; public String getModel(String type){ switch (type){ case "model": return entityModel; case "repository": return daoModel; case "service": return serviceModel; case "controller": return controllerModel; case "view": return viewModel; } return null; } public String getEntityModel() { return entityModel; } public void setEntityModel(String entityModel) { this.entityModel = entityModel; } public String getDaoModel() { return daoModel; } public void setDaoModel(String daoModel) { this.daoModel = daoModel; } public String getServiceModel() { return serviceModel; } public void setServiceModel(String serviceModel) { this.serviceModel = serviceModel; } public String getControllerModel() { return controllerModel; } public void setControllerModel(String controllerModel) { this.controllerModel = controllerModel; } public String getViewModel() { return viewModel; } public void setViewModel(String viewModel) { this.viewModel = viewModel; } }
package pl.nn44.rchat.client; import pl.nn44.rchat.client.impl.Clients; import pl.nn44.rchat.client.util.PropLoader; import pl.nn44.rchat.protocol.ChatService; import pl.nn44.rchat.protocol.exception.ChatException; import java.math.BigInteger; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Spammer { private static final int SLEEP_MS = 400; private final ChatService cs = new Clients<>(PropLoader.get(), ChatService.class).burlap(); private final Random random = new Random(); private final String username; private final String channel; public Spammer(String channel) { this.username = nextStr(); this.channel = channel; } public void go() throws ChatException, InterruptedException { String token = cs.login(username, null).getPayload(); cs.join(token, channel, null); //noinspection InfiniteLoopStatement while (true) { cs.message(token, channel, nextStr()); Thread.sleep(SLEEP_MS); } } private String nextStr() { return new BigInteger(40, random).toString(32); } // --------------------------------------------------------------------------------------------------------------- public static void main(String[] args) { ExecutorService executor = Executors.newCachedThreadPool(); executor.submit(() -> { new Spammer("python").go(); return 1; }); executor.submit(() -> { new Spammer("anybody").go(); return 1; }); } }
using System; using System.Collections.Generic; using System.Text; namespace Bpmtk.Bpmn2.Extensions { public interface IScriptEnabledElement { IList<Script> Scripts { get; } } }
```@meta CurrentModule = BellScenario ``` # BellScenario.jl - Games ```@docs AbstractGame Game BellGame ``` ## Conversion Methods A [`BellGame`](@ref) is a matrix representation of a linear inequality that bounds a LocalPolytope for some [`Scenario`](@ref). For convenience, conversion methods are provided to transform BellGames to alternative representations of polytope facets. There are two supported types which can be converted to/from BellGames: * Facet - `Vector{Int64}`, a column-major vectorization of the game matrix with the bound placed in the last element of the vector. * `IEQ` - A facet data structure defined in [XPORTA.jl](https://juliapolyhedra.github.io/XPORTA.jl/dev/). ```@docs convert(::Type{BellGame},::Vector{Int64},::BlackBox) convert(::Type{BellGame},::Vector{Int64},::BipartiteNonSignaling) convert(::Type{Vector{Int64}}, ::BellGame) convert(::Type{Vector{Int64}},BG::BellGame,scenario::BipartiteNonSignaling) convert(::Type{Vector{BellGame}},::IEQ,::BlackBox) convert(::Type{IEQ}, bell_games::Vector{BellGame}) ``` ## File I/O In practice, one may need to view are large set of `BellGame`s in a human-readable form. ```@docs pretty_print_txt ```
#OpenWan媒体资产管理系统 ========= ##为什么要引入媒体资产管理系统 媒体产业不断发展,第四代媒体已逐渐崛起,数字多媒体的应用,广播频道的扩充,媒体资源的多样性应用(一个节目被多种形式媒体采用)和重复使用(许多节目或素材被重新编辑后产生新的价值)显示出了它巨大的潜藏价值。而目前影视录像带、唱片等媒体资料的审看或回放是通过从大量无序的录像带和光盘中查找、调用,再通过录像机播放的方式操作,效率非常低,而且共享性能差,已经不能适应数字化时代的发展需要。同时,随着岁月的流逝,许多珍贵的历史资料和素材都急需加以复制和保护,由于磁带或唱片等介质存放保质期有限,而数量还在源源不断的增加,因此急需对其进行整理、复制和保存。 媒体资产数字化、信息化、网络化、智能化的改造是当前音像资料管理发展的趋势。很多单位都保存了一大批具有历史意义和科研价值的视音频节目素材,庞大的视音频资料保存、管理和应用的难度很大,如何实现对这些媒体资料的有效管理,已成为所有单位面临的一个重要课题。 为了长期保存珍藏的原始影像资料,为了快速检索所需要的影像资源,为了方便管理并具有高保密性和安全性,为了实现网上共享、浏览、播放,主要解决视音频等多媒体数据资料的数字化存储、编目管理、检索查询和资料发布等问题的媒体资产管理(Media Asset Management)系统将成为信息数字化过程中不可或缺的部分。 ##OpenWan 概述 OpenWan媒体资产管理系统是以智能存储为中心,建立具有资源共享的数据化、网络化、自动化系统,能够支持广播电台、电视台各频道节目的数字化采集、编辑、播出、审查和存储等业务,为视频资料的利用与再利用提供简便、安全、快捷、准确可行的方法。 OpenWan媒媒体资产管理系统集成了先进的硬件架构,采用MPEG-2、MPEG-4编码压缩技术,并融合数字视频压缩、网络传输、资料检索、存储管理、多媒体、数据库、WEB等技术,形成了一套集媒体资料创建、编目、存储、管理、检索和发布应用为一体的资产管理系统。 系统使用PHP语言开发,框架采用QeePHP2.1优秀的开发框架,Mysql数据库,媒体文件转码使用FFmpeg组件,全文检索使用Sphinx引擎,在线播放音乐及视频等。优秀的权限访问控制功能,包含:用户管理、用户组管理、角色管理、权限管理、浏览等级管理等。 1. 使用BSD开源协议,源代码完全开源,没有商业限制。 2. 使用PHP语言开发,简单易学,学习成本低,维护成本低。 3. 完全兼容目前最流行浏览器(IE6、IE7+、Firefox、Chrome)。 ## 快速安装 1. 将程序拷贝到服务器站点目录下 2. 将 db/openwan_db_20100809.sql 导入到MySql数据库 3. 修改 config/database.yaml 数据库配置 4. 修改PHP配置(php.ini) post_max_size = 100M upload_max_filesize = 100M max_execution_time = 6000 5. 全文搜索引擎配置 (CSFT: coreseek.cn) 运行csft\install.bat文件,安装搜索引擎 6. 启动Web浏览器,在地址栏中输入 http://localhost 按Enter键,即可进入OpenWan主页(用户名:admin 密码:admin)。 ## 环境要求 操作系统: Windows NT 5.0 以上 服务器:Apache2或IIS5 + PHP5 以上 数据库:MySql 5.1 以上 ## 常见问题 问题:如果你使用IIS服务器并无法进行视频转码。 解决:为C:\Windows\System32\cmd.exe(系统不是安装在C盘请相应更改)添加IUSER_ComputerName (ComputerName是你的计算机名称)允许用户的读取、运行权限。 ## 更多文档 [OpenWan介绍演示.docx](https://github.com/thinkgem/openwan/raw/master/OpenWan%E4%BB%8B%E7%BB%8D%E6%BC%94%E7%A4%BA.docx)
from enum import Enum class FactType(Enum): FACT = 'FACT' BLOOPER = 'BLOOPER'
/* * Copyright (C) 2016 - 2021 Marko Salmela * * http://fuusio.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fuusio.flx.core import org.fuusio.flx.core.vm.Ctx abstract class EvaluableObject : Object { override fun eval(ctx: Ctx): Any = this override fun isArray() = false override fun isBoolean() = false override fun isByte() = false override fun isChar() = false override fun isColor() = false override fun isDate() = false override fun isDouble() = false override fun isFalse() = false override fun isFloat() = false override fun isIndexable() = false override fun isInt() = false override fun isList() = false override fun isMap() = false override fun isSequence() = false override fun isSet() = false override fun isSizable() = false override fun isLong() = false override fun isNil() = false override fun isShort() = false override fun isString() = false override fun isSymbol() = false override fun isTrue() = true override fun toBoolean() = true override fun toLiteral() = toString() }
<?php class ProfileTableSeeder extends Seeder { public function run() { $profile = new Profile(); $profile->location = "San Antonio, TX"; $profile->bio = "22 year old from TX. Just making a blog page."; $profile->user_id = User::first()->id; $profile->save(); } }
const express = require('express'); // router const router = express.Router(); // controller methods const { getListing, getListings, updateListing, createListing, uploadProfile, deleteListing, } = require('../../controllers/listings'); const Listing = require('../../models/listing'); const advancedResults = require('../../middleware/advancedResults'); router .route('/') .get(advancedResults(Listing), getListings) .post(createListing); router .route('/:id') .get(getListing) .put(updateListing) .delete(deleteListing); router.post('/:id/profile', uploadProfile); module.exports = router;
{-# LANGUAGE QuasiQuotes, DataKinds, OverloadedStrings #-} module Test where import Language.Cypher import Language.Cypher.Quasiquoter import Database.Neo4j (queryDB) import Database.Neo4j.Types (Server (..)) query :: Query '[Number] query = [cypher| return case $ x - 1 $ when 0 then $ x $ else 2 end limit 1|] where x :: E Number x = EProp (EIdent "actor") "name" query2 :: Query '[Str, Str, Number] query2 = [cypher| MATCH (movie:Movie) WHERE movie.title =~ {zero} RETURN movie.title as title, movie.tagline as tagline, movie.released as released|] main :: IO () main = do x <- queryDB localServer query print x where localServer = Server "http://neo4j.skeweredrook.com:7474/db/data/transaction/commit"
export const ASR_CORRECTIONS = [ ["replacethis", "with this"], ["apparantly", "apparently"], ["foster", "faster"], ["swift bic", "SWIFTBIC"] ];
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTransaksisTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('transaksis', function(Blueprint $table) { $table->increments('id'); $table->integer('id_koperasi'); $table->integer('id_induk'); $table->integer('id_anggota'); $table->string('no_transaksi'); $table->string('jenis_transaksi'); $table->integer('id_jenis'); $table->decimal('bunga',65); $table->decimal('admin',65); $table->decimal('asuransi',65); $table->decimal('tabungan',65); $table->decimal('jumlah_asli',65); $table->decimal('jumlah_bunga',65); $table->decimal('biaya_admin',65); $table->decimal('biaya_materai',65); $table->decimal('biaya_asuransi',65); $table->decimal('total_tabungan',65); $table->decimal('tabungan_per_bulan',65); $table->decimal('total_peminjaman',65); $table->decimal('angsuran',65); $table->decimal('jumlah_total',65); $table->decimal('total_denda',65); $table->integer('denda'); $table->integer('info_ke'); $table->integer('bulan'); $table->integer('tahun'); $table->string('status'); $table->text('keterangan'); $table->integer('created_by'); $table->timestamps(); $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('transaksis'); } }
<?php // 5 MVC Pattern // 5.7 Templates // 5.7.1 Simple replaces use Book\Control\Page; class TwigWelcomeControl extends Page { public function __construct() { parent::__construct(); require_once 'Lib/Twig/Autoloader.php'; Twig_Autoloader::register(); $loader = new Twig_Loader_Filesystem('App/Resources'); $twig = new Twig_Environment($loader); $template = $twig->loadTemplate('welcome.html'); $replaces = []; $replaces['name'] = 'John Doe'; $replaces['street'] = 'Doe street'; $replaces['cep'] = '77789456123'; $replaces['phone'] = '789456123'; $content = $template->render($replaces); echo $content; } public function onKnowMore($params) { echo 'More info'; } } //https://php-filipe1309.c9users.io/php_oo_3ed/5_chapter/index.php?class=TwigWelcomeControl
<?php namespace Codem\DamnFineUploader; use Exception; class MissingDataException extends Exception { }
//! States for the `bootcom` serial boot protocol state machine. //! //! This modules is private and restricted to the //! [`boot_protocol`](crate::boot_protocol) scope. The public interface of the //! serial boot protocol state machine is provided by //! [`boot_protocol`](crate::boot_protocol). //! //! ```ignore //! use super::events::*; //! ``` //! //! Refer to the [`state_machine`](super::state_machine) module for an overview //! of states, events and transitions. use std::fmt; use serialport::SerialPort; use crate::Settings; // ============================================================================= // Crate-Public Interface // ============================================================================= // SwitchToTerminalModeEvent =================================================== /// Event fired to trigger a transition to [`TerminalModeState`]. /// /// This event can happen under one of the following circumstances: /// /// 1. While at the [`InitState`] and after a serial port has been successfully /// opened and configured. /// 2. While at the [`KernelModeState`] after the kernel image has been /// successfully pushed. pub struct SwitchToTerminalModeEvent { pub settings: Settings, /// The serial port to be used in the next state. Consumed and moved to the /// next state. pub port: Box<dyn SerialPort>, } impl fmt::Debug for SwitchToTerminalModeEvent { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let port = &self.port; debug_fmt_serialport!(port, f).finish() } } // SwitchToKernelModeEvent ===================================================== /// Event fired to trigger a transition to [`KernelSendModeState`]. /// /// This event can happen under one of the following circumstances: /// /// 1. While at the [`TerminalModeState`] upon reception of the `send_kernel` /// command from the booting device. pub struct SwitchToKernelSendModeEvent { pub settings: Settings, /// The serial port to be used in the next state. Consumed and moved to the /// next state. pub port: Box<dyn SerialPort>, } impl fmt::Debug for SwitchToKernelSendModeEvent { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let port = &self.port; debug_fmt_serialport!(port, f).finish() } } // DoneState =================================================================== /// Event fired when the boot protocol execution completes and is about to /// terminate. It triggers a transition to the `Done` state. /// /// This event can heppen at any state due to normal termination, user initiated /// termination or abnormal termination caused by an unrecoverable error. #[derive(Debug)] pub(crate) struct DoneEvent { pub settings: Settings, /// When `true`, indicates an abnormal completion caused by an error. pub with_errors: bool, } // ExitEvent =================================================================== /// The last event that can be triggered in the boot protocol state machine and /// will result in the event loop terminating with an `exit status`, handing /// back the control to the original caller that started the state machine event /// loop. /// /// The returned `status code` can be interpreted as whether the completion was /// normal or abnormal. /// /// **Example** /// ```ignore /// use crate::settings::*; /// use crate::boot_protocol as bpsm; /// /// let settings = SettingsBuilder::new().finalize(); /// let mut sm = bpsm::factory(settings); /// let status = sm.run(); // status code returned after the `Exit` event /// println!("status: {}", status); /// ``` #[derive(Debug)] pub(crate) struct ExitEvent { pub settings: Settings, pub with_error: bool, } // Events enum ================================================================== /// Events that can be triggered within the serial boot protocol state machine /// of `bootcom`. /// /// Each possible value holds an `event`, which in turn may hold additional data /// for the state transition. Such data is passed by the origin state for /// potential use by the target state. #[derive(Debug)] pub(crate) enum Event { SwitchToTerminalMode(SwitchToTerminalModeEvent), SwitchToKernelSendMode(SwitchToKernelSendModeEvent), Done(DoneEvent), Exit(ExitEvent), }
require 'active_support/core_ext/hash/indifferent_access' module WorkableJsonAssertions module Assertions def json_response_body(options = {symbolize_names: true}) JSON.parse(response.body.strip, options) end def assert_json_response_empty assert_empty response.body.strip end def assert_json_response_equal(json) json = json.with_indifferent_access if json.is_a?(Hash) assert_equal json, json_response_body end def assert_json_response_equal_except(json, blacklist = []) json = json.with_indifferent_access if json.is_a?(Hash) assert_json_equal_except(json, json_response_body, blacklist) end def assert_json_response_includes(hash) assert_match hash, json_response_body end def assert_json_response_has_key(key) assert json_response_body.has_key?(key.to_sym) end def refute_json_response_has_key(key) refute json_response_body.has_key?(key.to_sym) end private def assert_json_equal_except(json1, json2, blacklist = []) json1 = recursive_except(json1, blacklist) json2 = recursive_except(json2, blacklist) assert_equal json1, json2 end def recursive_except(obj, blacklist) case obj when Hash obj = obj.with_indifferent_access obj.each do |k, v| obj[k] = recursive_except(v, blacklist) end.except(*blacklist) when Array obj.map do |i| recursive_except(i, blacklist) end else obj end end end end
#!/usr/bin/env ruby require_relative '../githubarchive' storage = Githubarchive::Database.new(ENV['DATABASE_URL']) # required if you want to import filtered events filter = Proc.new do |event| !(event['type'] == 'PullRequestEvent' && event['payload']['action'] == 'opened') end archive = Githubarchive.new(filter: filter, procesor: storage) # create events table if not present # storage.create_table # generate archive links from start, end times archive_links = archive.to_links( Time.parse('2016-01-27 00:00:00'), Time.parse('2016-01-27 23:59:59') ) archive.call(archive_links)
<?php include 'header.php'; use BODM\ActiveModel; /* * ETC * */ class Post extends ActiveModel { protected $references = ['author']; } class Author extends ActiveModel { protected $compressed = ['name', 'Post' => ['reputation']]; } $author = new Author(['name' => 'Mike', 'reputation' => 111, 'dateJoined' => '2016-03-03']); $post = new Post(['author' => $author, 'content' => 'Hey']); //To switch to fullDebug mode $post->switchFullDebug(); var_dump($post); /* * Output: object(Post)#8 (14) { ["references"]=> array(1) { [0]=> string(6) "author" } ["dbName"]=> string(7) "default" ["collectionName"]=> string(4) "post" ["embedded"]=> bool(false) ["autoExpand"]=> bool(false) ["graceful"]=> bool(true) ["collection"]=> object(MongoDB\Collection)#9 (7) { ["collectionName"]=> string(4) "post" ["databaseName"]=> string(7) "default" ["manager"]=> object(MongoDB\Driver\Manager)#3 (3) { ["request_id"]=> int(11766) ["uri"]=> string(25) "mongodb://localhost:27017" ["cluster"]=> array(1) { [0]=> array(11) { ["host"]=> string(9) "localhost" ["port"]=> int(27017) ["type"]=> int(0) ["is_primary"]=> bool(false) ["is_secondary"]=> bool(false) ["is_arbiter"]=> bool(false) ["is_hidden"]=> bool(false) ["is_passive"]=> bool(false) ["tags"]=> array(0) { } ["last_is_master"]=> array(0) { } ["round_trip_time"]=> int(-1) } } } ["readConcern"]=> object(MongoDB\Driver\ReadConcern)#10 (1) { ["level"]=> NULL } ["readPreference"]=> object(MongoDB\Driver\ReadPreference)#11 (2) { ["mode"]=> int(1) ["tags"]=> array(0) { } } ["typeMap"]=> array(3) { ["array"]=> string(23) "MongoDB\Model\BSONArray" ["document"]=> string(26) "MongoDB\Model\BSONDocument" ["root"]=> string(26) "MongoDB\Model\BSONDocument" } ["writeConcern"]=> object(MongoDB\Driver\WriteConcern)#12 (4) { ["w"]=> NULL ["wmajority"]=> bool(false) ["wtimeout"]=> int(0) ["journal"]=> NULL } } ["lastResult"]=> NULL ["compressed"]=> array(0) { } ["referenceObjects"]=> array(0) { } ["attributes"]=> array(2) { ["author"]=> object(Author)#2 (3) { ["name"]=> string(4) "Mike" ["reputation"]=> int(111) ["dateJoined"]=> string(10) "2016-03-03" } ["content"]=> string(3) "Hey" } ["original"]=> array(2) { ["author"]=> object(Author)#2 (3) { ["name"]=> string(4) "Mike" ["reputation"]=> int(111) ["dateJoined"]=> string(10) "2016-03-03" } ["content"]=> string(3) "Hey" } ["updates"]=> array(0) { } ["fullDebug"]=> bool(true) } */ //Suggested constructing method class Foo extends ActiveModel { public static function create(int $bar, array $baz) { return parent::construct(['bar' => $bar, 'baz' => $baz]); } } $foo = Foo::create(2, ['foo', 'bar', 'baz']); echo $foo.PHP_EOL; /* * Output: { "bar": 2, "baz": [ "foo", "bar", "baz" ] } */
collection @proposals attributes :id, :statement #extends "proposals/show" # would be more object oriented? node(:updated_at) do |proposal| if proposal.updated_at > 10.months.ago proposal.updated_at.strftime("%b %e, %l:%M%P") elsif proposal.updated_at > 16.months.ago 'About a year ago' else 'Over a year ago' end end node(:related_proposals_count) { |proposal| proposal.root.related_proposals.count + 1 } # n+1 queries node(:votes_in_tree) { |proposal| proposal.votes_in_tree } node(:is_editable) { |proposal| proposal.editable?(current_user) } child :hub do attributes :id, :short_hub end child :votes do attributes :gravatar_hash, :facebook_auth, :username end
/* SPDX-License-Identifier: GPL-2.0-only */ /* * Port on Texas Instruments TMS320C6x architecture * * Copyright (C) 2004, 2009, 2010, 2011 Texas Instruments Incorporated * Author: Aurelien Jacquiot ([email protected]) */ #ifndef _ASM_C6X_DELAY_H #define _ASM_C6X_DELAY_H #include <linux/kernel.h> extern unsigned int ticks_per_ns_scaled; static inline void __delay(unsigned long loops) { uint32_t tmp; /* 6 cycles per loop */ asm volatile (" mv .s1 %0,%1\n" "0: [%1] b .s1 0b\n" " add .l1 -6,%0,%0\n" " cmplt .l1 1,%0,%1\n" " nop 3\n" : "+a"(loops), "=A"(tmp)); } static inline void _c6x_tickdelay(unsigned int x) { uint32_t cnt, endcnt; asm volatile (" mvc .s2 TSCL,%0\n" " add .s2x %0,%1,%2\n" " || mvk .l2 1,B0\n" "0: [B0] b .s2 0b\n" " mvc .s2 TSCL,%0\n" " sub .s2 %0,%2,%0\n" " cmpgt .l2 0,%0,B0\n" " nop 2\n" : "=b"(cnt), "+a"(x), "=b"(endcnt) : : "B0"); } /* use scaled math to avoid slow division */ #define C6X_NDELAY_SCALE 10 static inline void _ndelay(unsigned int n) { _c6x_tickdelay((ticks_per_ns_scaled * n) >> C6X_NDELAY_SCALE); } static inline void _udelay(unsigned int n) { while (n >= 10) { _ndelay(10000); n -= 10; } while (n-- > 0) _ndelay(1000); } #define udelay(x) _udelay((unsigned int)(x)) #define ndelay(x) _ndelay((unsigned int)(x)) #endif /* _ASM_C6X_DELAY_H */
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace RandomCodeOrg.ENetFramework.UI { public interface IRenderContext { void Render(XmlDocument document); void Render(XmlDocument document, XmlElement element); T Resolve<T>(string statement); string BuildParmeterName(XmlElement element, string parameterStatement); void PushVariable(string name, object value); void PopVariable(string name); } }
#!/bin/sh # chmod 777 release-mac.sh NAME=goman VERSION=$1 TYPE=$2 SRC=github.com/zaaksam/goman/go/main/$TYPE function BUILD() { DIR=$(cd $(dirname $0); pwd) DISTDIR=$DIR/dist DISTNAME=$NAME.$VERSION.$TYPE-win DISTSYSO=$GOPATH/src/$SRC/$NAME.syso ZIPNAME=$DISTNAME.zip echo echo $ZIPNAME building... echo cd $DISTDIR cp -f $DIR/$NAME.syso $DISTSYSO # See github.com/karalabe/xgo xgo -ldflags="-H windowsgui" -out $DISTNAME --targets=windows-10.0/amd64 $GOPATH/src/$SRC rm $DISTSYSO mv $DISTNAME-windows-10.0-amd64.exe $DISTNAME.exe zip -m $ZIPNAME $DISTNAME.exe echo } function USAGE() { echo echo argument error. echo echo e.g. \"./release-win.sh v0.1.0 web\" or \"./release-win.sh v0.1.0 app\" echo } if [ "$VERSION" == "" ];then USAGE; elif [ "$TYPE" == "web" ];then BUILD; elif [ "$TYPE" == "app" ];then BUILD; else USAGE; fi
use ts_rs::TS; #[test] fn list() { #[derive(TS)] struct List { #[allow(dead_code)] data: Option<Vec<u32>>, } assert_eq!( List::decl(), "interface List { data: Array<number> | null, }" ); }
# -*- coding: utf-8 -*- from abc import abstractmethod from pre_commit_hooks.loaderon_hooks.util.template_methods.files_bunches_checker_template_method import \ FileBunchesCheckerTemplateMethod from pre_commit_hooks.loaderon_hooks.util.template_methods.lines_checker_template_method import \ LinesCheckerTemplateMethod class FileBunchesLinesCheckerTemplateMethod(FileBunchesCheckerTemplateMethod, LinesCheckerTemplateMethod): @abstractmethod def _get_regexp(self): pass def _check_bunch(self): """ This method uses LinesCheckerTemplateMethod's _check_lines. Which receives self._file_lines. In this case, our 'file lines' will be the bunches of lines got by split_by_classes. """ super(FileBunchesLinesCheckerTemplateMethod, self)._check_bunch() self._file_lines = self._bunch_of_lines self._check_lines() @abstractmethod def _check_line(self): super(FileBunchesLinesCheckerTemplateMethod, self)._check_line() pass
--- title: Appearance Crouching searchTitle: Lua Appearance Crouching weight: 1 hidden: true menuTitle: Appearance Crouching description: Makes a NPC appear crouching --- ## Crouching Makes a NPC appear crouching ```lua Appearance.Crouching ```
buildscript { var ossrhUser: String? by extra ossrhUser = if(ossrhUser!=null) ossrhUser else System.getenv("ossrhUser") var ossrhPassword: String? by extra ossrhPassword = if(ossrhPassword!=null) ossrhPassword else System.getenv("ossrhPassword") } allprojects { group = "de.qualityminds.gta" version = "0.0.1-SNAPSHOT" repositories { jcenter() mavenCentral() maven { url = uri("https://oss.sonatype.org/content/repositories/snapshots") } } }
import java.util.*; public class RankingMethods { final static String[] input = {"44 Solomon", "42 Jason", "42 Errol", "41 Garry", "41 Bernard", "41 Barry", "39 Stephen"}; public static void main(String[] args) { int len = input.length; Map<String, int[]> map = new TreeMap<>((a, b) -> b.compareTo(a)); for (int i = 0; i < len; i++) { String key = input[i].split("\\s+")[0]; int[] arr; if ((arr = map.get(key)) == null) arr = new int[]{i, 0}; arr[1]++; map.put(key, arr); } int[][] groups = map.values().toArray(new int[map.size()][]); standardRanking(len, groups); modifiedRanking(len, groups); denseRanking(len, groups); ordinalRanking(len); fractionalRanking(len, groups); } private static void standardRanking(int len, int[][] groups) { System.out.println("\nStandard ranking"); for (int i = 0, rank = 0, group = 0; i < len; i++) { if (group < groups.length && i == groups[group][0]) { rank = i + 1; group++; } System.out.printf("%d %s%n", rank, input[i]); } } private static void modifiedRanking(int len, int[][] groups) { System.out.println("\nModified ranking"); for (int i = 0, rank = 0, group = 0; i < len; i++) { if (group < groups.length && i == groups[group][0]) rank += groups[group++][1]; System.out.printf("%d %s%n", rank, input[i]); } } private static void denseRanking(int len, int[][] groups) { System.out.println("\nDense ranking"); for (int i = 0, rank = 0; i < len; i++) { if (rank < groups.length && i == groups[rank][0]) rank++; System.out.printf("%d %s%n", rank, input[i]); } } private static void ordinalRanking(int len) { System.out.println("\nOrdinal ranking"); for (int i = 0; i < len; i++) System.out.printf("%d %s%n", i + 1, input[i]); } private static void fractionalRanking(int len, int[][] groups) { System.out.println("\nFractional ranking"); float rank = 0; for (int i = 0, tmp = 0, group = 0; i < len; i++) { if (group < groups.length && i == groups[group][0]) { tmp += groups[group++][1]; rank = (i + 1 + tmp) / 2.0F; } System.out.printf("%2.1f %s%n", rank, input[i]); } } }
# encoding: UTF-8 require 'metadata/processors' require 'tempfile' class TestProcessor < Minitest::Test def test_creates_instance_of_shellrunner shell_runner = Minitest::Mock.new shell_runner.expect :new, self Metadata.stub_const(:ShellRunner, shell_runner) do Metadata::Processor.new end shell_runner.verify end end class TestYAMLFrontmatterProcessor < Minitest::Test def setup @metadata = {'title' => 'My great note', 'tags' => 'foo'} @content = 'My Markdown content' @file = Tempfile.new('YAMLFM') @yamlfm = Metadata::YAMLFrontmatterProcessor.new end def teardown @file.close! end def test_reads_and_strips_frontmatter_if_found document = ['---', *@metadata.map {|k,v| "#{k}: #{v}" }, '---', @content].join($/) << $/ @file.write(document) @file.rewind assert_equal [@metadata, @content], @yamlfm.call(@file) end def test_leaves_file_alone_if_no_frontmatter_found document = [@content, 'Some *nice* stuff here.'].join($/) << $/ @file.write(document) @file.rewind assert_equal([{}, nil], @yamlfm.call(@file)) assert_equal document, File.read(@file.path) end def test_returns_empty_if_file_invalid @file.close! assert_equal([{}, nil], @yamlfm.call(@file)) end end class TestLegacyFrontmatterProcessor < Minitest::Test def setup @metadata = {'=' => 'My notebook', '@' => 'foo'} @content = 'My Markdown content' @file = Tempfile.new('LegacyFM') @legacyfm = Metadata::LegacyFrontmatterProcessor.new end def teardown @file.close! end def test_converts_frontmatter_to_mmd_metadata_if_found document = [*@metadata.map {|k,v| "#{k} #{v}" }, '', @content].join($/) converted = document.gsub(/^= /, 'Notebook: ').gsub(/^\@ /, 'Tags: ') @file.write(document) @file.rewind assert_equal([{}, converted], @legacyfm.call(@file)) end def test_leaves_file_alone_if_no_frontmatter_found document = [@content, 'Some *nice* stuff here.'].join($/) @file.write(document) @file.rewind assert_equal([{}, document], @legacyfm.call(@file)) end def test_raises_runtime_error_on_sed_error @file.close! e = assert_raises(RuntimeError) { assert_output('', /^.+ sed .+$/) { @legacyfm.call(@file) } } assert_match /`sed` exited with status [1-9][0-9]*/, e.to_s end end class TestAggregatingProcessor < Minitest::Test def setup @values = {scalar: 'Foo', set: [1, 2]} end def new_processor(**keys) # We must `eval` to get @values as the block is `instance_exec`’d in the Processor’s context. eval "Metadata::AggregatingProcessor.new(**keys) { |file, key| #{@values}[key] }" end def test_exposes_keys_reader processor = new_processor(@values) assert_respond_to processor, :keys refute_respond_to processor, :keys= assert_equal @values, processor.keys end def test_retrieves_a_hash_of_values_indexed_on_keys keys = {string: :scalar, array: :set} processor = new_processor(**keys) values = processor.call(__FILE__) assert_instance_of Hash, values assert_equal keys.keys, values.keys end def test_retrieves_and_merges_scalar_data_points processor = new_processor(string: [:scalar, :scalar]) values = processor.call(__FILE__) assert_equal @values[:scalar], values[:string] end def test_retrieves_and_merges_array_data_points processor = new_processor(array: [:set, :set]) values = processor.call(__FILE__) assert_equal @values[:set], values[:array] end def test_retrieves_and_merges_mixed_data_points processor = new_processor(mix: [:scalar, :set]) values = processor.call(__FILE__) assert_equal @values.values.flatten, values[:mix] end def test_raises_argument_error_if_keys_or_block_missing assert_raises(ArgumentError) { new_processor } assert_raises(ArgumentError) { Metadata::AggregatingProcessor.new(@values) } end end class TestSpotlightPropertiesProcessor < Minitest::Test def setup @file = File.new(__FILE__) end def teardown @file.close end def new_processor(**keys) Metadata::SpotlightPropertiesProcessor.new(**keys) end def test_retrieves_and_merges_scalar_data_points values = new_processor(name: 'kMDItemFSName').call(@file) assert_instance_of String, values[:name] assert_equal File.basename(@file.path), values[:name] values = new_processor(type: ['kMDItemContentType', 'kMDItemKind']).call(@file) assert_instance_of Array, values[:type] assert_equal values[:type].compact.uniq.count, values[:type].count end def test_retrieves_and_merges_array_data_points single = new_processor(tree: 'kMDItemContentTypeTree').call(@file) assert_instance_of Array, single[:tree] assert_equal single[:tree].compact.uniq.count, single[:tree].count double = new_processor(tree: ['kMDItemContentTypeTree', 'kMDItemContentTypeTree']).call(@file) assert_instance_of Array, double[:tree] assert_equal single, double end end class FilePropertiesProcessor < Minitest::Test def setup @file = File.new(__FILE__) end def teardown @file.close end def test_retrieves_file_method_properties keys = {atime: :atime, path: :path} values = Metadata::FilePropertiesProcessor.new(**keys).call(@file) assert_equal keys.count, values.count assert_instance_of Time, values[:atime] assert_instance_of String, values[:path] end end
package org.luxons.sevenwonders.ui.redux.sagas import kotlinx.coroutines.* import org.luxons.sevenwonders.ui.test.runSuspendingTest import redux.RAction import redux.Store import redux.WrapperAction import redux.applyMiddleware import redux.compose import redux.createStore import redux.rEnhancer import kotlin.test.Test import kotlin.test.assertEquals private data class State(val data: String) private data class UpdateData(val newData: String) : RAction private class DuplicateData : RAction private class SideEffectAction(val data: String) : RAction private fun reduce(state: State, action: RAction): State = when (action) { is UpdateData -> State(action.newData) is DuplicateData -> State(state.data + state.data) else -> state } private fun configureTestStore(initialState: State): TestRedux { val sagaMiddlewareFactory = SagaManager<State, RAction, WrapperAction>() val sagaMiddleware = sagaMiddlewareFactory.createMiddleware() val enhancers = compose(applyMiddleware(sagaMiddleware), rEnhancer()) val store = createStore(::reduce, initialState, enhancers) return TestRedux(store, sagaMiddlewareFactory) } private data class TestRedux( val store: Store<State, RAction, WrapperAction>, val sagas: SagaManager<State, RAction, WrapperAction>, ) class SagaContextTest { @Test fun dispatch() = runSuspendingTest { val redux = configureTestStore(State("initial")) redux.sagas.runSaga { dispatch(UpdateData("Bob")) } assertEquals(State("Bob"), redux.store.getState(), "state is not as expected") } @Test fun next() = runSuspendingTest { val redux = configureTestStore(State("initial")) val job = redux.sagas.launchSaga(this) { val action = next<SideEffectAction>() dispatch(UpdateData("effect-${action.data}")) } assertEquals(State("initial"), redux.store.getState()) redux.store.dispatch(SideEffectAction("data")) job.join() assertEquals(State("effect-data"), redux.store.getState()) } @Test fun onEach() = runSuspendingTest { val redux = configureTestStore(State("initial")) val job = redux.sagas.launchSaga(this) { onEach<SideEffectAction> { dispatch(UpdateData("effect-${it.data}")) } } assertEquals(State("initial"), redux.store.getState()) redux.store.dispatch(SideEffectAction("data")) delay(50) assertEquals(State("effect-data"), redux.store.getState()) job.cancel() } }
window.onload = function(){ var p = document.getElementById("descripcion"); p.innerHTML = 0; function calculoPalabras(){ var total = 0; var cuantasLetras = document.getElementById("comentario").value.length; if(cuantasLetras < 3001){ p.innerHTML = total + cuantasLetras; } } document.getElementById("comentario").addEventListener("keyup", calculoPalabras); }
/* * Copyright 2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.restassured.scalatra import org.scalatra.ScalatraServlet import scala.collection.mutable import scala.util.Random class CustomAuthExample extends ScalatraServlet { val authenticatedSessions = new mutable.HashMap[String, Int]() before() { contentType = "application/json" } post("/login") { val rand = new Random(System.currentTimeMillis()) val operandA = rand.nextInt(1000) val operandB = rand.nextInt(1000) val expectedSum = operandA + operandB val id = rand.nextLong().toString authenticatedSessions += id -> expectedSum "{ \"operandA\" : "+operandA + ", \"operandB\" : "+operandB + ", \"id\" : \""+id+"\" }" } get("/secretMessage") { returnIfLoggedIn("I'm secret") } get("/secretMessage2") { returnIfLoggedIn("I'm also secret") } private def returnIfLoggedIn(message: => String) : String = { val actualSum = request.getParameter("sum") val id = request.getParameter("id") val expectedSum = authenticatedSessions.getOrElse(id, -1) if (actualSum == null || id == null || expectedSum == -1 || actualSum.toInt != expectedSum) { """{ "message" : "You're not authorized to see the secret message" }""" } else { "{ \"message\" : \""+message+"\" }" } } }
package zhstructures; /** * This is the interface describing the actions * on a simple stack. */ public interface ZHStack<T> { /** * empty() returns true if the Stack is empty. */ public boolean empty(); /** * push(value) adds value to the top of the stack. * <p><b>Postcondition<b>The stack has a new item at its top. * </p><br> */ public void push(T value); /** * peek() returns the value at the top of the stack. * The stack is unchanged. * <p><b>Precondition: <b>The queue is not empty. * </p><br> */ public T peek() throws ZHEmptyStackException; /** * pop() returns the value at the top of the stack. * and removes that value from the stack. * <p><b>Precondition: <b>The queue is not empty.</p><br> * <p><b>Postcondition: <b>The top item is removed and * the item pushed before the top item becomes the top * item. */ public T pop() throws ZHEmptyStackException; }
package com.kotlin.mvvm.repository.db import androidx.room.Database import androidx.room.RoomDatabase import com.kotlin.mvvm.repository.model.TodoModel /** * Developed by Waheed on 20,June,2021 * * App Database * Define all entities and access doa's here/ Each entity is a table. */ @Database( entities = [TodoModel::class], version = 1, exportSchema = false ) abstract class AppDatabase : RoomDatabase() { abstract fun todoDao(): TodoDao }
require 'uber/models/delivery/delivery' require 'uber/models/delivery/quote' require 'uber/models/delivery/rating' require 'uber/models/delivery/rating_tag' require 'uber/models/delivery/receipt' require 'uber/models/delivery/region'
#pragma once // Header file for preprocessor class - see preprocessor.cpp for descriptions #include <map> #include "pipePacket.hpp" template<typename nodeType> class preprocessor { private: public: bool configured = false; std::string procName = "preprocessor"; bool debug = 0; std::string outputFile; utils ut; preprocessor(); virtual ~preprocessor(); static preprocessor* newPreprocessor(const std::string&); void runPreprocessorWrapper(pipePacket<nodeType> &inData); virtual void runPreprocessor(pipePacket<nodeType> &inData); virtual void outputData(pipePacket<nodeType>&); virtual void outputData(std::vector<unsigned>); virtual void outputData(std::vector<std::vector<double>>); virtual bool configPreprocessor(std::map<std::string, std::string> &configMap); };
#ifndef __CCLUA_PLUGIN_WECHAT_H__ #define __CCLUA_PLUGIN_WECHAT_H__ #include "cclua/plugin.h" #include <string> #if defined(CCLUA_OS_IOS) || defined(CCLUA_OS_ANDROID) NS_CCLUA_PLUGIN_BEGIN class WeChat { public: enum class ShareType {NONE, TEXT, IMAGE, MUSIC, VIDEO, WEB}; enum class ProgramType {RELEASE = 0, TEST = 1, PREVIEW = 2}; #ifdef CCLUA_OS_ANDROID static void pay(const std::string &partnerId, const std::string &prepayId, const std::string &noncestr, const std::string &timestamp, const std::string &packageValue, const std::string &sign); #endif static void init(const std::string &appid, const std::string &universalLink); static bool isInstalled(); static void auth(const std::string &scope, const std::string &state); static void authQRCode(const std::string &appid, const std::string &nonceStr, const std::string &timestamp, const std::string &scope, const std::string &signature); static void stopAuth(); static void share(ShareType type, cocos2d::ValueMap &value); static void open(const std::string &username, const std::string path = "", ProgramType type = ProgramType::RELEASE); DISPATCHER_IMPL }; NS_CCLUA_PLUGIN_END #endif #endif //__CCLUA_PLUGIN_WECHAT_H__
(ns chesty.db (:require [chesty.db.views :as v] [clojure.string :as str] [krulak :as kr] [manila-john :as mj])) (def ^:dynamic *sites-db* (System/getenv "CHESTY_SITES_DB")) (defmacro with-sites-db [& body] `(mj/with-db *sites-db* ~@body)) (defn site-for-host [host] (with-sites-db (-> {:key (str/lower-case host) :limit 1 :include_docs true} v/sites-by-host first :doc))) (defn id [doc-or-id] (if (string? doc-or-id) doc-or-id (:_id doc-or-id (:id doc-or-id)))) (defn user-id [doc] (or (:user-id doc) (id (:user doc)))) (defn path [doc] (or (first (:paths doc)) (:path doc))) (defn doc-for-uri [uri & options] (->> (merge {:include_docs true :key (str/lower-case uri) :limit 1} options) (v/docs-by-uri) first :doc)) (defn user-for-username [username & [options]] (->> (merge {:include_docs true :key (str/lower-case username) :limit 1} options) (v/users-by-username) first :doc)) (defn username-available? [username] (let [username-owner (future (user-for-username username)) uri-owner (->> username kr/to-url-slug (str \/) doc-for-uri future)] (not (or @username-owner @uri-owner))))
package org.theponies.ponecrafter.model enum class Age(val id: Int) { ANY(0), ADULT(1), FOAL(2); companion object { fun getById(id: Int) = values().firstOrNull { it.id == id } ?: ANY } }
import { COUNT_SELECTOR, ORIGIN_FALLBACK_ID } from "coral-framework/constants"; import detectCountScript from "coral-framework/helpers/detectCountScript"; import resolveStoryURL from "coral-framework/helpers/resolveStoryURL"; import jsonp from "coral-framework/utils/jsonp"; import getCurrentScriptOrigin from "./getCurrentScriptOrigin"; import injectJSONPCallback from "./injectJSONPCallback"; /** Arguments that will be send to the server. */ interface CountQueryArgs { id?: string; url?: string; notext?: boolean; } /** createCountQueryRef creates a unique reference from the query args */ function createCountQueryRef(args: CountQueryArgs) { return btoa(`${JSON.stringify(!!args.notext)};${args.id || args.url}`); } /** Detects count elements and use jsonp to inject the counts. */ function detectAndInject() { const ORIGIN = getCurrentScriptOrigin(ORIGIN_FALLBACK_ID); const STORY_URL = resolveStoryURL(); /** A map of references pointing to the count query arguments */ const queryMap: Record<string, CountQueryArgs> = {}; // Find all the selected elements and fill the queryMap. const elements = document.querySelectorAll(COUNT_SELECTOR); Array.prototype.forEach.call(elements, (element: HTMLElement) => { let url = element.dataset.coralUrl; const id = element.dataset.coralId; const notext = element.dataset.coralNotext === "true"; if (!url && !id) { url = STORY_URL; element.dataset.coralUrl = STORY_URL; } const args = { id, url, notext }; const ref = createCountQueryRef(args); if (!(ref in queryMap)) { queryMap[ref] = args; } element.dataset.coralRef = ref; }); // Call server using JSONP. Object.keys(queryMap).forEach((ref) => { const { url, id, notext } = queryMap[ref]; const args = { url, id, notext: notext ? "true" : "false", ref }; jsonp(`${ORIGIN}/api/story/count.js`, "CoralCount.setCount", args); }); } export function main() { injectJSONPCallback(); detectAndInject(); } if (!detectCountScript() && process.env.NODE_ENV !== "test") { main(); }
import { Avatar, Box, Divider, Flex, Heading, Stack, Text, useBreakpointValue, IconButton, Drawer, DrawerOverlay, DrawerContent, DrawerCloseButton, HStack, Alert, } from '@chakra-ui/react'; import { HamburgerIcon } from '@chakra-ui/icons'; import { Navigate, useLocation, useNavigate, useParams, } from 'react-router-dom'; import { useState } from 'react'; import { SidebarDiscordServerLinks } from '@/features/discordServers'; import { SidebarFeedLinks } from '@/features/feed'; import { useDiscordBot, useDiscordUserMe, UserStatusTag } from '@/features/discordUser'; import { DiscordUserDropdown } from '@/features/discordUser/components/DiscordUserDropdown'; import { LogoutButton } from '@/features/auth'; import { Loading } from '../Loading'; interface Props { requireFeed?: boolean; } export const PageContent: React.FC<Props> = ({ requireFeed, children }) => { const staticSidebarShown = useBreakpointValue<boolean>({ base: false, xl: true }); const navigate = useNavigate(); const location = useLocation(); const { feedId, serverId } = useParams(); const [sidebarToggledOpen, setSidebarToggledOpen] = useState(false); const { data: userMe, } = useDiscordUserMe(); const { data: discordBotData, error: discordBotError, status: discordBotStatus, } = useDiscordBot(); const onPathChanged = (path: string) => { navigate(path, { replace: true, }); if (!staticSidebarShown) { setSidebarToggledOpen(false); } }; if (!serverId) { return <Navigate to="/servers" />; } if (!feedId && requireFeed) { return <Navigate to={`/servers/${serverId}/feeds`} />; } const sidebarContent = ( <> <Flex justifyContent="center" flexDir="column" // height="75px" width="full" background={staticSidebarShown ? 'gray.700' : 'gray.800'} paddingX="4" paddingY="2" > {discordBotData && !discordBotError && ( <> <Flex alignItems="center" paddingBottom="1"> <Avatar src={discordBotData.result.avatar || undefined} size="xs" name={discordBotData.result.username} marginRight="2" backgroundColor="transparent" /> <Heading fontSize="xl" whiteSpace="nowrap" overflow="hidden" textOverflow="ellipsis" title={discordBotData.result.username} > {discordBotData.result.username} </Heading> </Flex> <Text display="block">Control Panel</Text> </> )} {discordBotError && <Alert status="error">{discordBotError.message}</Alert>} {discordBotStatus === 'loading' && <Box><Loading /></Box>} </Flex> <Stack paddingX="6" marginTop="6" display="flex" alignItems="flex-start" spacing="2" > <Stack width="100%" alignItems="flex-start" spacing="4" > <Avatar name={userMe?.username} src={userMe?.iconUrl} size="lg" /> <DiscordUserDropdown /> </Stack> <UserStatusTag /> </Stack> <Divider marginY="8" /> <Stack px="6" spacing="9"> <SidebarDiscordServerLinks currentPath={location.pathname} onChangePath={onPathChanged} serverId={serverId} /> <SidebarFeedLinks currentPath={location.pathname} feedId={feedId} serverId={serverId} onChangePath={onPathChanged} /> </Stack> <Divider /> <LogoutButton /> </> ); if (!staticSidebarShown) { return ( <Box> <Drawer size="md" isOpen={sidebarToggledOpen} onClose={() => { setSidebarToggledOpen(false); }} placement="left" > <DrawerOverlay /> <DrawerContent overflow="auto"> <DrawerCloseButton /> {sidebarContent} </DrawerContent> </Drawer> <HStack spacing={4} height="60px" background="gray.700" width="100%" paddingX="4" display="flex" alignItems="center" > <IconButton onClick={() => setSidebarToggledOpen(true)} variant="outline" icon={<HamburgerIcon fontSize="xl" />} aria-label="Open menu" /> <Heading>Monito.RSS</Heading> </HStack> {children} </Box> ); } return ( <Flex flexGrow={1} height="100%" // overflow="auto" > <Flex overflow="auto" as="nav" direction="column" maxW="325px" height="100%" width="full" paddingBottom="4" borderRightWidth="1px" > {sidebarContent} </Flex> <Flex width="100%" justifyContent="center" overflow="auto" > <Box width="100%"> {children} </Box> </Flex> </Flex> ); };
package vn.com.ntq_solution.domain.utils /** List application typo character. */ class Typography { companion object { const val CURLY_BRACKET_OPEN = "{" const val CURLY_BRACKET_CLOSE = "}" const val DOT = "." const val DOLLAR = "$" const val DOUBLE_DOT = ":" const val HYPHEN = "-" const val SHARP = "#" const val SPACE = " " } }
'use strict'; var running = 4; var epsilon = 1e-2; function Vec(x, y) { this.x = x; this.y = y; this.length = function() { return Math.sqrt(x*x + y*y); } this.add = function(vec) { return new Vec(this.x + vec.x, this.y + vec.y); } this.sub = function(vec) { return new Vec(this.x - vec.x, this.y - vec.y); } this.scale = function(s) { return new Vec(this.x * s, this.y * s); } this.dot = function(vec) { return this.x * vec.x + this.y * vec.y; } this.ortho = function() { return new Vec(-this.y, this.x); } this.normalize = function() { let len = this.length(); return new Vec(this.x / len, this.y / len); } } function Ball(size, path) { this.size = size; this.path = path; this.type = 'ball'; this.color = 'black'; this.paint = function(ctx, t) { let pos = this.path.getPosition(t); ctx.save(); ctx.fillStyle = this.color; ctx.beginPath(); ctx.arc(pos.x, pos.y, this.size, 0, Math.PI * 2, true); ctx.closePath(); ctx.fill(); ctx.restore(); let begin = this.path.origin; let end = this.path.getEndPosition(); ctx.save(); ctx.beginPath(); ctx.arc(begin.x, begin.y, this.size, 0, Math.PI * 2, true); ctx.closePath(); ctx.stroke(); ctx.beginPath(); ctx.arc(end.x, end.y, this.size, 0, Math.PI * 2, true); ctx.closePath(); ctx.stroke(); ctx.setLineDash([10]); ctx.beginPath(); ctx.moveTo(begin.x, begin.y); ctx.lineTo(end.x, end.y); ctx.closePath(); ctx.stroke(); ctx.restore(); } this.update = function(t) { if (this.path.isMoving(t)) { return; } console.log('update'); let origin_new = this.path.getEndPosition(); let velocity_old = this.path.velocity; let start = this.path.start + this.path.duration; if (this.path.intersect.type == 'wall') { let n = this.path.intersect.normal; let velocity_new = velocity_old.sub( n.scale(velocity_old.dot(n) * 2) ); origin_new = origin_new.add(velocity_new.scale(epsilon)); intersectScene(origin_new, velocity_new, this, start); } else if (this.path.intersect.type == 'ball' ) { let that = this.path.intersect; console.log('this moving', this.path.isMoving(t)); console.log('that moving', that.path.isMoving(t)); let ball2_pos = that.path.getPosition(start); let un = ball2_pos.sub(origin_new).normalize(); let ut = un.ortho(); let v1 = velocity_old; let v2 = that.path.velocity; let m1 = this.size; let m2 = that.size; let v1n = un.dot(v1); let v1t = ut.dot(v1); let v2n = un.dot(v2); let v2t = ut.dot(v2); let v1tp = v1t; let v2tp = v2t; let v1np = (v1n * (m1 - m2) + 2 * m2 * v2n) / (m1 + m2); let v2np = (v2n * (m2 - m1) + 2 * m1 * v1n) / (m1 + m2); let v1p = un.scale(v1np).add(ut.scale(v1tp)); let v2p = un.scale(v2np).add(ut.scale(v2tp)); origin_new = origin_new.add(v1p.scale(epsilon)); intersectScene(origin_new, v1p, this, start); console.log('this.path', this.index, this.path); ball2_pos = ball2_pos.add(v2p.scale(epsilon)); intersectScene(ball2_pos, v2p, that, start); console.log('that.path', that.index, that.path); console.log('this moving', this.path.isMoving(t)); console.log('that moving', that.path.isMoving(t)); } running--; } } function Path(origin, velocity, start, duration, intersection) { this.origin = origin; this.velocity = velocity; this.start = start; this.duration = duration; this.intersect = intersection; this.getPosition = function(t) { let diff = Math.min(t - this.start, this.duration); return this.origin.add(velocity.scale(diff)); } this.getEndPosition = function() { return this.origin.add(this.velocity.scale(this.duration)); } this.isMoving = function(t) { return (t < (this.duration + this.start)); } } function Wall(origin, normal) { this.origin = origin; this.normal = normal.normalize(); this.type = 'wall'; let dir = normal.ortho(); let invdirx = 1/dir.x; let invdiry = 1/dir.y; let tmin, tmax; if (invdirx >= 0) { tmin = (0 - this.origin.x) * invdirx; tmax = (state.canvas.width - this.origin.x) * invdirx; } else { tmin = (state.canvas.width - this.origin.x) * invdirx; tmax = (0 - this.origin.x) * invdirx; } let tymin, tymax; if (invdiry >= 0) { tymin = (0 - this.origin.y) * invdiry; tymax = (state.canvas.height - this.origin.y) * invdiry; } else { tymin = (state.canvas.height - this.origin.y) * invdiry; tymax = (0 - this.origin.y) * invdiry; } if (tymin > tmin) { tmin = tymin; } if (tymax < tmax) { tmax = tymax; } this.p0 = this.origin.add(dir.scale(tmin)); this.p1 = this.origin.add(dir.scale(tmax)); this.paint = function(ctx, t) { /* ctx.beginPath(); ctx.setLineDash([]); ctx.moveTo(this.p0.x, this.p0.y); ctx.lineTo(this.p1.x, this.p1.y); ctx.closePath(); ctx.stroke(); */ } this.update = function(t) { } } var scene = []; var state = {}; function intersectWall(origin, direction, ball, wall) { let denom = wall.normal.dot(direction); if (Math.abs(denom) > 1e-6) { let p0l0 = wall.origin.sub(origin); let t = p0l0.dot(wall.normal) / denom; return t + (ball.size / denom); } return -1; } function intersectBall(origin, velocity, ball1, ball2) { // running--; let l = ball1.size + ball2.size; let pq = origin.sub(ball2.path.origin); let rs = velocity.sub(ball2.path.velocity); let a = rs.dot(rs); if (a < 1e-6 && a > -1e-6) { return -1; } let b = 2 * rs.dot(pq); let c = pq.dot(pq) - l*l; let square = b*b - 4*a*c; if (square < 0) { return -1; } if (square < 1e-6) { return (-b / (2*a)) * velocity.length(); } let sqr = Math.sqrt(square); let t1 = (-b + sqr) / (2 * a) * velocity.length(); let t2 = (-b - sqr) / (2 * a) * velocity.length(); let tmin = Math.min(t1, t2); let tmax = Math.max(t1, t2); if (tmin < 0) { return tmax; } else { return tmin; } } function intersectScene(origin, velocity, obj, start) { let dir = velocity.normalize(); let ts = scene.map(function(el, idx) { if (idx == obj.index) { return -1; } if (el.type == 'wall') { return intersectWall(origin, dir, obj, el); } else if (el.type == 'ball') { let t = intersectBall(origin, velocity, obj, el); return t; } else { console.error('unknown type'); } }); let tmin = ts.reduce(function(acc, el, idx) { if ((el > 0) && (el < acc[0])) { return [el, idx]; } return acc; }, [Infinity, -1]); console.log('tmin', tmin); let duration = tmin[0] / velocity.length(); let intersection = scene[tmin[1]]; obj.path = new Path(origin, velocity, start, duration, intersection); // return; if (intersection.type == 'ball') { // console.log(intersection); // let other_duration = (start + duration) - intersection.path.start; // intersection.path.duration = other_duration; } } function getTime() { return new Date().valueOf() / 100; } function draw() { let now = getTime(); state.ctx.clearRect(0, 0, state.canvas.width, state.canvas.height); scene.forEach(e => e.update(now)); scene.forEach(e => e.paint(state.ctx, now)); if (running > 0) { window.requestAnimationFrame(draw); } else { console.log('running', running); } } function onInit() { let now = getTime(); state.canvas = document.getElementById('canvas'); state.ctx = canvas.getContext('2d'); scene.push(new Wall(new Vec(0, 0), new Vec(1, 0))); scene.push(new Wall(new Vec(0, 0), new Vec(0, 1))); scene.push(new Wall(new Vec(state.canvas.width, state.canvas.height), new Vec(0, -1))); scene.push(new Wall(new Vec(state.canvas.width, state.canvas.height), new Vec(-1, 0))); let radiusa = 10; let balla = new Ball(radiusa, null); balla.color = 'red'; scene.push(balla); scene.forEach((e, i) => e.index = i); let origina = new Vec(50, 150); let velocitya = new Vec(10, 0); let tmina = intersectScene(origina, velocitya, balla, now); let radiusb = 10; let ballb = new Ball(radiusb, null); ballb.color = 'blue'; scene.push(ballb); scene.forEach((e, i) => e.index = i); let originb = new Vec(150, 50); let velocityb = new Vec(0, 10); let tminb = intersectScene(originb, velocityb, ballb, now); window.requestAnimationFrame(draw); }
<?php /** * Copyright (C) Alibaba Cloud Computing * All rights reserved. * * 版权所有 (C)阿里云计算有限公司 */ namespace Aliyun\OSS\Utilities; class ResponseHeaderOverrides { const RESPONSE_HEADER_CONTENT_TYPE = "response-content-type"; const RESPONSE_HEADER_CONTENT_LANGUAGE = "response-content-language"; const RESPONSE_HEADER_EXPIRES = "response-expires"; const RESPONSE_HEADER_CACHE_CONTROL = "response-cache-control"; const RESPONSE_HEADER_CONTENT_DISPOSITION = "response-content-disposition"; const RESPONSE_HEADER_CONTENT_ENCODING = "response-content-encoding"; }
################################################################ #This script will impose stress on specified processors with the #arguments passed based on stress type. ################################################################ #!/bin/bash function usage() { echo "" echo "Usage --> $0 [-c CPU] [-t timeout] [-a stress-args][-h]" echo " CPU : 1/0-2 ; default is 22-43" echo " timeout : N(number)" echo " stress-args : "--cpu=100 --vm=100 --io=10 --hdd=100"" echo " -h : Help section" echo "" } ## --- Parse command line arguments / parameters --- while getopts ":c:t:a:h" option; do case $option in c) # processor processors=$OPTARG ;; t) # output_dir timeout=$OPTARG ;; a)#istress args args=$OPTARG ;; :) echo "Option -$OPTARG requires an argument." usage exit 1 ;; h) usage exit 0 ;; *) echo "Unknown option: $OPTARG." usage exit 1 ;; ?) echo "[WARNING] Unknown parameters!!!" echo "Using default values for CPU,timeout and stress parameters" esac done if [[ -z "$processors" ]] then processors='22-43' fi if [[ -z "$timeout" ]] then timeout='10m' fi if [[ -z "$args" ]] then args="--cpu=100" fi stress_params=$(echo $args | sed 's/[,=]/ /g'|sed -e 's/\r//g') cmd="taskset -c $processors stress --timeout ${timeout} ${stress_params}" echo $cmd eval "${cmd}" &>/dev/null &disown
package net.corda.serialization.djvm.deserializers import org.apache.qpid.proton.amqp.UnsignedByte import java.util.function.Function class UnsignedByteDeserializer : Function<ByteArray, UnsignedByte> { override fun apply(underlying: ByteArray): UnsignedByte { return UnsignedByte(underlying[0]) } }
import numpy as np from scipy.special import logsumexp def exp_normalize(x): b = x.max() y = np.exp(x - b) return y / y.sum() def sum_lnspace(a, b): """ Given a = ln(p) and b=ln(q), return ln(p+q) in natural log space""" if a > b: # ensure a is always the smallest term, so log function is on smaller. temp = a a = b b = temp ln_sum = b + np.log(np.exp(a - b) + 1) return ln_sum
describe HttpStub::Server::Daemon do let(:server_name_in_rakefile) { :example_server_daemon } let(:port_in_rakefile) { 8001 } let(:configurator) { HttpStub::ConfiguratorFixture.create(port: port_in_rakefile) } let(:server) { HttpStub::Server::Daemon.new(name: server_name_in_rakefile, configurator: configurator) } it_behaves_like "a managed http server" end
import { Structure as _Structure_ } from "@aws-sdk/types"; export const RestoreTableFromClusterSnapshotInput: _Structure_ = { type: "structure", required: [ "ClusterIdentifier", "SnapshotIdentifier", "SourceDatabaseName", "SourceTableName", "NewTableName" ], members: { ClusterIdentifier: { shape: { type: "string" } }, SnapshotIdentifier: { shape: { type: "string" } }, SourceDatabaseName: { shape: { type: "string" } }, SourceSchemaName: { shape: { type: "string" } }, SourceTableName: { shape: { type: "string" } }, TargetDatabaseName: { shape: { type: "string" } }, TargetSchemaName: { shape: { type: "string" } }, NewTableName: { shape: { type: "string" } } } };
class Venue { final String id; String name; double lat; double lng; int distance; List<dynamic> address; Venue(this.id, this.name, this.lat, this.lng, this.distance, this.address); factory Venue.fromJson(Map<String, dynamic> json) { //print(json); Venue newVenue = Venue( json["id"], json["name"], json["location"]["lat"], json["location"]["lng"], json["location"]["distance"], json["location"]["formattedAddress"]); return newVenue; } @override String toString() { return this.id + ", " + this.name + ", " + this.lat.toString() + ", " + this.lng.toString() + ", " + this.distance.toString() + ", " + this.address.toString(); } }
package panel; import java.util.List; import java.awt.Color; import java.awt.Point; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; public class Line { final private List<ColoredSizedPoint> points; private Color actualLineColor; private Color LineLastColor; private int actualLineSize; public Line() { this.points = new ArrayList<>(); } public Color getLineColor() { this.points.forEach(point -> actualLineColor = point.getPointColor()); return this.actualLineColor; } public Color getLineLastColor() { this.points.forEach(point -> LineLastColor = point.getPointLastColor()); return this.LineLastColor; } public int getLineSize() { this.points.forEach(point -> actualLineSize = point.getPointSize()); return this.actualLineSize; } public void addPoint(ColoredSizedPoint p) { this.points.add(p); } public List<ColoredSizedPoint> getColoredSizedPoint() { return this.points; } public Set<Point> getPoints() { Set<Point> pointsCoordinates = new HashSet<>(); this.points.forEach(point -> pointsCoordinates.add(point.getPointCoordinates())); return pointsCoordinates; } }
.home ===== This repository contains dotfiles, scripts, and plugins that personalize my Linux environment. Install ------- git clone git://github.com/trinitylundgren/.home.git ~/.home cd ~/.home ./install You may clone the repository into a different directory if you prefer. It does not need to be located in `~/.home`. See `install -h` for more options. Installation Behavior --------------------- Each file in this directory structure will get symlinked into your `$HOME` at its corresponding location. Any directories beginning with `_` are collapsed into its parent directory and are only used for organizing this repository. So, for example: * `~/.home/_zsh/.zshrc` gets linked from `~/.zshrc`. * `~/.home/_git/.zsh/git.zsh` gets linked from `~/.zsh/git.zsh` * `~/.home/_vim/.zsh/vim.zsh` gets linked from `~/.zsh/vim.zsh` If any of the files already exist at the destination, you will be prompted to skip, overwrite, or backup that file. Files specified in `.homeignore` will be ignored. Each pattern is specified on its own line. See the `-path` description in the `find` manpage for a description of the syntax used. Uninstall --------- To remove all of the installed symlinks and restore all files that were backed up, use `install -r`. To remove the symlinks without restoring files, use `install -u`. cd ~/.home ./install -r ~/.home/backup.abcde # Where backup.abcde is the backup you # want to restore from. Forking and Contributing ------------------------ This repository has two branches, `core` and `master`. `core` contains the installation script, related files, and documentation. `master` contains my own personal configuration. This should make it easy to merge upstream changes to `core` or to fork a repo with none of my configuration. Feel free to log issues or pull requests on [GitHub][]. [GitHub]: https://github.com/trinitylundgren/.home
; RUN: llc -mtriple=x86_64-apple-macosx -mattr=+cx16 -x86-use-base-pointer=true -stackrealign -stack-alignment=32 %s -o - | FileCheck --check-prefix=CHECK --check-prefix=USE_BASE --check-prefix=USE_BASE_64 %s ; RUN: llc -mtriple=x86_64-apple-macosx -mattr=+cx16 -x86-use-base-pointer=false -stackrealign -stack-alignment=32 %s -o - | FileCheck --check-prefix=CHECK --check-prefix=DONT_USE_BASE %s ; RUN: llc -mtriple=x86_64-linux-gnux32 -mattr=+cx16 -x86-use-base-pointer=true -stackrealign -stack-alignment=32 %s -o - | FileCheck --check-prefix=CHECK --check-prefix=USE_BASE --check-prefix=USE_BASE_32 %s ; RUN: llc -mtriple=x86_64-linux-gnux32 -mattr=+cx16 -x86-use-base-pointer=false -stackrealign -stack-alignment=32 %s -o - | FileCheck --check-prefix=CHECK --check-prefix=DONT_USE_BASE %s ; This function uses dynamic allocated stack to force the use ; of a frame pointer. ; The inline asm clobbers a bunch of registers to make sure ; the frame pointer will need to be used (for spilling in that case). ; ; Then, we check that when we use rbx as the base pointer, ; we do not use cmpxchg, since using that instruction requires ; to clobbers rbx to set the arguments of the instruction and when ; rbx is used as the base pointer, RA cannot fix the code for us. ; ; CHECK-LABEL: cmp_and_swap16: ; Check that we actually use rbx. ; gnux32 use the 32bit variant of the registers. ; USE_BASE_64: movq %rsp, %rbx ; USE_BASE_32: movl %esp, %ebx ; ; Make sure the base pointer is saved before the RBX argument for ; cmpxchg16b is set. ; ; Because of how the test is written, we spill SAVE_RBX. ; However, it would have been perfectly fine to just keep it in register. ; USE_BASE: movq %rbx, [[SAVE_RBX_SLOT:[0-9]*\(%[er]bx\)]] ; ; SAVE_RBX must be in register before we clobber rbx. ; It is fine to use any register but rbx and the ones defined and use ; by cmpxchg. Since such regex would be complicated to write, just stick ; to the numbered registers. The bottom line is: if this test case fails ; because of that regex, this is likely just the regex being too conservative. ; USE_BASE: movq [[SAVE_RBX_SLOT]], [[SAVE_RBX:%r[0-9]+]] ; ; USE_BASE: movq {{[^ ]+}}, %rbx ; USE_BASE-NEXT: cmpxchg16b ; USE_BASE-NEXT: movq [[SAVE_RBX]], %rbx ; ; DONT_USE_BASE-NOT: movq %rsp, %rbx ; DONT_USE_BASE-NOT: movl %esp, %ebx ; DONT_USE_BASE: cmpxchg define i1 @cmp_and_swap16(i128 %a, i128 %b, i128* %addr, i32 %n) { %dummy = alloca i32, i32 %n tail call void asm sideeffect "nop", "~{rax},~{rcx},~{rdx},~{rsi},~{rdi},~{rbp},~{r8},~{r9},~{r10},~{r11},~{r12},~{r13},~{r14},~{r15}"() %cmp = cmpxchg i128* %addr, i128 %a, i128 %b seq_cst seq_cst %res = extractvalue { i128, i1 } %cmp, 1 %idx = getelementptr i32, i32* %dummy, i32 5 store i32 %n, i32* %idx ret i1 %res }
# -*- coding: utf-8 -*- #------------------------------------------------------------------------------ # Package: Pikos toolkit # File: external/api.py # License: LICENSE.TXT # # Copyright (c) 2012, Enthought, Inc. # All rights reserved. #------------------------------------------------------------------------------ __all__ = [ 'PythonCProfiler', ] import warnings from pikos.external.python_cprofiler import PythonCProfiler try: from pikos.external.yappi_profiler import YappiProfiler except ImportError: warnings.warn( 'YappiProfiler cannot be imported and will not be available') else: def yappi_profile(buildins=None): """ Factory function that returns a yappi monitor. """ return YappiProfiler(buildins) __all__.extend(['YappiProfiler', 'yappi_profile']) try: from pikos.external.line_profiler import LineProfiler except ImportError: warnings.warn( 'LineProfile cannot be imported and will not be available') else: def line_profile(*args, **kwrds): """ Factory function that returns a line profiler. Please refer to `<http://packages.python.org/line_profiler/ for more information>_` for initialization options. """ return LineProfiler(*args, **kwrds) __all__.extend(['LineProfiler', 'line_profile'])
unit Antlr.Runtime.Collections.Tests; { Delphi DUnit Test Case ---------------------- This unit contains a skeleton test case class generated by the Test Case Wizard. Modify the generated code to correctly setup and call the methods from the unit being tested. } interface uses TestFramework, Antlr.Runtime.Collections, Generics.Collections, Antlr.Runtime.Tools; type // Test methods for class IHashList TestIHashList = class(TTestCase) strict private FIHashList: IHashList<Integer, String>; public procedure SetUp; override; procedure TearDown; override; published procedure TestInsertionOrder; procedure TestRemove; end; // Test methods for class IStackList TestIStackList = class(TTestCase) strict private FIStackList: IStackList<String>; public procedure SetUp; override; procedure TearDown; override; published procedure TestPushPop; procedure TestPeek; end; implementation uses SysUtils; const Values: array [0..9] of Integer = (50, 1, 33, 76, -22, 22, 34, 2, 88, 12); procedure TestIHashList.SetUp; var I: Integer; begin FIHashList := THashList<Integer, String>.Create; for I in Values do FIHashList.Add(I,'Value' + IntToStr(I)); end; procedure TestIHashList.TearDown; begin FIHashList := nil; end; procedure TestIHashList.TestInsertionOrder; var I: Integer; P: TPair<Integer, String>; begin I := 0; for P in FIHashList do begin CheckEquals(P.Key, Values[I]); CheckEquals(P.Value, 'Value' + IntToStr(Values[I])); Inc(I); end; end; procedure TestIHashList.TestRemove; var I: Integer; P: TPair<Integer, String>; begin FIHashList.Remove(34); I := 0; for P in FIHashList do begin if (Values[I] = 34) then Inc(I); CheckEquals(P.Key, Values[I]); CheckEquals(P.Value, 'Value' + IntToStr(Values[I])); Inc(I); end; end; procedure TestIStackList.SetUp; begin FIStackList := TStackList<String>.Create; end; procedure TestIStackList.TearDown; begin FIStackList := nil; end; procedure TestIStackList.TestPushPop; var Item: String; begin Item := 'Item 1'; FIStackList.Push(Item); Item := 'Item 2'; FIStackList.Push(Item); CheckEquals(FIStackList.Pop,'Item 2'); CheckEquals(FIStackList.Pop,'Item 1'); end; procedure TestIStackList.TestPeek; begin FIStackList.Push('Item 1'); FIStackList.Push('Item 2'); FIStackList.Push('Item 3'); FIStackList.Pop; CheckEquals(FIStackList.Peek, 'Item 2'); CheckEquals(FIStackList.Pop, 'Item 2'); end; initialization // Register any test cases with the test runner RegisterTest(TestIHashList.Suite); RegisterTest(TestIStackList.Suite); end.
import '../../less/campus/campus.less'; import '../common/common';
#!/usr/bin/env bash BUILDPATH=docs SOURCEPATH=docs/source rm $BUILDPATH/*.html sphinx-build -b html $SOURCEPATH $BUILDPATH echo 'Documentation website in '$BUILDPATH
# Project Archived ## Tech Stack HTML, CSS, PHP, JS, Bootstrap, Wordpress - Front End ## Getting Started 1. Install Wordpress and create a new site using [Local](https://local.getflywheel.com/). 2. Navigate to Themes Folder and clone repo. 3. Activate new theme for site from WP admin panel. 4. Install `pre-commit` Mac Users -->\ Install homebrew and run `brew install pre-commit`\ Run `pre-commit install` Windows Users -->\ Install the latest Python (3.7) executable file from <https://www.python.org/downloads/>\ Install pip `curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py`\ Run `python get-pip.py`\ Run `pip install pre-commit`\ Run `pre-commit install` ## License This project is licensed under the MIT License.
package ch.dreipol.multiplatform.reduxsample.shared.ui import ch.dreipol.multiplatform.reduxsample.shared.database.DisposalType import ch.dreipol.multiplatform.reduxsample.shared.database.RemindTime import ch.dreipol.multiplatform.reduxsample.shared.database.SettingsDataStore data class NotificationSettingsViewState( val notificationEnabled: Boolean = false, val remindTimes: List<Pair<RemindTime, Boolean>> = RemindTime.values() .map { if (SettingsDataStore.defaultRemindTime == it) it to true else it to false }, val selectedDisposalTypes: List<DisposalType> = DisposalType.values().toList(), val headerViewState: HeaderViewState = HeaderViewState("settings_notifications"), val introductionKey: String = "settings_notification_description" ) interface NotificationSettingsView : BaseView { override fun presenter() = notificationSettingsPresenter fun render(notificationSettingsViewState: NotificationSettingsViewState) } val notificationSettingsPresenter = presenter<NotificationSettingsView> { { select({ it.settingsViewState.notificationSettingsViewState }) { render(state.settingsViewState.notificationSettingsViewState) } } }
// == Contoh == // function tambah(a, b) { /* * variabel a dan b disebut parameter, * dan akan menangkap nilai yang dikirimkan saat function dipanggil */ return a + b; } console.log(tambah(4, 8)); // 12 console.log(tambah(10, 20)); // 30 function sapa(nama) { return "Halo " + nama + ", Selamat Pagi!"; } console.log(sapa("Joe")); // Halo Joe, Selamat Pagi! console.log(sapa("Andi")); // Halo Andi, Selamat Pagi!
# ブロック要素のスタイル require_relative 'typeset_margin' require_relative 'typeset_padding' class BlockNodeStyle def initialize @sfnt_font = nil @font_size = nil @line_gap = 0 @margin = TypesetMargin.zero_margin @padding = TypesetPadding.zero_padding @begin_new_page = false @indent = 0 end attr_accessor :sfnt_font, :font_size attr_accessor :line_gap, :margin, :padding attr_accessor :begin_new_page alias_method :begin_new_page?, :begin_new_page attr_accessor :indent end
package dreme.runtime; import dreme.*; /** * Created by IntelliJ IDEA. * User: oysta * Date: 21/02/2010 * Time: 8:58:15 PM * To change this template use File | Settings | File Templates. */ class SchemeProcessor extends AbstractSchemeObjectVisitor { private final ExecutionContext ctx; public SchemeProcessor(ExecutionContext ctx) { this.ctx = ctx; } public void object(SchemeObject obj) { ctx.addResult(obj); } public void identifier(Identifier identifier) { if (!ctx.getEnvironment().contains(identifier)) throw new IllegalStateException("Unbound variable: " + identifier.getName()); object(ctx.getEnvironment().get(identifier)); } public void list(List list) { ctx.execute(list, ctx.getEnvironment()); } public void unspecified(Unspecified unspecified) { throw new IllegalArgumentException("Attempted to evaluate " + unspecified); } public void evaluate(SchemeObject schemeObject) { schemeObject.acceptVisitor(this); } public void apply(Operator operator) { operator.apply(ctx); } }
//using log4net; using System.Threading; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using Quobject.EngineIoClientDotNet.Client; using System; using Quobject.EngineIoClientDotNet.Modules; namespace Quobject.EngineIoClientDotNet_Tests.ClientTests { [TestClass] public class UsageTest : Connection { [TestMethod] public void Usage1() { LogManager.SetupLogManager(); var log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod()); log.Info("Start"); var options = CreateOptions(); var socket = new Socket(options); //You can use `Socket` to connect: //var socket = new Socket("ws://localhost"); socket.On(Socket.EVENT_OPEN, () => { socket.Send("hi"); socket.Close(); }); socket.Open(); //System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2)); } private ManualResetEvent _manualResetEvent = null; [TestMethod] public void Usage2() { LogManager.SetupLogManager(); var log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod()); log.Info("Start"); _manualResetEvent = new ManualResetEvent(false); var options = CreateOptions(); var socket = new Socket(options); //Receiving data //var socket = new Socket("ws://localhost:3000"); socket.On(Socket.EVENT_OPEN, () => { socket.On(Socket.EVENT_MESSAGE, (data) => Console.WriteLine((string)data)); _manualResetEvent.Set(); }); socket.Open(); _manualResetEvent.WaitOne(); socket.Close(); } } }
int ** recebeImagem(){ FILE *arq = fopen("Treino.txt","r"); int i,j; int qtd,**imagem; fscanf(arq,"%d",&qtd); imagem = (int **)malloc(sizeof(int)*qtd); for (i=0;i<qtd;i++){ imagem[i] = (int *)malloc(sizeof(int)*601); } for (i=0;i<qtd;i++){ for (j=0;j<600;j++){ fscanf(arq,"%d",&imagem[i][j]); } desvet(imagem[i]); } return imagem; }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.runtime.checkpoint.channel; import org.apache.flink.core.memory.MemorySegmentFactory; import org.apache.flink.runtime.checkpoint.channel.ChannelStateWriter.ChannelStateWriteResult; import org.apache.flink.runtime.io.network.buffer.Buffer; import org.apache.flink.runtime.io.network.buffer.FreeingBufferRecycler; import org.apache.flink.runtime.io.network.buffer.NetworkBuffer; import org.apache.flink.runtime.state.CheckpointStorageLocationReference; import org.apache.flink.util.CloseableIterator; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.util.List; import java.util.Optional; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.Optional.empty; import static java.util.Optional.of; import static org.apache.flink.runtime.checkpoint.channel.ChannelStateWriteRequest.completeInput; import static org.apache.flink.runtime.checkpoint.channel.ChannelStateWriteRequest.completeOutput; import static org.apache.flink.runtime.checkpoint.channel.ChannelStateWriteRequest.write; import static org.apache.flink.runtime.state.ChannelPersistenceITCase.getStreamFactoryFactory; import static org.junit.Assert.fail; /** {@link ChannelStateWriteRequestDispatcherImpl} tests. */ @RunWith(Parameterized.class) public class ChannelStateWriteRequestDispatcherTest { private final List<ChannelStateWriteRequest> requests; private final Optional<Class<?>> expectedException; public static final long CHECKPOINT_ID = 42L; @Parameters public static Object[][] data() { return new Object[][] { // valid calls new Object[] {empty(), asList(start(), completeIn(), completeOut())}, new Object[] {empty(), asList(start(), writeIn(), completeIn())}, new Object[] {empty(), asList(start(), writeOut(), completeOut())}, new Object[] {empty(), asList(start(), completeIn(), writeOut())}, new Object[] {empty(), asList(start(), completeOut(), writeIn())}, // invalid without start new Object[] {of(IllegalArgumentException.class), singletonList(writeIn())}, new Object[] {of(IllegalArgumentException.class), singletonList(writeOut())}, new Object[] {of(IllegalArgumentException.class), singletonList(completeIn())}, new Object[] {of(IllegalArgumentException.class), singletonList(completeOut())}, // invalid double complete new Object[] { of(IllegalArgumentException.class), asList(start(), completeIn(), completeIn()) }, new Object[] { of(IllegalArgumentException.class), asList(start(), completeOut(), completeOut()) }, // invalid write after complete new Object[] { of(IllegalStateException.class), asList(start(), completeIn(), writeIn()) }, new Object[] { of(IllegalStateException.class), asList(start(), completeOut(), writeOut()) }, // invalid double start new Object[] {of(IllegalStateException.class), asList(start(), start())} }; } private static CheckpointInProgressRequest completeOut() { return completeOutput(CHECKPOINT_ID); } private static CheckpointInProgressRequest completeIn() { return completeInput(CHECKPOINT_ID); } private static ChannelStateWriteRequest writeIn() { return write( CHECKPOINT_ID, new InputChannelInfo(1, 1), CloseableIterator.ofElement( new NetworkBuffer( MemorySegmentFactory.allocateUnpooledSegment(1), FreeingBufferRecycler.INSTANCE), Buffer::recycleBuffer)); } private static ChannelStateWriteRequest writeOut() { return write( CHECKPOINT_ID, new ResultSubpartitionInfo(1, 1), new NetworkBuffer( MemorySegmentFactory.allocateUnpooledSegment(1), FreeingBufferRecycler.INSTANCE)); } private static CheckpointStartRequest start() { return new CheckpointStartRequest( CHECKPOINT_ID, new ChannelStateWriteResult(), new CheckpointStorageLocationReference(new byte[] {1})); } public ChannelStateWriteRequestDispatcherTest( Optional<Class<?>> expectedException, List<ChannelStateWriteRequest> requests) { this.requests = requests; this.expectedException = expectedException; } @Test public void doRun() { ChannelStateWriteRequestDispatcher processor = new ChannelStateWriteRequestDispatcherImpl( "dummy task", 0, getStreamFactoryFactory(), new ChannelStateSerializerImpl()); try { for (ChannelStateWriteRequest request : requests) { processor.dispatch(request); } } catch (Throwable t) { if (expectedException.filter(e -> e.isInstance(t)).isPresent()) { return; } throw new RuntimeException("unexpected exception", t); } expectedException.ifPresent(e -> fail("expected exception " + e)); } }
module Sequel # This module makes it easy to print deprecation warnings with optional backtraces to a given stream. # There are a couple of methods you can use to change where the deprecation methods are printed # and whether they should include backtraces: # # Sequel::Deprecation.output = $stderr # print deprecation messages to standard error (default) # Sequel::Deprecation.output = File.open('deprecated_calls.txt', 'wb') # use a file instead # Sequel::Deprecation.backtraces = false # don't include backtraces # Sequel::Deprecation.backtraces = true # include full backtraces # Sequel::Deprecation.backtraces = 10 # include 10 backtrace lines (default) # Sequel::Deprecation.backtraces = 1 # include 1 backtrace line module Deprecation extend Metaprogramming @output = $stderr @backtraces = 10 metaattr_accessor :output, :backtraces # Print the message to the output stream def self.deprecate(method, instead=nil) message = instead ? "#{method} is deprecated and will be removed in Sequel 3.0. #{instead}." : method return unless output output.puts(message) case backtraces when Integer b = backtraces caller.each do |c| b -= 1 output.puts(c) break if b == 0 end when true caller.each{|c| output.puts(c)} end end end end
# Text Selection Context Menu A context menu that pops up when the selecting text. ## License Licensed under the [MIT license](http://www.opensource.org/licenses/mit-license.php).
class RenameCouponsToLandingPages < ActiveRecord::Migration[5.2] def change rename_table :coupons, :landing_pages rename_column :subscriptions, :coupon_code, :landing_page_slug end end
;++ ; ; Copyright (c) Microsoft Corporation. All rights reserved. ; ; Licensed under the MIT License. ; ; Module Name: ; ; TransKernelFma3.asm ; ; Abstract: ; ; This module implements kernels for various transcendental functions. ; ; This implementation uses AVX fused multiply/add instructions. ; ;-- .xlist INCLUDE mlasi.inc INCLUDE TransKernelCommon.inc .list EXTERN MlasMaskMoveTableAvx:NEAR EXTERN MlasExpConstants:NEAR ;++ ; ; Routine Description: ; ; This routine implements a vectorized kernel for the exponential function. ; ; Arguments: ; ; Input (rcx) - Supplies the input buffer. ; ; Output (rdx) - Supplies the output buffer. ; ; N (r8) - Supplies the number of elements to process. ; ; Return Value: ; ; None. ; ;-- NESTED_ENTRY MlasComputeExpF32KernelFma3, _TEXT alloc_stack (TransKernelFrame.ReturnAddress) save_xmm128 xmm6,TransKernelFrame.SavedXmm6 save_xmm128 xmm7,TransKernelFrame.SavedXmm7 save_xmm128 xmm8,TransKernelFrame.SavedXmm8 save_xmm128 xmm9,TransKernelFrame.SavedXmm9 save_xmm128 xmm10,TransKernelFrame.SavedXmm10 save_xmm128 xmm11,TransKernelFrame.SavedXmm11 save_xmm128 xmm12,TransKernelFrame.SavedXmm12 save_xmm128 xmm13,TransKernelFrame.SavedXmm13 save_xmm128 xmm14,TransKernelFrame.SavedXmm14 save_xmm128 xmm15,TransKernelFrame.SavedXmm15 END_PROLOGUE lea rax,MlasExpConstants vbroadcastss ymm4,ExpConstants.LowerRange[rax] vbroadcastss ymm5,ExpConstants.UpperRange[rax] vbroadcastss ymm6,ExpConstants.MinimumExponent[rax] vbroadcastss ymm7,ExpConstants.MaximumExponent[rax] vbroadcastss ymm8,ExpConstants.RoundingBias[rax] vbroadcastss ymm9,ExpConstants.Log2Low[rax] vbroadcastss ymm10,ExpConstants.poly_0[rax] vbroadcastss ymm11,ExpConstants.poly_1[rax] vbroadcastss ymm12,ExpConstants.poly_2[rax] vbroadcastss ymm13,ExpConstants.poly_3[rax] vbroadcastss ymm14,ExpConstants.poly_4[rax] vbroadcastss ymm15,ExpConstants.poly_56[rax] sub r8,8 jb ProcessRemainingCount ComputeExpBy8Loop: vmaxps ymm0,ymm4,YMMWORD PTR [rcx] ; clamp lower bound vbroadcastss ymm2,ExpConstants.Log2Reciprocal[rax] vminps ymm0,ymm5,ymm0 ; clamp upper bound vbroadcastss ymm3,ExpConstants.Log2High[rax] vfmadd213ps ymm2,ymm0,ymm8 ; (x / ln2) plus rounding bias vsubps ymm1,ymm2,ymm8 ; m = round(x / ln2) vfmadd231ps ymm0,ymm1,ymm3 ; range reduce: x -= (m * ln2_high) vfmadd231ps ymm0,ymm1,ymm9 ; range reduce: x -= (m * ln2_low) vmovaps ymm1,ymm10 ; p = poly_0 vfmadd213ps ymm1,ymm0,ymm11 ; p = p * x + poly_1 vpslld ymm2,ymm2,23 ; shift m to exponent field vfmadd213ps ymm1,ymm0,ymm12 ; p = p * x + poly_2 vpminsd ymm3,ymm2,ymm7 ; clamp upper normal exponent to +127 vfmadd213ps ymm1,ymm0,ymm13 ; p = p * x + poly_3 vpmaxsd ymm3,ymm3,ymm6 ; clamp lower normal exponent to -126 vfmadd213ps ymm1,ymm0,ymm14 ; p = p * x + poly_4 vpsubd ymm2,ymm2,ymm3 ; compute overflow exponent vpaddd ymm3,ymm3,ymm7 ; add exponent bias to normal scale vpaddd ymm2,ymm2,ymm7 ; add exponent bias to overflow scale vfmadd213ps ymm1,ymm0,ymm15 ; p = p * x + poly_56 vmulps ymm0,ymm0,ymm2 ; scale x with overflow exponent vfmadd213ps ymm1,ymm0,ymm2 ; p = p * (x * overflow) + overflow vmulps ymm1,ymm1,ymm3 ; scale p with normal exponent add rcx,8*4 ; advance input by 8 elements vmovups YMMWORD PTR [rdx],ymm1 add rdx,8*4 ; advance output by 8 elements sub r8,8 jae ComputeExpBy8Loop ProcessRemainingCount: add r8,8 ; correct for over-subtract above jz ExitKernel neg r8 lea r10,MlasMaskMoveTableAvx+8*4 vmovups ymm2,YMMWORD PTR [r10+r8*4] vmaskmovps ymm0,ymm2,YMMWORD PTR [rcx] vmaxps ymm0,ymm4,ymm0 ; clamp lower bound vbroadcastss ymm4,ExpConstants.Log2Reciprocal[rax] vminps ymm0,ymm5,ymm0 ; clamp upper bound vbroadcastss ymm3,ExpConstants.Log2High[rax] vfmadd213ps ymm4,ymm0,ymm8 ; (x / ln2) plus rounding bias vsubps ymm1,ymm4,ymm8 ; m = round(x / ln2) vfmadd231ps ymm0,ymm1,ymm3 ; range reduce: x -= (m * ln2_high) vfmadd231ps ymm0,ymm1,ymm9 ; range reduce: x -= (m * ln2_low) vmovaps ymm1,ymm10 ; p = poly_0 vfmadd213ps ymm1,ymm0,ymm11 ; p = p * x + poly_1 vpslld ymm4,ymm4,23 ; shift m to exponent field vfmadd213ps ymm1,ymm0,ymm12 ; p = p * x + poly_2 vpminsd ymm3,ymm4,ymm7 ; clamp upper normal exponent to +127 vfmadd213ps ymm1,ymm0,ymm13 ; p = p * x + poly_3 vpmaxsd ymm3,ymm3,ymm6 ; clamp lower normal exponent to -126 vfmadd213ps ymm1,ymm0,ymm14 ; p = p * x + poly_4 vpsubd ymm4,ymm4,ymm3 ; compute overflow exponent vpaddd ymm3,ymm3,ymm7 ; add exponent bias to normal scale vpaddd ymm4,ymm4,ymm7 ; add exponent bias to overflow scale vfmadd213ps ymm1,ymm0,ymm15 ; p = p * x + poly_5 vmulps ymm0,ymm0,ymm4 ; scale x with overflow exponent vfmadd213ps ymm1,ymm0,ymm4 ; p = p * (x * overflow) + overflow vmulps ymm1,ymm1,ymm3 ; scale p with normal exponent vmaskmovps YMMWORD PTR [rdx],ymm2,ymm1 ExitKernel: vzeroupper movaps xmm6,TransKernelFrame.SavedXmm6[rsp] movaps xmm7,TransKernelFrame.SavedXmm7[rsp] movaps xmm8,TransKernelFrame.SavedXmm8[rsp] movaps xmm9,TransKernelFrame.SavedXmm9[rsp] movaps xmm10,TransKernelFrame.SavedXmm10[rsp] movaps xmm11,TransKernelFrame.SavedXmm11[rsp] movaps xmm12,TransKernelFrame.SavedXmm12[rsp] movaps xmm13,TransKernelFrame.SavedXmm13[rsp] movaps xmm14,TransKernelFrame.SavedXmm14[rsp] movaps xmm15,TransKernelFrame.SavedXmm15[rsp] add rsp,(TransKernelFrame.ReturnAddress) BEGIN_EPILOGUE ret NESTED_END MlasComputeExpF32KernelFma3, _TEXT ;++ ; ; Routine Description: ; ; This routine implements a vectorized kernel for the sum of exponential ; functions. ; ; Arguments: ; ; Input (rcx) - Supplies the input buffer. ; ; Output (rdx) - Optionally supplies the output buffer. When used for Softmax, ; the output buffer is used to store the intermediate exp() results. When ; used for LogSoftmax, the intermediate exp() results are not required. ; ; N (r8) - Supplies the number of elements to process. ; ; NegativeMaximum (r9) - Supplies the address of the negative maximum value ; that is added to each element before computing the exponential function. ; ; Return Value: ; ; Returns the sum of the exponential functions. ; ;-- NESTED_ENTRY MlasComputeSumExpF32KernelFma3, _TEXT alloc_stack (TransKernelFrame.ReturnAddress) save_xmm128 xmm6,TransKernelFrame.SavedXmm6 save_xmm128 xmm7,TransKernelFrame.SavedXmm7 save_xmm128 xmm8,TransKernelFrame.SavedXmm8 save_xmm128 xmm9,TransKernelFrame.SavedXmm9 save_xmm128 xmm10,TransKernelFrame.SavedXmm10 save_xmm128 xmm11,TransKernelFrame.SavedXmm11 save_xmm128 xmm12,TransKernelFrame.SavedXmm12 save_xmm128 xmm13,TransKernelFrame.SavedXmm13 save_xmm128 xmm14,TransKernelFrame.SavedXmm14 save_xmm128 xmm15,TransKernelFrame.SavedXmm15 END_PROLOGUE lea rax,MlasExpConstants vbroadcastss ymm9,DWORD PTR [r9] ; broadcast negative maximum value vxorps xmm10,xmm10,xmm10 ; clear exp() accumulator sub r8,24 jb ProcessRemainingCount ComputeExpBy24Loop: vbroadcastss ymm11,ExpConstants.LowerRangeSumExp[rax] vbroadcastss ymm2,ExpConstants.Log2Reciprocal[rax] vaddps ymm0,ymm9,YMMWORD PTR [rcx] ; bias by negative maximum value vaddps ymm3,ymm9,YMMWORD PTR [rcx+32] vaddps ymm6,ymm9,YMMWORD PTR [rcx+64] vbroadcastss ymm15,ExpConstants.RoundingBias[rax] vmaxps ymm0,ymm11,ymm0 ; clamp lower bound vmovaps ymm5,ymm2 vmaxps ymm3,ymm11,ymm3 vmovaps ymm8,ymm2 vmaxps ymm6,ymm11,ymm6 vbroadcastss ymm13,ExpConstants.Log2High[rax] vfmadd213ps ymm2,ymm0,ymm15 ; (x / ln2) plus rounding bias vfmadd213ps ymm5,ymm3,ymm15 vfmadd213ps ymm8,ymm6,ymm15 vbroadcastss ymm14,ExpConstants.Log2Low[rax] vsubps ymm1,ymm2,ymm15 ; m = round(x / ln2) vsubps ymm4,ymm5,ymm15 vsubps ymm7,ymm8,ymm15 vfmadd231ps ymm0,ymm1,ymm13 ; range reduce: x -= (m * ln2_high) vfmadd231ps ymm3,ymm4,ymm13 vfmadd231ps ymm6,ymm7,ymm13 vfmadd231ps ymm0,ymm1,ymm14 ; range reduce: x -= (m * ln2_low) vfmadd231ps ymm3,ymm4,ymm14 vfmadd231ps ymm6,ymm7,ymm14 vbroadcastss ymm1,ExpConstants.poly_0[rax] vbroadcastss ymm13,ExpConstants.poly_1[rax] vmovaps ymm4,ymm1 vmovaps ymm7,ymm1 vfmadd213ps ymm1,ymm0,ymm13 ; p = p * x + poly_1 vfmadd213ps ymm4,ymm3,ymm13 vfmadd213ps ymm7,ymm6,ymm13 vbroadcastss ymm14,ExpConstants.poly_2[rax] vpslld ymm2,ymm2,23 ; shift m to exponent field vpslld ymm5,ymm5,23 vpslld ymm8,ymm8,23 vbroadcastss ymm15,ExpConstants.MaximumExponent[rax] vfmadd213ps ymm1,ymm0,ymm14 ; p = p * x + poly_2 vfmadd213ps ymm4,ymm3,ymm14 vfmadd213ps ymm7,ymm6,ymm14 vbroadcastss ymm13,ExpConstants.poly_3[rax] vpaddd ymm2,ymm2,ymm15 ; add exponent bias to scale vpaddd ymm5,ymm5,ymm15 vpaddd ymm8,ymm8,ymm15 vbroadcastss ymm14,ExpConstants.poly_4[rax] vfmadd213ps ymm1,ymm0,ymm13 ; p = p * x + poly_3 vfmadd213ps ymm4,ymm3,ymm13 vfmadd213ps ymm7,ymm6,ymm13 vbroadcastss ymm15,ExpConstants.poly_56[rax] vfmadd213ps ymm1,ymm0,ymm14 ; p = p * x + poly_4 vfmadd213ps ymm4,ymm3,ymm14 vfmadd213ps ymm7,ymm6,ymm14 vfmadd213ps ymm1,ymm0,ymm15 ; p = p * x + poly_5 vfmadd213ps ymm4,ymm3,ymm15 vfmadd213ps ymm7,ymm6,ymm15 vfmadd213ps ymm1,ymm0,ymm15 ; p = p * x + poly_6 vfmadd213ps ymm4,ymm3,ymm15 vfmadd213ps ymm7,ymm6,ymm15 vmulps ymm1,ymm1,ymm2 ; scale p with exponent vmulps ymm4,ymm4,ymm5 vaddps ymm10,ymm10,ymm1 ; accumulate exp() results vmulps ymm7,ymm7,ymm8 vaddps ymm10,ymm10,ymm4 add rcx,24*4 ; advance input by 24 elements vaddps ymm10,ymm10,ymm7 test rdx,rdx jz SkipStoreResultsBy24 vmovups YMMWORD PTR [rdx],ymm1 vmovups YMMWORD PTR [rdx+32],ymm4 vmovups YMMWORD PTR [rdx+64],ymm7 add rdx,24*4 ; advance output by 24 elements SkipStoreResultsBy24: sub r8,24 jae ComputeExpBy24Loop ProcessRemainingCount: add r8,24 ; correct for over-subtract above jz ReduceAccumulator vbroadcastss ymm11,ExpConstants.LowerRangeSumExp[rax] ComputeExpBy8Loop: cmp r8,8 ; remaining count < 8? jb LoadPartialVector vmovups ymm0,YMMWORD PTR [rcx] jmp ProcessSingleVector LoadPartialVector: lea r10,MlasMaskMoveTableAvx+8*4 neg r8 ; carry flag unchanged vmovups ymm3,YMMWORD PTR [r10+r8*4] vmaskmovps ymm0,ymm3,YMMWORD PTR [rcx] vandps ymm9,ymm9,ymm3 ; mask unused maximum value to 0.0 ProcessSingleVector: vbroadcastss ymm2,ExpConstants.Log2Reciprocal[rax] vaddps ymm0,ymm9,ymm0 ; bias by negative maximum value vbroadcastss ymm15,ExpConstants.RoundingBias[rax] vmaxps ymm0,ymm11,ymm0 ; clamp lower bound vbroadcastss ymm13,ExpConstants.Log2High[rax] vfmadd213ps ymm2,ymm0,ymm15 ; (input / ln2) plus rounding bias vbroadcastss ymm14,ExpConstants.Log2Low[rax] vsubps ymm1,ymm2,ymm15 ; round(input / ln2) vfmadd231ps ymm0,ymm1,ymm13 ; range reduce: x -= (m * ln2_high) vfmadd231ps ymm0,ymm1,ymm14 ; range reduce: x -= (m * ln2_low) vbroadcastss ymm1,ExpConstants.poly_0[rax] vbroadcastss ymm13,ExpConstants.poly_1[rax] vfmadd213ps ymm1,ymm0,ymm13 ; p = p * x + poly_1 vbroadcastss ymm14,ExpConstants.poly_2[rax] vpslld ymm2,ymm2,23 ; shift m to exponent field vbroadcastss ymm15,ExpConstants.MaximumExponent[rax] vfmadd213ps ymm1,ymm0,ymm14 ; p = p * x + poly_2 vbroadcastss ymm13,ExpConstants.poly_3[rax] vpaddd ymm2,ymm2,ymm15 ; add exponent bias to scale vbroadcastss ymm14,ExpConstants.poly_4[rax] vfmadd213ps ymm1,ymm0,ymm13 ; p = p * x + poly_3 vbroadcastss ymm15,ExpConstants.poly_56[rax] vfmadd213ps ymm1,ymm0,ymm14 ; p = p * x + poly_4 vfmadd213ps ymm1,ymm0,ymm15 ; p = p * x + poly_5 vfmadd213ps ymm1,ymm0,ymm15 ; p = p * x + poly_6 vmulps ymm1,ymm1,ymm2 jb StorePartialVector ; remaining count < 8? vaddps ymm10,ymm10,ymm1 ; accumulate exp() results test rdx,rdx ; store exp() results? jz SkipStoreResultsBy8 vmovups YMMWORD PTR [rdx],ymm1 add rdx,8*4 ; advance output by 8 elements SkipStoreResultsBy8: add rcx,8*4 ; advance input by 8 elements sub r8,8 jnz ComputeExpBy8Loop jmp ReduceAccumulator StorePartialVector: vandps ymm1,ymm1,ymm3 ; mask unused exp() results to 0.0 vaddps ymm10,ymm10,ymm1 ; accumulate exp() results test rdx,rdx ; store exp() results? jz ReduceAccumulator vmaskmovps YMMWORD PTR [rdx],ymm3,ymm1 ReduceAccumulator: vhaddps ymm10,ymm10,ymm10 vhaddps ymm10,ymm10,ymm10 vextractf128 xmm0,ymm10,1 vaddss xmm0,xmm0,xmm10 vzeroupper movaps xmm6,TransKernelFrame.SavedXmm6[rsp] movaps xmm7,TransKernelFrame.SavedXmm7[rsp] movaps xmm8,TransKernelFrame.SavedXmm8[rsp] movaps xmm9,TransKernelFrame.SavedXmm9[rsp] movaps xmm10,TransKernelFrame.SavedXmm10[rsp] movaps xmm11,TransKernelFrame.SavedXmm11[rsp] movaps xmm12,TransKernelFrame.SavedXmm12[rsp] movaps xmm13,TransKernelFrame.SavedXmm13[rsp] movaps xmm14,TransKernelFrame.SavedXmm14[rsp] movaps xmm15,TransKernelFrame.SavedXmm15[rsp] add rsp,(TransKernelFrame.ReturnAddress) BEGIN_EPILOGUE ret NESTED_END MlasComputeSumExpF32KernelFma3, _TEXT END