text stringlengths 2 1.04M | meta dict |
|---|---|
@implementation UAEC2Region
@synthesize regionName=_regionName, endpoint=_endpoint;
+ (NSString *)XPathPrefix
{
return @"./";
}
+ (NSDictionary *)XMLKeyPathsByPropertyKey
{
// Start with super's key paths (if there are any)
NSMutableDictionary *keyPaths = [[UAEC2Model XMLKeyPathsByPropertyKey] mutableCopy];
[keyPaths addEntriesFromDictionary:
@{
@"regionName": @"ec2:regionName",
@"endpoint": @"ec2:regionEndpoint"
}];
return [keyPaths copy];
}
@end
#pragma clang diagnostic pop | {
"content_hash": "904d33b749ef1f9b51382d65f9b6de49",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 88,
"avg_line_length": 21.2,
"alnum_prop": 0.6886792452830188,
"repo_name": "unsignedapps/ua-aws-sdk-ios",
"id": "db268573ddf857f184f0aad0c3a8eea27621d5ca",
"size": "813",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AWS iOS SDK/EC2/Models/UAEC2Region.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "42359"
},
{
"name": "Objective-C",
"bytes": "4812683"
},
{
"name": "Ruby",
"bytes": "1520"
}
],
"symlink_target": ""
} |
FROM umeice/python
MAINTAINER @bungoume <bungoume@gmail.com>
# Install OpenCV.
RUN \
apt-get update && apt-get upgrade -y && \
pip install numpy && \
apt-get install -y libjpeg-dev libpng12-dev opencl-headers libeigen3-dev cmake && \
git clone https://github.com/Itseez/opencv.git && \
cd opencv && \
git checkout -b v2.4.9 refs/tags/2.4.9 && \
cmake . && \
make && make install
# Define mountable directories.
VOLUME ["/data"]
# Define working directory.
WORKDIR /data
# Define default command.
# CMD ["python"]
# Expose ports.
# - 5000: HTTP
EXPOSE 5000
| {
"content_hash": "cd1f2f6d9afd0f91b2380048ad048117",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 85,
"avg_line_length": 21.48148148148148,
"alnum_prop": 0.6741379310344827,
"repo_name": "umeice/opencv",
"id": "097ecc5b59460224a095d5e96a3ecbd4deea9cb2",
"size": "668",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Dockerfile",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "668"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
>
<channel>
<title>Marketing – Miller Ad Agency</title>
<atom:link href="./index.html" rel="self" type="application/rss+xml" />
<link>./../../../index.html</link>
<description>Your Neighborhood Ad Agency</description>
<lastBuildDate>Sun, 11 Jun 2017 14:47:41 +0000</lastBuildDate>
<language>en-US</language>
<sy:updatePeriod>hourly</sy:updatePeriod>
<sy:updateFrequency>1</sy:updateFrequency>
<generator>https://wordpress.org/?v=4.8</generator>
<item>
<title>Why repetitive advertising forced me to buy premium services.</title>
<link>./../../../about-miller-ad-agency/blog/why-repetitive-advertising-forced-me-to-buy-premium-services/index.html</link>
<comments>./../../../about-miller-ad-agency/blog/why-repetitive-advertising-forced-me-to-buy-premium-services/index.html#respond</comments>
<pubDate>Wed, 30 Nov 2016 16:34:00 +0000</pubDate>
<dc:creator><![CDATA[Jigar Naik]]></dc:creator>
<category><![CDATA[Advertising]]></category>
<category><![CDATA[Blogging]]></category>
<category><![CDATA[Business]]></category>
<category><![CDATA[hulu]]></category>
<category><![CDATA[Marketing]]></category>
<category><![CDATA[premium services]]></category>
<category><![CDATA[streaming]]></category>
<guid isPermaLink="false">./../../../about-miller-ad-agency/blog/why-repetitive-advertising-forced-me-to-buy-premium-services/index.html</guid>
<description><![CDATA[<p>Sometimes the premium services/features pay off like with Spotify, however with Hulu I feel I was annoyed to death into switching to a premium service.</p>
<p>The post <a rel="nofollow" href="./../../../about-miller-ad-agency/blog/why-repetitive-advertising-forced-me-to-buy-premium-services/index.html">Why repetitive advertising forced me to buy premium services.</a> appeared first on <a rel="nofollow" href="./../../../index.html">Miller Ad Agency</a>.</p>
]]></description>
<wfw:commentRss>./../../../about-miller-ad-agency/blog/why-repetitive-advertising-forced-me-to-buy-premium-services/feed/index.html</wfw:commentRss>
<slash:comments>0</slash:comments>
</item>
<item>
<title>Marketers Have Spoken: They Want Higher Quality Leads</title>
<link>./../../../about-miller-ad-agency/blog/marketers-have-spoken-they-want-higher-quality-leads/index.html</link>
<comments>./../../../about-miller-ad-agency/blog/marketers-have-spoken-they-want-higher-quality-leads/index.html#respond</comments>
<pubDate>Mon, 10 Oct 2016 17:08:00 +0000</pubDate>
<dc:creator><![CDATA[Team Miller]]></dc:creator>
<category><![CDATA[Business]]></category>
<category><![CDATA[Marketing]]></category>
<category><![CDATA[Advertising]]></category>
<category><![CDATA[counter]]></category>
<category><![CDATA[leads]]></category>
<guid isPermaLink="false">./../../../about-miller-ad-agency/blog/marketers-have-spoken-they-want-higher-quality-leads/index.html</guid>
<description><![CDATA[<p>Higher quality leads create efficiency in the sales process, bringing together well informed prospects with salespeople eager to make the sale. So why haven't we seen more of these?</p>
<p>The post <a rel="nofollow" href="./../../../about-miller-ad-agency/blog/marketers-have-spoken-they-want-higher-quality-leads/index.html">Marketers Have Spoken: They Want Higher Quality Leads</a> appeared first on <a rel="nofollow" href="./../../../index.html">Miller Ad Agency</a>.</p>
]]></description>
<wfw:commentRss>./../../../about-miller-ad-agency/blog/marketers-have-spoken-they-want-higher-quality-leads/feed/index.html</wfw:commentRss>
<slash:comments>0</slash:comments>
</item>
<item>
<title>Pointless over-promotion is making the blockbuster lackluster</title>
<link>./../../../about-miller-ad-agency/blog/pointless-over-promotion-is-making-the-blockbuster-lackluster/index.html</link>
<comments>./../../../about-miller-ad-agency/blog/pointless-over-promotion-is-making-the-blockbuster-lackluster/index.html#respond</comments>
<pubDate>Fri, 09 Sep 2016 14:03:00 +0000</pubDate>
<dc:creator><![CDATA[Sasha Gelemanovic]]></dc:creator>
<category><![CDATA[Business]]></category>
<category><![CDATA[Marketing]]></category>
<category><![CDATA[blockbuster]]></category>
<category><![CDATA[films]]></category>
<category><![CDATA[movies]]></category>
<category><![CDATA[promotion]]></category>
<guid isPermaLink="false">./../../../about-miller-ad-agency/blog/pointless-over-promotion-is-making-the-blockbuster-lackluster/index.html</guid>
<description><![CDATA[<p>Everyone enjoys a rip-roaring summer blockbuster movie, right? It’s the perfect chance to grab some popcorn, and at least for 90 minutes or so, forget about your day-to-day worries and immerse yourself in fantasy, adventure, and excitement.</p>
<p>The post <a rel="nofollow" href="./../../../about-miller-ad-agency/blog/pointless-over-promotion-is-making-the-blockbuster-lackluster/index.html">Pointless over-promotion is making the blockbuster lackluster</a> appeared first on <a rel="nofollow" href="./../../../index.html">Miller Ad Agency</a>.</p>
]]></description>
<wfw:commentRss>./../../../about-miller-ad-agency/blog/pointless-over-promotion-is-making-the-blockbuster-lackluster/feed/index.html</wfw:commentRss>
<slash:comments>0</slash:comments>
</item>
<item>
<title>The Effects of Celebrity Endorsements</title>
<link>./../../../about-miller-ad-agency/blog/the-effects-of-celebrity-endorsements/index.html</link>
<comments>./../../../about-miller-ad-agency/blog/the-effects-of-celebrity-endorsements/index.html#respond</comments>
<pubDate>Wed, 31 Aug 2016 18:22:00 +0000</pubDate>
<dc:creator><![CDATA[Cheryl Sinclair]]></dc:creator>
<category><![CDATA[Culture]]></category>
<category><![CDATA[celebrities]]></category>
<category><![CDATA[endorsements]]></category>
<category><![CDATA[Marketing]]></category>
<guid isPermaLink="false">./../../../about-miller-ad-agency/blog/the-effects-of-celebrity-endorsements/index.html</guid>
<description><![CDATA[<p>In today’s age, a company must be transparent and relevant to its consumers. To do so, many brands choose to sponsor individuals to represent their brand and what they stand for.</p>
<p>The post <a rel="nofollow" href="./../../../about-miller-ad-agency/blog/the-effects-of-celebrity-endorsements/index.html">The Effects of Celebrity Endorsements</a> appeared first on <a rel="nofollow" href="./../../../index.html">Miller Ad Agency</a>.</p>
]]></description>
<wfw:commentRss>./../../../about-miller-ad-agency/blog/the-effects-of-celebrity-endorsements/feed/index.html</wfw:commentRss>
<slash:comments>0</slash:comments>
</item>
<item>
<title>A Lot of a Little, or a Little of a Lot?</title>
<link>./../../../about-miller-ad-agency/blog/a-lot-of-a-little-or-a-little-of-a-lot/index.html</link>
<comments>./../../../about-miller-ad-agency/blog/a-lot-of-a-little-or-a-little-of-a-lot/index.html#respond</comments>
<pubDate>Thu, 18 Aug 2016 14:21:00 +0000</pubDate>
<dc:creator><![CDATA[Stuart Lang]]></dc:creator>
<category><![CDATA[Business]]></category>
<category><![CDATA[Marketing]]></category>
<category><![CDATA[Advertising]]></category>
<category><![CDATA[customers]]></category>
<category><![CDATA[focus]]></category>
<category><![CDATA[reach]]></category>
<guid isPermaLink="false">./../../../about-miller-ad-agency/blog/a-lot-of-a-little-or-a-little-of-a-lot/index.html</guid>
<description><![CDATA[<p> Should you attempt to reach as many people as the budget allows, knowing those people may only be exposed to the message once, or reach a smaller number of people many times? The answer, as with most things in life, is “it depends”.</p>
<p>The post <a rel="nofollow" href="./../../../about-miller-ad-agency/blog/a-lot-of-a-little-or-a-little-of-a-lot/index.html">A Lot of a Little, or a Little of a Lot?</a> appeared first on <a rel="nofollow" href="./../../../index.html">Miller Ad Agency</a>.</p>
]]></description>
<wfw:commentRss>./../../../about-miller-ad-agency/blog/a-lot-of-a-little-or-a-little-of-a-lot/feed/index.html</wfw:commentRss>
<slash:comments>0</slash:comments>
</item>
<item>
<title>Decades Later, Frequency Still A Challenge For Marketers</title>
<link>./../../../about-miller-ad-agency/blog/decades-later-frequency-still-a-challenge-for-marketers/index.html</link>
<comments>./../../../about-miller-ad-agency/blog/decades-later-frequency-still-a-challenge-for-marketers/index.html#respond</comments>
<pubDate>Fri, 08 Jul 2016 18:35:00 +0000</pubDate>
<dc:creator><![CDATA[Team Miller]]></dc:creator>
<category><![CDATA[Business]]></category>
<category><![CDATA[Culture]]></category>
<category><![CDATA[Marketing]]></category>
<category><![CDATA[Behavior]]></category>
<category><![CDATA[business]]></category>
<category><![CDATA[Consumers]]></category>
<category><![CDATA[entertainment]]></category>
<category><![CDATA[time]]></category>
<guid isPermaLink="false">./../../../about-miller-ad-agency/blog/decades-later-frequency-still-a-challenge-for-marketers/index.html</guid>
<description><![CDATA[<p>While much has changed in advertising and media since this concept emerged in the 1930s from the entertainment industry, it’s widely agreed that multiple messages are required to change a consumer’s behavior.</p>
<p>The post <a rel="nofollow" href="./../../../about-miller-ad-agency/blog/decades-later-frequency-still-a-challenge-for-marketers/index.html">Decades Later, Frequency Still A Challenge For Marketers</a> appeared first on <a rel="nofollow" href="./../../../index.html">Miller Ad Agency</a>.</p>
]]></description>
<wfw:commentRss>./../../../about-miller-ad-agency/blog/decades-later-frequency-still-a-challenge-for-marketers/feed/index.html</wfw:commentRss>
<slash:comments>0</slash:comments>
</item>
<item>
<title>Millennials Want More Than Ads</title>
<link>./../../../about-miller-ad-agency/blog/millennials-want-more-than-ads/index.html</link>
<comments>./../../../about-miller-ad-agency/blog/millennials-want-more-than-ads/index.html#respond</comments>
<pubDate>Wed, 01 Jun 2016 15:53:00 +0000</pubDate>
<dc:creator><![CDATA[Seth Wilson]]></dc:creator>
<category><![CDATA[Blogging]]></category>
<category><![CDATA[Lifestyle]]></category>
<category><![CDATA[Marketing]]></category>
<category><![CDATA[ads]]></category>
<category><![CDATA[Advertising]]></category>
<category><![CDATA[Brands]]></category>
<category><![CDATA[millennials]]></category>
<guid isPermaLink="false">./../../../about-miller-ad-agency/blog/millennials-want-more-than-ads/index.html</guid>
<description><![CDATA[<p>In previous generations, the logic of marketing was that more the number of advertisements you throw at youngsters, the sooner you could hook them to your brand. During those times, this approach actually made some sense, but now, reaching out to the younger generation takes a lot more than traditional ads.</p>
<p>The post <a rel="nofollow" href="./../../../about-miller-ad-agency/blog/millennials-want-more-than-ads/index.html">Millennials Want More Than Ads</a> appeared first on <a rel="nofollow" href="./../../../index.html">Miller Ad Agency</a>.</p>
]]></description>
<wfw:commentRss>./../../../about-miller-ad-agency/blog/millennials-want-more-than-ads/feed/index.html</wfw:commentRss>
<slash:comments>0</slash:comments>
</item>
<item>
<title>Find your Voice, Find the Future</title>
<link>./../../../about-miller-ad-agency/blog/find-your-voice-find-the-future/index.html</link>
<comments>./../../../about-miller-ad-agency/blog/find-your-voice-find-the-future/index.html#respond</comments>
<pubDate>Fri, 20 May 2016 18:41:00 +0000</pubDate>
<dc:creator><![CDATA[Jimmy Lee]]></dc:creator>
<category><![CDATA[Automotive Advertising]]></category>
<category><![CDATA[Marketing]]></category>
<category><![CDATA[commercials]]></category>
<category><![CDATA[customer service]]></category>
<guid isPermaLink="false">./../../../about-miller-ad-agency/blog/find-your-voice-find-the-future/index.html</guid>
<description><![CDATA[<p>There’s more to auto dealer advertising than screaming commercials.</p>
<p>The post <a rel="nofollow" href="./../../../about-miller-ad-agency/blog/find-your-voice-find-the-future/index.html">Find your Voice, Find the Future</a> appeared first on <a rel="nofollow" href="./../../../index.html">Miller Ad Agency</a>.</p>
]]></description>
<wfw:commentRss>./../../../about-miller-ad-agency/blog/find-your-voice-find-the-future/feed/index.html</wfw:commentRss>
<slash:comments>0</slash:comments>
</item>
<item>
<title>Got Lemons</title>
<link>./../../../about-miller-ad-agency/blog/got-lemons/index.html</link>
<comments>./../../../about-miller-ad-agency/blog/got-lemons/index.html#respond</comments>
<pubDate>Fri, 06 May 2016 15:23:00 +0000</pubDate>
<dc:creator><![CDATA[Jenni Halamuda]]></dc:creator>
<category><![CDATA[Business]]></category>
<category><![CDATA[beyonce]]></category>
<category><![CDATA[lemon]]></category>
<category><![CDATA[Marketing]]></category>
<category><![CDATA[PR]]></category>
<guid isPermaLink="false">./../../../about-miller-ad-agency/blog/got-lemons/index.html</guid>
<description><![CDATA[<p>This title should bring a few things to mind like either a bad new car, a milk ad campaign, or of course Lemonade. The difference is now Lemonade has an entirely new meaning.</p>
<p>The post <a rel="nofollow" href="./../../../about-miller-ad-agency/blog/got-lemons/index.html">Got Lemons</a> appeared first on <a rel="nofollow" href="./../../../index.html">Miller Ad Agency</a>.</p>
]]></description>
<wfw:commentRss>./../../../about-miller-ad-agency/blog/got-lemons/feed/index.html</wfw:commentRss>
<slash:comments>0</slash:comments>
</item>
<item>
<title>Winning the Branding Battle</title>
<link>./../../../about-miller-ad-agency/blog/winning-the-branding-battle/index.html</link>
<comments>./../../../about-miller-ad-agency/blog/winning-the-branding-battle/index.html#respond</comments>
<pubDate>Thu, 21 Apr 2016 14:18:00 +0000</pubDate>
<dc:creator><![CDATA[Cheryl Sinclair]]></dc:creator>
<category><![CDATA[Advertising]]></category>
<category><![CDATA[Culture]]></category>
<category><![CDATA[Marketing]]></category>
<category><![CDATA[Brands]]></category>
<category><![CDATA[china]]></category>
<category><![CDATA[coke]]></category>
<category><![CDATA[ikea]]></category>
<category><![CDATA[pepsi]]></category>
<category><![CDATA[usa]]></category>
<guid isPermaLink="false">./../../../about-miller-ad-agency/blog/winning-the-branding-battle/index.html</guid>
<description><![CDATA[<p>The United States is, by far, the largest advertising market in the world. If you are advertising within the United States then you are fighting a seemingly insurmountable battle on the world’s largest advertising stage. So, the question is: What are the key ingredients in the recipe for a successful branding strategy?</p>
<p>The post <a rel="nofollow" href="./../../../about-miller-ad-agency/blog/winning-the-branding-battle/index.html">Winning the Branding Battle</a> appeared first on <a rel="nofollow" href="./../../../index.html">Miller Ad Agency</a>.</p>
]]></description>
<wfw:commentRss>./../../../about-miller-ad-agency/blog/winning-the-branding-battle/feed/index.html</wfw:commentRss>
<slash:comments>0</slash:comments>
</item>
</channel>
</rss>
| {
"content_hash": "a73f48ecda4ec3594d57ad7b6e107d07",
"timestamp": "",
"source": "github",
"line_count": 222,
"max_line_length": 351,
"avg_line_length": 71.33783783783784,
"alnum_prop": 0.7051840626381259,
"repo_name": "williampansky/pants",
"id": "67cb1f1335dd75db58d80530c03f6956f1876010",
"size": "15854",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/projects/miller.agency/demo/tag/marketing/feed/index.xml",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "658862"
},
{
"name": "HTML",
"bytes": "19377591"
},
{
"name": "Hack",
"bytes": "2495"
},
{
"name": "JavaScript",
"bytes": "317984"
}
],
"symlink_target": ""
} |
body {
margin: 0;
padding: 0;
font-family: "Segoe UI", Segoe, Tahoma, Arial, Verdana, sans-serif;
overflow: hidden;
}
| {
"content_hash": "de7b9e58f40dfa646964ba844c44c702",
"timestamp": "",
"source": "github",
"line_count": 6,
"max_line_length": 69,
"avg_line_length": 21,
"alnum_prop": 0.6507936507936508,
"repo_name": "blinksocks/blinksocks-desktop",
"id": "f0601631b4eb5485cf5f476aa254a2bdda0426f6",
"size": "126",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/index.css",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "6304"
},
{
"name": "HTML",
"bytes": "188"
},
{
"name": "JavaScript",
"bytes": "127042"
},
{
"name": "Shell",
"bytes": "1776"
}
],
"symlink_target": ""
} |
<!--
# @markup markdown
# @title Getting Started
# @author SaltStack Inc.
-->
# Getting Started #
This tutorial is going to be using the following repository: <https://github.com/gtmanfred/wordpress-formula>
## Installation ##
KitchenSalt is a ruby gem, so ruby will be required. The easiest ways to get an up to date ruby version is to use [rbenv](https://github.com/rbenv/rbenv) or [rvm](https://rvm.io/). Luckily, a script installer is provided here.
### Installing Ruby ###
#### rbenv ####
For Mac, there is an `rbenv` package in homebrew.
brew install rbenv
For Linux, there is an [installer script](https://github.com/rbenv/rbenv-installer/tree/master/bin/rbenv-installer).
The following instructions will allow for a global install of rbenv.
1. Install the dependencies for building ruby, referencing the `ruby-build` [Suggested build environment](https://github.com/rbenv/ruby-build/wiki#suggested-build-environment) documentation.
1. clone git repos and setup path
- [Basic GitHub Checkout/setup of rbenv](https://github.com/rbenv/rbenv#basic-github-checkout)
- [Installation of `ruby-build`](https://github.com/rbenv/ruby-build#installation)
1. Install ruby and set `2.6.3` as the version to use by default. Salt uses this version of Ruby in CI pipelines, which is why it is preferred here, but newer versions of ruby may work without issue.
rbenv install 2.6.3
rbenv local 2.6.3
# OPTIONAL: Set global default version
# rbenv global 2.6.3
If gemsets are needed, the [rbenv-gemset](https://github.com/jf/rbenv-gemset) plugin can be added to the gemsets repository.
#### rvm ####
rvm is another method of managing ruby version.
1. Import the gpg key from <https://rvm.io>
gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
1. Run the installer script
\curl -sSL https://get.rvm.io | bash -s stable
1. Install and use ruby
rvm use --install --create ruby@salt
and rvm will manage installing all of the required packages for managing ruby versions via rvm. The `@salt` portion creates a specific gemset (`rvm help gemset`).
### Installing KitchenSalt ###
There are a few things that are needed for running kitchen-salt
1. The bundler gem should be installed
gem install bundler
This will make the `bundle` command available. Bundler only lets uses the gems listed in the `Gemfile` in the directory tree where commands are run.
1. Create a gemfile. Now a [kitchen driver](https://docs.chef.io/config_yml_kitchen.html#drivers) will need to be choosen. This tutorial is going to use `kitchen-docker`.
# Gemfile
source 'https://rubygems.org'
gem 'kitchen-salt'
gem 'kitchen-docker'
gem 'kitchen-sync'
`kitchen-sync` is not required for this, but it does copy files to the container faster.
1. Run bundler to install gems.
bundle install
This will install all the gems from the Gemfile, and make only those gems available when commands are run with `bundle exec <command>`
For more complicated setups where different methods of running Kitchen are required, groups can be assigned in the Gemfile.
# Gemfile
source 'https://rubygems.org'
gem 'test-kitchen', :git => 'https://github.com/gtmanfred/test-kitchen.git'
gem 'kitchen-salt', :git => 'https://github.com/saltstack/kitchen-salt.git'
gem 'kitchen-sync'
gem 'git'
group :docker do
gem 'kitchen-docker', :git => 'https://github.com/test-kitchen/kitchen-docker.git'
end
group :windows do
gem 'vagrant-wrapper'
gem 'kitchen-vagrant'
gem 'winrm', '~>2.0'
gem 'winrm-fs', :git => 'https://github.com/gtmanfred/winrm-fs.git'
end
To specify only installing certain groups, use the `--with` and `--without` arguements
bundle install --with windows --without docker
## Setup ##
Now the `.kitchen.yml` file needs to be setup for running tests. The following sections should be copied into the {file:docs/example-kitchen.yml.md} file in the root of the directory for the `wordpress-formula`
### driver ###
The driver needs to be setup to build the test instance correctly.
driver:
name: docker
use_sudo: false
privileged: true
forward:
- 80
The example will be using docker. If `sudo` is required to run the docker command to build containers, then `use_sudo` should be set to True. The `privileged` options enables the container to run systemd as the Exec Command for the docker container. And lastly, port 80 will be forwarded to the host so that the tests can check that the wordpress website is running.
If different platforms or different suites need to have different driver configurations, they can be set in the `driver_config`.
### transport ###
Here is where the `kitchen-sync` transport is specified.
transport:
name: sftp
If windows is being tested, `winrm-transport` will probably be required for the `winrm` transport.
### platforms ###
This section is where the distributions and operating systems that will be tested are specified. Because different distributions put the systemd binary in different places, the `run_command` is specified here in the `driver_config`.
platforms:
- name: centos
driver_config:
run_command: /usr/lib/systemd/systemd
### suites ###
This is the section where the different test suites are specified. Common uses will be to test different paths through the formulas or different versions of salt with the same formula.
suites:
- name: nitrogen
provisioner:
salt_bootstrap_options: -X -p git stable 2017.7
- name: carbon
provisioner:
salt_bootstrap_options: -X -p git stable 2016.11
Because different versions of salt are being tested, different `salt_bootstrap_options` are used.
### verifier ###
The verifier is where the testing to check if the states run was successfull.
verifier:
name: shell
remote_exec: false
command: pytest -v tests/integration/
In the `wordpress-formula`, pytest is used to make http calls to the server to check that the wordpress website is up, and configured the way that it was specified. There are several other things that could be used here:
- [testinfra](https://pypi.python.org/pypi/testinfra)
- [busser](https://github.com/test-kitchen/busser)
- [InSpec](https://www.chef.io/inspec/)
- [Serverspec](http://serverspec.org/)
And then basically any other unit test framework that could be run from the shell could be used to replace the one above.
### provisioner ###
This is what kitchen-salt actually provides.
provisioner:
name: salt_solo
salt_install: bootstrap
is_file_root: true
require_chef: false
salt_copy_filter:
- .git
dependencies:
- name: apache
repo: git
source: https://github.com/saltstack-formulas/apache-formula.git
- name: mysql
repo: git
source: https://github.com/saltstack-formulas/mysql-formula.git
- name: php
repo: git
source: https://github.com/saltstack-formulas/php-formula.git
state_top:
base:
"*":
- wordpress
pillars:
top.sls:
base:
"*":
- wordpress
pillars_from_files:
wordpress.sls: pillar.example
In this, the salt provisioner is specified by the name `salt_solo`. The [salt-bootstrap](https://github.com/saltstack/salt-bootstrap) script is used to install salt. The option `is_file_root` specifies that the top level directory of this git repository should be copied to the salt `file_root` in the test instance. Since ruby is not being used to test the instance in the verifier step, `require_chef` is set to `False`.
Next, the `dependencies` are different repositories that the `wordpress-formula` depends on to be available to work correctly. The `state_top` specifies the top file that will be applied. Like the `state_top`, the `pillars` and `pillars_from_files` directives specifies different files to drop into the salt `pillar_roots` on the test instance. If there are multiple groups of state or pillar files that can be tested independently, it would probably be useful to specify the extra ones under the different suites.
## Run Tests ##
Now that TestKitchen is all setup, the `wordpress-formula` can be tested and verified.
First, kitchen commands that will be useful.
- list: show the current state of each configured environment
- create: create the test environment with ssh or winrm.
- converge: run the provision command, in this case, salt_solo and the specified states
- verify: run the verifier.
- login: login to created environment
- destroy: remove the created environment
- test: run create, converge, verify, and then destroy if it all succeeds
And since this formula is being tested by [pytest](https://docs.pytest.org/en/latest/), it will need to be installed.
pip install -r requirements
The above command will install requests and testinfra, which will also pull in the pytest dependency which is required by testinfra.
Now the following commands can finally be run.
bundle exec kitchen list
bundle exec kitchen create
bundle exec kitchen converge
bundle exec kitchen verify
bundle exec kitchen destroy
Or to simplify it
bundle exec kitchen test
With either of these, test-kitchen will do the following
1. Create the instance using the method specified by the `driver`.
1. Install salt and run the specified states defined in the provisioner (This step is called converging).
1. Run the test suite verifier.
1. Destroy the instance if everything passed.
If `kitchen test` was run, then the `kitchen list` command will show all the instances and what the result of their last command was.
## Run test interactivaly ##
If your `converge` or `verify` step is failing, by default `kitchen` will keep your VM running, so you can login using
ssh and debug things from there. To run the `state.apply` that converge is doing, run the following :
kitchen login
sudo salt-call --config-dir=/tmp/kitchen/etc/salt/ --log-level=debug state.apply
If you are using the `minion_id` argument run :
kitchen login
sudo salt-call --config-dir=/tmp/kitchen/etc/salt/ --log-level=debug --id=salt-minion-id state.apply
## Closing ##
This instance is now tested. For more information about `kitchen-salt` and `test-kitchen` in general please see the following links:
- {file:docs/provisioner_options.md}
- [Kitchen Salt](https://github.com/saltstack/kitchen-salt)
- [Test Kitchen Docs](https://docs.chef.io/kitchen.html)
- [KitchenCI](http://kitchen.ci/)
- [Test Kitchen Github](https://github.com/test-kitchen)
| {
"content_hash": "77cb9039d967d08ae1d11e2863cbe077",
"timestamp": "",
"source": "github",
"line_count": 282,
"max_line_length": 515,
"avg_line_length": 38.59574468085106,
"alnum_prop": 0.7188533627342889,
"repo_name": "simonmcc/kitchen-salt",
"id": "1a40e4a5755039aa6696b8433483b812452e9472",
"size": "10884",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "docs/gettingstarted.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2792"
},
{
"name": "Ruby",
"bytes": "31081"
},
{
"name": "Shell",
"bytes": "3152"
}
],
"symlink_target": ""
} |
static TString arrayBrackets(int index)
{
TStringStream stream;
stream << "[" << index << "]";
return stream.str();
}
// Returns the data type for an attribute or uniform.
static ShDataType getVariableDataType(const TType& type)
{
switch (type.getBasicType()) {
case EbtFloat:
if (type.isMatrix()) {
switch (type.getNominalSize()) {
case 2: return SH_FLOAT_MAT2;
case 3: return SH_FLOAT_MAT3;
case 4: return SH_FLOAT_MAT4;
default: UNREACHABLE();
}
} else if (type.isVector()) {
switch (type.getNominalSize()) {
case 2: return SH_FLOAT_VEC2;
case 3: return SH_FLOAT_VEC3;
case 4: return SH_FLOAT_VEC4;
default: UNREACHABLE();
}
} else {
return SH_FLOAT;
}
case EbtInt:
if (type.isMatrix()) {
UNREACHABLE();
} else if (type.isVector()) {
switch (type.getNominalSize()) {
case 2: return SH_INT_VEC2;
case 3: return SH_INT_VEC3;
case 4: return SH_INT_VEC4;
default: UNREACHABLE();
}
} else {
return SH_INT;
}
case EbtBool:
if (type.isMatrix()) {
UNREACHABLE();
} else if (type.isVector()) {
switch (type.getNominalSize()) {
case 2: return SH_BOOL_VEC2;
case 3: return SH_BOOL_VEC3;
case 4: return SH_BOOL_VEC4;
default: UNREACHABLE();
}
} else {
return SH_BOOL;
}
case EbtSampler2D: return SH_SAMPLER_2D;
case EbtSamplerCube: return SH_SAMPLER_CUBE;
default: UNREACHABLE();
}
return SH_NONE;
}
static void getBuiltInVariableInfo(const TType& type,
const TString& name,
TVariableInfoList& infoList);
static void getUserDefinedVariableInfo(const TType& type,
const TString& name,
TVariableInfoList& infoList);
// Returns info for an attribute or uniform.
static void getVariableInfo(const TType& type,
const TString& name,
TVariableInfoList& infoList)
{
if (type.getBasicType() == EbtStruct) {
if (type.isArray()) {
for (int i = 0; i < type.getArraySize(); ++i) {
TString lname = name + arrayBrackets(i);
getUserDefinedVariableInfo(type, lname, infoList);
}
} else {
getUserDefinedVariableInfo(type, name, infoList);
}
} else {
getBuiltInVariableInfo(type, name, infoList);
}
}
void getBuiltInVariableInfo(const TType& type,
const TString& name,
TVariableInfoList& infoList)
{
ASSERT(type.getBasicType() != EbtStruct);
TVariableInfo varInfo;
if (type.isArray()) {
varInfo.name = (name + "[0]").c_str();
varInfo.size = type.getArraySize();
} else {
varInfo.name = name.c_str();
varInfo.size = 1;
}
varInfo.type = getVariableDataType(type);
infoList.push_back(varInfo);
}
void getUserDefinedVariableInfo(const TType& type,
const TString& name,
TVariableInfoList& infoList)
{
ASSERT(type.getBasicType() == EbtStruct);
TString lname = name + ".";
const TTypeList* structure = type.getStruct();
for (size_t i = 0; i < structure->size(); ++i) {
const TType* fieldType = (*structure)[i].type;
getVariableInfo(*fieldType,
lname + fieldType->getFieldName(),
infoList);
}
}
CollectAttribsUniforms::CollectAttribsUniforms(TVariableInfoList& attribs,
TVariableInfoList& uniforms)
: mAttribs(attribs),
mUniforms(uniforms)
{
}
// We are only interested in attribute and uniform variable declaration.
void CollectAttribsUniforms::visitSymbol(TIntermSymbol*)
{
}
void CollectAttribsUniforms::visitConstantUnion(TIntermConstantUnion*)
{
}
bool CollectAttribsUniforms::visitBinary(Visit, TIntermBinary*)
{
return false;
}
bool CollectAttribsUniforms::visitUnary(Visit, TIntermUnary*)
{
return false;
}
bool CollectAttribsUniforms::visitSelection(Visit, TIntermSelection*)
{
return false;
}
bool CollectAttribsUniforms::visitAggregate(Visit, TIntermAggregate* node)
{
bool visitChildren = false;
switch (node->getOp())
{
case EOpSequence:
// We need to visit sequence children to get to variable declarations.
visitChildren = true;
break;
case EOpDeclaration: {
const TIntermSequence& sequence = node->getSequence();
TQualifier qualifier = sequence.front()->getAsTyped()->getQualifier();
if (qualifier == EvqAttribute || qualifier == EvqUniform)
{
TVariableInfoList& infoList = qualifier == EvqAttribute ?
mAttribs : mUniforms;
for (TIntermSequence::const_iterator i = sequence.begin();
i != sequence.end(); ++i)
{
const TIntermSymbol* variable = (*i)->getAsSymbolNode();
// The only case in which the sequence will not contain a
// TIntermSymbol node is initialization. It will contain a
// TInterBinary node in that case. Since attributes and unifroms
// cannot be initialized in a shader, we must have only
// TIntermSymbol nodes in the sequence.
ASSERT(variable != NULL);
getVariableInfo(variable->getType(), variable->getSymbol(),
infoList);
}
}
break;
}
default: break;
}
return visitChildren;
}
bool CollectAttribsUniforms::visitLoop(Visit, TIntermLoop*)
{
return false;
}
bool CollectAttribsUniforms::visitBranch(Visit, TIntermBranch*)
{
return false;
}
| {
"content_hash": "c81572073035b23d2bcb9cde9d0a1c09",
"timestamp": "",
"source": "github",
"line_count": 202,
"max_line_length": 80,
"avg_line_length": 31.094059405940595,
"alnum_prop": 0.5521413787613437,
"repo_name": "stephaneAG/PengPod700",
"id": "ad2e08f303d0d48eb0fdf5fb1e5fcf39ef20ddfa",
"size": "6503",
"binary": false,
"copies": "18",
"ref": "refs/heads/master",
"path": "QtEsrc/backup_qt/qt-everywhere-opensource-src-4.8.5/src/3rdparty/webkit/Source/ThirdParty/ANGLE/src/compiler/VariableInfo.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "167426"
},
{
"name": "Batchfile",
"bytes": "25368"
},
{
"name": "C",
"bytes": "3755463"
},
{
"name": "C#",
"bytes": "9282"
},
{
"name": "C++",
"bytes": "177871700"
},
{
"name": "CSS",
"bytes": "600936"
},
{
"name": "GAP",
"bytes": "758872"
},
{
"name": "GLSL",
"bytes": "32226"
},
{
"name": "Groff",
"bytes": "106542"
},
{
"name": "HTML",
"bytes": "273585110"
},
{
"name": "IDL",
"bytes": "1194"
},
{
"name": "JavaScript",
"bytes": "435912"
},
{
"name": "Makefile",
"bytes": "289373"
},
{
"name": "Objective-C",
"bytes": "1898658"
},
{
"name": "Objective-C++",
"bytes": "3222428"
},
{
"name": "PHP",
"bytes": "6074"
},
{
"name": "Perl",
"bytes": "291672"
},
{
"name": "Prolog",
"bytes": "102468"
},
{
"name": "Python",
"bytes": "22546"
},
{
"name": "QML",
"bytes": "3580408"
},
{
"name": "QMake",
"bytes": "2191574"
},
{
"name": "Scilab",
"bytes": "2390"
},
{
"name": "Shell",
"bytes": "116533"
},
{
"name": "TypeScript",
"bytes": "42452"
},
{
"name": "Visual Basic",
"bytes": "8370"
},
{
"name": "XQuery",
"bytes": "25094"
},
{
"name": "XSLT",
"bytes": "252382"
}
],
"symlink_target": ""
} |
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <unistd.h>
#include <sys/queue.h>
#include <string.h>
#include <rte_common.h>
#include <rte_memory.h>
#include <rte_per_lcore.h>
#include <rte_launch.h>
#include <rte_pflock.h>
#include <rte_eal.h>
#include <rte_lcore.h>
#include <rte_cycles.h>
#include "test.h"
/*
* phase-fair lock test
* ====================
* Provides UT for phase-fair lock API.
* Main concern is on functional testing, but also provides some
* performance measurements.
* Obviously for proper testing need to be executed with more than one lcore.
*/
static rte_pflock_t sl;
static rte_pflock_t sl_tab[RTE_MAX_LCORE];
static uint32_t synchro;
static int
test_pflock_per_core(__rte_unused void *arg)
{
rte_pflock_write_lock(&sl);
printf("Global write lock taken on core %u\n", rte_lcore_id());
rte_pflock_write_unlock(&sl);
rte_pflock_write_lock(&sl_tab[rte_lcore_id()]);
printf("Hello from core %u !\n", rte_lcore_id());
rte_pflock_write_unlock(&sl_tab[rte_lcore_id()]);
rte_pflock_read_lock(&sl);
printf("Global read lock taken on core %u\n", rte_lcore_id());
rte_delay_ms(100);
printf("Release global read lock on core %u\n", rte_lcore_id());
rte_pflock_read_unlock(&sl);
return 0;
}
static rte_pflock_t lk = RTE_PFLOCK_INITIALIZER;
static uint64_t time_count[RTE_MAX_LCORE] = {0};
#define MAX_LOOP 10000
static int
load_loop_fn(void *arg)
{
uint64_t time_diff = 0, begin;
uint64_t hz = rte_get_timer_hz();
uint64_t lcount = 0;
const int use_lock = *(int *)arg;
const unsigned int lcore = rte_lcore_id();
/* wait synchro for workers */
if (lcore != rte_get_main_lcore())
rte_wait_until_equal_32(&synchro, 1, __ATOMIC_RELAXED);
begin = rte_rdtsc_precise();
while (lcount < MAX_LOOP) {
if (use_lock)
rte_pflock_write_lock(&lk);
lcount++;
if (use_lock)
rte_pflock_write_unlock(&lk);
if (use_lock) {
rte_pflock_read_lock(&lk);
rte_pflock_read_unlock(&lk);
}
}
time_diff = rte_rdtsc_precise() - begin;
time_count[lcore] = time_diff * 1000000 / hz;
return 0;
}
static int
test_pflock_perf(void)
{
unsigned int i;
int lock = 0;
uint64_t total = 0;
const unsigned int lcore = rte_lcore_id();
printf("\nTest with no lock on single core...\n");
__atomic_store_n(&synchro, 1, __ATOMIC_RELAXED);
load_loop_fn(&lock);
printf("Core [%u] Cost Time = %"PRIu64" us\n",
lcore, time_count[lcore]);
memset(time_count, 0, sizeof(time_count));
printf("\nTest with phase-fair lock on single core...\n");
lock = 1;
__atomic_store_n(&synchro, 1, __ATOMIC_RELAXED);
load_loop_fn(&lock);
printf("Core [%u] Cost Time = %"PRIu64" us\n",
lcore, time_count[lcore]);
memset(time_count, 0, sizeof(time_count));
printf("\nPhase-fair test on %u cores...\n", rte_lcore_count());
/* clear synchro and start workers */
__atomic_store_n(&synchro, 0, __ATOMIC_RELAXED);
if (rte_eal_mp_remote_launch(load_loop_fn, &lock, SKIP_MAIN) < 0)
return -1;
/* start synchro and launch test on main */
__atomic_store_n(&synchro, 1, __ATOMIC_RELAXED);
load_loop_fn(&lock);
rte_eal_mp_wait_lcore();
RTE_LCORE_FOREACH(i) {
printf("Core [%u] cost time = %"PRIu64" us\n",
i, time_count[i]);
total += time_count[i];
}
printf("Total cost time = %"PRIu64" us\n", total);
memset(time_count, 0, sizeof(time_count));
return 0;
}
/*
* - There is a global pflock and a table of pflocks (one per lcore).
*
* - The test function takes all of these locks and launches the
* ``test_pflock_per_core()`` function on each core (except the main).
*
* - The function takes the global write lock, display something,
* then releases the global lock.
* - Then, it takes the per-lcore write lock, display something, and
* releases the per-core lock.
* - Finally, a read lock is taken during 100 ms, then released.
*
* - The main function unlocks the per-lcore locks sequentially and
* waits between each lock. This triggers the display of a message
* for each core, in the correct order.
*
* Then, it tries to take the global write lock and display the last
* message. The autotest script checks that the message order is correct.
*/
static int
test_pflock(void)
{
int i;
rte_pflock_init(&sl);
for (i = 0; i < RTE_MAX_LCORE; i++)
rte_pflock_init(&sl_tab[i]);
rte_pflock_write_lock(&sl);
RTE_LCORE_FOREACH_WORKER(i) {
rte_pflock_write_lock(&sl_tab[i]);
rte_eal_remote_launch(test_pflock_per_core, NULL, i);
}
rte_pflock_write_unlock(&sl);
RTE_LCORE_FOREACH_WORKER(i) {
rte_pflock_write_unlock(&sl_tab[i]);
rte_delay_ms(100);
}
rte_pflock_write_lock(&sl);
/* this message should be the last message of test */
printf("Global write lock taken on main core %u\n", rte_lcore_id());
rte_pflock_write_unlock(&sl);
rte_eal_mp_wait_lcore();
if (test_pflock_perf() < 0)
return -1;
return 0;
}
REGISTER_TEST_COMMAND(pflock_autotest, test_pflock);
| {
"content_hash": "5251499a7bd77f5455e9abe009e0e780",
"timestamp": "",
"source": "github",
"line_count": 194,
"max_line_length": 77,
"avg_line_length": 25.309278350515463,
"alnum_prop": 0.665376782077393,
"repo_name": "john-mcnamara-intel/dpdk",
"id": "38da6bce27cd2a537adbfe136ffddbdf40474923",
"size": "4997",
"binary": false,
"copies": "6",
"ref": "refs/heads/main",
"path": "app/test/test_pflock.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Awk",
"bytes": "1623"
},
{
"name": "C",
"bytes": "39269990"
},
{
"name": "C++",
"bytes": "860345"
},
{
"name": "Makefile",
"bytes": "342834"
},
{
"name": "Meson",
"bytes": "144875"
},
{
"name": "Objective-C",
"bytes": "224248"
},
{
"name": "Python",
"bytes": "115929"
},
{
"name": "Shell",
"bytes": "77250"
},
{
"name": "SmPL",
"bytes": "2074"
}
],
"symlink_target": ""
} |
namespace blink {
void NavigatorContentUtilsClientMock::registerProtocolHandler(const String& scheme, const KURL& baseURL,
const KURL& url, const String& title)
{
ProtocolInfo info;
info.scheme = scheme;
info.baseURL = baseURL;
info.url = url;
info.title = title;
m_protocolMap.set(scheme, info);
}
NavigatorContentUtilsClient::CustomHandlersState NavigatorContentUtilsClientMock::isProtocolHandlerRegistered(const String& scheme,
const KURL& baseURL, const KURL& url)
{
// "declined" state is checked by NavigatorContentUtils::isProtocolHandlerRegistered() before calling this function.
if (m_protocolMap.contains(scheme))
return NavigatorContentUtilsClient::CustomHandlersRegistered;
return NavigatorContentUtilsClient::CustomHandlersNew;
}
void NavigatorContentUtilsClientMock::unregisterProtocolHandler(const String& scheme, const KURL& baseURL,
const KURL& url)
{
m_protocolMap.remove(scheme);
}
} // namespace blink
| {
"content_hash": "ed087c02ed7edc094c0ce6dd5f4e581b",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 131,
"avg_line_length": 31.870967741935484,
"alnum_prop": 0.7651821862348178,
"repo_name": "xin3liang/platform_external_chromium_org_third_party_WebKit",
"id": "1319a3d2910330214642289fd1f6141aa8290eda",
"size": "1362",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Source/modules/navigatorcontentutils/testing/NavigatorContentUtilsClientMock.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "14584"
},
{
"name": "C",
"bytes": "1474298"
},
{
"name": "C++",
"bytes": "40172832"
},
{
"name": "CSS",
"bytes": "381605"
},
{
"name": "Java",
"bytes": "66510"
},
{
"name": "JavaScript",
"bytes": "9259993"
},
{
"name": "Objective-C",
"bytes": "23525"
},
{
"name": "Objective-C++",
"bytes": "377761"
},
{
"name": "PHP",
"bytes": "3941"
},
{
"name": "Perl",
"bytes": "492247"
},
{
"name": "Python",
"bytes": "3698359"
},
{
"name": "Ruby",
"bytes": "141818"
},
{
"name": "Shell",
"bytes": "8806"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Fullscreen Slit Slider with CSS3 and jQuery</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Fullscreen Slit Slider with CSS3 and jQuery" />
<meta name="keywords" content="slit slider, plugin, css3, transitions, jquery, fullscreen, autoplay" />
<meta name="author" content="Codrops" />
<link rel="shortcut icon" href="../favicon.ico">
<link rel="stylesheet" type="text/css" href="css/demo.css" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<link rel="stylesheet" type="text/css" href="css/custom.css" />
<script type="text/javascript" src="js/modernizr.custom.79639.js"></script>
<noscript>
<link rel="stylesheet" type="text/css" href="css/styleNoJS.css" />
</noscript>
</head>
<body>
<div class="container demo-1" >
<!-- Codrops top bar -->
<nav class="codrops-demos">
</nav>
<div id="slider" class="sl-slider-wrapper">
<div class="sl-slider">
<div class="sl-slide bg-1" data-orientation="horizontal" data-slice1-rotation="-25" data-slice2-rotation="-25" data-slice1-scale="2" data-slice2-scale="2">
<div class="sl-slide-inner">
<div class="deco" ><img src="images/didit.jpg" width="150px" height="150" /></div>
<blockquote><p>You have just dined, and however scrupulously the slaughterhouse is concealed in the graceful distance of miles, there is complicity.</p><cite>Ralph Waldo Emerson</cite></blockquote>
</div>
</div>
<div class="sl-slide bg-2" data-orientation="vertical" data-slice1-rotation="10" data-slice2-rotation="-15" data-slice1-scale="1.5" data-slice2-scale="1.5">
<div class="sl-slide-inner">
<div class="deco" ><img src="images/didit.jpg" width="150px" height="150" /></div>
<blockquote><p>Until he extends the circle of his compassion to all living things, man will not himself find peace.</p><cite>Albert Schweitzer</cite></blockquote>
</div>
</div>
<div class="sl-slide bg-3" data-orientation="horizontal" data-slice1-rotation="3" data-slice2-rotation="3" data-slice1-scale="2" data-slice2-scale="1">
<div class="sl-slide-inner">
<div class="deco" ><img src="images/didit.jpg" width="150px" height="150" /></div>
<blockquote><p>Thousands of people who say they 'love' animals sit down once or twice a day to enjoy the flesh of creatures who have been utterly deprived of everything that could make their lives worth living </p><cite>Dame Jane Morris Goodall</cite></blockquote>
</div>
</div>
<div class="sl-slide bg-4" data-orientation="vertical" data-slice1-rotation="-5" data-slice2-rotation="25" data-slice1-scale="2" data-slice2-scale="1">
<div class="sl-slide-inner">
<div class="deco" ><img src="images/didit.jpg" width="150px" height="150" /></div>
<blockquote><p>The human body has no more need for cows' milk than it does for dogs' milk, horses' milk, or giraffes' milk.</p><cite>Michael Klaper M.D.</cite></blockquote>
</div>
</div>
<div class="sl-slide bg-5" data-orientation="horizontal" data-slice1-rotation="-5" data-slice2-rotation="10" data-slice1-scale="2" data-slice2-scale="1">
<div class="sl-slide-inner">
<div class="deco" ><img src="images/didit.jpg" width="150px" height="150" /></div>
<blockquote><p>I think if you want to eat more meat you should kill it yourself and eat it raw so that you are not blinded by the hypocrisy of having it processed for you.</p><cite>Margi Clarke</cite></blockquote>
</div>
</div>
</div><!-- /sl-slider -->
<nav id="nav-arrows" class="nav-arrows">
<span class="nav-arrow-prev">Previous</span>
<span class="nav-arrow-next">Next</span>
</nav>
<nav id="nav-dots" class="nav-dots">
<span class="nav-dot-current"></span>
<span></span>
<span></span>
<span></span>
<span></span>
</nav>
</div><!-- /slider-wrapper -->
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.ba-cond.min.js"></script>
<script type="text/javascript" src="js/jquery.slitslider.js"></script>
<script type="text/javascript">
$(function() {
var Page = (function() {
var $navArrows = $( '#nav-arrows' ),
$nav = $( '#nav-dots > span' ),
slitslider = $( '#slider' ).slitslider( {
onBeforeChange : function( slide, pos ) {
$nav.removeClass( 'nav-dot-current' );
$nav.eq( pos ).addClass( 'nav-dot-current' );
}
} ),
init = function() {
initEvents();
},
initEvents = function() {
// add navigation events
$navArrows.children( ':last' ).on( 'click', function() {
slitslider.next();
return false;
} );
$navArrows.children( ':first' ).on( 'click', function() {
slitslider.previous();
return false;
} );
$nav.each( function( i ) {
$( this ).on( 'click', function( event ) {
var $dot = $( this );
if( !slitslider.isActive() ) {
$nav.removeClass( 'nav-dot-current' );
$dot.addClass( 'nav-dot-current' );
}
slitslider.jump( i + 1 );
return false;
} );
} );
};
return { init : init };
})();
Page.init();
/**
* Notes:
*
* example how to add items:
*/
/*
var $items = $('<div class="sl-slide sl-slide-color-2" data-orientation="horizontal" data-slice1-rotation="-5" data-slice2-rotation="10" data-slice1-scale="2" data-slice2-scale="1"><div class="sl-slide-inner bg-1"><div class="sl-deco" data-icon="t"></div><h2>some text</h2><blockquote><p>bla bla</p><cite>Margi Clarke</cite></blockquote></div></div>');
// call the plugin's add method
ss.add($items);
*/
});
</script>
</body>
</html> | {
"content_hash": "31a6c690d4e06043246eaa4b8c190529",
"timestamp": "",
"source": "github",
"line_count": 176,
"max_line_length": 357,
"avg_line_length": 36.15909090909091,
"alnum_prop": 0.5917661847894407,
"repo_name": "didits/schematics15",
"id": "77823d4b783ac96c76d38e744231be73cea4e15f",
"size": "6364",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "assets/slider_nlc/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "364"
},
{
"name": "CSS",
"bytes": "18004"
},
{
"name": "HTML",
"bytes": "48029"
},
{
"name": "JavaScript",
"bytes": "75542"
},
{
"name": "Makefile",
"bytes": "4614"
},
{
"name": "PHP",
"bytes": "2050494"
},
{
"name": "Python",
"bytes": "11575"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using PcapDotNet.Core;
using PcapDotNet.Packets;
namespace OWDemo
{
class Sniffer
{
PacketDevice Device;
PacketCommunicator Communicator;
Task ReceiveTask;
string ReplayServerAddr = "";
string DemoName = "";
/// <summary>
/// Matches the replay server packet data.
/// </summary>
Regex ReplayServerMatcher = new Regex(@"(replay\d+\.valve\.net)");
/// <summary>
/// Matches the demo filename packet data.
/// </summary>
Regex DemoNameMatcher = new Regex(@"(\/730\/[\d|_]+\.dem\.bz2)");
/// <summary>
/// The URL to the demo file (constructed after both necessary packets have been received).
/// </summary>
public string URL { get; private set; }
/// <summary>
/// Whether or not we are currently monitoring network traffic.
/// </summary>
public bool Running { get; private set; }
public Sniffer(PacketDevice device)
{
this.Device = device;
}
private void HandlePacket(Packet packet)
{
var data = Encoding.Default.GetString(packet.Buffer);
//If we don't already have the server address, check the packet for it.
if(ReplayServerAddr.Equals(""))
{
var match = ReplayServerMatcher.Match(data);
if(match.Success)
{
ReplayServerAddr = match.Groups[1].Value;
Console.WriteLine("Replay server: {0}", ReplayServerAddr);
}
}
//If we don't already have the demo filename, check the packet for it.
if (DemoName.Equals(""))
{
var match = DemoNameMatcher.Match(data);
if(match.Success)
{
DemoName = match.Groups[1].Value;
Console.WriteLine("Demo filename: {0}", DemoName);
}
}
}
/// <summary>
/// Starts the receiver thread that listens for incoming packets.
/// </summary>
public void Start()
{
Communicator = Device.Open(65536, PacketDeviceOpenAttributes.None, 1000);
Running = true;
ReceiveTask = Task.Run(() => ReceivePackets());
Console.WriteLine("Now listening...");
}
/// <summary>
/// Stops listening for incoming packets and waits for the receiver thread to end.
/// </summary>
public void Stop()
{
if (Running)
{
Running = false;
Task.WaitAll(ReceiveTask);
Communicator.Dispose();
Communicator = null;
}
}
/// <summary>
/// Loop to receive packets (blocking).
/// </summary>
private void ReceivePackets()
{
Packet packet;
while(Running)
{
var result = Communicator.ReceivePacket(out packet);
switch(result)
{
case PacketCommunicatorReceiveResult.Timeout:
continue;
case PacketCommunicatorReceiveResult.Ok: //Only handle a packet if it was successfully received
HandlePacket(packet);
break;
default:
break;
}
//If we have received both necesarry packets, construct URL and stop listening
if (!(ReplayServerAddr.Equals("") || DemoName.Equals("")))
{
URL = string.Format("http://{0}{1}", ReplayServerAddr, DemoName);
Stop();
}
}
}
}
}
| {
"content_hash": "cb4a1b39b1579e06b30690eff0f480ef",
"timestamp": "",
"source": "github",
"line_count": 130,
"max_line_length": 115,
"avg_line_length": 31.553846153846155,
"alnum_prop": 0.5095075572891272,
"repo_name": "rakijah/OWDemo",
"id": "0f923dd4e2bb6921c745ed7d773a1cc2c9895ff8",
"size": "4104",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "OWDemo/Sniffer.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C#",
"bytes": "11072"
}
],
"symlink_target": ""
} |
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { MemoryService } from '../services/memory.service';
@Injectable()
export class CanPlayGuard implements CanActivate {
constructor(private router: Router,
private memoryService: MemoryService) {
}
canActivate(): boolean {
if (this.memoryService.isReadyToPlay()) {
return true;
}
this.router.navigateByUrl('/');
return false;
}
}
| {
"content_hash": "5ea7cad1e87691c881da74fee2e61ff2",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 59,
"avg_line_length": 24.523809523809526,
"alnum_prop": 0.6330097087378641,
"repo_name": "AerisG222/mikeandwan.us",
"id": "eed928678f275a0920dccc1bad315dc80b269415",
"size": "515",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/client_apps_ng/projects/memory/src/app/play/can-play-guard.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "574432"
},
{
"name": "HTML",
"bytes": "44848917"
},
{
"name": "JavaScript",
"bytes": "19626"
},
{
"name": "PLpgSQL",
"bytes": "106573"
},
{
"name": "SCSS",
"bytes": "10103"
},
{
"name": "Shell",
"bytes": "52855"
},
{
"name": "TypeScript",
"bytes": "96877"
}
],
"symlink_target": ""
} |
module Game.Lib.Units
( module Game.Lib.Units.Instances
) where
import Game.Lib.Units.Instances
| {
"content_hash": "f105596876563ca156469990e0a32574",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 41,
"avg_line_length": 23,
"alnum_prop": 0.6695652173913044,
"repo_name": "j-rock/strat",
"id": "e947301da5a7a387d4ab5b73c1993c89c8b85db3",
"size": "115",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Game/Lib/Units.hs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Haskell",
"bytes": "4945"
},
{
"name": "Makefile",
"bytes": "174"
}
],
"symlink_target": ""
} |
import TCD
import TCDExtra
import Control.Monad
import System.Environment (getArgs)
import Text.Printf
main :: IO ()
main = do
(station:date:_) <- getArgs
opened <- openDefaultTideDb
unless opened $ error "Cannot open tide database"
hdr <- getTideDbHeader
let nConstituents = fromIntegral (hdrConstituents hdr) :: Int
baseYear = fromIntegral (hdrStartYear hdr) :: Int
yearNum = read date - baseYear
indices = [0..nConstituents-1]
nodeFactors <- mapM (`getNodeFactor` yearNum) indices
num <- searchStation station
unless (num >= 0) $ error "Cannot find station"
(rn, r) <- readTideRecord num
unless (rn == num) $ error "Cannot read record"
let amplitudes = trAmplitudes r
offset = trDatumOffset r
putStrLn " i Amplitude Factor Result"
putStrLn "--- --------- ------ ------"
forM_ (zip3 indices amplitudes nodeFactors) $ \(i, a, f) ->
when (a /= 0.0) $
putStrLn $ printf "%3d %6.4f * %6.4f = %6.4f" (i :: Int) a f (a * f)
let maxamp = innerProduct amplitudes nodeFactors
m2ft = (/ 0.3048)
putStrLn $ printf "Maximum amplitude: %.6f - %.6f = %.6f = %.6fft"
(offset+maxamp) (offset-maxamp) (2*maxamp) (m2ft $ 2*maxamp)
where
innerProduct xs ys = sum $ zipWith (*) xs ys
| {
"content_hash": "a3925354d403aff1d6ff94b606bcdc5b",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 85,
"avg_line_length": 28.145833333333332,
"alnum_prop": 0.5988156920799408,
"repo_name": "neilmayhew/Tides",
"id": "962035e11e162816217bace2da4dd982acacd3e5",
"size": "1351",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "TideAmplitudes.hs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "274"
},
{
"name": "Haskell",
"bytes": "50594"
},
{
"name": "Nix",
"bytes": "3761"
},
{
"name": "Shell",
"bytes": "279"
}
],
"symlink_target": ""
} |
require "rspec"
require 'coveralls'
Coveralls.wear!
$LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + "/../lib"))
require "redis"
require "redis-sentinel"
RSpec.configure do |config|
config.filter_run :focus => true
config.run_all_when_everything_filtered = true
end
| {
"content_hash": "0787f137c6c0e7e97b246d49338b71b8",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 72,
"avg_line_length": 21.923076923076923,
"alnum_prop": 0.7263157894736842,
"repo_name": "mrkeng/redis-sentinel",
"id": "2b921c35aa6d8b4f5e583087fa45f46d5c9d8e6d",
"size": "285",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "spec/spec_helper.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "20770"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ $Id$
~ $Revision$
~ $Date$
~ $Author$
~
~ The DOMS project.
~ Copyright (C) 2007-2010 The State and University Library
~
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>dk.statsbiblioteket.doms.central</groupId>
<artifactId>central</artifactId>
<version>1.22-SNAPSHOT</version>
</parent>
<artifactId>summaSearch-interface</artifactId>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>1.12</version>
<executions>
<execution>
<goals>
<goal>wsimport</goal>
</goals>
<configuration>
<wsdlDirectory>src/main/resources/wsdl</wsdlDirectory>
<packageName>${project.groupId}.summasearch</packageName>
<sourceDestDir>target/generated-sources/java</sourceDestDir>
<verbose>true</verbose>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project> | {
"content_hash": "2c99f532c1651e52aa7546778b86ded7",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 204,
"avg_line_length": 37.65079365079365,
"alnum_prop": 0.595699831365936,
"repo_name": "statsbiblioteket/doms-server",
"id": "19aaedfb38bb8d725027ebe77b5344af0e1d2589",
"size": "2372",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "summaSearch-interface/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "111722"
}
],
"symlink_target": ""
} |
unifi_watchdog - USG failover watchdog
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Checks a Unifi Security Gateway to make sure the failover WAN is healthy. Connects via SSH; the USG must be in your :file:`known_hosts` file. Requires the specified interface to have status ``Running`` and the ping target to be ``REACHABLE``.
.. confval:: router_address
:type: string
:required: true
the address of the USG
.. confval:: router_username
:type: string
:required: true
the username to log in as
.. confval:: router_password
:type: string
:required: conditional
the password to log in with. Required if not using ``ssh_key``.
.. confval:: ssh_key
:type: string
:required: conditional
path to the SSH private key to log in with. Required if not using ``router_password``.
.. confval:: primary_interface
:type: string
:required: false
:default: ``pppoe0``
the primary WAN interface
.. confval:: secondary_interface
:type: string
:required: false
:default: ``eth2``
the secondary (failover) WAN interface
.. _unix_service:
| {
"content_hash": "32920dfccefcacf84299aed62f79ffb7",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 242,
"avg_line_length": 21.80392156862745,
"alnum_prop": 0.6546762589928058,
"repo_name": "jamesoff/simplemonitor",
"id": "4ab238745390153923de49aec8c4f226b13e0e2e",
"size": "1112",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "docs/monitors/unifi_watchdog.rst",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "11111"
},
{
"name": "Dockerfile",
"bytes": "2491"
},
{
"name": "HTML",
"bytes": "25694"
},
{
"name": "JavaScript",
"bytes": "1816"
},
{
"name": "Makefile",
"bytes": "1826"
},
{
"name": "Python",
"bytes": "345905"
},
{
"name": "Ruby",
"bytes": "191"
},
{
"name": "Shell",
"bytes": "8390"
}
],
"symlink_target": ""
} |
cask 'streamlink-twitch-gui' do
version '1.5.0'
sha256 'd359136b0f69739eccc607ac5049397a474bec9856058ee9511661d0b1bb0fb5'
url "https://github.com/streamlink/streamlink-twitch-gui/releases/download/v#{version}/streamlink-twitch-gui-v#{version}-macOS.tar.gz"
appcast 'https://github.com/streamlink/streamlink-twitch-gui/releases.atom'
name 'Streamlink Twitch GUI'
homepage 'https://github.com/streamlink/streamlink-twitch-gui/'
depends_on formula: 'streamlink'
app 'Streamlink Twitch GUI.app'
end
| {
"content_hash": "275a6cd0219b750fcb4c61ae5b139b0d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 136,
"avg_line_length": 39.53846153846154,
"alnum_prop": 0.7821011673151751,
"repo_name": "dcondrey/homebrew-cask",
"id": "fec025f4e80d89e012fc8dd0e1169f088c0331c4",
"size": "514",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "Casks/streamlink-twitch-gui.rb",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Ruby",
"bytes": "2120987"
},
{
"name": "Shell",
"bytes": "39580"
}
],
"symlink_target": ""
} |
// (C) Copyright 2015 Martin Dougiamas
//
// 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.
angular.module('mm.core.question')
/**
* Helper to gather some common functions for question directives.
*
* @module mm.core.question
* @ngdoc service
* @name $mmQuestionHelper
*/
.factory('$mmQuestionHelper', function($mmUtil, $mmText, $ionicModal, mmQuestionComponent, $mmSitesManager, $mmFilepool, $q,
$mmQuestion, $mmSite) {
var self = {},
lastErrorShown = 0;
/**
* Add a behaviour button to the question's "behaviourButtons" property.
*
* @param {Object} question Question.
* @param {Object} button Button (DOM element).
*/
function addBehaviourButton(question, button) {
if (!button || !question) {
return;
}
if (!question.behaviourButtons) {
question.behaviourButtons = [];
}
// Extract the data we want.
question.behaviourButtons.push({
id: button.id,
name: button.name,
value: button.value,
disabled: button.disabled
});
}
/**
* Convenience function to initialize a question directive.
* Performs some common checks and extracts the question's text.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#directiveInit
* @param {Object} scope Directive's scope.
* @param {Object} log $log instance to log messages.
* @return {Object} Angular DOM element of the question's HTML. Undefined if an error happens.
*/
self.directiveInit = function(scope, log) {
var question = scope.question,
questionEl;
if (!question) {
log.warn('Aborting because of no question received.');
return self.showDirectiveError(scope);
}
questionEl = angular.element(question.html);
// Extract question text.
question.text = $mmUtil.getContentsOfElement(questionEl, '.qtext');
if (typeof question.text == 'undefined') {
log.warn('Aborting because of an error parsing question.', question.name);
return self.showDirectiveError(scope);
}
return questionEl;
};
/**
* Extract question behaviour submit buttons from the question's HTML and add them to "behaviourButtons" property.
* The buttons aren't deleted from the content because all the im-controls block will be removed afterwards.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#extractQbehaviourButtons
* @param {Object} question Question to treat.
* @param {String} [selector] Selector to search the buttons. By default, '.im-controls input[type="submit"]'.
* @return {Void}
*/
self.extractQbehaviourButtons = function(question, selector) {
selector = selector || '.im-controls input[type="submit"]';
// Create a fake div element so we can search using querySelector.
var div = document.createElement('div'),
buttons;
div.innerHTML = question.html;
// Search the buttons.
buttons = div.querySelectorAll(selector);
angular.forEach(buttons, function(button) {
addBehaviourButton(question, button);
});
question.html = div.innerHTML;
};
/**
* Check if the question has CBM and, if so, extract the certainty options and add them to a new
* "behaviourCertaintyOptions" property.
* The value of the selected option is stored in question.behaviourCertaintySelected.
* We don't remove them from HTML because all the im-controls block will be removed afterwards.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#extractQbehaviourCBM
* @param {Object} question Question to treat.
* @return {Boolean} True if the seen input is found, false otherwise.
*/
self.extractQbehaviourCBM = function(question) {
// Create a fake div element so we can search using querySelector.
var div = document.createElement('div'),
labels;
div.innerHTML = question.html;
labels = div.querySelectorAll('.im-controls .certaintychoices label[for*="certainty"]');
question.behaviourCertaintyOptions = [];
angular.forEach(labels, function(label) {
var input = label.querySelector('input[type="radio"]');
if (input) {
question.behaviourCertaintyOptions.push({
id: input.id,
name: input.name,
value: input.value,
text: $mmText.cleanTags(label.innerHTML),
disabled: input.disabled
});
if (input.checked) {
question.behaviourCertaintySelected = input.value;
}
}
});
// If we have a certainty value stored in local we'll use that one.
if (question.localAnswers && typeof question.localAnswers['-certainty'] != 'undefined') {
question.behaviourCertaintySelected = question.localAnswers['-certainty'];
}
return labels && labels.length;
};
/**
* Check if the question has a redo button and, if so, add it to "behaviourButtons" property
* and remove it from the HTML.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#extractQbehaviourRedoButton
* @param {Object} question Question to treat.
* @return {Void}
*/
self.extractQbehaviourRedoButton = function(question) {
// Create a fake div element so we can search using querySelector.
var div = document.createElement('div'),
redoSelector = 'input[type="submit"][name*=redoslot], input[type="submit"][name*=tryagain]';
// Search redo button in feedback (Moodle 3.1+).
if (!searchButton('html', '.outcome ' + redoSelector)) {
// Not found in question HTML.
if (question.feedbackHtml) {
// We extracted the feedback already, search it in there.
if (searchButton('feedbackHtml', redoSelector)) {
// Button found, stop.
return;
}
}
// Button still not found. Now search in the info box if it exists.
if (question.infoHtml) {
searchButton('infoHtml', redoSelector);
}
}
// Search the button in a certain question property containing HTML.
function searchButton(htmlProperty, selector) {
var button;
div.innerHTML = question[htmlProperty];
button = div.querySelector(selector);
if (button) {
addBehaviourButton(question, button);
angular.element(button).remove();
question[htmlProperty] = div.innerHTML;
return true;
}
return false;
}
};
/**
* Check if the question contains a "seen" input.
* If so, add the name and value to a "behaviourSeenInput" property and remove the input.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#extractQbehaviourSeenInput
* @param {Object} question Question to treat.
* @return {Boolean} True if the seen input is found, false otherwise.
*/
self.extractQbehaviourSeenInput = function(question) {
// Create a fake div element so we can search using querySelector.
var div = document.createElement('div'),
seenInput;
div.innerHTML = question.html;
// Search the "seen" input.
seenInput = div.querySelector('input[type="hidden"][name*=seen]');
if (seenInput) {
// Get the data and remove the input.
question.behaviourSeenInput = {
name: seenInput.name,
value: seenInput.value
};
angular.element(seenInput).remove();
question.html = div.innerHTML;
// Return the directive to render this input.
return true;
}
return false;
};
/**
* Removes the comment from the question HTML code and adds it in a new "commentHtml" property.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#extractQuestionComment
* @param {Object} question Question.
* @return {Void}
*/
self.extractQuestionComment = function(question) {
extractQuestionLastElementNotInContent(question, '.comment', 'commentHtml');
};
/**
* Removes the feedback from the question HTML code and adds it in a new "feedbackHtml" property.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#extractQuestionFeedback
* @param {Object} question Question.
* @return {Void}
*/
self.extractQuestionFeedback = function(question) {
extractQuestionLastElementNotInContent(question, '.outcome', 'feedbackHtml');
};
/**
* Extracts the info box from a question and add it to an "infoHtml" property.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#extractQuestionInfoBox
* @param {Object} question Question.
* @param {String} selector Selector to search the element.
* @return {Void}
*/
self.extractQuestionInfoBox = function(question, selector) {
extractQuestionLastElementNotInContent(question, selector, 'infoHtml');
};
/**
* Searches the last occurrence of a certain element and check it's not in the question contents.
* If found, removes it from the question HTML and adds it to a new property inside question.
*
*
* @param {Object} question Question.
* @param {String} selector Selector to search the element.
* @param {String} attrName Name of the attribute to store the HTML in.
* @return {Void}
*/
function extractQuestionLastElementNotInContent(question, selector, attrName) {
// Create a fake div element so we can search using querySelector.
var div = document.createElement('div'),
matches,
last,
position;
div.innerHTML = question.html;
matches = div.querySelectorAll(selector);
// Get the last element and check it's not in the question contents.
// We don't use .pop() because the result of querySelectorAll doesn't support it.
position = matches.length -1;
last = matches[position];
while (last) {
if (!$mmUtil.closest(last, '.formulation')) {
question[attrName] = last.innerHTML;
angular.element(last).remove();
question.html = div.innerHTML;
return;
}
// It's inside the question content, treat next element.
position--;
last = matches[position];
}
}
/**
* Removes the scripts from a question's HTML and adds it in a new 'scriptsCode' property.
* It will also search for init_question functions of the question type and add the object to an 'initObjects' property.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#extractQuestionScripts
* @param {Object} question Question.
* @return {Void}
*/
self.extractQuestionScripts = function(question) {
var matches;
question.scriptsCode = '';
question.initObjects = [];
if (question.html) {
// Search the scripts.
matches = question.html.match(/<script[^>]*>[\s\S]*?<\/script>/mg);
angular.forEach(matches, function(match) {
// Add the script to scriptsCode and remove it from html.
question.scriptsCode += match;
question.html = question.html.replace(match, '');
// Search init_question functions for this type.
var initMatches = match.match(new RegExp('M\.qtype_' + question.type + '\.init_question\\(.*?}\\);', 'mg'));
if (initMatches) {
var initMatch = initMatches.pop();
// Remove start and end of the match, we only want the object.
initMatch = initMatch.replace('M.qtype_' + question.type + '.init_question(', '');
initMatch = initMatch.substr(0, initMatch.length - 2);
// Try to convert it to an object and add it to the question.
try {
question.initObjects = JSON.parse(initMatch);
} catch(ex) {}
}
});
}
};
/**
* Get the names of all the inputs inside an HTML code.
* This function will return an object where the keys are the input names. The values will always be true.
* This is in order to make this function compatible with other functions like $mmQuestion#getBasicAnswers.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#getAllInputNamesFromHtml
* @param {String} html HTML code.
* @return {Object} Object where the keys are the names.
*/
self.getAllInputNamesFromHtml = function(html) {
var form = document.createElement('form'),
answers = {};
form.innerHTML = html;
// Search all input elements.
angular.forEach(form.elements, function(element) {
var name = element.name || '';
// Ignore flag and submit inputs.
if (!name || name.match(/_:flagged$/) || element.type == 'submit' || element.tagName == 'BUTTON') {
return;
}
answers[$mmQuestion.removeQuestionPrefix(name)] = true;
});
return answers;
};
/**
* Retrieve the answers entered in a form.
* We don't use ng-model because it doesn't detect changes done by JavaScript and some questions might do that.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#getAnswersFromForm
* @param {Object} form Form (DOM element).
* @return {Object} Object with the answers.
*/
self.getAnswersFromForm = function(form) {
if (!form || !form.elements) {
return {};
}
var answers = {};
angular.forEach(form.elements, function(element) {
var name = element.name || '';
// Ignore flag and submit inputs.
if (!name || name.match(/_:flagged$/) || element.type == 'submit' || element.tagName == 'BUTTON') {
return;
}
// Get the value.
if (element.type == 'checkbox') {
answers[name] = !!element.checked;
} else if (element.type == 'radio') {
if (element.checked) {
answers[name] = element.value;
}
} else {
answers[name] = element.value;
}
});
return answers;
};
/**
* Given an HTML code with list of attachments, returns the list of attached files (filename and fileurl).
* Please take into account that this function will treat all the anchors in the HTML, you should provide
* an HTML containing only the attachments anchors.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#getQuestionAttachmentsFromHtml
* @param {String} html HTML code to search in.
* @return {Object[]} Attachments.
*/
self.getQuestionAttachmentsFromHtml = function(html) {
var el = angular.element('<div></div>'),
anchors,
attachments = [];
// Add the HTML and get the plain JS element.
el.html(html);
el = el[0];
// Remove the filemanager (area to attach files to a question).
$mmUtil.removeElement(el, 'div[id*=filemanager]');
// Search the anchors.
anchors = el.querySelectorAll('a');
angular.forEach(anchors, function(anchor) {
var content = anchor.innerHTML;
// Check anchor is valid.
if (anchor.href && content) {
content = $mmText.cleanTags(content, true).trim();
attachments.push({
filename: content,
fileurl: anchor.href
});
}
});
return attachments;
};
/**
* Get the sequence check from a question HTML.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#getQuestionSequenceCheckFromHtml
* @param {String} html Question's HTML.
* @return {Object} Object with the sequencecheck name and value.
*/
self.getQuestionSequenceCheckFromHtml = function(html) {
var el,
input;
if (html) {
el = angular.element(html)[0];
// Search the input holding the sequencecheck.
input = el.querySelector('input[name*=sequencecheck]');
if (input && typeof input.name != 'undefined' && typeof input.value != 'undefined') {
return {
name: input.name,
value: input.value
};
}
}
};
/**
* Get the CSS class for a question based on its state.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#getQuestionStateClass
* @param {String} name Question's state name.
* @return {String} State class.
*/
self.getQuestionStateClass = function(name) {
var state = $mmQuestion.getState(name);
return state ? state.class : '';
};
/**
* Get the validation error message from a question HTML if it's there.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#getValidationErrorFromHtml
* @param {String} html Question's HTML.
* @return {Object} Validation error message if present.
*/
self.getValidationErrorFromHtml = function(html) {
return $mmUtil.getContentsOfElement(angular.element(html), '.validationerror');
};
/**
* Check if some HTML contains draft file URLs for the current site.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#hasDraftFileUrls
* @param {String} html Question's HTML.
* @return {Boolean} True if contains draft files URLs, false otherwise.
*/
self.hasDraftFileUrls = function(html) {
var url = $mmSite.getURL();
if (url.slice(-1) != '/') {
url = url += '/';
}
url += 'draftfile.php';
return html.indexOf(url) != -1;
};
/**
* Generic link function for question directives with an input of type "text".
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#inputTextDirective
* @param {Object} scope Directive's scope.
* @param {Object} log $log instance to log messages.
* @return {Void}
*/
self.inputTextDirective = function(scope, log) {
var questionEl = self.directiveInit(scope, log);
if (questionEl) {
questionEl = questionEl[0] || questionEl; // Convert from jqLite to plain JS if needed.
// Get the input element.
input = questionEl.querySelector('input[type="text"][name*=answer]');
if (!input) {
log.warn('Aborting because couldn\'t find input.', question.name);
return self.showDirectiveError(scope);
}
scope.input = {
id: input.id,
name: input.name,
value: input.value,
readOnly: input.readOnly
};
// Check if question is marked as correct.
if (input.className.indexOf('incorrect') >= 0) {
scope.input.isCorrect = 0;
} else if (input.className.indexOf('correct') >= 0) {
scope.input.isCorrect = 1;
}
}
};
/**
* For each input element found in the HTML, search if there's a local answer stored and
* override the HTML's value with the local one.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#loadLocalAnswersInHtml
* @param {String} component Component the answers belong to.
* @param {Number} attemptId Attempt ID.
* @param {Object} question Question.
* @return {Void}
*/
self.loadLocalAnswersInHtml = function(question) {
var form = document.createElement('form');
form.innerHTML = question.html;
// Search all input elements.
angular.forEach(form.elements, function(element) {
var name = element.name || '';
// Ignore flag and submit inputs.
if (!name || name.match(/_:flagged$/) || element.type == 'submit' || element.tagName == 'BUTTON') {
return;
}
// Search if there's a local answer.
name = $mmQuestion.removeQuestionPrefix(name);
if (question.localAnswers && typeof question.localAnswers[name] != 'undefined') {
var selected;
if (element.tagName == 'TEXTAREA') {
element.innerHTML = question.localAnswers[name];
} else if (element.tagName == 'SELECT') {
// Search the selected option and select it.
selected = element.querySelector('option[value="' + question.localAnswers[name] + '"]');
if (selected) {
selected.setAttribute('selected', 'selected');
}
} else if (element.type == 'radio' || element.type == 'checkbox') {
if (element.value == question.localAnswers[name]) {
element.setAttribute('checked', 'checked');
}
} else {
element.setAttribute('value', question.localAnswers[name]);
}
}
});
question.html = form.innerHTML;
};
/**
* Generic link function for question directives with a "matching" (selects).
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#matchingDirective
* @param {Object} scope Directive's scope.
* @param {Object} log $log instance to log messages.
* @return {Void}
*/
self.matchingDirective = function(scope, log) {
var questionEl = self.directiveInit(scope, log),
question = scope.question,
rows;
if (questionEl) {
questionEl = questionEl[0] || questionEl; // Convert from jqLite to plain JS if needed.
// Find rows.
rows = questionEl.querySelectorAll('tr');
if (!rows || !rows.length) {
log.warn('Aborting because couldn\'t find any row.', question.name);
return self.showDirectiveError(scope);
}
question.rows = [];
angular.forEach(rows, function(row) {
var rowModel = {},
select,
options,
accessibilityLabel,
columns = row.querySelectorAll('td');
if (!columns || columns.length < 2) {
log.warn('Aborting because couldn\'t find the right columns.', question.name);
return self.showDirectiveError(scope);
}
// Get the row's text. It should be in the first column.
rowModel.text = columns[0].innerHTML;
// Get the select and the options.
select = columns[1].querySelector('select');
options = columns[1].querySelectorAll('option');
if (!select || !options || !options.length) {
log.warn('Aborting because couldn\'t find select or options.', question.name);
return self.showDirectiveError(scope);
}
rowModel.id = select.id;
rowModel.name = select.name;
rowModel.disabled = select.disabled;
rowModel.selected = false;
rowModel.options = [];
// Check if answer is correct.
if (columns[1].className.indexOf('incorrect') >= 0) {
rowModel.isCorrect = 0;
} else if (columns[1].className.indexOf('correct') >= 0) {
rowModel.isCorrect = 1;
}
// Treat each option.
angular.forEach(options, function(option) {
if (typeof option.value == 'undefined') {
log.warn('Aborting because couldn\'t find option value.', question.name);
return self.showDirectiveError(scope);
}
var opt = {
value: option.value,
label: option.innerHTML,
selected: option.selected
};
if (opt.selected) {
rowModel.selected = opt;
}
rowModel.options.push(opt);
});
// Get the accessibility label.
accessibilityLabel = columns[1].querySelector('label.accesshide');
rowModel.accessibilityLabel = accessibilityLabel.innerHTML;
question.rows.push(rowModel);
});
question.loaded = true;
}
};
/**
* Generic link function for question directives with a multi choice input.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#multiChoiceDirective
* @param {Object} scope Directive's scope.
* @param {Object} log $log instance to log messages.
* @return {Void}
*/
self.multiChoiceDirective = function(scope, log) {
var questionEl = self.directiveInit(scope, log),
question = scope.question;
// We need a model to store the answers for radio buttons since ng-checked isn't available for ion-radio.
scope.mcAnswers = {};
if (questionEl) {
questionEl = questionEl[0] || questionEl; // Convert from jqLite to plain JS if needed.
// Get the prompt.
question.prompt = $mmUtil.getContentsOfElement(questionEl, '.prompt');
// Search radio buttons first (single choice).
var options = questionEl.querySelectorAll('input[type="radio"]');
if (!options || !options.length) {
// Radio buttons not found, it should be a multi answer. Search for checkbox.
question.multi = true;
options = questionEl.querySelectorAll('input[type="checkbox"]');
if (!options || !options.length) {
// No checkbox found either. Abort.
log.warn('Aborting because of no radio and checkbox found.', question.name);
return self.showDirectiveError(scope);
}
}
question.options = [];
angular.forEach(options, function(element) {
var option = {
id: element.id,
name: element.name,
value: element.value,
checked: element.checked,
disabled: element.disabled
},
label,
parent = element.parentNode,
feedback;
// Get the label with the question text.
label = questionEl.querySelector('label[for="' + option.id + '"]');
if (label) {
option.text = label.innerHTML;
// Check that we were able to successfully extract options required data.
if (typeof option.name != 'undefined' && typeof option.value != 'undefined' &&
typeof option.text != 'undefined') {
if (element.checked) {
// If the option is checked and it's a single choice we use the model to select the one.
if (!question.multi) {
scope.mcAnswers[option.name] = option.value;
}
if (parent) {
// Check if answer is correct.
if (parent && parent.className.indexOf('incorrect') >= 0) {
option.isCorrect = 0;
} else if (parent && parent.className.indexOf('correct') >= 0) {
option.isCorrect = 1;
}
// Search the feedback.
feedback = parent.querySelector('.specificfeedback');
if (feedback) {
option.feedback = feedback.innerHTML;
}
}
}
question.options.push(option);
return;
}
}
// Something went wrong when extracting the questions data. Abort.
log.warn('Aborting because of an error parsing options.', question.name, option.name);
return self.showDirectiveError(scope);
});
}
};
/**
* Prefetch the files in a question HTML.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#prefetchQuestionFiles
* @param {Object} question Question.
* @param {String} [siteId] Site ID. If not defined, current site.
* @param {String} component The component to link the files to. If not defined, question component.
* @param {Mixed} [componentId] An ID to use in conjunction with the component. If not defined, question ID.
* @return {Promise} Promise resolved when all the files have been downloaded.
*/
self.prefetchQuestionFiles = function(question, siteId, component, componentId) {
var urls = $mmUtil.extractDownloadableFilesFromHtml(question.html);
if (!component) {
component = mmQuestionComponent;
componentId = question.id;
}
return $mmSitesManager.getSite(siteId).then(function(site) {
var promises = [];
angular.forEach(urls, function(url) {
if (!site.canDownloadFiles() && $mmUtil.isPluginFileUrl(url)) {
return;
}
if (url.indexOf('theme/image.php') > -1 && url.indexOf('flagged') > -1) {
// Ignore flag images.
return;
}
promises.push($mmFilepool.addToQueueByUrl(siteId, url, component, componentId));
});
return $q.all(promises);
});
};
/**
* Replace Moodle's correct/incorrect classes with the Mobile ones.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#replaceCorrectnessClasses
* @param {Object} element DOM element.
* @return {Void}
*/
self.replaceCorrectnessClasses = function(element) {
$mmUtil.replaceClassesInElement(element, {
correct: 'mm-question-answer-correct',
incorrect: 'mm-question-answer-incorrect'
});
};
/**
* Replace Moodle's feedback classes with the Mobile ones.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#replaceFeedbackClasses
* @param {Object} element DOM element.
* @return {Void}
*/
self.replaceFeedbackClasses = function(element) {
$mmUtil.replaceClassesInElement(element, {
outcome: 'mm-question-feedback-container mm-question-feedback-padding',
specificfeedback: 'mm-question-feedback-container mm-question-feedback-inline'
});
};
/**
* Convenience function to show a parsing error and abort.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#showDirectiveError
* @param {Object} scope Directive scope.
* @param {String} [error] Error to show.
* @return {Void}
*/
self.showDirectiveError = function(scope, error) {
error = error || 'Error processing the question. This could be caused by custom modifications in your site.';
// Prevent consecutive errors.
var now = new Date().getTime();
if (now - lastErrorShown > 500) {
lastErrorShown = now;
$mmUtil.showErrorModal(error);
}
scope.abort();
};
/**
* Treat correctness icons, replacing them with local icons and setting click events to show the feedback if needed.
*
* @module mm.core.question
* @ngdoc method
* @name $mmQuestionHelper#treatCorrectnessIcons
* @param {Object} scope Directive scope.
* @param {Object} element DOM element.
* @return {Void}
*/
self.treatCorrectnessIcons = function(scope, element) {
element = element[0] || element; // Convert from jqLite to plain JS if needed.
var icons = element.querySelectorAll('.questioncorrectnessicon');
angular.forEach(icons, function(icon) {
var parent;
// Replace the icon with the local version.
if (icon.src && icon.src.indexOf('incorrect') > -1) {
icon.src = 'img/icons/grade_incorrect.svg';
} else if (icon.src && icon.src.indexOf('correct') > -1) {
icon.src = 'img/icons/grade_correct.svg';
}
// Search if there's a hidden feedback for this element.
parent = icon.parentNode;
if (!parent) {
return;
}
if (!parent.querySelector('.feedbackspan.accesshide')) {
return;
}
// There's a hidden feedback, set up ngClick to show the feedback.
icon.setAttribute('ng-click', 'questionCorrectnessIconClicked($event)');
});
// Set icon click function.
scope.questionCorrectnessIconClicked = function(event) {
var parent = event.target.parentNode,
feedback;
if (parent) {
feedback = parent.querySelector('.feedbackspan.accesshide');
if (feedback && feedback.innerHTML) {
scope.currentFeedback = feedback.innerHTML;
scope.feedbackModal.show();
}
}
};
// Feedback modal.
$ionicModal.fromTemplateUrl('core/components/question/templates/feedbackmodal.html', {
scope: scope
}).then(function(modal) {
scope.feedbackModal = modal;
scope.closeModal = function() {
modal.hide();
};
});
};
return self;
});
| {
"content_hash": "f9d29f9875e53124b33d3be4e049892f",
"timestamp": "",
"source": "github",
"line_count": 980,
"max_line_length": 124,
"avg_line_length": 36.91428571428571,
"alnum_prop": 0.557828394515701,
"repo_name": "Diaa75/moodlemobile2",
"id": "beb11c82bda843f893af2fa43f5168a11ad0c749",
"size": "36180",
"binary": false,
"copies": "12",
"ref": "refs/heads/leasy",
"path": "www/core/components/question/services/helper.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "61649"
},
{
"name": "HTML",
"bytes": "322567"
},
{
"name": "JavaScript",
"bytes": "4088312"
}
],
"symlink_target": ""
} |
/*
* $Id: DOMLSParserImpl.hpp 673679 2008-07-03 13:50:10Z borisk $
*/
#if !defined(XERCESC_INCLUDE_GUARD_DOMBUILDERIMPL_HPP)
#define XERCESC_INCLUDE_GUARD_DOMBUILDERIMPL_HPP
#include <xercesc/parsers/AbstractDOMParser.hpp>
#include <xercesc/dom/DOMLSParser.hpp>
#include <xercesc/dom/DOMLSInput.hpp>
#include <xercesc/dom/DOMConfiguration.hpp>
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/RefVectorOf.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class XMLEntityResolver;
class XMLResourceIdentifier;
class DOMStringListImpl;
class DOMLSResourceResolver;
/**
* Introduced in DOM Level 3
*
* DOMLSParserImpl provides an implementation of a DOMLSParser interface.
* A DOMLSParser instance is obtained from the DOMImplementationLS interface
* by invoking its createDOMLSParser method.
*/
class PARSERS_EXPORT DOMLSParserImpl : public AbstractDOMParser,
public DOMLSParser,
public DOMConfiguration
{
public :
// -----------------------------------------------------------------------
// Constructors and Detructor
// -----------------------------------------------------------------------
/** @name Constructors and Destructor */
//@{
/** Construct a DOMLSParserImpl, with an optional validator
*
* Constructor with an instance of validator class to use for
* validation. If you don't provide a validator, a default one will
* be created for you in the scanner.
*
* @param valToAdopt Pointer to the validator instance to use. The
* parser is responsible for freeing the memory.
* @param manager The memory manager to be used for memory allocations
* @param gramPool Pointer to the grammar pool instance from
* external application.
* The parser does NOT own it.
*
*/
DOMLSParserImpl
(
XMLValidator* const valToAdopt = 0
, MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager
, XMLGrammarPool* const gramPool = 0
);
/**
* Destructor
*/
virtual ~DOMLSParserImpl();
//@}
// -----------------------------------------------------------------------
// Implementation of DOMLSParser interface
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
/** @name Getter methods */
//@{
/**
* @see DOMLSParser#getDomConfig
*/
virtual DOMConfiguration* getDomConfig();
/**
* @see DOMLSParser#getFilter
*/
virtual const DOMLSParserFilter* getFilter() const;
/**
* @see DOMLSParser#getAsync
*/
virtual bool getAsync() const;
/**
* @see DOMLSParser#getBusy
*/
virtual bool getBusy() const;
//@}
// -----------------------------------------------------------------------
// Setter methods
// -----------------------------------------------------------------------
/** @name Setter methods */
//@{
/**
* @see DOMLSParser#setFilter
*/
virtual void setFilter(DOMLSParserFilter* const filter);
//@}
// -----------------------------------------------------------------------
// Parsing methods
// -----------------------------------------------------------------------
/** @name Parsing methods */
//@{
// -----------------------------------------------------------------------
// Parsing methods
// -----------------------------------------------------------------------
/**
* @see DOMLSParser#parse
*/
virtual DOMDocument* parse(const DOMLSInput* source);
/**
* @see DOMLSParser#parseURI
*/
virtual DOMDocument* parseURI(const XMLCh* const uri);
/**
* @see DOMLSParser#parseURI
*/
virtual DOMDocument* parseURI(const char* const uri);
/**
* @see DOMLSParser#parseWithContext
*/
virtual void parseWithContext
(
const DOMLSInput* source
, DOMNode* contextNode
, const ActionType action
);
/**
* @see DOMLSParser#abort
*/
virtual void abort();
// -----------------------------------------------------------------------
// Non-standard Extension
// -----------------------------------------------------------------------
/** @name Non-standard Extension */
//@{
/**
* Called to indicate that this DOMLSParser is no longer in use
* and that the implementation may relinquish any resources associated with it.
*
*/
virtual void release();
/** Reset the documents vector pool and release all the associated memory
* back to the system.
*
* When parsing a document using a DOM parser, all memory allocated
* for a DOM tree is associated to the DOM document.
*
* If you do multiple parse using the same DOM parser instance, then
* multiple DOM documents will be generated and saved in a vector pool.
* All these documents (and thus all the allocated memory)
* won't be deleted until the parser instance is destroyed.
*
* If you don't need these DOM documents anymore and don't want to
* destroy the DOM parser instance at this moment, then you can call this method
* to reset the document vector pool and release all the allocated memory
* back to the system.
*
* It is an error to call this method if you are in the middle of a
* parse (e.g. in the mid of a progressive parse).
*
* @exception IOException An exception from the parser if this function
* is called when a parse is in progress.
*
*/
virtual void resetDocumentPool();
/**
* Preparse schema grammar (XML Schema, DTD, etc.) via an input source
* object.
*
* This method invokes the preparsing process on a schema grammar XML
* file specified by the DOMLSInput parameter. If the 'toCache' flag
* is enabled, the parser will cache the grammars for re-use. If a grammar
* key is found in the pool, no caching of any grammar will take place.
*
* @param source A const reference to the DOMLSInput object which
* points to the schema grammar file to be preparsed.
* @param grammarType The grammar type (Schema or DTD).
* @param toCache If <code>true</code>, we cache the preparsed grammar,
* otherwise, no chaching. Default is <code>false</code>.
* @return The preparsed schema grammar object (SchemaGrammar or
* DTDGrammar). That grammar object is owned by the parser.
*
* @exception SAXException Any SAX exception, possibly
* wrapping another exception.
* @exception XMLException An exception from the parser or client
* handler code.
* @exception DOMException A DOM exception as per DOM spec.
*
* @see DOMLSInput#DOMLSInput
*/
virtual Grammar* loadGrammar(const DOMLSInput* source,
const Grammar::GrammarType grammarType,
const bool toCache = false);
/**
* Preparse schema grammar (XML Schema, DTD, etc.) via a file path or URL
*
* This method invokes the preparsing process on a schema grammar XML
* file specified by the file path parameter. If the 'toCache' flag
* is enabled, the parser will cache the grammars for re-use. If a grammar
* key is found in the pool, no caching of any grammar will take place.
*
* @param systemId A const XMLCh pointer to the Unicode string which
* contains the path to the XML grammar file to be
* preparsed.
* @param grammarType The grammar type (Schema or DTD).
* @param toCache If <code>true</code>, we cache the preparsed grammar,
* otherwise, no chaching. Default is <code>false</code>.
* @return The preparsed schema grammar object (SchemaGrammar or
* DTDGrammar). That grammar object is owned by the parser.
*
* @exception SAXException Any SAX exception, possibly
* wrapping another exception.
* @exception XMLException An exception from the parser or client
* handler code.
* @exception DOMException A DOM exception as per DOM spec.
*/
virtual Grammar* loadGrammar(const XMLCh* const systemId,
const Grammar::GrammarType grammarType,
const bool toCache = false);
/**
* Preparse schema grammar (XML Schema, DTD, etc.) via a file path or URL
*
* This method invokes the preparsing process on a schema grammar XML
* file specified by the file path parameter. If the 'toCache' flag
* is enabled, the parser will cache the grammars for re-use. If a grammar
* key is found in the pool, no caching of any grammar will take place.
*
* @param systemId A const char pointer to a native string which contains
* the path to the XML grammar file to be preparsed.
* @param grammarType The grammar type (Schema or DTD).
* @param toCache If <code>true</code>, we cache the preparsed grammar,
* otherwise, no chaching. Default is <code>false</code>.
* @return The preparsed schema grammar object (SchemaGrammar or
* DTDGrammar). That grammar object is owned by the parser.
*
* @exception SAXException Any SAX exception, possibly
* wrapping another exception.
* @exception XMLException An exception from the parser or client
* handler code.
* @exception DOMException A DOM exception as per DOM spec.
*/
virtual Grammar* loadGrammar(const char* const systemId,
const Grammar::GrammarType grammarType,
const bool toCache = false);
/**
* Retrieve the grammar that is associated with the specified namespace key
*
* @param nameSpaceKey Namespace key
* @return Grammar associated with the Namespace key.
*/
virtual Grammar* getGrammar(const XMLCh* const nameSpaceKey) const;
/**
* Retrieve the grammar where the root element is declared.
*
* @return Grammar where root element declared
*/
virtual Grammar* getRootGrammar() const;
/**
* Returns the string corresponding to a URI id from the URI string pool.
*
* @param uriId id of the string in the URI string pool.
* @return URI string corresponding to the URI id.
*/
virtual const XMLCh* getURIText(unsigned int uriId) const;
/**
* Clear the cached grammar pool
*/
virtual void resetCachedGrammarPool();
/**
* Returns the current src offset within the input source.
* To be used only while parsing is in progress.
*
* @return offset within the input source
*/
virtual XMLFilePos getSrcOffset() const;
//@}
// -----------------------------------------------------------------------
// Implementation of the DOMConfiguration interface.
// -----------------------------------------------------------------------
/** @name Implementation of the DOMConfiguration interface. */
//@{
/**
* Set the value of a parameter.
*
* @param name The name of the parameter to set.
* @param value The new value or null if the user wishes to unset the
* parameter. While the type of the value parameter is defined as
* <code>DOMUserData</code>, the object type must match the type defined
* by the definition of the parameter. For example, if the parameter is
* "error-handler", the value must be of type <code>DOMErrorHandler</code>
*
* @exception DOMException (NOT_SUPPORTED_ERR) Raised when the
* parameter name is recognized but the requested value cannot be set.
* @exception DOMException (NOT_FOUND_ERR) Raised when the
* parameter name is not recognized.
*
* @since DOM level 3
**/
virtual void setParameter(const XMLCh* name, const void* value);
virtual void setParameter(const XMLCh* name, bool value);
/**
* Return the value of a parameter if known.
*
* @param name The name of the parameter.
* @return The current object associated with the specified parameter or
* null if no object has been associated or if the parameter is not
* supported.
*
* @exception DOMException (NOT_FOUND_ERR) Raised when the i
* boolean parameter
* name is not recognized.
*
* @since DOM level 3
**/
virtual const void* getParameter(const XMLCh* name) const;
/**
* Check if setting a parameter to a specific value is supported.
*
* @param name The name of the parameter to check.
* @param value An object. if null, the returned value is true.
* @return true if the parameter could be successfully set to the specified
* value, or false if the parameter is not recognized or the requested value
* is not supported. This does not change the current value of the parameter
* itself.
*
* @since DOM level 3
**/
virtual bool canSetParameter(const XMLCh* name, const void* value) const;
virtual bool canSetParameter(const XMLCh* name, bool value) const;
/**
* The list of the parameters supported by this DOMConfiguration object and
* for which at least one value can be set by the application.
* Note that this list can also contain parameter names defined outside this specification.
*
* @return The list of parameters that can be used with setParameter/getParameter
* @since DOM level 3
**/
virtual const DOMStringList* getParameterNames() const;
//@}
// -----------------------------------------------------------------------
// Implementation of the XMLErrorReporter interface.
// -----------------------------------------------------------------------
/** @name Implementation of the XMLErrorReporter interface. */
//@{
/** Handle errors reported from the parser
*
* This method is used to report back errors found while parsing the
* XML file. This method is also borrowed from the SAX specification.
* It calls the corresponding user installed Error Handler method:
* 'fatal', 'error', 'warning' depending on the severity of the error.
* This classification is defined by the XML specification.
*
* @param errCode An integer code for the error.
* @param msgDomain A const pointer to an Unicode string representing
* the message domain to use.
* @param errType An enumeration classifying the severity of the error.
* @param errorText A const pointer to an Unicode string representing
* the text of the error message.
* @param systemId A const pointer to an Unicode string representing
* the system id of the XML file where this error
* was discovered.
* @param publicId A const pointer to an Unicode string representing
* the public id of the XML file where this error
* was discovered.
* @param lineNum The line number where the error occurred.
* @param colNum The column number where the error occurred.
* @see DOMErrorHandler
*/
virtual void error
(
const unsigned int errCode
, const XMLCh* const msgDomain
, const XMLErrorReporter::ErrTypes errType
, const XMLCh* const errorText
, const XMLCh* const systemId
, const XMLCh* const publicId
, const XMLFileLoc lineNum
, const XMLFileLoc colNum
);
/** Reset any error data before a new parse
*
* This method allows the user installed Error Handler callback to
* 'reset' itself.
*
* <b><font color="#FF0000">This method is a no-op for this DOM
* implementation.</font></b>
*/
virtual void resetErrors();
//@}
// -----------------------------------------------------------------------
// Implementation of the XMLEntityHandler interface.
// -----------------------------------------------------------------------
/** @name Implementation of the XMLEntityHandler interface. */
//@{
/** Handle an end of input source event
*
* This method is used to indicate the end of parsing of an external
* entity file.
*
* <b><font color="#FF0000">This method is a no-op for this DOM
* implementation.</font></b>
*
* @param inputSource A const reference to the InputSource object
* which points to the XML file being parsed.
* @see InputSource
*/
virtual void endInputSource(const InputSource& inputSource);
/** Expand a system id
*
* This method allows an installed XMLEntityHandler to further
* process any system id's of enternal entities encountered in
* the XML file being parsed, such as redirection etc.
*
* <b><font color="#FF0000">This method always returns 'false'
* for this DOM implementation.</font></b>
*
* @param systemId A const pointer to an Unicode string representing
* the system id scanned by the parser.
* @param toFill A pointer to a buffer in which the application
* processed system id is stored.
* @return 'true', if any processing is done, 'false' otherwise.
*/
virtual bool expandSystemId
(
const XMLCh* const systemId
, XMLBuffer& toFill
);
/** Reset any entity handler information
*
* This method allows the installed XMLEntityHandler to reset
* itself.
*
* <b><font color="#FF0000">This method is a no-op for this DOM
* implementation.</font></b>
*/
virtual void resetEntities();
/** Resolve a public/system id
*
* This method allows a user installed entity handler to further
* process any pointers to external entities. The applications can
* implement 'redirection' via this callback.
*
* @param resourceIdentifier An object containing the type of
* resource to be resolved and the associated data members
* corresponding to this type.
* @return The value returned by the user installed resolveEntity
* method or NULL otherwise to indicate no processing was done.
* The returned InputSource is owned by the parser which is
* responsible to clean up the memory.
* @see XMLEntityHandler
* @see XMLEntityResolver
*/
virtual InputSource* resolveEntity
(
XMLResourceIdentifier* resourceIdentifier
);
/** Handle a 'start input source' event
*
* This method is used to indicate the start of parsing an external
* entity file.
*
* <b><font color="#FF0000">This method is a no-op for this DOM parse
* implementation.</font></b>
*
* @param inputSource A const reference to the InputSource object
* which points to the external entity
* being parsed.
*/
virtual void startInputSource(const InputSource& inputSource);
//@}
// -----------------------------------------------------------------------
// Implementation of the XMLDocumentHandler interface.
// -----------------------------------------------------------------------
virtual void docCharacters
(
const XMLCh* const chars
, const XMLSize_t length
, const bool cdataSection
);
virtual void docComment
(
const XMLCh* const comment
);
virtual void docPI
(
const XMLCh* const target
, const XMLCh* const data
);
virtual void endElement
(
const XMLElementDecl& elemDecl
, const unsigned int urlId
, const bool isRoot
, const XMLCh* const elemPrefix
);
virtual void startElement
(
const XMLElementDecl& elemDecl
, const unsigned int urlId
, const XMLCh* const elemPrefix
, const RefVectorOf<XMLAttr>& attrList
, const XMLSize_t attrCount
, const bool isEmpty
, const bool isRoot
);
private :
// -----------------------------------------------------------------------
// Initialize/Cleanup methods
// -----------------------------------------------------------------------
void resetParse();
// -----------------------------------------------------------------------
// Private data members
//
// fEntityResolver
// The installed DOM entity resolver, if any. Null if none.
//
// fXMLEntityResolver
// The installed Xerces entity resolver, if any. Null if none.
//
// fErrorHandler
// The installed DOM error handler, if any. Null if none.
//
// fFilter
// The installed application filter, if any. Null if none.
//
// fCharsetOverridesXMLEncoding
// Indicates if the "charset-overrides-xml-encoding" is set or not
//
// fUserAdoptsDocument
// The DOMDocument ownership has been transferred to application
// If set to true, the parser does not own the document anymore
// and thus will not release its memory.
//
// fSupportedParameters
// A list of the parameters that can be set, including the ones
// specific of Xerces
//
//-----------------------------------------------------------------------
DOMLSResourceResolver* fEntityResolver;
XMLEntityResolver* fXMLEntityResolver;
DOMErrorHandler* fErrorHandler;
DOMLSParserFilter* fFilter;
bool fCharsetOverridesXMLEncoding;
bool fUserAdoptsDocument;
DOMStringListImpl* fSupportedParameters;
// -----------------------------------------------------------------------
// Unimplemented constructors and operators
// -----------------------------------------------------------------------
DOMLSParserImpl(const DOMLSParserImpl &);
DOMLSParserImpl & operator = (const DOMLSParserImpl &);
};
// ---------------------------------------------------------------------------
// DOMLSParserImpl: Handlers for the XMLEntityHandler interface
// ---------------------------------------------------------------------------
inline void DOMLSParserImpl::endInputSource(const InputSource&)
{
// The DOM entity resolver doesn't handle this
}
inline bool DOMLSParserImpl::expandSystemId(const XMLCh* const, XMLBuffer&)
{
// The DOM entity resolver doesn't handle this
return false;
}
inline void DOMLSParserImpl::resetEntities()
{
// Nothing to do on this one
}
inline void DOMLSParserImpl::startInputSource(const InputSource&)
{
// The DOM entity resolver doesn't handle this
}
// ---------------------------------------------------------------------------
// DOMLSParserImpl: Getter methods
// ---------------------------------------------------------------------------
inline DOMConfiguration* DOMLSParserImpl::getDomConfig()
{
return this;
}
inline bool DOMLSParserImpl::getAsync() const
{
// We are a synchronous parser
return false;
}
inline const DOMLSParserFilter* DOMLSParserImpl::getFilter() const
{
return fFilter;
}
XERCES_CPP_NAMESPACE_END
#endif
| {
"content_hash": "c7ab4da19289f830e4e80c83e16e2534",
"timestamp": "",
"source": "github",
"line_count": 660,
"max_line_length": 95,
"avg_line_length": 36.846969696969694,
"alnum_prop": 0.5602204037994983,
"repo_name": "AuditoryBiophysicsLab/EarLab",
"id": "cc72adffade29583bfd101f92c91019cec26474a",
"size": "25121",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/SupportClasses/xercesc/parsers/DOMLSParserImpl.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2897"
},
{
"name": "C",
"bytes": "2948189"
},
{
"name": "C#",
"bytes": "2669637"
},
{
"name": "C++",
"bytes": "13833969"
},
{
"name": "HTML",
"bytes": "100731"
},
{
"name": "Inno Setup",
"bytes": "76845"
},
{
"name": "MATLAB",
"bytes": "155995"
},
{
"name": "Makefile",
"bytes": "414201"
}
],
"symlink_target": ""
} |
<?php
/**
* WP to Twitter Widgets
*
* @category Widgets
* @package WP to Twitter
* @author Joe Dolson
* @license GPLv2 or later
* @link https://www.joedolson.com/wp-to-twitter/
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
require_once( dirname( __FILE__ ) . '/classes/class-wpt-latest-tweets-widget.php' );
require_once( dirname( __FILE__ ) . '/classes/class-wpt-search-tweets-widget.php' );
/**
* Adds links to the contents of a tweet.
* Forked from genesis_tweet_linkify, removed target = _blank
*
* Takes the content of a tweet, detects @replies, #hashtags, and
* http:// links, and links them appropriately.
*
* @since 0.1
*
* @link http://www.snipe.net/2009/09/php-twitter-clickable-links/
*
* @param string $text A string representing the content of a tweet.
* @param array $opts Array of options.
* @param array $tweet Array of Tweet information.
*
* @return string Linkified tweet content
*/
function wpt_tweet_linkify( $text, $opts, $tweet ) {
if ( true == $opts['show_images'] ) {
$media = isset( $tweet['entities']['media'] ) ? $tweet['entities']['media'] : false;
if ( $media ) {
$media_urls = array();
if ( ! empty( $media ) ) {
foreach ( $media as $key => $image ) {
$media_urls[] = $image['url'];
$alt = isset( $tweet['extended_entities']['media'][ $key ]['ext_alt_text'] ) ? $tweet['extended_entities']['media'][ $key ]['ext_alt_text'] : '';
$text .= "<img src='$image[media_url_https]' alt='$alt' class='wpt-twitter-image' />";
}
}
if ( ! empty( $media_urls ) ) {
foreach ( $media_urls as $media_url ) {
$text = str_replace( $media_url, '', $text );
}
}
}
}
$restore = false;
if ( false !== strpos( $text, '…' ) ) {
$text = str_replace( '…', ' ______ ', $text );
$restore = true;
}
$text = ( true == $opts['links'] ) ? preg_replace( '#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#', '\\1<a href="\\2" rel="nofollow">\\2</a>', $text ) : $text;
$text = ( true == $opts['links'] ) ? preg_replace( '#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#', '\\1<a href="http://\\2" rel="nofollow">\\2</a>', $text ) : $text;
$text = ( true == $opts['mentions'] ) ? preg_replace( '/@(\w+)/', '<a href="https://twitter.com/\\1" rel="nofollow">@\\1</a>', $text ) : $text;
$text = ( true == $opts['hashtags'] ) ? preg_replace( '/#(\w+)/', '<a href="https://twitter.com/search?q=%23\\1" rel="nofollow">#\\1</a>', $text ) : $text;
$urls = $tweet['entities']['urls'];
if ( is_array( $urls ) ) {
foreach ( $urls as $url ) {
$text = str_replace( ">$url[url]<", ">$url[display_url]<", $text );
}
}
if ( true == $restore ) {
$text = str_replace( ' ______ ', '…', $text );
}
return $text;
}
/**
* Implement get_tweets
*
* @param int $count How many Tweets.
* @param string $username Username passed.
* @param array $options Widget options.
*
* @return Tweets.
*/
function wpt_get_tweets( $count = 20, $username = false, $options = false ) {
$config['key'] = get_option( 'app_consumer_key' );
$config['secret'] = get_option( 'app_consumer_secret' );
$config['token'] = get_option( 'oauth_token' );
$config['token_secret'] = get_option( 'oauth_token_secret' );
$config['screenname'] = get_option( 'wtt_twitter_username' );
$config['cache_expire'] = intval( apply_filters( 'wpt_cache_expire', 1800 ) );
if ( $config['cache_expire'] < 1 ) {
$config['cache_expire'] = 1800;
}
$config['directory'] = plugin_dir_path( __FILE__ );
$obj = new WPT_TwitterFeed( $config );
$res = $obj->get_tweets( $count, $username, $options );
update_option( 'wpt_tdf_last_error', $obj->st_last_error );
return $res;
}
/**
* Generate relevant classes for a Tweet.
*
* @param array $tweet Tweet info.
*
* @return array classes.
*/
function wpt_generate_classes( $tweet ) {
// take Tweet array and parse selected options into classes.
$classes[] = ( $tweet['favorited'] ) ? 'favorited' : '';
$clasees[] = ( $tweet['retweeted'] ) ? 'retweeted' : '';
$classes[] = ( isset( $tweet['possibly_sensitive'] ) && $tweet['possibly_sensitive'] ) ? 'sensitive' : '';
$classes[] = 'lang-' . $tweet['lang'];
$class = trim( implode( ' ', $classes ) );
return $class;
}
/**
* Get information about user.
*
* @param string $twitter_id Twitter screen name.
*
* @return array
*/
function wpt_get_user( $twitter_id = false ) {
if ( ! $twitter_id ) {
return;
}
$options = array( 'screen_name' => $twitter_id );
$key = get_option( 'app_consumer_key' );
$secret = get_option( 'app_consumer_secret' );
$token = get_option( 'oauth_token' );
$token_secret = get_option( 'oauth_token_secret' );
if ( $key && $secret && $token && $token_secret ) {
$connection = new Wpt_TwitterOAuth( $key, $secret, $token, $token_secret );
$result = $connection->get( "https://api.twitter.com/1.1/users/show.json?screen_name=$twitter_id&include_ext_alt_text=true", $options );
return json_decode( $result );
} else {
return array();
}
}
add_shortcode( 'get_tweets', 'wpt_get_twitter_feed' );
/**
* Get a Twitter Feed.
*
* @param array $atts Display attributes.
* @param string $content Fallback content.
*
* @return Twitter feed.
*/
function wpt_get_twitter_feed( $atts, $content ) {
$atts = shortcode_atts(
array(
'id' => false,
'num' => 10,
'duration' => 1800,
'replies' => 0,
'rts' => 1,
'links' => 1,
'mentions' => 1,
'hashtags' => 0,
'intents' => 1,
'source' => 0,
'show_images' => 1,
'hide_header' => 0,
),
$atts,
'get_tweets'
);
$instance = array(
'twitter_id' => $atts['id'],
'twitter_num' => $atts['num'],
'twitter_duration' => $atts['duration'],
'twitter_hide_replies' => $atts['replies'],
'twitter_include_rts' => $atts['rts'],
'link_links' => $atts['links'],
'link_mentions' => $atts['mentions'],
'link_hashtags' => $atts['hashtags'],
'intents' => $atts['intents'],
'source' => $atts['source'],
'show_images' => $atts['show_images'],
'hide_header' => $atts['hide_header'],
);
return wpt_twitter_feed( $instance );
}
/**
* Get the twitter feed data.
*
* @param array $instance Config for this instance.
*
* @return string.
*/
function wpt_twitter_feed( $instance ) {
$header = '';
if ( ! isset( $instance['search'] ) ) {
$twitter_id = ( isset( $instance['twitter_id'] ) && '' != $instance['twitter_id'] ) ? $instance['twitter_id'] : get_option( 'wtt_twitter_username' );
$user = wpt_get_user( $twitter_id );
if ( empty( $user ) ) {
return __( 'Error: You are not connected to Twitter.', 'wp-to-twitter' );
}
if ( isset( $user->errors ) && $user->errors[0]->message ) {
return __( 'Error:', 'wp-to-twitter' ) . ' ' . $user->errors[0]->message;
}
$avatar = $user->profile_image_url_https;
$name = $user->name;
$verified = sanitize_title( $user->verified );
$img_alignment = ( is_rtl() ) ? 'wpt-right' : 'wpt-left';
$follow_alignment = ( is_rtl() ) ? 'wpt-left' : 'wpt-right';
$follow_url = esc_url( 'https://twitter.com/' . $twitter_id );
$follow_button = apply_filters( 'wpt_follow_button', "<a href='$follow_url' class='twitter-follow-button $follow_alignment' data-width='30px' data-show-screen-name='false' data-size='large' data-show-count='false' data-lang='en'>Follow @" . esc_html( $twitter_id ) . '</a>' );
$header .= '<div class="wpt-header">';
$header .= "<div class='wpt-follow-button'>$follow_button</div>
<p>
<img src='$avatar' alt='' class='wpt-twitter-avatar $img_alignment $verified' />
<span class='wpt-twitter-name'>$name</span><br />
<span class='wpt-twitter-id'><a href='$follow_url'>@" . esc_html( $twitter_id ) . '</a></span>
</p>';
$header .= '</div>';
} else {
$twitter_id = false;
}
$hide_header = ( isset( $instance['hide_header'] ) && 1 == $instance['hide_header'] ) ? true : false;
if ( ! isset( $instance['search'] ) ) {
$options['exclude_replies'] = ( isset( $instance['twitter_hide_replies'] ) ) ? $instance['twitter_hide_replies'] : false;
$options['include_rts'] = $instance['twitter_include_rts'];
} else {
$options['search'] = $instance['search'];
$options['geocode'] = $instance['geocode'];
$options['result_type'] = $instance['result_type'];
}
if ( $hide_header ) {
$header = '';
}
$return = $header . '<ul>' . "\n";
$opts['links'] = $instance['link_links'];
$opts['mentions'] = $instance['link_mentions'];
$opts['hashtags'] = $instance['link_hashtags'];
$opts['show_images'] = isset( $instance['show_images'] ) ? $instance['show_images'] : false;
$rawtweets = wpt_get_tweets( $instance['twitter_num'], $twitter_id, $options );
if ( isset( $rawtweets['error'] ) ) {
$return .= '<li>' . $rawtweets['error'] . '</li>';
} else {
// Build the tweets array.
$tweets = array();
foreach ( $rawtweets as $tweet ) {
if ( is_object( $tweet ) ) {
$tweet = json_decode( json_encode( $tweet ), true );
}
if ( isset( $tweet['retweeted_status']['user']['id_str'] ) ) {
$posted_by = $tweet['retweeted_status']['user']['id_str'];
} elseif ( isset( $tweet['in_reply_to_screen_name'] ) ) {
$posted_by = $tweet['in_reply_to_screen_name'];
} elseif ( isset( $tweet['user']['id_str'] ) ) {
$posted_by = $tweet['user']['id_str'];
} else {
$posted_by = $twitter_id;
}
if ( $instance['source'] ) {
$source = $tweet['source'];
// Translators: 1 - time string, 2 - name of Tweet app, 3 - Link to Tweet.
$timetweet = sprintf( __( '<a href="%3$s">about %1$s ago</a> via %2$s', 'wp-to-twitter' ), human_time_diff( strtotime( $tweet['created_at'] ) ), $source, 'http://twitter.com/' . $posted_by . "/status/$tweet[id_str]" );
} else {
// Translators: 1 - time string; 2 - link to Tweet.
$timetweet = sprintf( __( '<a href="%2$s">about %1$s ago</a>', 'wp-to-twitter' ), human_time_diff( strtotime( $tweet['created_at'] ) ), "http://twitter.com/$posted_by/status/$tweet[id_str]" );
}
$tweet_classes = wpt_generate_classes( $tweet );
$intents = ( $instance['intents'] ) ? "<div class='wpt-intents-border'></div><div class='wpt-intents'><a class='wpt-reply' href='https://twitter.com/intent/tweet?in_reply_to=$tweet[id_str]'><span></span><span class='intent-text reply-text'>Reply</span></a> <a class='wpt-retweet' href='https://twitter.com/intent/retweet?tweet_id=$tweet[id_str]'><span></span><span class='intent-text retweet-text'>Retweet</span></a> <a class='wpt-favorite' href='https://twitter.com/intent/favorite?tweet_id=$tweet[id_str]'><span></span><span class='intent-text favorite-text'>Favorite</span></a></div>" : '';
// Add tweet to array.
$before_tweet = apply_filters( 'wpt_before_tweet', '', $tweet );
$after_tweet = apply_filters( 'wpt_after_tweet', '', $tweet );
$tweets[] = '<li class="' . $tweet_classes . '">' . $before_tweet . wpt_tweet_linkify( $tweet['text'], $opts, $tweet ) . "<br /><span class='wpt-tweet-time'>$timetweet</span> $intents " . $after_tweet . "</li>\n";
}
}
if ( is_array( $tweets ) ) {
foreach ( $tweets as $tweet ) {
$return .= $tweet;
}
}
$return .= '</ul>' . "\n";
return $return;
}
| {
"content_hash": "5c306269ec77cdb461abe932e06302b1",
"timestamp": "",
"source": "github",
"line_count": 304,
"max_line_length": 596,
"avg_line_length": 37.44407894736842,
"alnum_prop": 0.5708512694368796,
"repo_name": "mandino/www.bloggingshakespeare.com",
"id": "5c91dff2639344b8bb38bfc277609fa68d20090f",
"size": "11389",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "reviewing-shakespeare/wp-content/plugins/wp-to-twitter/wpt-widget.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "5211957"
},
{
"name": "CoffeeScript",
"bytes": "552"
},
{
"name": "HTML",
"bytes": "525757"
},
{
"name": "JavaScript",
"bytes": "6055696"
},
{
"name": "Modelica",
"bytes": "10338"
},
{
"name": "PHP",
"bytes": "44197755"
},
{
"name": "Perl",
"bytes": "2554"
},
{
"name": "Ruby",
"bytes": "3917"
},
{
"name": "Smarty",
"bytes": "27821"
},
{
"name": "XSLT",
"bytes": "34552"
}
],
"symlink_target": ""
} |
<?php
return array(
// 'number.decimals_separator' => '',
// 'number.thousands_separator' => '',
'None' => 'Hiçbiri',
'edit' => 'düzenle',
'Edit' => 'Düzenle',
'remove' => 'sil',
'Remove' => 'Sil',
'Update' => 'Güncelle',
'Yes' => 'Evet',
'No' => 'Hayır',
'cancel' => 'İptal',
'or' => 'veya',
'Yellow' => 'Sarı',
'Blue' => 'Mavi',
'Green' => 'Yeşil',
'Purple' => 'Mor',
'Red' => 'Kırmızı',
'Orange' => 'Turuncu',
'Grey' => 'Gri',
// 'Brown' => '',
// 'Deep Orange' => '',
// 'Dark Grey' => '',
// 'Pink' => '',
// 'Teal' => '',
// 'Cyan' => '',
// 'Lime' => '',
// 'Light Green' => '',
// 'Amber' => '',
'Save' => 'Kaydet',
'Login' => 'Giriş',
'Official website:' => 'Resmi internet sitesi:',
'Unassigned' => 'Atanmamış',
'View this task' => 'Bu görevi görüntüle',
'Remove user' => 'Kullanıcıyı kaldır',
'Do you really want to remove this user: "%s"?' => 'Bu kullanıcıyı gerçekten silmek istiyor musunuz: "%s"?',
'New user' => 'Yeni kullanıcı',
'All users' => 'Tüm kullanıcılar',
'Username' => 'Kullanıcı adı',
'Password' => 'Şifre',
'Administrator' => 'Yönetici',
'Sign in' => 'Giriş yap',
'Users' => 'Kullanıcılar',
'No user' => 'Kullanıcı yok',
'Forbidden' => 'Yasak',
'Access Forbidden' => 'Erişim yasak',
'Edit user' => 'Kullanıcıyı düzenle',
'Logout' => 'Çıkış yap',
'Bad username or password' => 'Hatalı kullanıcı adı veya şifre',
'Edit project' => 'Projeyi düzenle',
'Name' => 'İsim',
'Projects' => 'Projeler',
'No project' => 'Proje yok',
'Project' => 'Proje',
'Status' => 'Durum',
'Tasks' => 'Görevler',
'Board' => 'Tablo',
'Actions' => 'İşlemler',
'Inactive' => 'Aktif değil',
'Active' => 'Aktif',
'Add this column' => 'Bu sütunu ekle',
'%d tasks on the board' => '%d görev bu tabloda',
'%d tasks in total' => '%d görev toplam',
'Unable to update this board.' => 'Bu tablo güncellenemiyor.',
'Edit board' => 'Tabloyu düzenle',
'Disable' => 'Devre dışı bırak',
'Enable' => 'Etkinleştir',
'New project' => 'Yeni proje',
'Do you really want to remove this project: "%s"?' => 'Bu projeyi gerçekten silmek istiyor musunuz: "%s"?',
'Remove project' => 'Projeyi sil',
'Edit the board for "%s"' => 'Tabloyu "%s" için güncelle',
'All projects' => 'Tüm projeler',
'Change columns' => 'Sütunları değiştir',
'Add a new column' => 'Yeni sütun ekle',
'Title' => 'Başlık',
'Nobody assigned' => 'Kullanıcı atanmamış',
'Assigned to %s' => '%s kullanıcısına atanmış',
'Remove a column' => 'Bir sütunu sil',
'Remove a column from a board' => 'Tablodan bir sütunu sil',
'Unable to remove this column.' => 'Bu sütun silinemiyor.',
'Do you really want to remove this column: "%s"?' => 'Bu sütunu gerçekten silmek istiyor musunuz: "%s"?',
'This action will REMOVE ALL TASKS associated to this column!' => 'Bu komut sütun içindeki TÜM GÖREVLERİ silecek!',
'Settings' => 'Ayarlar',
'Application settings' => 'Uygulama ayarları',
'Language' => 'Dil',
// 'Webhook token:' => '',
'API token:' => 'API Token:',
'Database size:' => 'Veritabanı boyutu :',
'Download the database' => 'Veritabanını indir',
'Optimize the database' => 'Veritabanını optimize et',
'(VACUUM command)' => '(VACUUM komutu)',
'(Gzip compressed Sqlite file)' => '(Gzip ile sıkıştırılmış Sqlite dosyası)',
'Close a task' => 'Bir görevi kapat',
'Edit a task' => 'Bir görevi düzenle',
'Column' => 'Sütun',
'Color' => 'Renk',
'Assignee' => 'Atanan',
'Create another task' => 'Başka bir görev oluştur',
'New task' => 'Nouvelle tâche',
'Open a task' => 'Bir görevi aç',
'Do you really want to open this task: "%s"?' => 'Bu görevi gerçekten açmak istiyor musunuz: "%s"?',
'Back to the board' => 'Tabloya dön',
// 'Created on %B %e, %Y at %k:%M %p' => '',
'There is nobody assigned' => 'Kimse atanmamış',
'Column on the board:' => 'Tablodaki sütun:',
'Status is open' => 'Açık durumda',
'Status is closed' => 'Kapalı durumda',
'Close this task' => 'Görevi kapat',
'Open this task' => 'Görevi aç',
'There is no description.' => 'Açıklama yok.',
'Add a new task' => 'Yeni görev ekle',
'The username is required' => 'Kullanıcı adı gerekli',
'The maximum length is %d characters' => 'Maksimum uzunluk %d karakterdir',
'The minimum length is %d characters' => 'Minimum uzunluk %d karakterdir',
'The password is required' => 'Şifre gerekli',
'This value must be an integer' => 'Bu değer bir rakam olmak zorunda',
'The username must be unique' => 'Kullanıcı adı daha önceden var',
'The user id is required' => 'Kullanıcı kodu gerekli',
'Passwords don\'t match' => 'Şifreler uyuşmuyor',
'The confirmation is required' => 'Onay gerekli',
'The project is required' => 'Proje gerekli',
'The id is required' => 'Kod gerekli',
'The project id is required' => 'Proje kodu gerekli',
'The project name is required' => 'Proje adı gerekli',
'This project must be unique' => 'Bu projenin tekil olması gerekli',
'The title is required' => 'Başlık gerekli',
'Settings saved successfully.' => 'Ayarlar başarıyla kaydedildi.',
'Unable to save your settings.' => 'Ayarlarınız kaydedilemedi.',
'Database optimization done.' => 'Veritabanı optimizasyonu tamamlandı.',
'Your project have been created successfully.' => 'Projeniz başarıyla oluşturuldu.',
'Unable to create your project.' => 'Proje oluşturulamadı.',
'Project updated successfully.' => 'Proje başarıyla güncellendi.',
'Unable to update this project.' => 'Bu proje güncellenemedi.',
'Unable to remove this project.' => 'Bu proje silinemedi.',
'Project removed successfully.' => 'Proje başarıyla silindi.',
'Project activated successfully.' => 'Proje başarıyla aktive edildi.',
'Unable to activate this project.' => 'Bu proje aktive edilemedi.',
'Project disabled successfully.' => 'Proje devre dışı bırakıldı.',
'Unable to disable this project.' => 'Bu proje devre dışı bırakılamadı.',
'Unable to open this task.' => 'Bu görev açılamıyor.',
'Task opened successfully.' => 'Görev başarıyla açıldı.',
'Unable to close this task.' => 'Bu görev kapatılamıyor.',
'Task closed successfully.' => 'Görev başarıyla kapatıldı.',
'Unable to update your task.' => 'Görev güncellenemiyor.',
'Task updated successfully.' => 'Görev başarıyla güncellendi.',
'Unable to create your task.' => 'Görev oluşturulamadı.',
'Task created successfully.' => 'Görev başarıyla oluşturuldu.',
'User created successfully.' => 'Kullanıcı başarıyla oluşturuldu',
'Unable to create your user.' => 'Kullanıcı oluşturulamıyor.',
'User updated successfully.' => 'Kullanıcı başarıyla güncellendi.',
'Unable to update your user.' => 'Kullanıcı güncellenemiyor.',
'User removed successfully.' => 'Kullanıcı silindi.',
'Unable to remove this user.' => 'Bu kullanıcı silinemiyor.',
'Board updated successfully.' => 'Tablo başarıyla güncellendi.',
'Ready' => 'Hazır',
'Backlog' => 'Bekleme listesi',
'Work in progress' => 'İşlemde',
'Done' => 'Tamamlandı',
'Application version:' => 'Uygulama versiyonu:',
// 'Completed on %B %e, %Y at %k:%M %p' => '',
// '%B %e, %Y at %k:%M %p' => '',
'Date created' => 'Oluşturulma tarihi',
'Date completed' => 'Tamamlanma tarihi',
'Id' => 'Kod',
'%d closed tasks' => '%d kapatılmış görevler',
// 'No task for this project' => '',
'Public link' => 'Dışa açık link',
'Change assignee' => 'Atanmış Kullanıcıyı değiştir',
'Change assignee for the task "%s"' => '"%s" görevi için atanmış kullanıcıyı değiştir',
'Timezone' => 'Saat dilimi',
// 'Sorry, I didn\'t find this information in my database!' => '',
'Page not found' => 'Sayfa bulunamadı',
'Complexity' => 'Zorluk seviyesi',
'Task limit' => 'Görev limiti',
'Task count' => 'Görev sayısı',
'Edit project access list' => 'Proje erişim listesini düzenle',
'Allow this user' => 'Bu kullanıcıya izin ver',
'Don\'t forget that administrators have access to everything.' => 'Dikkat: Yöneticilerin herşeye erişimi olduğunu unutmayın!',
'Revoke' => 'Iptal et',
'List of authorized users' => 'Yetkili kullanıcıların listesi',
'User' => 'Kullanıcı',
'Nobody have access to this project.' => 'Bu projeye kimsenin erişimi yok.',
'Comments' => 'Yorumlar',
'Write your text in Markdown' => 'Yazınızı Markdown ile yazın',
'Leave a comment' => 'Bir yorum ekle',
'Comment is required' => 'Yorum gerekli',
'Leave a description' => 'Açıklama ekleyin',
'Comment added successfully.' => 'Yorum eklendi',
'Unable to create your comment.' => 'Yorumunuz oluşturulamadı',
'Edit this task' => 'Bu görevi değiştir',
'Due Date' => 'Termin',
'Invalid date' => 'Geçersiz tarihi',
// 'Must be done before %B %e, %Y' => '',
'%B %e, %Y' => '%d %B %Y',
'%b %e, %Y' => '%d/%m/%Y',
'Automatic actions' => 'Otomatik işlemler',
'Your automatic action have been created successfully.' => 'Otomatik işlem başarıyla oluşturuldu',
'Unable to create your automatic action.' => 'Otomatik işleminiz oluşturulamadı',
'Remove an action' => 'Bir işlemi sil',
'Unable to remove this action.' => 'Bu işlem silinemedi',
'Action removed successfully.' => 'İşlem başarıyla silindi',
'Automatic actions for the project "%s"' => '"%s" projesi için otomatik işlemler',
'Defined actions' => 'Tanımlanan işlemler',
'Add an action' => 'İşlem ekle',
'Event name' => 'Durum adı',
'Action name' => 'İşlem adı',
'Action parameters' => 'İşlem parametreleri',
'Action' => 'İşlem',
'Event' => 'Durum',
'When the selected event occurs execute the corresponding action.' => 'Seçilen durum oluştuğunda ilgili eylemi gerçekleştir.',
'Next step' => 'Sonraki adım',
'Define action parameters' => 'İşlem parametrelerini düzenle',
'Save this action' => 'Bu işlemi kaydet',
'Do you really want to remove this action: "%s"?' => 'Bu işlemi silmek istediğinize emin misiniz: "%s"?',
'Remove an automatic action' => 'Bir otomatik işlemi sil',
'Assign the task to a specific user' => 'Görevi bir kullanıcıya ata',
'Assign the task to the person who does the action' => 'Görevi, işlemi gerçekleştiren kullanıcıya ata',
'Duplicate the task to another project' => 'Görevi bir başka projeye kopyala',
'Move a task to another column' => 'Bir görevi başka bir sütuna taşı',
'Task modification' => 'Görev düzenleme',
'Task creation' => 'Görev oluşturma',
'Closing a task' => 'Bir görev kapatılıyor',
'Assign a color to a specific user' => 'Bir kullanıcıya renk tanımla',
'Column title' => 'Sütun başlığı',
'Position' => 'Pozisyon',
'Move Up' => 'Yukarı taşı',
'Move Down' => 'Aşağı taşı',
'Duplicate to another project' => 'Başka bir projeye kopyala',
'Duplicate' => 'Kopya oluştur',
'link' => 'link',
'Comment updated successfully.' => 'Yorum güncellendi.',
'Unable to update your comment.' => 'Yorum güncellenemedi.',
'Remove a comment' => 'Bir yorumu sil',
'Comment removed successfully.' => 'Yorum silindi.',
'Unable to remove this comment.' => 'Bu yorum silinemiyor.',
'Do you really want to remove this comment?' => 'Bu yorumu silmek istediğinize emin misiniz?',
'Only administrators or the creator of the comment can access to this page.' => 'Bu sayfaya yalnızca yorum sahibi ve yöneticiler erişebilir.',
'Current password for the user "%s"' => 'Kullanıcı için mevcut şifre "%s"',
'The current password is required' => 'Mevcut şifre gerekli',
'Wrong password' => 'Yanlış Şifre',
'Unknown' => 'Bilinmeyen',
'Last logins' => 'Son kullanıcı girişleri',
'Login date' => 'Giriş tarihi',
'Authentication method' => 'Doğrulama yöntemi',
'IP address' => 'IP adresi',
'User agent' => 'Kullanıcı sistemi',
'Persistent connections' => 'Kalıcı bağlantılar',
// 'No session.' => '',
'Expiration date' => 'Geçerlilik sonu',
'Remember Me' => 'Beni hatırla',
'Creation date' => 'Oluşturulma tarihi',
'Everybody' => 'Herkes',
'Open' => 'Açık',
'Closed' => 'Kapalı',
'Search' => 'Ara',
'Nothing found.' => 'Hiçbir şey bulunamadı',
'Due date' => 'Termin',
'Others formats accepted: %s and %s' => 'Diğer kabul edilen formatlar: %s ve %s',
'Description' => 'Açıklama',
'%d comments' => '%d yorumlar',
'%d comment' => '%d yorum',
'Email address invalid' => 'E-Posta adresi geçersiz',
// 'Your external account is not linked anymore to your profile.' => '',
// 'Unable to unlink your external account.' => '',
// 'External authentication failed' => '',
// 'Your external account is linked to your profile successfully.' => '',
'Email' => 'E-Posta',
'Link my Google Account' => 'Google hesabımla bağ oluştur',
'Unlink my Google Account' => 'Google hesabımla bağı kaldır',
'Login with my Google Account' => 'Google hesabımla giriş yap',
'Project not found.' => 'Proje bulunamadı',
'Task removed successfully.' => 'Görev silindi',
'Unable to remove this task.' => 'Görev silinemiyor',
'Remove a task' => 'Bir görevi sil',
'Do you really want to remove this task: "%s"?' => 'Bu görevi silmek istediğinize emin misiniz: "%s"?',
'Assign automatically a color based on a category' => 'Kategoriye göre otomatik renk ata',
'Assign automatically a category based on a color' => 'Rengine göre otomatik kategori ata',
'Task creation or modification' => 'Görev oluşturma veya değiştirme',
'Category' => 'Kategori',
'Category:' => 'Kategori:',
'Categories' => 'Kategoriler',
'Category not found.' => 'Kategori bulunamadı',
'Your category have been created successfully.' => 'Kategori oluşturuldu',
'Unable to create your category.' => 'Kategori oluşturulamadı',
'Your category have been updated successfully.' => 'Kategori başarıyla güncellendi',
'Unable to update your category.' => 'Kategori güncellenemedi',
'Remove a category' => 'Bir kategoriyi sil',
'Category removed successfully.' => 'Kategori silindi',
'Unable to remove this category.' => 'Bu kategori silinemedi',
'Category modification for the project "%s"' => '"%s" projesi için kategori değiştirme',
'Category Name' => 'Kategori adı',
'Add a new category' => 'Yeni kategori ekle',
'Do you really want to remove this category: "%s"?' => 'Bu kategoriyi silmek istediğinize emin misiniz: "%s"?',
'All categories' => 'Tüm kategoriler',
'No category' => 'Kategori Yok',
'The name is required' => 'İsim gerekli',
'Remove a file' => 'Dosya sil',
'Unable to remove this file.' => 'Dosya silinemedi',
'File removed successfully.' => 'Dosya silindi',
'Attach a document' => 'Dosya ekle',
'Do you really want to remove this file: "%s"?' => 'Bu dosyayı silmek istediğinize emin misiniz: "%s"?',
'Attachments' => 'Ekler',
'Edit the task' => 'Görevi değiştir',
'Edit the description' => 'Açıklamayı değiştir',
'Add a comment' => 'Yorum ekle',
'Edit a comment' => 'Yorum değiştir',
'Summary' => 'Özet',
'Time tracking' => 'Zaman takibi',
'Estimate:' => 'Tahmini:',
'Spent:' => 'Harcanan:',
'Do you really want to remove this sub-task?' => 'Bu alt görevi silmek istediğinize emin misiniz',
'Remaining:' => 'Kalan',
'hours' => 'saat',
'spent' => 'harcanan',
'estimated' => 'tahmini',
'Sub-Tasks' => 'Alt Görev',
'Add a sub-task' => 'Alt görev ekle',
// 'Original estimate' => '',
'Create another sub-task' => 'Başka bir alt görev daha oluştur',
// 'Time spent' => '',
'Edit a sub-task' => 'Alt görev düzenle',
'Remove a sub-task' => 'Alt görev sil',
'The time must be a numeric value' => 'Zaman alfanumerik bir değer olmalı',
'Todo' => 'Yapılacaklar',
'In progress' => 'İşlemde',
'Sub-task removed successfully.' => 'Alt görev silindi',
'Unable to remove this sub-task.' => 'Alt görev silinemedi',
'Sub-task updated successfully.' => 'Alt görev güncellendi',
'Unable to update your sub-task.' => 'Alt görev güncellenemiyor',
'Unable to create your sub-task.' => 'Alt görev oluşturulamadı',
'Sub-task added successfully.' => 'Alt görev başarıyla eklendii',
'Maximum size: ' => 'Maksimum boyutu',
'Unable to upload the file.' => 'Karşıya yükleme başarısız',
'Display another project' => 'Başka bir proje göster',
// 'Login with my Github Account' => '',
// 'Link my Github Account' => '',
// 'Unlink my Github Account' => '',
'Created by %s' => '%s tarafından oluşturuldu',
'Last modified on %B %e, %Y at %k:%M %p' => 'Son değişiklik tarihi %d.%m.%Y, saati %H:%M',
'Tasks Export' => 'Görevleri dışa aktar',
'Tasks exportation for "%s"' => '"%s" için görevleri dışa aktar',
'Start Date' => 'Başlangıç tarihi',
'End Date' => 'Bitiş tarihi',
'Execute' => 'Gerçekleştir',
'Task Id' => 'Görev No',
'Creator' => 'Oluşturan',
'Modification date' => 'Değişiklik tarihi',
'Completion date' => 'Tamamlanma tarihi',
'Clone' => 'Kopya oluştur',
'Project cloned successfully.' => 'Proje kopyası başarıyla oluşturuldu.',
'Unable to clone this project.' => 'Proje kopyası oluşturulamadı.',
'Enable email notifications' => 'E-Posta bilgilendirmesini aç',
'Task position:' => 'Görev pozisyonu',
'The task #%d have been opened.' => '#%d numaralı görev açıldı.',
'The task #%d have been closed.' => '#%d numaralı görev kapatıldı.',
'Sub-task updated' => 'Alt görev güncellendi',
'Title:' => 'Başlık',
'Status:' => 'Durum',
'Assignee:' => 'Sorumlu:',
'Time tracking:' => 'Zaman takibi',
'New sub-task' => 'Yeni alt görev',
'New attachment added "%s"' => 'Yeni dosya "%s" eklendi.',
'Comment updated' => 'Yorum güncellendi',
'New comment posted by %s' => '%s tarafından yeni yorum eklendi',
'New attachment' => 'Yeni dosya eki',
'New comment' => 'Yeni yorum',
'New subtask' => 'Yeni alt görev',
'Subtask updated' => 'Alt görev güncellendi',
'Task updated' => 'Görev güncellendi',
'Task closed' => 'Görev kapatıldı',
'Task opened' => 'Görev açıldı',
'I want to receive notifications only for those projects:' => 'Yalnızca bu projelerle ilgili bildirim almak istiyorum:',
'view the task on Kanboard' => 'bu görevi Kanboard\'da göster',
'Public access' => 'Dışa açık erişim',
'User management' => 'Kullanıcı yönetimi',
'Active tasks' => 'Aktif görevler',
'Disable public access' => 'Dışa açık erişimi kapat',
'Enable public access' => 'Dışa açık erişimi aç',
'Public access disabled' => 'Dışa açık erişim kapatıldı',
'Do you really want to disable this project: "%s"?' => 'Bu projeyi devre dışı bırakmak istediğinize emin misiniz?: "%s"',
'Do you really want to enable this project: "%s"?' => 'Bu projeyi aktive etmek istediğinize emin misiniz?: "%s"',
'Project activation' => 'Proje aktivasyonu',
'Move the task to another project' => 'Görevi başka projeye taşı',
'Move to another project' => 'Başka projeye taşı',
'Do you really want to duplicate this task?' => 'Bu görevin kopyasını oluşturmak istediğinize emin misiniz?',
'Duplicate a task' => 'Görevin kopyasını oluştur',
'External accounts' => 'Dış hesaplar',
'Account type' => 'Hesap türü',
'Local' => 'Yerel',
'Remote' => 'Uzak',
'Enabled' => 'Etkinleştirildi',
'Disabled' => 'Devre dışı bırakıldı',
'Username:' => 'Kullanıcı adı',
'Name:' => 'Ad',
'Email:' => 'E-Posta',
'Notifications:' => 'Bildirimler:',
'Notifications' => 'Bildirimler',
'Group:' => 'Grup',
'Regular user' => 'Varsayılan kullanıcı',
'Account type:' => 'Hesap türü:',
'Edit profile' => 'Profili değiştir',
'Change password' => 'Şifre değiştir',
'Password modification' => 'Şifre değişimi',
'External authentications' => 'Dış kimlik doğrulamaları',
'Google Account' => 'Google hesabı',
'Github Account' => 'Github hesabı',
'Never connected.' => 'Hiç bağlanmamış.',
'No account linked.' => 'Bağlanmış hesap yok.',
'Account linked.' => 'Hesap bağlandı',
'No external authentication enabled.' => 'Dış kimlik doğrulama kapalı.',
'Password modified successfully.' => 'Şifre başarıyla değiştirildi.',
'Unable to change the password.' => 'Şifre değiştirilemedi.',
'Change category for the task "%s"' => '"%s" görevi için kategori değiştirme',
'Change category' => 'Kategori değiştirme',
'%s updated the task %s' => '%s kullanıcısı %s görevini güncelledi',
'%s opened the task %s' => '%s kullanıcısı %s görevini açtı',
'%s moved the task %s to the position #%d in the column "%s"' => '%s kullanıcısı %s görevini #%d pozisyonu "%s" sütununa taşıdı',
'%s moved the task %s to the column "%s"' => '%s kullanıcısı %s görevini "%s" sütununa taşıdı',
'%s created the task %s' => '%s kullanıcısı %s görevini oluşturdu',
'%s closed the task %s' => '%s kullanıcısı %s görevini kapattı',
'%s created a subtask for the task %s' => '%s kullanıcısı %s görevi için bir alt görev oluşturdu',
'%s updated a subtask for the task %s' => '%s kullanıcısı %s görevinin bir alt görevini güncelledi',
'Assigned to %s with an estimate of %s/%sh' => '%s kullanıcısına tahmini %s/%s saat tamamlanma süresi ile atanmış',
'Not assigned, estimate of %sh' => 'Kimseye atanmamış, tahmini süre %s saat',
'%s updated a comment on the task %s' => '%s kullanıcısı %s görevinde bir yorumu güncelledi',
'%s commented the task %s' => '%s kullanıcısı %s görevine yorum ekledi',
'%s\'s activity' => '%s\'in aktivitesi',
'RSS feed' => 'RSS kaynağı',
'%s updated a comment on the task #%d' => '%s kullanıcısı #%d nolu görevde bir yorumu güncelledi',
'%s commented on the task #%d' => '%s kullanıcısı #%d nolu göreve yorum ekledi',
'%s updated a subtask for the task #%d' => '%s kullanıcısı #%d nolu görevin bir alt görevini güncelledi',
'%s created a subtask for the task #%d' => '%s kullanıcısı #%d nolu göreve bir alt görev ekledi',
'%s updated the task #%d' => '%s kullanıcısı #%d nolu görevi güncelledi',
'%s created the task #%d' => '%s kullanıcısı #%d nolu görevi oluşturdu',
'%s closed the task #%d' => '%s kullanıcısı #%d nolu görevi kapattı',
'%s open the task #%d' => '%s kullanıcısı #%d nolu görevi açtı',
'%s moved the task #%d to the column "%s"' => '%s kullanıcısı #%d nolu görevi "%s" sütununa taşıdı',
'%s moved the task #%d to the position %d in the column "%s"' => '%s kullanıcısı #%d nolu görevi %d pozisyonu "%s" sütununa taşıdı',
'Activity' => 'Aktivite',
'Default values are "%s"' => 'Varsayılan değerler "%s"',
'Default columns for new projects (Comma-separated)' => 'Yeni projeler için varsayılan sütunlar (virgül ile ayrılmış)',
'Task assignee change' => 'Göreve atanan kullanıcı değişikliği',
'%s change the assignee of the task #%d to %s' => '%s kullanıcısı #%d nolu görevin sorumlusunu %s olarak değiştirdi',
'%s changed the assignee of the task %s to %s' => '%s kullanıcısı %s görevinin sorumlusunu %s olarak değiştirdi',
'New password for the user "%s"' => '"%s" kullanıcısı için yeni şifre',
'Choose an event' => 'Bir durum seçin',
// 'Github commit received' => '',
// 'Github issue opened' => '',
// 'Github issue closed' => '',
// 'Github issue reopened' => '',
// 'Github issue assignee change' => '',
// 'Github issue label change' => '',
'Create a task from an external provider' => 'Dış sağlayıcı ile bir görev oluştur',
'Change the assignee based on an external username' => 'Dış kaynaklı kullanıcı adı ile göreve atananı değiştir',
'Change the category based on an external label' => 'Dış kaynaklı bir etiket ile kategori değiştir',
'Reference' => 'Referans',
'Reference: %s' => 'Referans: %s',
'Label' => 'Etiket',
'Database' => 'Veri bankası',
'About' => 'Hakkında',
'Database driver:' => 'Veri bankası sürücüsü',
'Board settings' => 'Tablo ayarları',
'URL and token' => 'URL veya Token',
'Webhook settings' => 'Webhook ayarları',
'URL for task creation:' => 'Görev oluşturma için URL',
'Reset token' => 'Reset Token',
'API endpoint:' => 'API endpoint',
'Refresh interval for private board' => 'Özel tablolar için yenileme sıklığı',
'Refresh interval for public board' => 'Dışa açık tablolar için yenileme sıklığı',
'Task highlight period' => 'Görevi öne çıkarma süresi',
'Period (in second) to consider a task was modified recently (0 to disable, 2 days by default)' => 'Bir görevin yeni değiştirilmiş sayılması için süre (saniye olarak) (Bu özelliği iptal etmek için 0, varsayılan değer 2 gün)',
'Frequency in second (60 seconds by default)' => 'Saniye olarak frekans (varsayılan 60 saniye)',
'Frequency in second (0 to disable this feature, 10 seconds by default)' => 'Saniye olarak frekans (Bu özelliği iptal etmek için 0, varsayılan değer 10 saniye)',
'Application URL' => 'Uygulama URL',
'Example: http://example.kanboard.net/ (used by email notifications)' => 'Örneğin: http://example.kanboard.net/ (E-posta bildirimleri için kullanılıyor)',
'Token regenerated.' => 'Token yeniden oluşturuldu.',
'Date format' => 'Tarih formatı',
'ISO format is always accepted, example: "%s" and "%s"' => 'ISO formatı her zaman kabul edilir, örneğin: "%s" ve "%s"',
'New private project' => 'Yeni özel proje',
'This project is private' => 'Bu proje özel',
'Type here to create a new sub-task' => 'Yeni bir alt görev oluşturmak için buraya yazın',
'Add' => 'Ekle',
'Estimated time: %s hours' => 'Tahmini süre: %s Saat',
'Time spent: %s hours' => 'Kullanılan süre: %s Saat',
'Started on %B %e, %Y' => '%B %e %Y tarihinde başlatıldı',
'Start date' => 'Başlangıç tarihi',
'Time estimated' => 'Tahmini süre',
'There is nothing assigned to you.' => 'Size atanan hiçbir şey yok.',
'My tasks' => 'Görevlerim',
'Activity stream' => 'Güncel olay akışı',
'Dashboard' => 'Anasayfa',
'Confirmation' => 'Onay',
'Allow everybody to access to this project' => 'Bu projeye herkesin erişimine izin ver',
'Everybody have access to this project.' => 'Bu projeye herkesin erişimi var.',
'Webhooks' => 'Webhooks',
'API' => 'API',
'Github webhooks' => 'Github Webhook',
'Help on Github webhooks' => 'Github Webhooks hakkında yardım',
'Create a comment from an external provider' => 'Dış sağlayıcı ile bir yorum oluştur',
'Github issue comment created' => 'Github hata yorumu oluşturuldu',
'Project management' => 'Proje yönetimi',
'My projects' => 'Projelerim',
'Columns' => 'Sütunlar',
'Task' => 'Görev',
'Your are not member of any project.' => 'Hiç bir projenin üyesi değilsiniz.',
'Percentage' => 'Yüzde',
'Number of tasks' => 'Görev sayısı',
'Task distribution' => 'Görev dağılımı',
'Reportings' => 'Raporlar',
'Task repartition for "%s"' => '"%s" için görev dağılımı',
'Analytics' => 'Analiz',
'Subtask' => 'Alt görev',
'My subtasks' => 'Alt görevlerim',
'User repartition' => 'Kullanıcı dağılımı',
'User repartition for "%s"' => '"%s" için kullanıcı dağılımı',
'Clone this project' => 'Projenin kopyasını oluştur',
'Column removed successfully.' => 'Sütun başarıyla kaldırıldı.',
'Github Issue' => 'Github Issue',
'Not enough data to show the graph.' => 'Grafik gösterimi için yeterli veri yok.',
'Previous' => 'Önceki',
'The id must be an integer' => 'ID bir tamsayı olmalı',
'The project id must be an integer' => 'Proje numarası bir tam sayı olmalı',
'The status must be an integer' => 'Durum bir tam sayı olmalı',
'The subtask id is required' => 'Alt görev numarası gerekli',
'The subtask id must be an integer' => 'Alt görev numarası bir tam sayı olmalı',
'The task id is required' => 'Görev numarası gerekli',
'The task id must be an integer' => 'Görev numarası bir tam sayı olmalı',
'The user id must be an integer' => 'Kullanıcı numarası bir tam sayı olmalı',
'This value is required' => 'Bu değer gerekli',
'This value must be numeric' => 'Bu değer sayı olmalı',
'Unable to create this task.' => 'Bu görev oluşturulamıyor.',
'Cumulative flow diagram' => 'Kümülatif akış diyagramı',
'Cumulative flow diagram for "%s"' => '"%s" için kümülatif akış diyagramı',
'Daily project summary' => 'Günlük proje özeti',
'Daily project summary export' => 'Günlük proje özetini dışa aktar',
'Daily project summary export for "%s"' => '"%s" için günlük proje özetinin dışa',
'Exports' => 'Dışa aktarımlar',
'This export contains the number of tasks per column grouped per day.' => 'Bu dışa aktarım günlük gruplanmış olarak her sütundaki görev sayısını içerir.',
'Nothing to preview...' => 'Önizleme yapılacak bir şey yok ...',
'Preview' => 'Önizleme',
'Write' => 'Değiştir',
'Active swimlanes' => 'Aktif Kulvar',
'Add a new swimlane' => 'Yeni bir Kulvar ekle',
'Change default swimlane' => 'Varsayılan Kulvarı değiştir',
'Default swimlane' => 'Varsayılan Kulvar',
'Do you really want to remove this swimlane: "%s"?' => 'Bu Kulvarı silmek istediğinize emin misiniz?: "%s"?',
'Inactive swimlanes' => 'Pasif Kulvarlar',
'Set project manager' => 'Proje yöneticisi olarak ata',
'Set project member' => 'Proje üyesi olarak ata',
'Remove a swimlane' => 'Kulvarı sil',
'Rename' => 'Yeniden adlandır',
'Show default swimlane' => 'Varsayılan Kulvarı göster',
'Swimlane modification for the project "%s"' => '"%s" Projesi için Kulvar değişikliği',
'Swimlane not found.' => 'Kulvar bulunamadı',
'Swimlane removed successfully.' => 'Kulvar başarıyla kaldırıldı.',
'Swimlanes' => 'Kulvarlar',
'Swimlane updated successfully.' => 'Kulvar başarıyla güncellendi.',
'The default swimlane have been updated successfully.' => 'Varsayılan Kulvarlar başarıyla güncellendi.',
'Unable to create your swimlane.' => 'Bu Kulvarı oluşturmak mümkün değil.',
'Unable to remove this swimlane.' => 'Bu Kulvarı silmek mümkün değil.',
'Unable to update this swimlane.' => 'Bu Kulvarı değiştirmek mümkün değil.',
'Your swimlane have been created successfully.' => 'Kulvar başarıyla oluşturuldu.',
'Example: "Bug, Feature Request, Improvement"' => 'Örnek: "Sorun, Özellik talebi, İyileştirme"',
'Default categories for new projects (Comma-separated)' => 'Yeni projeler için varsayılan kategoriler (Virgül ile ayrılmış)',
// 'Gitlab commit received' => '',
// 'Gitlab issue opened' => '',
// 'Gitlab issue closed' => '',
// 'Gitlab webhooks' => '',
// 'Help on Gitlab webhooks' => '',
'Integrations' => 'Entegrasyon',
'Integration with third-party services' => 'Dış servislerle entegrasyon',
'Role for this project' => 'Bu proje için rol',
'Project manager' => 'Proje Yöneticisi',
'Project member' => 'Proje Üyesi',
'A project manager can change the settings of the project and have more privileges than a standard user.' => 'Bir Proje Yöneticisi proje ayarlarını değiştirebilir ve bir üyeden daha fazla yetkiye sahiptir.',
// 'Gitlab Issue' => '',
'Subtask Id' => 'Alt görev No:',
'Subtasks' => 'Alt görevler',
'Subtasks Export' => 'Alt görevleri dışa aktar',
'Subtasks exportation for "%s"' => '"%s" için alt görevleri dışa aktarımı',
'Task Title' => 'Görev Başlığı',
'Untitled' => 'Başlıksız',
'Application default' => 'Uygulama varsayılanları',
'Language:' => 'Dil:',
'Timezone:' => 'Saat dilimi:',
'All columns' => 'Tüm sütunlar',
'Calendar' => 'Takvim',
'Next' => 'Sonraki',
'#%d' => '#%d',
'All swimlanes' => 'Tüm Kulvarlar',
'All colors' => 'Tüm Renkler',
'Moved to column %s' => '%s Sütununa taşındı',
'Change description' => 'Açıklamayı değiştir',
'User dashboard' => 'Kullanıcı Anasayfası',
'Allow only one subtask in progress at the same time for a user' => 'Bir kullanıcı için aynı anda yalnızca bir alt göreve izin ver',
'Edit column "%s"' => '"%s" sütununu değiştir',
'Select the new status of the subtask: "%s"' => '"%s" alt görevi için yeni durum seçin.',
'Subtask timesheet' => 'Alt görev için zaman takip tablosu',
'There is nothing to show.' => 'Gösterilecek hiçbir şey yok.',
'Time Tracking' => 'Zaman takibi',
'You already have one subtask in progress' => 'Zaten işlemde olan bir alt görev var',
'Which parts of the project do you want to duplicate?' => 'Projenin hangi kısımlarının kopyasını oluşturmak istiyorsunuz?',
// 'Disallow login form' => '',
'Bitbucket commit received' => 'Bitbucket commit alındı',
'Bitbucket webhooks' => 'Bitbucket webhooks',
'Help on Bitbucket webhooks' => 'Bitbucket webhooks için yardım',
'Start' => 'Başlangıç',
'End' => 'Son',
'Task age in days' => 'Görev yaşı gün olarak',
'Days in this column' => 'Bu sütunda geçirilen gün',
'%dd' => '%dG',
'Add a link' => 'Link ekle',
'Add a new link' => 'Yeni link ekle',
'Do you really want to remove this link: "%s"?' => '"%s" linkini gerçekten silmek istiyor musunuz?',
'Do you really want to remove this link with task #%d?' => '#%d numaralı görev ile linki gerçekten silmek istiyor musunuz?',
'Field required' => 'Bu alan gerekli',
'Link added successfully.' => 'Link başarıyla eklendi.',
'Link updated successfully.' => 'Link başarıyla güncellendi.',
'Link removed successfully.' => 'Link başarıyla silindi.',
'Link labels' => 'Link etiketleri',
'Link modification' => 'Link değiştirme',
'Links' => 'Links',
'Link settings' => 'Link ayarları',
'Opposite label' => 'Zıt etiket',
'Remove a link' => 'Bir link silmek',
'Task\'s links' => 'Görevin linkleri',
'The labels must be different' => 'Etiketler farklı olmalı',
'There is no link.' => 'Hiç bir bağ yok',
'This label must be unique' => 'Bu etiket tek olmalı',
'Unable to create your link.' => 'Link oluşturulamadı.',
'Unable to update your link.' => 'Link güncellenemiyor.',
'Unable to remove this link.' => 'Link kaldırılamıyor',
'relates to' => 'şununla ilgili',
'blocks' => 'şunu engelliyor',
'is blocked by' => 'şunun tarafından engelleniyor',
'duplicates' => 'şunun kopyasını oluşturuyor',
'is duplicated by' => 'şunun tarafından kopyası oluşturuluyor',
'is a child of' => 'şunun astı',
'is a parent of' => 'şunun üstü',
'targets milestone' => 'şu kilometre taşını hedefliyor',
'is a milestone of' => 'şunun için bir kilometre taşı',
'fixes' => 'düzeltiyor',
'is fixed by' => 'şunun tarafından düzeltildi',
'This task' => 'Bu görev',
'<1h' => '<1s',
'%dh' => '%ds',
// '%b %e' => '',
'Expand tasks' => 'Görevleri genişlet',
'Collapse tasks' => 'Görevleri daralt',
'Expand/collapse tasks' => 'Görevleri genişlet/daralt',
'Close dialog box' => 'İletiyi kapat',
'Submit a form' => 'Formu gönder',
'Board view' => 'Tablo görünümü',
'Keyboard shortcuts' => 'Klavye kısayolları',
'Open board switcher' => 'Tablo seçim listesini aç',
'Application' => 'Uygulama',
'since %B %e, %Y at %k:%M %p' => '%B %e, %Y saat %k:%M %p\'den beri',
'Compact view' => 'Ekrana sığdır',
'Horizontal scrolling' => 'Geniş görünüm',
'Compact/wide view' => 'Ekrana sığdır / Geniş görünüm',
// 'No results match:' => '',
// 'Currency' => '',
// 'Files' => '',
// 'Images' => '',
// 'Private project' => '',
// 'AUD - Australian Dollar' => '',
// 'CAD - Canadian Dollar' => '',
// 'CHF - Swiss Francs' => '',
// 'Custom Stylesheet' => '',
// 'download' => '',
// 'EUR - Euro' => '',
// 'GBP - British Pound' => '',
// 'INR - Indian Rupee' => '',
// 'JPY - Japanese Yen' => '',
// 'NZD - New Zealand Dollar' => '',
// 'RSD - Serbian dinar' => '',
// 'USD - US Dollar' => '',
// 'Destination column' => '',
// 'Move the task to another column when assigned to a user' => '',
// 'Move the task to another column when assignee is cleared' => '',
// 'Source column' => '',
// 'Transitions' => '',
// 'Executer' => '',
// 'Time spent in the column' => '',
// 'Task transitions' => '',
// 'Task transitions export' => '',
// 'This report contains all column moves for each task with the date, the user and the time spent for each transition.' => '',
// 'Currency rates' => '',
// 'Rate' => '',
// 'Change reference currency' => '',
// 'Add a new currency rate' => '',
// 'Reference currency' => '',
// 'The currency rate have been added successfully.' => '',
// 'Unable to add this currency rate.' => '',
// 'Webhook URL' => '',
// '%s remove the assignee of the task %s' => '',
// 'Enable Gravatar images' => '',
// 'Information' => '',
// 'Check two factor authentication code' => '',
// 'The two factor authentication code is not valid.' => '',
// 'The two factor authentication code is valid.' => '',
// 'Code' => '',
// 'Two factor authentication' => '',
// 'Enable/disable two factor authentication' => '',
// 'This QR code contains the key URI: ' => '',
// 'Save the secret key in your TOTP software (by example Google Authenticator or FreeOTP).' => '',
// 'Check my code' => '',
// 'Secret key: ' => '',
// 'Test your device' => '',
// 'Assign a color when the task is moved to a specific column' => '',
// '%s via Kanboard' => '',
// 'uploaded by: %s' => '',
// 'uploaded on: %s' => '',
// 'size: %s' => '',
// 'Burndown chart for "%s"' => '',
// 'Burndown chart' => '',
// 'This chart show the task complexity over the time (Work Remaining).' => '',
// 'Screenshot taken %s' => '',
// 'Add a screenshot' => '',
// 'Take a screenshot and press CTRL+V or ⌘+V to paste here.' => '',
// 'Screenshot uploaded successfully.' => '',
// 'SEK - Swedish Krona' => '',
// 'The project identifier is an optional alphanumeric code used to identify your project.' => '',
// 'Identifier' => '',
// 'Disable two factor authentication' => '',
// 'Do you really want to disable the two factor authentication for this user: "%s"?' => '',
// 'Edit link' => '',
// 'Start to type task title...' => '',
// 'A task cannot be linked to itself' => '',
// 'The exact same link already exists' => '',
// 'Recurrent task is scheduled to be generated' => '',
// 'Recurring information' => '',
// 'Score' => '',
// 'The identifier must be unique' => '',
// 'This linked task id doesn\'t exists' => '',
// 'This value must be alphanumeric' => '',
// 'Edit recurrence' => '',
// 'Generate recurrent task' => '',
// 'Trigger to generate recurrent task' => '',
// 'Factor to calculate new due date' => '',
// 'Timeframe to calculate new due date' => '',
// 'Base date to calculate new due date' => '',
// 'Action date' => '',
// 'Base date to calculate new due date: ' => '',
// 'This task has created this child task: ' => '',
// 'Day(s)' => '',
// 'Existing due date' => '',
// 'Factor to calculate new due date: ' => '',
// 'Month(s)' => '',
// 'Recurrence' => '',
// 'This task has been created by: ' => '',
// 'Recurrent task has been generated:' => '',
// 'Timeframe to calculate new due date: ' => '',
// 'Trigger to generate recurrent task: ' => '',
// 'When task is closed' => '',
// 'When task is moved from first column' => '',
// 'When task is moved to last column' => '',
// 'Year(s)' => '',
// 'Calendar settings' => '',
// 'Project calendar view' => '',
// 'Project settings' => '',
// 'Show subtasks based on the time tracking' => '',
// 'Show tasks based on the creation date' => '',
// 'Show tasks based on the start date' => '',
// 'Subtasks time tracking' => '',
// 'User calendar view' => '',
// 'Automatically update the start date' => '',
// 'iCal feed' => '',
// 'Preferences' => '',
// 'Security' => '',
// 'Two factor authentication disabled' => '',
// 'Two factor authentication enabled' => '',
// 'Unable to update this user.' => '',
// 'There is no user management for private projects.' => '',
// 'User that will receive the email' => '',
// 'Email subject' => '',
// 'Date' => '',
// 'By @%s on Bitbucket' => '',
// 'Bitbucket Issue' => '',
// 'Commit made by @%s on Bitbucket' => '',
// 'Commit made by @%s on Github' => '',
// 'By @%s on Github' => '',
// 'Commit made by @%s on Gitlab' => '',
// 'Add a comment log when moving the task between columns' => '',
// 'Move the task to another column when the category is changed' => '',
// 'Send a task by email to someone' => '',
// 'Reopen a task' => '',
// 'Bitbucket issue opened' => '',
// 'Bitbucket issue closed' => '',
// 'Bitbucket issue reopened' => '',
// 'Bitbucket issue assignee change' => '',
// 'Bitbucket issue comment created' => '',
// 'Column change' => '',
// 'Position change' => '',
// 'Swimlane change' => '',
// 'Assignee change' => '',
// '[%s] Overdue tasks' => '',
// 'Notification' => '',
// '%s moved the task #%d to the first swimlane' => '',
// '%s moved the task #%d to the swimlane "%s"' => '',
// 'Swimlane' => '',
// 'Gravatar' => '',
// '%s moved the task %s to the first swimlane' => '',
// '%s moved the task %s to the swimlane "%s"' => '',
// 'This report contains all subtasks information for the given date range.' => '',
// 'This report contains all tasks information for the given date range.' => '',
// 'Project activities for %s' => '',
// 'view the board on Kanboard' => '',
// 'The task have been moved to the first swimlane' => '',
// 'The task have been moved to another swimlane:' => '',
// 'Overdue tasks for the project "%s"' => '',
// 'New title: %s' => '',
// 'The task is not assigned anymore' => '',
// 'New assignee: %s' => '',
// 'There is no category now' => '',
// 'New category: %s' => '',
// 'New color: %s' => '',
// 'New complexity: %d' => '',
// 'The due date have been removed' => '',
// 'There is no description anymore' => '',
// 'Recurrence settings have been modified' => '',
// 'Time spent changed: %sh' => '',
// 'Time estimated changed: %sh' => '',
// 'The field "%s" have been updated' => '',
// 'The description have been modified' => '',
// 'Do you really want to close the task "%s" as well as all subtasks?' => '',
// 'Swimlane: %s' => '',
// 'I want to receive notifications for:' => '',
// 'All tasks' => '',
// 'Only for tasks assigned to me' => '',
// 'Only for tasks created by me' => '',
// 'Only for tasks created by me and assigned to me' => '',
// '%A' => '',
// '%b %e, %Y, %k:%M %p' => '',
// 'New due date: %B %e, %Y' => '',
// 'Start date changed: %B %e, %Y' => '',
// '%k:%M %p' => '',
// '%%Y-%%m-%%d' => '',
// 'Total for all columns' => '',
// 'You need at least 2 days of data to show the chart.' => '',
// '<15m' => '',
// '<30m' => '',
// 'Stop timer' => '',
// 'Start timer' => '',
// 'Add project member' => '',
// 'Enable notifications' => '',
// 'My activity stream' => '',
// 'My calendar' => '',
// 'Search tasks' => '',
// 'Back to the calendar' => '',
// 'Filters' => '',
// 'Reset filters' => '',
// 'My tasks due tomorrow' => '',
// 'Tasks due today' => '',
// 'Tasks due tomorrow' => '',
// 'Tasks due yesterday' => '',
// 'Closed tasks' => '',
// 'Open tasks' => '',
// 'Not assigned' => '',
// 'View advanced search syntax' => '',
// 'Overview' => '',
// '%b %e %Y' => '',
// 'Board/Calendar/List view' => '',
// 'Switch to the board view' => '',
// 'Switch to the calendar view' => '',
// 'Switch to the list view' => '',
// 'Go to the search/filter box' => '',
// 'There is no activity yet.' => '',
// 'No tasks found.' => '',
// 'Keyboard shortcut: "%s"' => '',
// 'List' => '',
// 'Filter' => '',
// 'Advanced search' => '',
// 'Example of query: ' => '',
// 'Search by project: ' => '',
// 'Search by column: ' => '',
// 'Search by assignee: ' => '',
// 'Search by color: ' => '',
// 'Search by category: ' => '',
// 'Search by description: ' => '',
// 'Search by due date: ' => '',
// 'Lead and Cycle time for "%s"' => '',
// 'Average time spent into each column for "%s"' => '',
// 'Average time spent into each column' => '',
// 'Average time spent' => '',
// 'This chart show the average time spent into each column for the last %d tasks.' => '',
// 'Average Lead and Cycle time' => '',
// 'Average lead time: ' => '',
// 'Average cycle time: ' => '',
// 'Cycle Time' => '',
// 'Lead Time' => '',
// 'This chart show the average lead and cycle time for the last %d tasks over the time.' => '',
// 'Average time into each column' => '',
// 'Lead and cycle time' => '',
// 'Google Authentication' => '',
// 'Help on Google authentication' => '',
// 'Github Authentication' => '',
// 'Help on Github authentication' => '',
// 'Lead time: ' => '',
// 'Cycle time: ' => '',
// 'Time spent into each column' => '',
// 'The lead time is the duration between the task creation and the completion.' => '',
// 'The cycle time is the duration between the start date and the completion.' => '',
// 'If the task is not closed the current time is used instead of the completion date.' => '',
// 'Set automatically the start date' => '',
// 'Edit Authentication' => '',
// 'Google Id' => '',
// 'Github Id' => '',
// 'Remote user' => '',
// 'Remote users do not store their password in Kanboard database, examples: LDAP, Google and Github accounts.' => '',
// 'If you check the box "Disallow login form", credentials entered in the login form will be ignored.' => '',
// 'By @%s on Gitlab' => '',
// 'Gitlab issue comment created' => '',
// 'New remote user' => '',
// 'New local user' => '',
// 'Default task color' => '',
// 'Hide sidebar' => '',
// 'Expand sidebar' => '',
// 'This feature does not work with all browsers.' => '',
// 'There is no destination project available.' => '',
// 'Trigger automatically subtask time tracking' => '',
// 'Include closed tasks in the cumulative flow diagram' => '',
// 'Current swimlane: %s' => '',
// 'Current column: %s' => '',
// 'Current category: %s' => '',
// 'no category' => '',
// 'Current assignee: %s' => '',
// 'not assigned' => '',
// 'Author:' => '',
// 'contributors' => '',
// 'License:' => '',
// 'License' => '',
// 'Project Administrator' => '',
// 'Enter the text below' => '',
// 'Gantt chart for %s' => '',
// 'Sort by position' => '',
// 'Sort by date' => '',
// 'Add task' => '',
// 'Start date:' => '',
// 'Due date:' => '',
// 'There is no start date or due date for this task.' => '',
// 'Moving or resizing a task will change the start and due date of the task.' => '',
// 'There is no task in your project.' => '',
// 'Gantt chart' => '',
// 'People who are project managers' => '',
// 'People who are project members' => '',
// 'NOK - Norwegian Krone' => '',
// 'Show this column' => '',
// 'Hide this column' => '',
// 'open file' => '',
// 'End date' => '',
// 'Users overview' => '',
// 'Managers' => '',
// 'Members' => '',
// 'Shared project' => '',
// 'Project managers' => '',
// 'Project members' => '',
// 'Gantt chart for all projects' => '',
// 'Projects list' => '',
// 'Gantt chart for this project' => '',
// 'Project board' => '',
// 'End date:' => '',
// 'There is no start date or end date for this project.' => '',
// 'Projects Gantt chart' => '',
// 'Start date: %s' => '',
// 'End date: %s' => '',
// 'Link type' => '',
// 'Change task color when using a specific task link' => '',
// 'Task link creation or modification' => '',
// 'Login with my Gitlab Account' => '',
// 'Milestone' => '',
// 'Gitlab Authentication' => '',
// 'Help on Gitlab authentication' => '',
// 'Gitlab Id' => '',
// 'Gitlab Account' => '',
// 'Link my Gitlab Account' => '',
// 'Unlink my Gitlab Account' => '',
// 'Documentation: %s' => '',
// 'Switch to the Gantt chart view' => '',
// 'Reset the search/filter box' => '',
// 'Documentation' => '',
// 'Table of contents' => '',
// 'Gantt' => '',
// 'Help with project permissions' => '',
// 'Author' => '',
// 'Version' => '',
// 'Plugins' => '',
// 'There is no plugin loaded.' => '',
// 'Set maximum column height' => '',
// 'Remove maximum column height' => '',
// 'My notifications' => '',
// 'Custom filters' => '',
// 'Your custom filter have been created successfully.' => '',
// 'Unable to create your custom filter.' => '',
// 'Custom filter removed successfully.' => '',
// 'Unable to remove this custom filter.' => '',
// 'Edit custom filter' => '',
// 'Your custom filter have been updated successfully.' => '',
// 'Unable to update custom filter.' => '',
// 'Web' => '',
// 'New attachment on task #%d: %s' => '',
// 'New comment on task #%d' => '',
// 'Comment updated on task #%d' => '',
// 'New subtask on task #%d' => '',
// 'Subtask updated on task #%d' => '',
// 'New task #%d: %s' => '',
// 'Task updated #%d' => '',
// 'Task #%d closed' => '',
// 'Task #%d opened' => '',
// 'Column changed for task #%d' => '',
// 'New position for task #%d' => '',
// 'Swimlane changed for task #%d' => '',
// 'Assignee changed on task #%d' => '',
// '%d overdue tasks' => '',
// 'Task #%d is overdue' => '',
// 'No new notifications.' => '',
// 'Mark all as read' => '',
// 'Mark as read' => '',
// 'Total number of tasks in this column across all swimlanes' => '',
// 'Collapse swimlane' => '',
// 'Expand swimlane' => '',
// 'Add a new filter' => '',
// 'Share with all project members' => '',
// 'Shared' => '',
// 'Owner' => '',
// 'Unread notifications' => '',
// 'My filters' => '',
// 'Notification methods:' => '',
// 'Import tasks from CSV file' => '',
// 'Unable to read your file' => '',
// '%d task(s) have been imported successfully.' => '',
// 'Nothing have been imported!' => '',
// 'Import users from CSV file' => '',
// '%d user(s) have been imported successfully.' => '',
// 'Comma' => '',
// 'Semi-colon' => '',
// 'Tab' => '',
// 'Vertical bar' => '',
// 'Double Quote' => '',
// 'Single Quote' => '',
// '%s attached a file to the task #%d' => '',
// 'There is no column or swimlane activated in your project!' => '',
// 'Append filter (instead of replacement)' => '',
// 'Append/Replace' => '',
// 'Append' => '',
// 'Replace' => '',
// 'There is no notification method registered.' => '',
// 'Import' => '',
// 'change sorting' => '',
// 'Tasks Importation' => '',
// 'Delimiter' => '',
// 'Enclosure' => '',
// 'CSV File' => '',
// 'Instructions' => '',
// 'Your file must use the predefined CSV format' => '',
// 'Your file must be encoded in UTF-8' => '',
// 'The first row must be the header' => '',
// 'Duplicates are not verified for you' => '',
// 'The due date must use the ISO format: YYYY-MM-DD' => '',
// 'Download CSV template' => '',
// 'No external integration registered.' => '',
// 'Duplicates are not imported' => '',
// 'Usernames must be lowercase and unique' => '',
// 'Passwords will be encrypted if present' => '',
);
| {
"content_hash": "e8849424e19b33d6d53cbeae66d99ec5",
"timestamp": "",
"source": "github",
"line_count": 1067,
"max_line_length": 229,
"avg_line_length": 49.21274601686973,
"alnum_prop": 0.5880213292706151,
"repo_name": "kclabrador/kan-test",
"id": "05277797b1c2fe86a69d6e29ed6d6092cccc54b0",
"size": "53830",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "app/Locale/tr_TR/translations.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "957"
},
{
"name": "CSS",
"bytes": "30942"
},
{
"name": "JavaScript",
"bytes": "55863"
},
{
"name": "Makefile",
"bytes": "5439"
},
{
"name": "PHP",
"bytes": "3141451"
}
],
"symlink_target": ""
} |
<nav class="navbar navbar-default top_menu" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="{{site.baseurl}}/">웹Frameworks</a>
</div>
<div class="collapse navbar-collapse" id="navbar-collapse-1">
<ul class="nav navbar-nav navbar-left">
<li><a href="{{site.baseurl}}/getstarted">Get Started</a></li>
</ul>
<ul class="nav navbar-nav navbar-left">
<li><a href="{{site.baseurl}}/updates">Update</a></li>
</ul>
<ul class="nav navbar-nav navbar-left">
<li><a href="{{site.baseurl}}/tutorials">Tutorials</a></li>
</ul>
<ul class="nav navbar-nav navbar-left">
<li><a href="{{site.baseurl}}/quickstart">Quick Start</a></li>
</ul>
<ul class="nav navbar-nav navbar-left">
<li><a href="https://github.com/KoreaHTML5/webframeworks.kr/blob/master/CONTRIBUTE.md" target="_blank">참여하기</a></li>
</ul>
</div>
</div>
</nav>
| {
"content_hash": "93555a2ae96725aa00a0d91b352672eb",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 132,
"avg_line_length": 46.96774193548387,
"alnum_prop": 0.5260989010989011,
"repo_name": "webfrs/webfrs.github.io",
"id": "def8dd13f3323b3cf4933d139020a607e92dd2b1",
"size": "1466",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "contents/_includes/nav.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "7288"
},
{
"name": "JavaScript",
"bytes": "5203"
},
{
"name": "Ruby",
"bytes": "4617"
}
],
"symlink_target": ""
} |
'use strict';
// external deps
var ObjectId = require('mongodb').ObjectId;
require('mongodb-toolkit');
var BaseManager = require('module-toolkit').BaseManager;
var BateeqModels = require('bateeq-models');
var map = BateeqModels.map;
var generateCode = require('../../utils/code-generator');
var moment = require('moment');
var moduleId = "opname-balance";
module.exports = class StockOpnameBalanceManager extends BaseManager {
constructor(db, user) {
super(db, user);
this.collection = this.db.use(map.inventory.StockOpnameBalance)
}
create(stockOpnameBalance) {
return new Promise((resolve, reject) => {
this.collection.insert(stockOpnameBalance)
.then((result) => {
resolve(result);
})
.catch((error) => {
reject(error);
});
});
}
update(stockOpnameBalance) {
return new Promise((resolve, reject) => {
this.collection.update(stockOpnameBalance)
.then((result) => {
resolve(result);
})
.catch((error) => {
reject(error);
});
});
}
getByStorageCode(storeCode, productCode) {
return new Promise((resolve, reject) => {
var query = {
'storage.code': storeCode,
'product.code': productCode,
'_deleted': false
};
this.collection.singleOrDefault(query)
.then((result) => {
resolve(result);
})
.catch((error) => {
reject(error);
});
});
}
getBalanceByStorageCode(storageCode) {
return new Promise((resolve, reject) => {
var query = {
'storage.code' : storageCode
};
this.collection.find(query).toArray()
.then(result => {
resolve(result);
})
.catch(error => {
reject(error);
});
});
}
_getQuery(paging) {
var _default = {
_deleted: false
},
pagingFilter = paging.filter || {},
keywordFilter = {},
query = {};
if (paging.keyword) {
var regex = new RegExp(paging.keyword, "i");
var createdAgentFilter = {
"_createAgent": {
"$regex": regex
}
};
var codeFilter = {
"code": {
"$regex": regex
}
};
var storageFilter = {
"storage.name": {
"$regex": regex
}
};
var stockOpnameDocCodeFilter = {
"stockOpnameDocCodes": {
"$regex": regex
}
}
keywordFilter["$or"] = [createdAgentFilter, codeFilter, storageFilter, stockOpnameDocCodeFilter];
}
query["$and"] = [_default, keywordFilter, pagingFilter];
return query;
}
read(paging) {
var _paging = Object.assign({
page: 1,
size: 20,
order: {},
filter: {},
select: ["code", "storage.name", "products"]
}, paging);
var query = this._getQuery(_paging);
return this.collection
.where(query)
.select(_paging.select)
.page(_paging.page, _paging.size)
.order(_paging.order)
.execute();
}
} | {
"content_hash": "860780892d597f6dc494c0f6122db1ba",
"timestamp": "",
"source": "github",
"line_count": 137,
"max_line_length": 109,
"avg_line_length": 26.963503649635037,
"alnum_prop": 0.4523551705468327,
"repo_name": "danliris/bateeq-module",
"id": "f20b1d6ea5dcbaed78c56da943cbfee91b9ad584",
"size": "3694",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/managers/inventory/stock-opname-balance-manager.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "2440314"
}
],
"symlink_target": ""
} |
<html>
<head>
<title>Mozilla/5.0 (DirectFB; U; Linux 35230; en) AppleWebKit/531.2+ (KHTML, like Gecko) Safari/531.2+ LG Browser/4.1.4(+mouse+PORTAL_KEY+SCREEN+TUNER; LGE; 42LV470S-ZC; 06.01.04; 0x00000001;); LG NetCast.TV-2011</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="section">
<h1 class="header center orange-text">User agent detail</h1>
<div class="row center">
Mozilla/5.0 (DirectFB; U; Linux 35230; en) AppleWebKit/531.2+ (KHTML, like Gecko) Safari/531.2+ LG Browser/4.1.4(+mouse+PORTAL_KEY+SCREEN+TUNER; LGE; 42LV470S-ZC; 06.01.04; 0x00000001;); LG NetCast.TV-2011
<p>
Detected by 7 of 8 providers<br />
As bot detected by 0 of 7
</p>
</div>
</div>
<div class="section">
<table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Actions</th></tr><tr><td>BrowscapPhp<br /><small>6011</small></td>
<td colspan="12" class="center-align red lighten-1">
<strong>No result found</strong>
</td>
</tr><tr><td>DonatjUAParser<br /><small>v0.5.0</small></td><td>Safari 531.2</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-6fae891b-b0d5-4415-b07d-355015c3af67">Detail</a>
<!-- Modal Structure -->
<div id="modal-6fae891b-b0d5-4415-b07d-355015c3af67" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>DonatjUAParser result detail</h4>
<p><pre><code class="php">Array
(
[platform] => Linux
[browser] => Safari
[version] => 531.2
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>PiwikDeviceDetector<br /><small>3.5.1</small></td><td>Safari </td><td>WebKit </td><td>GNU/Linux </td><td>LG</td><td>NetCast</td><td>tv</td><td></td><td></td><td></td><td></td><td></td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-fc0f1b55-50d8-49c2-bb12-4cc1d8144ebf">Detail</a>
<!-- Modal Structure -->
<div id="modal-fc0f1b55-50d8-49c2-bb12-4cc1d8144ebf" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>PiwikDeviceDetector result detail</h4>
<p><pre><code class="php">Array
(
[client] => Array
(
[type] => browser
[name] => Safari
[short_name] => SF
[version] =>
[engine] => WebKit
)
[operatingSystem] => Array
(
[name] => GNU/Linux
[short_name] => LIN
[version] =>
[platform] =>
)
[device] => Array
(
[brand] => LG
[brandName] => LG
[model] => NetCast
[device] => 5
[deviceName] => tv
)
[bot] =>
[extra] => Array
(
[isBot] =>
[isBrowser] => 1
[isFeedReader] =>
[isMobileApp] =>
[isPIM] =>
[isLibrary] =>
[isMediaPlayer] =>
[isCamera] =>
[isCarBrowser] =>
[isConsole] =>
[isFeaturePhone] =>
[isPhablet] =>
[isPortableMediaPlayer] =>
[isSmartDisplay] =>
[isSmartphone] =>
[isTablet] =>
[isTV] => 1
[isDesktop] => 1
[isMobile] =>
[isTouchEnabled] =>
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.0</small></td><td>Safari </td><td><i class="material-icons">close</i></td><td>Linux </td><td><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-8c08f104-4e61-421b-9405-291b09c383dc">Detail</a>
<!-- Modal Structure -->
<div id="modal-8c08f104-4e61-421b-9405-291b09c383dc" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>SinergiBrowserDetector result detail</h4>
<p><pre><code class="php">Array
(
[browser] => Sinergi\BrowserDetector\Browser Object
(
[userAgent:Sinergi\BrowserDetector\Browser:private] => Sinergi\BrowserDetector\UserAgent Object
(
[userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (DirectFB; U; Linux 35230; en) AppleWebKit/531.2+ (KHTML, like Gecko) Safari/531.2+ LG Browser/4.1.4(+mouse+PORTAL_KEY+SCREEN+TUNER; LGE; 42LV470S-ZC; 06.01.04; 0x00000001;); LG NetCast.TV-2011
)
[name:Sinergi\BrowserDetector\Browser:private] => Safari
[version:Sinergi\BrowserDetector\Browser:private] => unknown
[isRobot:Sinergi\BrowserDetector\Browser:private] =>
[isChromeFrame:Sinergi\BrowserDetector\Browser:private] =>
)
[operatingSystem] => Sinergi\BrowserDetector\Os Object
(
[name:Sinergi\BrowserDetector\Os:private] => Linux
[version:Sinergi\BrowserDetector\Os:private] => unknown
[isMobile:Sinergi\BrowserDetector\Os:private] =>
[userAgent:Sinergi\BrowserDetector\Os:private] => Sinergi\BrowserDetector\UserAgent Object
(
[userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (DirectFB; U; Linux 35230; en) AppleWebKit/531.2+ (KHTML, like Gecko) Safari/531.2+ LG Browser/4.1.4(+mouse+PORTAL_KEY+SCREEN+TUNER; LGE; 42LV470S-ZC; 06.01.04; 0x00000001;); LG NetCast.TV-2011
)
)
[device] => Sinergi\BrowserDetector\Device Object
(
[name:Sinergi\BrowserDetector\Device:private] => unknown
[userAgent:Sinergi\BrowserDetector\Device:private] => Sinergi\BrowserDetector\UserAgent Object
(
[userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (DirectFB; U; Linux 35230; en) AppleWebKit/531.2+ (KHTML, like Gecko) Safari/531.2+ LG Browser/4.1.4(+mouse+PORTAL_KEY+SCREEN+TUNER; LGE; 42LV470S-ZC; 06.01.04; 0x00000001;); LG NetCast.TV-2011
)
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>UAParser<br /><small>v3.4.5</small></td><td>WebKit Nightly 531.2</td><td><i class="material-icons">close</i></td><td>Linux </td><td>LG</td><td>42LV470S-ZC</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td></td><td></td><td><i class="material-icons">close</i></td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-8f4c86c5-433e-4536-b799-ad26d77264e0">Detail</a>
<!-- Modal Structure -->
<div id="modal-8f4c86c5-433e-4536-b799-ad26d77264e0" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>UAParser result detail</h4>
<p><pre><code class="php">UAParser\Result\Client Object
(
[ua] => UAParser\Result\UserAgent Object
(
[major] => 531
[minor] => 2
[patch] =>
[family] => WebKit Nightly
)
[os] => UAParser\Result\OperatingSystem Object
(
[major] =>
[minor] =>
[patch] =>
[patchMinor] =>
[family] => Linux
)
[device] => UAParser\Result\Device Object
(
[brand] => LG
[model] => 42LV470S-ZC
[family] => NetCast.TV
)
[originalUserAgent] => Mozilla/5.0 (DirectFB; U; Linux 35230; en) AppleWebKit/531.2+ (KHTML, like Gecko) Safari/531.2+ LG Browser/4.1.4(+mouse+PORTAL_KEY+SCREEN+TUNER; LGE; 42LV470S-ZC; 06.01.04; 0x00000001;); LG NetCast.TV-2011
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>WhichBrowser<br /><small>2.0.9</small></td><td>LG Browser 4.1</td><td>Webkit 531.2</td><td> </td><td>LG</td><td>LV470S NetCast TV 2011</td><td>television</td><td></td><td><i class="material-icons">close</i></td><td></td><td></td><td><i class="material-icons">close</i></td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-62f1f3a3-0c44-4ecb-9ee2-48145e35736b">Detail</a>
<!-- Modal Structure -->
<div id="modal-62f1f3a3-0c44-4ecb-9ee2-48145e35736b" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>WhichBrowser result detail</h4>
<p><pre><code class="php">Array
(
[browser] => Array
(
[name] => LG Browser
[version] => 4.1
[type] => browser
)
[engine] => Array
(
[name] => Webkit
[version] => 531.2
)
[device] => Array
(
[type] => television
[manufacturer] => LG
[model] => LV470S
[series] => NetCast TV 2011
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>Woothee<br /><small>v1.2.0</small></td><td>Safari </td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>pc</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td></td><td></td><td><i class="material-icons">close</i></td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-bd437f52-91e9-4ce8-88f7-6e5206ed6635">Detail</a>
<!-- Modal Structure -->
<div id="modal-bd437f52-91e9-4ce8-88f7-6e5206ed6635" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Woothee result detail</h4>
<p><pre><code class="php">Array
(
[name] => Safari
[vendor] => Apple
[version] => UNKNOWN
[category] => pc
[os] => Linux
[os_version] => UNKNOWN
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr><tr><td>Wurfl<br /><small>1.6.4</small></td><td>Opera 12.50</td><td><i class="material-icons">close</i></td><td>Linux armv7l </td><td></td><td>SmartTV</td><td>Smart-TV</td><td></td><td></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>
<!-- Modal Trigger -->
<a class="modal-trigger btn waves-effect waves-light" href="#modal-3a72b31e-c3c1-4317-a357-7a6d5e3c7027">Detail</a>
<!-- Modal Structure -->
<div id="modal-3a72b31e-c3c1-4317-a357-7a6d5e3c7027" class="modal modal-fixed-footer">
<div class="modal-content">
<h4>Wurfl result detail</h4>
<p><pre><code class="php">Array
(
[virtual] => Array
(
[is_android] => false
[is_ios] => false
[is_windows_phone] => false
[is_app] => false
[is_full_desktop] => false
[is_largescreen] => true
[is_mobile] => false
[is_robot] => false
[is_smartphone] => false
[is_touchscreen] => false
[is_wml_preferred] => false
[is_xhtmlmp_preferred] => false
[is_html_preferred] => true
[advertised_device_os] => Linux armv7l
[advertised_device_os_version] =>
[advertised_browser] => Opera
[advertised_browser_version] => 12.50
[complete_device_name] => Generic SmartTV
[form_factor] => Smart-TV
[is_phone] => false
[is_app_webview] => false
)
[all] => Array
(
[brand_name] => Generic
[model_name] => SmartTV
[unique] => true
[ununiqueness_handler] =>
[is_wireless_device] => false
[device_claims_web_support] => true
[has_qwerty_keyboard] => true
[can_skip_aligned_link_row] => true
[uaprof] =>
[uaprof2] =>
[uaprof3] =>
[nokia_series] => 0
[nokia_edition] => 0
[device_os] =>
[mobile_browser] =>
[mobile_browser_version] =>
[device_os_version] =>
[pointing_method] =>
[release_date] => 2011_january
[marketing_name] =>
[model_extra_info] =>
[nokia_feature_pack] => 0
[can_assign_phone_number] => false
[is_tablet] => false
[manufacturer_name] =>
[is_bot] => false
[is_google_glass] => false
[proportional_font] => false
[built_in_back_button_support] => false
[card_title_support] => false
[softkey_support] => false
[table_support] => false
[numbered_menus] => false
[menu_with_select_element_recommended] => false
[menu_with_list_of_links_recommended] => false
[icons_on_menu_items_support] => false
[break_list_of_links_with_br_element_recommended] => false
[access_key_support] => false
[wrap_mode_support] => false
[times_square_mode_support] => false
[deck_prefetch_support] => false
[elective_forms_recommended] => false
[wizards_recommended] => false
[image_as_link_support] => false
[insert_br_element_after_widget_recommended] => false
[wml_can_display_images_and_text_on_same_line] => false
[wml_displays_image_in_center] => false
[opwv_wml_extensions_support] => false
[wml_make_phone_call_string] => none
[chtml_display_accesskey] => false
[emoji] => false
[chtml_can_display_images_and_text_on_same_line] => false
[chtml_displays_image_in_center] => false
[imode_region] => none
[chtml_make_phone_call_string] => tel:
[chtml_table_support] => true
[xhtml_honors_bgcolor] => true
[xhtml_supports_forms_in_table] => true
[xhtml_support_wml2_namespace] => false
[xhtml_autoexpand_select] => false
[xhtml_select_as_dropdown] => true
[xhtml_select_as_radiobutton] => true
[xhtml_select_as_popup] => true
[xhtml_display_accesskey] => false
[xhtml_supports_invisible_text] => false
[xhtml_supports_inline_input] => false
[xhtml_supports_monospace_font] => false
[xhtml_supports_table_for_layout] => false
[xhtml_supports_css_cell_table_coloring] => false
[xhtml_format_as_css_property] => false
[xhtml_format_as_attribute] => false
[xhtml_nowrap_mode] => false
[xhtml_marquee_as_css_property] => false
[xhtml_readable_background_color1] => #FFFFFF
[xhtml_readable_background_color2] => #FFFFFF
[xhtml_allows_disabled_form_elements] => false
[xhtml_document_title_support] => true
[xhtml_preferred_charset] => utf8
[opwv_xhtml_extensions_support] => false
[xhtml_make_phone_call_string] => none
[xhtmlmp_preferred_mime_type] => text/html
[xhtml_table_support] => false
[xhtml_send_sms_string] => none
[xhtml_send_mms_string] => none
[xhtml_file_upload] => supported
[cookie_support] => true
[accept_third_party_cookie] => true
[xhtml_supports_iframe] => full
[xhtml_avoid_accesskeys] => true
[xhtml_can_embed_video] => play_and_stop
[ajax_support_javascript] => true
[ajax_manipulate_css] => true
[ajax_support_getelementbyid] => true
[ajax_support_inner_html] => true
[ajax_xhr_type] => standard
[ajax_manipulate_dom] => true
[ajax_support_events] => true
[ajax_support_event_listener] => true
[ajax_preferred_geoloc_api] => none
[xhtml_support_level] => 4
[preferred_markup] => html_web_4_0
[wml_1_1] => false
[wml_1_2] => false
[wml_1_3] => false
[html_wi_w3_xhtmlbasic] => true
[html_wi_oma_xhtmlmp_1_0] => false
[html_wi_imode_html_1] => false
[html_wi_imode_html_2] => false
[html_wi_imode_html_3] => false
[html_wi_imode_html_4] => false
[html_wi_imode_html_5] => false
[html_wi_imode_htmlx_1] => false
[html_wi_imode_htmlx_1_1] => false
[html_wi_imode_compact_generic] => false
[html_web_3_2] => true
[html_web_4_0] => true
[voicexml] => false
[multipart_support] => false
[total_cache_disable_support] => false
[time_to_live_support] => false
[resolution_width] => 685
[resolution_height] => 600
[columns] => 120
[max_image_width] => 650
[max_image_height] => 600
[rows] => 200
[physical_screen_width] => 400
[physical_screen_height] => 400
[dual_orientation] => false
[density_class] => 1.0
[wbmp] => false
[bmp] => true
[epoc_bmp] => false
[gif_animated] => true
[jpg] => true
[png] => true
[tiff] => false
[transparent_png_alpha] => false
[transparent_png_index] => false
[svgt_1_1] => true
[svgt_1_1_plus] => false
[greyscale] => false
[gif] => true
[colors] => 65536
[webp_lossy_support] => false
[webp_lossless_support] => false
[post_method_support] => true
[basic_authentication_support] => true
[empty_option_value_support] => true
[emptyok] => false
[nokia_voice_call] => false
[wta_voice_call] => false
[wta_phonebook] => false
[wta_misc] => false
[wta_pdc] => false
[https_support] => true
[phone_id_provided] => false
[max_data_rate] => 3200
[wifi] => true
[sdio] => false
[vpn] => false
[has_cellular_radio] => false
[max_deck_size] => 100000
[max_url_length_in_requests] => 128
[max_url_length_homepage] => 0
[max_url_length_bookmark] => 0
[max_url_length_cached_page] => 0
[max_no_of_connection_settings] => 0
[max_no_of_bookmarks] => 0
[max_length_of_username] => 0
[max_length_of_password] => 0
[max_object_size] => 0
[downloadfun_support] => false
[directdownload_support] => false
[inline_support] => false
[oma_support] => false
[ringtone] => false
[ringtone_3gpp] => false
[ringtone_midi_monophonic] => false
[ringtone_midi_polyphonic] => false
[ringtone_imelody] => false
[ringtone_digiplug] => false
[ringtone_compactmidi] => false
[ringtone_mmf] => false
[ringtone_rmf] => false
[ringtone_xmf] => false
[ringtone_amr] => false
[ringtone_awb] => false
[ringtone_aac] => false
[ringtone_wav] => false
[ringtone_mp3] => false
[ringtone_spmidi] => false
[ringtone_qcelp] => false
[ringtone_voices] => 1
[ringtone_df_size_limit] => 0
[ringtone_directdownload_size_limit] => 0
[ringtone_inline_size_limit] => 0
[ringtone_oma_size_limit] => 0
[wallpaper] => false
[wallpaper_max_width] => 0
[wallpaper_max_height] => 0
[wallpaper_preferred_width] => 0
[wallpaper_preferred_height] => 0
[wallpaper_resize] => none
[wallpaper_wbmp] => false
[wallpaper_bmp] => false
[wallpaper_gif] => false
[wallpaper_jpg] => false
[wallpaper_png] => false
[wallpaper_tiff] => false
[wallpaper_greyscale] => false
[wallpaper_colors] => 2
[wallpaper_df_size_limit] => 0
[wallpaper_directdownload_size_limit] => 0
[wallpaper_inline_size_limit] => 0
[wallpaper_oma_size_limit] => 0
[screensaver] => false
[screensaver_max_width] => 0
[screensaver_max_height] => 0
[screensaver_preferred_width] => 0
[screensaver_preferred_height] => 0
[screensaver_resize] => none
[screensaver_wbmp] => false
[screensaver_bmp] => false
[screensaver_gif] => false
[screensaver_jpg] => false
[screensaver_png] => false
[screensaver_greyscale] => false
[screensaver_colors] => 2
[screensaver_df_size_limit] => 0
[screensaver_directdownload_size_limit] => 0
[screensaver_inline_size_limit] => 0
[screensaver_oma_size_limit] => 0
[picture] => false
[picture_max_width] => 0
[picture_max_height] => 0
[picture_preferred_width] => 0
[picture_preferred_height] => 0
[picture_resize] => none
[picture_wbmp] => false
[picture_bmp] => false
[picture_gif] => false
[picture_jpg] => false
[picture_png] => false
[picture_greyscale] => false
[picture_colors] => 2
[picture_df_size_limit] => 0
[picture_directdownload_size_limit] => 0
[picture_inline_size_limit] => 0
[picture_oma_size_limit] => 0
[video] => false
[oma_v_1_0_forwardlock] => false
[oma_v_1_0_combined_delivery] => false
[oma_v_1_0_separate_delivery] => false
[streaming_video] => false
[streaming_3gpp] => false
[streaming_mp4] => false
[streaming_mov] => false
[streaming_video_size_limit] => 0
[streaming_real_media] => none
[streaming_flv] => false
[streaming_3g2] => false
[streaming_vcodec_h263_0] => -1
[streaming_vcodec_h263_3] => -1
[streaming_vcodec_mpeg4_sp] => -1
[streaming_vcodec_mpeg4_asp] => -1
[streaming_vcodec_h264_bp] => -1
[streaming_acodec_amr] => none
[streaming_acodec_aac] => none
[streaming_wmv] => none
[streaming_preferred_protocol] => rtsp
[streaming_preferred_http_protocol] => none
[wap_push_support] => false
[connectionless_service_indication] => false
[connectionless_service_load] => false
[connectionless_cache_operation] => false
[connectionoriented_unconfirmed_service_indication] => false
[connectionoriented_unconfirmed_service_load] => false
[connectionoriented_unconfirmed_cache_operation] => false
[connectionoriented_confirmed_service_indication] => false
[connectionoriented_confirmed_service_load] => false
[connectionoriented_confirmed_cache_operation] => false
[utf8_support] => true
[ascii_support] => false
[iso8859_support] => false
[expiration_date] => false
[j2me_cldc_1_0] => false
[j2me_cldc_1_1] => false
[j2me_midp_1_0] => false
[j2me_midp_2_0] => false
[doja_1_0] => false
[doja_1_5] => false
[doja_2_0] => false
[doja_2_1] => false
[doja_2_2] => false
[doja_3_0] => false
[doja_3_5] => false
[doja_4_0] => false
[j2me_jtwi] => false
[j2me_mmapi_1_0] => false
[j2me_mmapi_1_1] => false
[j2me_wmapi_1_0] => false
[j2me_wmapi_1_1] => false
[j2me_wmapi_2_0] => false
[j2me_btapi] => false
[j2me_3dapi] => false
[j2me_locapi] => false
[j2me_nokia_ui] => false
[j2me_motorola_lwt] => false
[j2me_siemens_color_game] => false
[j2me_siemens_extension] => false
[j2me_heap_size] => 0
[j2me_max_jar_size] => 0
[j2me_storage_size] => 0
[j2me_max_record_store_size] => 0
[j2me_screen_width] => 0
[j2me_screen_height] => 0
[j2me_canvas_width] => 0
[j2me_canvas_height] => 0
[j2me_bits_per_pixel] => 0
[j2me_audio_capture_enabled] => false
[j2me_video_capture_enabled] => false
[j2me_photo_capture_enabled] => false
[j2me_capture_image_formats] => none
[j2me_http] => false
[j2me_https] => false
[j2me_socket] => false
[j2me_udp] => false
[j2me_serial] => false
[j2me_gif] => false
[j2me_gif89a] => false
[j2me_jpg] => false
[j2me_png] => false
[j2me_bmp] => false
[j2me_bmp3] => false
[j2me_wbmp] => false
[j2me_midi] => false
[j2me_wav] => false
[j2me_amr] => false
[j2me_mp3] => false
[j2me_mp4] => false
[j2me_imelody] => false
[j2me_rmf] => false
[j2me_au] => false
[j2me_aac] => false
[j2me_realaudio] => false
[j2me_xmf] => false
[j2me_wma] => false
[j2me_3gpp] => false
[j2me_h263] => false
[j2me_svgt] => false
[j2me_mpeg4] => false
[j2me_realvideo] => false
[j2me_real8] => false
[j2me_realmedia] => false
[j2me_left_softkey_code] => 0
[j2me_right_softkey_code] => 0
[j2me_middle_softkey_code] => 0
[j2me_select_key_code] => 0
[j2me_return_key_code] => 0
[j2me_clear_key_code] => 0
[j2me_datefield_no_accepts_null_date] => false
[j2me_datefield_broken] => false
[receiver] => false
[sender] => false
[mms_max_size] => 0
[mms_max_height] => 0
[mms_max_width] => 0
[built_in_recorder] => false
[built_in_camera] => false
[mms_jpeg_baseline] => false
[mms_jpeg_progressive] => false
[mms_gif_static] => false
[mms_gif_animated] => false
[mms_png] => false
[mms_bmp] => false
[mms_wbmp] => false
[mms_amr] => false
[mms_wav] => false
[mms_midi_monophonic] => false
[mms_midi_polyphonic] => false
[mms_midi_polyphonic_voices] => 0
[mms_spmidi] => false
[mms_mmf] => false
[mms_mp3] => false
[mms_evrc] => false
[mms_qcelp] => false
[mms_ota_bitmap] => false
[mms_nokia_wallpaper] => false
[mms_nokia_operatorlogo] => false
[mms_nokia_3dscreensaver] => false
[mms_nokia_ringingtone] => false
[mms_rmf] => false
[mms_xmf] => false
[mms_symbian_install] => false
[mms_jar] => false
[mms_jad] => false
[mms_vcard] => false
[mms_vcalendar] => false
[mms_wml] => false
[mms_wbxml] => false
[mms_wmlc] => false
[mms_video] => false
[mms_mp4] => false
[mms_3gpp] => false
[mms_3gpp2] => false
[mms_max_frame_rate] => 0
[nokiaring] => false
[picturemessage] => false
[operatorlogo] => false
[largeoperatorlogo] => false
[callericon] => false
[nokiavcard] => false
[nokiavcal] => false
[sckl_ringtone] => false
[sckl_operatorlogo] => false
[sckl_groupgraphic] => false
[sckl_vcard] => false
[sckl_vcalendar] => false
[text_imelody] => false
[ems] => false
[ems_variablesizedpictures] => false
[ems_imelody] => false
[ems_odi] => false
[ems_upi] => false
[ems_version] => 0
[siemens_ota] => false
[siemens_logo_width] => 101
[siemens_logo_height] => 29
[siemens_screensaver_width] => 101
[siemens_screensaver_height] => 50
[gprtf] => false
[sagem_v1] => false
[sagem_v2] => false
[panasonic] => false
[sms_enabled] => false
[wav] => false
[mmf] => false
[smf] => false
[mld] => false
[midi_monophonic] => false
[midi_polyphonic] => false
[sp_midi] => false
[rmf] => false
[xmf] => false
[compactmidi] => false
[digiplug] => false
[nokia_ringtone] => false
[imelody] => false
[au] => false
[amr] => false
[awb] => false
[aac] => false
[mp3] => false
[voices] => 1
[qcelp] => false
[evrc] => false
[flash_lite_version] =>
[fl_wallpaper] => false
[fl_screensaver] => false
[fl_standalone] => false
[fl_browser] => false
[fl_sub_lcd] => false
[full_flash_support] => true
[css_supports_width_as_percentage] => true
[css_border_image] => none
[css_rounded_corners] => none
[css_gradient] => none
[css_spriting] => true
[css_gradient_linear] => none
[is_transcoder] => false
[transcoder_ua_header] => user-agent
[rss_support] => false
[pdf_support] => true
[progressive_download] => true
[playback_vcodec_h263_0] => -1
[playback_vcodec_h263_3] => -1
[playback_vcodec_mpeg4_sp] => -1
[playback_vcodec_mpeg4_asp] => -1
[playback_vcodec_h264_bp] => -1
[playback_real_media] => none
[playback_3gpp] => false
[playback_3g2] => false
[playback_mp4] => false
[playback_mov] => false
[playback_acodec_amr] => none
[playback_acodec_aac] => none
[playback_df_size_limit] => 0
[playback_directdownload_size_limit] => 0
[playback_inline_size_limit] => 0
[playback_oma_size_limit] => 0
[playback_acodec_qcelp] => false
[playback_wmv] => none
[hinted_progressive_download] => false
[html_preferred_dtd] => html4
[viewport_supported] => false
[viewport_width] =>
[viewport_userscalable] =>
[viewport_initial_scale] =>
[viewport_maximum_scale] =>
[viewport_minimum_scale] =>
[mobileoptimized] => false
[handheldfriendly] => false
[canvas_support] => none
[image_inlining] => true
[is_smarttv] => true
[is_console] => false
[nfc_support] => false
[ux_full_desktop] => false
[jqm_grade] => A
[is_sencha_touch_ok] => true
[controlcap_is_smartphone] => default
[controlcap_is_ios] => default
[controlcap_is_android] => default
[controlcap_is_robot] => default
[controlcap_is_app] => default
[controlcap_advertised_device_os] => default
[controlcap_advertised_device_os_version] => default
[controlcap_advertised_browser] => default
[controlcap_advertised_browser_version] => default
[controlcap_is_windows_phone] => default
[controlcap_is_full_desktop] => default
[controlcap_is_largescreen] => default
[controlcap_is_mobile] => default
[controlcap_is_touchscreen] => default
[controlcap_is_wml_preferred] => default
[controlcap_is_xhtmlmp_preferred] => default
[controlcap_is_html_preferred] => default
[controlcap_form_factor] => default
[controlcap_complete_device_name] => default
)
)
</code></pre></p>
</div>
<div class="modal-footer">
<a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a>
</div>
</div>
</td></tr></table>
</div>
<div class="section">
<h1 class="header center orange-text">About this comparison</h1>
<div class="row center">
<h5 class="header light">
The primary goal of this project is simple<br />
I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br />
<br />
The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br />
<br />
You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br />
<br />
The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a>
</h5>
</div>
</div>
<div class="card">
<div class="card-content">
Comparison created <i>2016-01-26 16:41:47</i> | by
<a href="https://github.com/ThaDafinser">ThaDafinser</a>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.1.1/list.min.js"></script>
<script>
$(document).ready(function(){
// the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered
$('.modal-trigger').leanModal();
});
</script>
</body>
</html> | {
"content_hash": "e9d917ccf5e1c436f2f4db9be1b7c849",
"timestamp": "",
"source": "github",
"line_count": 907,
"max_line_length": 540,
"avg_line_length": 40.79051819184124,
"alnum_prop": 0.5182582371543639,
"repo_name": "ThaDafinser/UserAgentParserComparison",
"id": "c5685b405e835e89fd3ea3cb65ac5331cb20aefd",
"size": "36998",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "v3/user-agent-detail/54/24/5424f939-f2c5-4e4e-b8d7-8c434a065e0b.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "2060859160"
}
],
"symlink_target": ""
} |
<dom-module name="openlayers-layer-group">
<template>
<content select="*"></content>
</template>
<script>
Polymer({
is: 'openlayers-layer-group',
properties: {
isLayerGroup: {type: Boolean, value: true},
map: {
type: Object,
observer: '_mapChanged'
},
title: {
type: String,
value: ""
},
layerGroup: {
type: Object
}
},
created: function () {
// console.log(this.localName + '#' + this.id + ' created ', arguments);
},
ready: function () {
// console.log(this.localName + '#' + this.id + ' ready ', arguments);
var me = this;
this.async(function () {
me.domReady()
}, 1);
},
attached: function () {
// console.log(this.localName + '#' + this.id + ' attached ', arguments);
},
detached: function () {
// console.log(this.localName + '#' + this.id + ' detached ', arguments);
this._mutationObserver.disconnect();
},
attributeChanged: function () {
// console.log(this.localName + '#' + this.id + ' attributeChanged ', arguments);
},
domReady: function () {
this._mutationObserver = new MutationObserver(this.registerContainerOnChildren.bind(this));
this._mutationObserver.observe(this, {childList: true});
},
_mapChanged: function () {
if (this.map) {
var layerGroup = this.layerGroup = new ol.layer.Group({
'title': this.title,
'map': this.map
});
this.map.addLayer(layerGroup);
this.registerContainerOnChildren();
}
},
registerContainerOnChildren: function () {
for (var i = 0; i < this.children.length; i++) {
this.children[i].layerGroup = this.layerGroup;
}
},
detached: function () {
if (this.map && this.map) {
this.map.removeLayer(this.map);
}
this._mutationObserver.disconnect();
}
});
</script>
</dom-module>
| {
"content_hash": "399a57f95ab85584ee90a4d3a6b6df86",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 107,
"avg_line_length": 33.753246753246756,
"alnum_prop": 0.4197768372450943,
"repo_name": "routetopa/deep-components",
"id": "c8c2f1031cf3fe3d0ec062becdb6d4fa12f17e01",
"size": "2599",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "datalets/openlayers-datalet/openlayers-layer-group.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "341621"
},
{
"name": "HTML",
"bytes": "2356826"
},
{
"name": "JavaScript",
"bytes": "41898397"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using GestureSample.Views;
using Xamarin.Forms;
namespace GestureSample
{
public class App : Application
{
public static NavigationPage MainNavigation;
public App()
{
var samplePages = new[] {
"ContentPage",
"Layouts",
"Views",
"Cells",
"Tests",
};
var mainPage = new MainPage() { Title = "Control Categories", BindingContext = samplePages };
MainPage = MainNavigation = new NavigationPage(mainPage);
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}
}
| {
"content_hash": "f5ba3b436e54226b884134f9b148b7dd",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 96,
"avg_line_length": 17.355555555555554,
"alnum_prop": 0.674775928297055,
"repo_name": "pacificIT/GestureSample",
"id": "c0b122f3f32b8d8ef2f92e9dd4be0e59e4e0bfb6",
"size": "783",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "GestureSample/GestureSample/App.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "108871"
}
],
"symlink_target": ""
} |
<?php /* Smarty version Smarty-3.1.18, created on 2014-07-02 17:16:06
compiled from "simpla/design/html/pagination.tpl" */ ?>
<?php /*%%SmartyHeaderCode:101446896853b2af3d7be3c9-81900301%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'8525564c8d119ad869e403b6d8062e04fc797163' =>
array (
0 => 'simpla/design/html/pagination.tpl',
1 => 1404308249,
2 => 'file',
),
),
'nocache_hash' => '101446896853b2af3d7be3c9-81900301',
'function' =>
array (
),
'version' => 'Smarty-3.1.18',
'unifunc' => 'content_53b2af3db26106_97331173',
'variables' =>
array (
'pages_count' => 0,
'current_page' => 0,
'visible_pages' => 0,
'page_from' => 0,
'page_to' => 0,
'p' => 0,
),
'has_nocache_code' => false,
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_53b2af3db26106_97331173')) {function content_53b2af3db26106_97331173($_smarty_tpl) {?><?php if ($_smarty_tpl->tpl_vars['pages_count']->value>1) {?>
<script type="text/javascript" src="design/js/ctrlnavigate.js"></script>
<!-- Листалка страниц -->
<div id="pagination">
<?php $_smarty_tpl->tpl_vars['visible_pages'] = new Smarty_variable(11, null, 0);?>
<?php $_smarty_tpl->tpl_vars['page_from'] = new Smarty_variable(1, null, 0);?>
<?php if ($_smarty_tpl->tpl_vars['current_page']->value>floor($_smarty_tpl->tpl_vars['visible_pages']->value/2)) {?>
<?php $_smarty_tpl->tpl_vars['page_from'] = new Smarty_variable(max(1,$_smarty_tpl->tpl_vars['current_page']->value-floor($_smarty_tpl->tpl_vars['visible_pages']->value/2)-1), null, 0);?>
<?php }?>
<?php if ($_smarty_tpl->tpl_vars['current_page']->value>$_smarty_tpl->tpl_vars['pages_count']->value-ceil($_smarty_tpl->tpl_vars['visible_pages']->value/2)) {?>
<?php $_smarty_tpl->tpl_vars['page_from'] = new Smarty_variable(max(1,$_smarty_tpl->tpl_vars['pages_count']->value-$_smarty_tpl->tpl_vars['visible_pages']->value-1), null, 0);?>
<?php }?>
<?php $_smarty_tpl->tpl_vars['page_to'] = new Smarty_variable(min($_smarty_tpl->tpl_vars['page_from']->value+$_smarty_tpl->tpl_vars['visible_pages']->value,$_smarty_tpl->tpl_vars['pages_count']->value-1), null, 0);?>
<a class="<?php if ($_smarty_tpl->tpl_vars['current_page']->value==1) {?>selected<?php } else { ?>droppable<?php }?>" href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['url'][0][0]->url_modifier(array('page'=>1),$_smarty_tpl);?>
">1</a>
<?php if (isset($_smarty_tpl->tpl_vars['smarty']->value['section']['pages'])) unset($_smarty_tpl->tpl_vars['smarty']->value['section']['pages']);
$_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['name'] = 'pages';
$_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['loop'] = is_array($_loop=$_smarty_tpl->tpl_vars['page_to']->value) ? count($_loop) : max(0, (int) $_loop); unset($_loop);
$_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['start'] = (int) $_smarty_tpl->tpl_vars['page_from']->value;
$_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['show'] = true;
$_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['max'] = $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['loop'];
$_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['step'] = 1;
if ($_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['start'] < 0)
$_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['start'] = max($_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['step'] > 0 ? 0 : -1, $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['loop'] + $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['start']);
else
$_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['start'] = min($_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['start'], $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['step'] > 0 ? $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['loop'] : $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['loop']-1);
if ($_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['show']) {
$_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['total'] = min(ceil(($_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['step'] > 0 ? $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['loop'] - $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['start'] : $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['start']+1)/abs($_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['step'])), $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['max']);
if ($_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['total'] == 0)
$_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['show'] = false;
} else
$_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['total'] = 0;
if ($_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['show']):
for ($_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['index'] = $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['start'], $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['iteration'] = 1;
$_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['iteration'] <= $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['total'];
$_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['index'] += $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['step'], $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['iteration']++):
$_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['rownum'] = $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['iteration'];
$_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['index_prev'] = $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['index'] - $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['step'];
$_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['index_next'] = $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['index'] + $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['step'];
$_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['first'] = ($_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['iteration'] == 1);
$_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['last'] = ($_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['iteration'] == $_smarty_tpl->tpl_vars['smarty']->value['section']['pages']['total']);
?>
<?php $_smarty_tpl->tpl_vars['p'] = new Smarty_variable($_smarty_tpl->getVariable('smarty')->value['section']['pages']['index']+1, null, 0);?>
<?php if (($_smarty_tpl->tpl_vars['p']->value==$_smarty_tpl->tpl_vars['page_from']->value+1&&$_smarty_tpl->tpl_vars['p']->value!=2)||($_smarty_tpl->tpl_vars['p']->value==$_smarty_tpl->tpl_vars['page_to']->value&&$_smarty_tpl->tpl_vars['p']->value!=$_smarty_tpl->tpl_vars['pages_count']->value-1)) {?>
<a class="<?php if ($_smarty_tpl->tpl_vars['p']->value==$_smarty_tpl->tpl_vars['current_page']->value) {?>selected<?php }?>" href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['url'][0][0]->url_modifier(array('page'=>$_smarty_tpl->tpl_vars['p']->value),$_smarty_tpl);?>
">...</a>
<?php } else { ?>
<a class="<?php if ($_smarty_tpl->tpl_vars['p']->value==$_smarty_tpl->tpl_vars['current_page']->value) {?>selected<?php } else { ?>droppable<?php }?>" href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['url'][0][0]->url_modifier(array('page'=>$_smarty_tpl->tpl_vars['p']->value),$_smarty_tpl);?>
"><?php echo $_smarty_tpl->tpl_vars['p']->value;?>
</a>
<?php }?>
<?php endfor; endif; ?>
<a class="<?php if ($_smarty_tpl->tpl_vars['current_page']->value==$_smarty_tpl->tpl_vars['pages_count']->value) {?>selected<?php } else { ?>droppable<?php }?>" href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['url'][0][0]->url_modifier(array('page'=>$_smarty_tpl->tpl_vars['pages_count']->value),$_smarty_tpl);?>
"><?php echo $_smarty_tpl->tpl_vars['pages_count']->value;?>
</a>
<a href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['url'][0][0]->url_modifier(array('page'=>'all'),$_smarty_tpl);?>
">все сразу</a>
<?php if ($_smarty_tpl->tpl_vars['current_page']->value>1) {?><a id="PrevLink" href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['url'][0][0]->url_modifier(array('page'=>$_smarty_tpl->tpl_vars['current_page']->value-1),$_smarty_tpl);?>
">←назад</a><?php }?>
<?php if ($_smarty_tpl->tpl_vars['current_page']->value<$_smarty_tpl->tpl_vars['pages_count']->value) {?><a id="NextLink" href="<?php echo $_smarty_tpl->smarty->registered_plugins[Smarty::PLUGIN_FUNCTION]['url'][0][0]->url_modifier(array('page'=>$_smarty_tpl->tpl_vars['current_page']->value+1),$_smarty_tpl);?>
">вперед→</a><?php }?>
</div>
<!-- Листалка страниц (The End) -->
<?php }?>
<?php }} ?>
| {
"content_hash": "b634a67b2e3862e3f815b82d3720a336",
"timestamp": "",
"source": "github",
"line_count": 120,
"max_line_length": 515,
"avg_line_length": 76.9,
"alnum_prop": 0.6097745990463805,
"repo_name": "NickTaporuk/cloth",
"id": "63923751dcb1bc2018ec3fee7b7fd3c7dd026555",
"size": "9281",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "simpla/design/compiled/8525564c8d119ad869e403b6d8062e04fc797163.file.pagination.tpl.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "185669"
},
{
"name": "Java",
"bytes": "35588"
},
{
"name": "JavaScript",
"bytes": "3052880"
},
{
"name": "LiveScript",
"bytes": "6103"
},
{
"name": "PHP",
"bytes": "3417639"
},
{
"name": "Perl",
"bytes": "67663"
},
{
"name": "Shell",
"bytes": "334"
}
],
"symlink_target": ""
} |
// 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.
#pragma once
#include "Characters/EtherealCharacterMaster.h"
#include "Characters/Player/WeaponModes.h"
#include "Gear/Magic/Magic_AnimTypes.h"
//#include "NPCs/EtherealNPCMaster.h"
#include "NPCs/InteractAnims.h"
#include "EtherealPlayerState.h"
#include "EtherealPlayerController.h"
#include "EtherealPlayerMaster.generated.h"
#if !(UE_BUILD_SHIPPING || UE_BUILD_TEST)
//static void ConsoleGiveAllItems()
//{
// //GEngine->AddOnScreenDebugMessage(-1, 10.f, FColor::Red, "Do some bullshit here!");
//}
//
//FAutoConsoleCommand ConsoleAllItems(
// TEXT("EtherealConsole.GiveAllItems"),
// TEXT("Fills the player's inventory with all items available in the game."),
// FConsoleCommandDelegate::CreateStatic(ConsoleGiveAllItems)
//);
#endif
// Forward Declarations
class AEtherealEnemyMaster;
class AEtherealNPCMaster;
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FDeadPlayer);
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FMapOpened);
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FMapClosed);
UCLASS()
class ETHEREAL_API AEtherealPlayerMaster : public AEtherealCharacterMaster
{
GENERATED_BODY()
public:
AEtherealPlayerMaster(const FObjectInitializer& ObjectInitializer);
// BeginPlay Override
virtual void BeginPlay() override;
// Called every frame
virtual void Tick(float DeltaSeconds) override;
// Event Dispatcher for FadeOutEndGame
UPROPERTY(BlueprintAssignable, BlueprintCallable, Category = Dispatchers)
FDeadPlayer DeadPlayer;
//////////////////////////////////////////////////
// OBJECTS
// Exclamation Point mesh that appears over the player's head when in range of an NPC
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Default)
UStaticMeshComponent* Exclamation;
UStaticMesh* SM_Exclamation;
//////////////////////////////////////////////////
// DEFAULTS
// The Magic Anim Type to play when casting a spell.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Default)
EMagic_AnimTypes ActiveSpellAnimType;
// A reference to the Ethereal Player State.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Default)
AEtherealPlayerState* EtherealPlayerState;
// A reference to the Ethereal Player Controller.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Default)
AEtherealPlayerController* EtherealPlayerController;
// Enemy Aggro List. Enemies are added to this list as they are aggroed, and removed accordingly.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Default)
TArray<AEtherealEnemyMaster*> AggroList;
// This function will dynamically set the character's skin opacity mask, to strategically hide skin when certain armor pieces are equipped
UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = Default)
void SetSkinOpacityMask();
///////////////////////////////////////////////////
// A.I.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = AI)
UPawnNoiseEmitterComponent* PawnNoiseEmitter;
// The function that is going to play the footstep sound and report it to all enemies
UFUNCTION(BlueprintCallable, Category = AI)
void ReportFootstep(UAudioComponent* SoundToPlay);
////////////////////////////////////////////////////
// CONTROL STATES
// Stops all actions the player may be performing, including; movement, attacking, blocking, interacting
UFUNCTION(BlueprintCallable, Category = Controls)
void StopActions();
UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = Controls)
void StopAttacking();
UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = Controls)
void StopBlocking();
// Whether or not the player has toggled RUN status
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Controls)
bool IsRunning;
// Whether or not the player is attacking
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Controls)
bool IsAttacking;
// Whether or not the player is blocking
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Controls)
bool IsBlocking;
// Whether or not the player will take fall damage
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Controls)
bool TakeFallDamage;
// Plays the "Get Up" animation after reviving from death.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Controls)
bool GetUp;
////////////////////////////////////////////////
// SPELL CASTING
// Determines which Magic Binding Tier is active: 0 is base tier, 1 is secondary tier. We could add more tiers in the future by increasing this number...
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Spellcast)
int32 MagicTier;
// If the player is dashing. Useful for determining when other things are disallowed.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Spellcast)
bool IsDashing;
// This becomes true if the player is Hasted, so as to have an effect on other systems.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Spellcast)
bool IsHasted;
// Is True when a spell is charging.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Spellcast)
bool IsCharging;
// Becomes true when a spell is fully charged, but not yet cast.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Spellcast)
bool CanCast;
// Plays the cast animation, based on the currently charged spell type.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Spellcast)
bool DoCastAnim;
// The current charge rate of a spell. When it matches the TimeToCast, the spell is fully charged and ready to be cast.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Spellcast)
float ChargeRate = 0;
// The current charge rate of a spell. When it matches the TimeToCast, the spell is fully charged and ready to be cast.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Spellcast)
float TimeToCast = 0;
// This function returns the player to a certain location within the current realm.
UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = Default)
void TeleportReturn(bool ShouldRaise);
/////////////////////////////////////////////////
// MOVEMENT
// The Player's forward movement speed.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Movement)
float SpeedForward = 0;
// The Player's lateral movement speed.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Movement)
float SpeedRight = 0;
// Toggles the player's running speed
UFUNCTION(BlueprintCallable, Category = Movement)
void ToggleRunState();
// Sets teh player's movement speed
UFUNCTION(BlueprintCallable, Category = Movement)
void SetMovementSpeed();
//////////////////////////////////////////////////
// MENU / MAP CONTROL
// This is called if you have the menu open and are aggroed by an enemy
UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = Controls)
void EnemyCloseMenu();
// Map Control is true if the pause menu map is currently displayed. This allows the analog stick input to have a new context
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Map)
bool MapControl;
// Event Dispatcher for FadeOutEndGame
UPROPERTY(BlueprintAssignable, BlueprintCallable, Category = Dispatchers)
FMapOpened MapOpened;
// Event Dispatcher for FadeOutEndGame
UPROPERTY(BlueprintAssignable, BlueprintCallable, Category = Dispatchers)
FMapClosed MapClosed;
// Map Zoom Minimum Distance.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Map)
float MapZoom_Min = 50.0f;
// Map Zoom Maximum Distance.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Map)
float MapZoom_Max = 3500.0f;
// Map Scroll Speed.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Map)
float MapScroll_Speed = 20.0f;
// Map Scroll Maximum Distance in any direction.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Map)
float MapScroll_Max = 10000.0f;
//////////////////////////////////////////////////
// CAMERA CONTROL
// Max Camera Rotation Interp Speed
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Camera)
float CamRotSpeed = 10.0f;
// Camera Max Degree Clamp
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Camera)
float CamClampDegreeMax = 40.0f;
// Camera Min Degree Clamp
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Camera)
float CamClampDegreeMin = -40.0f;
//////////////////////////////////////////////////
// COMBAT
// Damage Output value during combat
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat)
float DamageOutput = 0.0f;
// Amount of DEF stored when blocking
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Combat)
int32 StoredDEF = 0.0f;
// This function sets the DamageOutput variable, based on the BaseAtk value of an attack. Returns the ultimate value of damage dealt to an enemy.
UFUNCTION(BlueprintCallable, Category = Combat)
void PlayerDealDamage(float BaseAtk);
// This function deals damage to the player, based on a DamageTaken value supplied by an enemy. This function is usually called by the enemy itself.
UFUNCTION(BlueprintCallable, Category = Combat)
void PlayerTakeDamage(float DamageTaken);
// Start the Death Cycle
UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = Combat)
void StartDeathCycle();
// Hide All Bound Weapons
UFUNCTION(BlueprintCallable, Category = Combat)
void HideAllBoundWeapons();
//////////////////////////////////////////////////
// NPC INTERACTION
// If the player is Interacting with an NPC
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = NPC)
bool IsInteracting;
// Play an NPC Interaction Animation
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = NPC)
bool DoInteractAnim;
// Do the Flight animation. This is only accessible from the Portal NPC
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = NPC)
bool DoFlight;
// The current NPC Interaction Animation
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = NPC)
EInteractAnims InteractAnimType = EInteractAnims::IA_None;
// Actor reference to the NPC with which the player is currently interacting
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = NPC)
AEtherealNPCMaster* InteractTarget;
// Interacts with a NPC, called by the player pressing the action button while in range of an NPC
UFUNCTION(BlueprintCallable, Category = NPC)
void Interact();
////////////////////////////////////////////////
// LEVEL UP
// Level Up FX
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = LevelUp)
UParticleSystemComponent* LevelUpFX;
UParticleSystem* P_LevelUpFX;
// Level Up Camera Shake
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = LevelUp)
TSubclassOf<UCameraShake> LevelUpCamShake;
///////////////////////////////////////////
// COMBAT LOCK ON TARGETING
// A reference for storing the Current Target.
// This is classed as an EtherealCharacterMaster because in an early prototype multiplayer version of Ethereal, you could also target other players.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Targeting)
AEtherealCharacterMaster* CurrentTarget;
// Minimum Targeting Distance
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Targeting)
float TargetingDistance_Min = 5.0f;
// Maximum Targeting Distance
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Targeting)
float TargetingDistance_Max = 500.0f;
// The current index of the target in the AvailableTargets array
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Targeting)
int32 TargetIndex;
// A list of currently available targets. Filled when the player first hits the left shoulder button.
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Targeting)
TArray<AEtherealCharacterMaster*> AvailableTargets;
// Whether or not the player is locked on a target
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Targeting)
bool LockedOnTarget;
///////////////////////////////////////////
// EQUIPMENT SPECIAL EFFECTS
// Whether or not the player has Shadow Gear equipped, which occasionally nullifies damage
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpecialEquipmentEffect)
bool HasDefenseWall;
// Whether or not the player has Shadow Gear equipped, which occasionally nullifies damage
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpecialEquipmentEffect)
bool HasShadowGear;
// Whether or not the player has sneak, which mask the sound of footsteps
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpecialEquipmentEffect)
bool HasSneak;
// Whether or not the player has fast pants equipped, which are Leg Armor that increases movement speed
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpecialEquipmentEffect)
bool HasFastPants;
// Whether or not the player is lightfooted, which prevents fall damage
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpecialEquipmentEffect)
bool HasLightfoot;
// Whether or not the player has the Reraise effect active
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpecialEquipmentEffect)
bool HasReraise;
// If the player has the Null Burn effect (generally granted via armor special effect)
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpecialEquipmentEffect)
bool NullBurn;
// If the player has the Null Poison effect (generally granted via armor special effect)
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpecialEquipmentEffect)
bool NullPoison;
// If the player has the Null Confuse effect (generally granted via armor special effect)
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpecialEquipmentEffect)
bool NullConfuse;
// If the player has the Null Silence effect (generally granted via armor special effect)
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpecialEquipmentEffect)
bool NullSilence;
// If the player has One-Handed Boost active
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpecialEquipmentEffect)
bool BoostOneHanded;
// If the player has Two-Handed Boost active
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpecialEquipmentEffect)
bool BoostTwoHanded;
// If the player has Ranged Boost active
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpecialEquipmentEffect)
bool BoostRanged;
// If the player has Cure Potency Boost active
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = SpecialEquipmentEffect)
float BoostCurePotency;
};
| {
"content_hash": "f607625662614937968397d8c93123f2",
"timestamp": "",
"source": "github",
"line_count": 399,
"max_line_length": 154,
"avg_line_length": 38.010025062656645,
"alnum_prop": 0.7359224581300277,
"repo_name": "Soverance/EtherealLegends",
"id": "791feb84ffa0a94b65938cc9661b4ca9667d9129",
"size": "15232",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Ethereal/Public/Characters/Player/EtherealPlayerMaster.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "2138"
},
{
"name": "C#",
"bytes": "5312"
},
{
"name": "C++",
"bytes": "1531001"
}
],
"symlink_target": ""
} |
package org.springframework.boot.context.web;
import javax.servlet.Filter;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.builder.ParentContextApplicationContextInitializer;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext;
import org.springframework.boot.context.embedded.ServletContextInitializer;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.WebApplicationContext;
/**
* An opinionated {@link WebApplicationInitializer} to run a {@link SpringApplication}
* from a traditional WAR deployment. Binds {@link Servlet}, {@link Filter} and
* {@link ServletContextInitializer} beans from the application context to the servlet
* container.
* <p>
* To configure the application either override the
* {@link #configure(SpringApplicationBuilder)} method (calling
* {@link SpringApplicationBuilder#sources(Object...)}) or make the initializer itself a
* {@code @Configuration}. If you are using {@link SpringBootServletInitializer} in
* combination with other {@link WebApplicationInitializer WebApplicationInitializers} you
* might also want to add an {@code @Ordered} annotation to configure a specific startup
* order.
* <p>
* Note that a WebApplicationInitializer is only needed if you are building a war file and
* deploying it. If you prefer to run an embedded container then you won't need this at
* all.
*
* @author Dave Syer
* @author Phillip Webb
* @see #configure(SpringApplicationBuilder)
*/
public abstract class SpringBootServletInitializer implements WebApplicationInitializer {
protected final Log logger = LogFactory.getLog(getClass());
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext rootAppContext = createRootApplicationContext(servletContext);
if (rootAppContext != null) {
servletContext.addListener(new ContextLoaderListener(rootAppContext) {
@Override
public void contextInitialized(ServletContextEvent event) {
// no-op because the application context is already initialized
}
});
}
else {
this.logger.debug("No ContextLoaderListener registered, as "
+ "createRootApplicationContext() did not "
+ "return an application context");
}
}
protected WebApplicationContext createRootApplicationContext(
ServletContext servletContext) {
SpringApplicationBuilder builder = createSpringApplicationBuilder();
ApplicationContext parent = getExistingRootWebApplicationContext(servletContext);
if (parent != null) {
this.logger.info("Root context already created (using as parent).");
servletContext.setAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null);
builder.initializers(new ParentContextApplicationContextInitializer(parent));
}
builder.initializers(new ServletContextApplicationContextInitializer(
servletContext));
builder.contextClass(AnnotationConfigEmbeddedWebApplicationContext.class);
builder = configure(builder);
SpringApplication application = builder.build();
if (application.getSources().isEmpty()
&& AnnotationUtils.findAnnotation(getClass(), Configuration.class) != null) {
application.getSources().add(getClass());
}
Assert.state(application.getSources().size() > 0,
"No SpringApplication sources have been defined. Either override the "
+ "configure method or add an @Configuration annotation");
// Ensure error pages are registered
application.getSources().add(ErrorPageFilter.class);
return run(application);
}
/**
* Returns the {@code SpringApplicationBuilder} that is used to configure and create
* the {@link SpringApplication}. The default implementation returns a new
* {@code SpringApplicationBuilder} in its default state.
*
* @return the {@code SpringApplicationBuilder}.
* @since 1.3.0
*/
protected SpringApplicationBuilder createSpringApplicationBuilder() {
return new SpringApplicationBuilder();
}
/**
* Called to run a fully configured {@link SpringApplication}.
* @param application the application to run
* @return the {@link WebApplicationContext}
*/
protected WebApplicationContext run(SpringApplication application) {
return (WebApplicationContext) application.run();
}
private ApplicationContext getExistingRootWebApplicationContext(
ServletContext servletContext) {
Object context = servletContext
.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
if (context instanceof ApplicationContext) {
return (ApplicationContext) context;
}
return null;
}
/**
* Configure the application. Normally all you would need to do it add sources (e.g.
* config classes) because other settings have sensible defaults. You might choose
* (for instance) to add default command line arguments, or set an active Spring
* profile.
* @param builder a builder for the application context
* @return the application builder
* @see SpringApplicationBuilder
*/
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder;
}
}
| {
"content_hash": "2687256abf018f30af0854f6e1a7a8fb",
"timestamp": "",
"source": "github",
"line_count": 141,
"max_line_length": 95,
"avg_line_length": 40.666666666666664,
"alnum_prop": 0.7881060341820718,
"repo_name": "tan9/spring-boot",
"id": "9bc3ae6da4629b14c151102a9aa5ae13025b2557",
"size": "6354",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "spring-boot/src/main/java/org/springframework/boot/context/web/SpringBootServletInitializer.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1948"
},
{
"name": "CSS",
"bytes": "5646"
},
{
"name": "Groovy",
"bytes": "45365"
},
{
"name": "HTML",
"bytes": "68753"
},
{
"name": "Java",
"bytes": "5837414"
},
{
"name": "JavaScript",
"bytes": "4197"
},
{
"name": "Ruby",
"bytes": "1305"
},
{
"name": "SQLPL",
"bytes": "20085"
},
{
"name": "Shell",
"bytes": "7505"
},
{
"name": "Smarty",
"bytes": "2885"
},
{
"name": "XSLT",
"bytes": "33894"
}
],
"symlink_target": ""
} |
package com.testclient.model;
import java.util.HashMap;
import java.util.Map;
import com.testclient.httpmodel.ServerItem;
public class SocketTarget {
private ServerItem server=new ServerItem();
private String code="";
private String head="";
private String body="";
private int datagramVersion=5;
private boolean indented=true;
private Map<String,Parameter> parameters=new HashMap<String,Parameter>();
private String serviceDescription;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public ServerItem getServer() {
return server;
}
public void setServer(ServerItem server) {
this.server = server;
}
public String getHead() {
return head;
}
public void setHead(String head) {
this.head = head;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public int getDatagramVersion() {
return datagramVersion;
}
public void setDatagramVersion(int datagramVersion) {
this.datagramVersion = datagramVersion;
}
public boolean isIndented() {
return indented;
}
public void setIndented(boolean indented) {
this.indented = indented;
}
public Map<String,Parameter> getParameters() {
return parameters;
}
public void setParameters(Map<String,Parameter> parameters) {
this.parameters = parameters;
}
public String getServiceDescription() {
return serviceDescription;
}
public void setServiceDescription(String serviceDescription) {
this.serviceDescription = serviceDescription;
}
}
| {
"content_hash": "4d015485503a2d0cee2d07e1ed82842f",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 74,
"avg_line_length": 22.98507462686567,
"alnum_prop": 0.7448051948051948,
"repo_name": "Gnail-nehc/testclient",
"id": "02d8cf607a1b3786e74831135cc4d2a53a2e3f1e",
"size": "1540",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/testclient/model/SocketTarget.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1240489"
},
{
"name": "HTML",
"bytes": "1564"
},
{
"name": "Java",
"bytes": "347006"
},
{
"name": "JavaScript",
"bytes": "415430"
}
],
"symlink_target": ""
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>W3C Test Case and Bug Report</title>
<meta name="description" content="A session of Test the Web Forward at Shanghai" href="http://testthewebforward.org/events/shanghai-2013.html">
<meta name="presdate" content="20130818">
<meta name="author" content="Zhiqiang Zhang" href="mailto:zhiqiang.zhang@intel.com">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<link rel="stylesheet" href="../../../css/reveal.min.css">
<link rel="stylesheet" href="../../../css/theme/beige.css" id="theme">
<!-- For syntax highlighting -->
<link rel="stylesheet" href="../../../lib/css/zenburn.css">
<!-- If the query includes 'print-pdf', use the PDF print sheet -->
<script>
document.write( '<link rel="stylesheet" href="../../../css/print/' + ( window.location.search.match( /print-pdf/gi ) ? 'pdf' : 'paper' ) + '.css" type="text/css" media="print">' );
</script>
<!--[if lt IE 9]>
<script src="../../../lib/js/html5shiv.js"></script>
<![endif]-->
</head>
<body>
<div class="reveal">
<div class="slides">
<section>
<h1>W3C Test Case and Bug Report</h1>
<p>
<i>Zhiqiang Zhang (<a href="https://github.com/zqzhang" class="url Nickname">zqzhang</a>), <a class="org" href="http://www.intel.com/">Intel</a></i>
</p>
</section>
<section>
<h2>Agenda</h2>
<ul>
<li>How to write a manual test case?</li>
<li>How to write a Reftest?</li>
<li>How to write a Script test?</li>
<li>How to file a good bug report?</li>
</ul>
</section>
<!-- Reftest -->
<section>
<section>
<h2>Start from Example in Spec</h2>
<img src="../../../img/reftest-spec-example.png">
<p>Example 14.3 in CSS3 <a href="http://www.w3.org/TR/css3-background/#the-background-size">background-size</a></p>
</section>
<section>
<h2>To Checkpoints</h2>
<ul>
<li><code>background-size: length auto</code>:
<br>scale the image width to 'length' and height to (1) the image's intrinsic ratio and the size of width, or (2) the image's intrinsic size, or (3) 100%</li>
<li><code>background-repeat: round repeat</code>:
<br>scale the image in width so that it fits a whole number of times in the background positioning area</li>
<li><code>round</code> for width and <code>auto</code> for height, so height is scaled to keep the image's original aspect ratio</li>
</ul>
</section>
<section>
<h2>Copy Test Case Template</h2>
<pre><code data-trim contenteditable>
<!DOCTYPE html>
<title>[Test Area]: [Title/Scope of Test]</title>
<link rel="author" title="[Name of Author]" href=mailto:EMAIL OR
http://CONTACT_PAGE">
<link rel="help" href="http://www.w3.org/TR/[direct link to tested
section]">
<link rel="match" href="[path to reference file]">
<meta name="flags" content="[requirement flags]">
<meta name="assert" content="Test checks that [explanation of what
you're trying to test].">
<style>
[CSS for test]
</style>
<body>
<p> Test passes if [description of pass condition].</p>
[Content of test]
</body>
</code></pre>
<p><a href="https://github.com/w3c/testtwf-website/blob/gh-pages/docs/test-templates.md#reftest-test-template">test-templates.md#reftest-test-template</a></p>
</section>
<section>
<h2>To Test Case: Style</h2>
<img src="../../../img/reftest-style.png">
</section>
<section>
<h2>To Test Case: Pass Condition</h2>
<img src="../../../img/reftest-pass-condition.png">
</section>
<section>
<h2>Try Test Case on Browsers</h2>
<img src="../../../img/reftest-opera12.png">
</section>
<section>
<h2>Try Test Case on Browsers</h2>
<img src="../../../img/reftest-chrome28.png">
<img src="../../../img/reftest-firefox23.png">
</section>
<section>
<h2>Complete Test File</h2>
<a href="http://test.csswg.org/source/contributors/intel/submitted/css3-background/background-size-029.html">http://test.csswg.org/source/contributors/intel/submitted/css3-background/background-size-029.html</a>
</section>
<section>
<h2>Reference File</h2>
<ul>
<p>The reference file should look exactly like the test file, except that the code behind it is different.</p>
<br>
<li>The <code>assert</code> metadata is taken out.</li>
<li>The <code>title</code> is generic, as this file can and may be shared among multiple tests</li>
<li>The <code>match</code> (or <code>mismatch</code>) metadata not necessary</li>
<li>The markup that created the actual test data is different: here, the same effect is created with very mundane, dependable technology.</li>
</section>
<section>
<h2>Copy Reference File Template</h2>
<pre><code data-trim contenteditable>
<!DOCTYPE html>
<title>[Test Area] Reference File</title>
<link rel="author" title="[Name of Author]" href=mailto:EMAIL OR
http://CONTACT_PAGE">
<style>
[CSS for test]
</style>
<body>
<p> Test passes if [description of pass condition].</p>
[Content of test]
</body>
</code></pre>
<p><a href="https://github.com/w3c/testtwf-website/blob/gh-pages/docs/test-templates.md#reftest-ref-template">test-templates.md#reftest-ref-template</a></p>
</section>
<section>
<h2>Reference File Source</h2>
<img src="../../../img/reftest-reference-style.png">
</section>
<section>
<h2>Try Reference File on Browsers</h2>
<img src="../../../img/reftest-opera12-ref.png">
<img src="../../../img/reftest-opera12.png">
</section>
<section>
<h2>Reftest</h2>
<ul>
<p><a href="https://github.com/w3c/testtwf-website/blob/gh-pages/docs/reftests.md#definition">Definition</a>:</p>
<li>A reftest is a test that compares the visual output of one file (the test case) with the output of one or more other files (the references).</li>
<p><a href="https://github.com/w3c/testtwf-website/blob/gh-pages/docs/reftests.md#components">Components</a>:</p>
<li>Test file: <a href="http://test.csswg.org/source/contributors/intel/submitted/css3-background/background-size-029.html">background-size-029.html</a></li>
<li>Reference file: <a href="http://test.csswg.org/source/contributors/intel/submitted/css3-background/reference/background-size-029-ref.xht">background-size-029-ref.html</a></li>
<li>Comparison:</li>
<pre><code data-trim contenteditable>
<link rel="match" href="reference/background-size-029-ref.xht">
</code></pre>
</ul>
</section>
<section>
<h2>Continue to Improve the Test</h2>
<img src="../../../img/reftest-commits.png">
<p><a href="http://hg.csswg.org/test/log/923e1f7bf2c6/contributors/intel/submitted/css3-background/background-size-029.html">Commits to background-size-029.html</a></p>
</section>
<section>
<p>background-size-029.html: <a href="http://hg.csswg.org/test/file/1d2d1d9ae507/contributors/intel/submitted/css3-background/background-size-029.html">approved</a> v.s. <a href="http://hg.csswg.org/test/file/d266aff0a27a/contributors/intel/submitted/css3-background/background-size-029.html">initial</a></p>
<img src="../../../img/reftest-compare-metadata.png">
</section>
<section>
<img src="../../../img/reftest-compare-style.png">
</section>
<section>
<img src="../../../img/reftest-compare-body.png">
</section>
</section>
<!-- Tips -->
<section>
<section>
<h2>Tests to avoid: long test</h2>
<ul>
<li>Manual test</li>
<li>Need to scroll to complete testing</li>
<li><a href="http://www.hixie.ch/tests/evil/mixed/lineheight3.html">Example</a> of a test that is too long</li>
</ul>
</section>
<section>
<h2>Tests to avoid: "this should be red" test</h2>
<ul>
<li>In the W3C <a href="https://github.com/w3c/testtwf-website/blob/gh-pages/docs/test-style-guidelines.md">test style guidelines</a> document, <span style="background-color:red">red</span> indicates a bug</li>
<li>Nothing should ever be <span style="background-color:red">red</span> in a test.</li>
<li>One exception: the test for the <span style="color:red">'red'</span> value for the color properties!</li>
</li>
</section>
<section>
<h2>Tests to avoid: unobvious test</h2>
<img src="../../../img/unobvious-test.png">
<p>The last <a href="http://www.w3.org/Style/CSS/Test/CSS1/current/sec525.htm">subtest on this page</a> shows this problem.</p>
</section>
<section>
<h2>Tips: vendor prefix</h2>
<ul>
<li>You may need to add a vendor prefix to the CSS property you're testing</li>
<li>If the prefix is necessary, your test will appear to fail without it</li>
<li>However, do not include vendor prefixes when pushing tests to the W3C</li>
</ul>
</section>
</section>
<!-- Script test -->
<section>
<section>
<h2>What is Script Test?</h2>
<pre><code data-trim contenteditable>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<link rel="stylesheet" href="/resources/testharness.css">
<div id="log"></div>
</code></pre>
<p><a href="https://github.com/w3c/testharness.js/blob/master/testharness.js">testharness.js</a></p>
<p><a href="https://github.com/w3c/testtwf-website/blob/gh-pages/docs/testharness-documentation.md">testharness-documentation.md</a></p>
</section>
<section>
<h2>From IDL Fragment in Spec</h2>
<img src="../../../img/script-test-idl.png">
<p><a href="http://www.w3.org/TR/FileAPI/#blob">Blob Interface</a> in FileAPI</p>
</section>
<section>
<h2>And Description in the Spec</h2>
<img src="../../../img/script-test-spec.png">
<p><a href="http://www.w3.org/TR/FileAPI/#constructorBlob">Blob Constructor</a> in FileAPI</p>
</section>
<section>
<h2>To Checkpoints</h2>
<ul>
<p>blob = Blob()</code>:</p>
<li>blob instanceof Blob</li>
<li>blob.size === 0</li>
<li>blob.type === ""</li>
</ul>
</section>
<section>
<h2>Copy Script Test Template</h2>
<pre><code data-trim contenteditable>
<!DOCTYPE html>
<title>[Test Area]: [Title/Scope of Test]</title>
<link rel="author" title="[Name of Author]" href=mailto:EMAIL OR
http://CONTACT_PAGE">
<link rel="help" href="http://www.w3.org/TR/[direct link to tested
section]">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<link rel="stylesheet" href="/resources/testharness.css">
<div id="log"></div>
<script>
test(function() {
[body of test function - must include at least one assert*()
function]
}, [Test Name]);
/* Include as many test() functions as you need */
</script>
</code></pre>
<p><a href="https://github.com/w3c/testtwf-website/blob/gh-pages/docs/test-templates.md#script-test-shared-metadata">test-templates.md#script-test-shared-metadata</a></p>
</section>
<section>
<h2>To Test Case</h2>
<p><a href="http://w3c-test.org/web-platform-tests/master/FileAPI/tests/submissions/Ms2ger/Blob-constructor.html">Blob-constructor.html</a></p>
<img src="../../../img/script-test-code.png">
</section>
<section>
<h2>Try Test Case on Browsers</h2>
<img src="../../../img/script-test-opera12.png">
</section>
</section>
<!-- Bug report -->
<section>
<section>
<h2>Where to Report a Bug?</h2>
<ul>
<li>Test bugs:</li>
<ul>
<li><a href="https://github.com/w3c/web-platform-tests/issues">https://github.com/w3c/web-platform-tests/issues</a></li>
<li><a href="https://test.csswg.org/shepherd/">https://test.csswg.org/shepherd/</a></li>
</ul>
<li>Browser bugs:</li>
<ul>
<li><a href="https://bugzilla.mozilla.org/">Mozilla Bugzilla</a>, <a href="https://bugs.webkit.org/">WebKit Bugzilla</a>, <a href="http://crbug.com/">Chrome Bugs</a>, <a href="http://connect.microsoft.com/IE">IE Bugs</a>, <a href="http://pcbbs.baidu.com/forum.php?gid=1">Baidu Bugs</a>, <a href="https://bugs.tizen.org/">Tizen Web Runtime Bugs</a></li>
<li>Other browsers - please check vendor's website for bug reporting information</li>
</ul>
<li>Spec bugs:</li>
<ul>
<li><a href="https://www.w3.org/Bugs/Public/">W3C Bugzilla</a></li>
<li><a href="http://lists.w3.org/">W3C mailing list</a></li>
</ul>
</ul>
</section>
<section>
<h2>Bug Reporting General Guidelines</h2>
<ul>
<li>Avoid duplicates: <strong>Search before you file!</strong></li>
<li>Always test the latest available build.</li>
<li><strong>One</strong> bug per report.</li>
<li>State useful facts, not opinions or complaints.</li>
<li>Flag security/privacy vulnerabilities as non-public.</li>
<br>
<li>Follow your project bug reporting guidelines instead of these!</li>
</ul>
</section>
<section>
<h2>How to File a Good Bug Report</h2>
<ul>
<li>Summary</li>
<li>Description</li>
<li>Steps to Reproduce</li>
<li>Actual Results</li>
<li>Expected Results</li>
<li>Reduced Test Case</li>
<li>Version, Platform and OS</li>
<li>Crash data and/or Screenshot</li>
</ul>
</section>
<section>
<h2><a href="https://bugzilla.mozilla.org/show_bug.cgi?id=869878">Bug Report Sample</a></h2>
<img src="../../../img/bug-example.png">
</section>
</section>
<section>
<h2>References</h2>
<ul>
<li><a href="https://github.com/w3c/testtwf-website">https://github.com/w3c/testtwf-website</a></li>
<ul>
<li><a href="https://github.com/w3c/testtwf-website/blob/gh-pages/docs/reftests.md">reftests.md</a></li>
<li><a href="https://github.com/w3c/testtwf-website/blob/gh-pages/docs/testharness-documentation.md">testharness-documentation.md</a></li>
<li><a href="https://github.com/w3c/testtwf-website/blob/gh-pages/docs/bugreporting.md">bugreporting.md</a></li>
</ul>
<br>
<li><a href="https://github.com/w3c/web-platform-tests">https://github.com/w3c/web-platform-tests</a></li>
<br>
<li><a href="https://github.com/w3c/csswg-test">https://github.com/w3c/csswg-test</a></li>
</ul>
</section>
<section>
<h2>Acknowledgements</h2>
<ul>
<li>Rebecca Hauck & Jacob Goldstein, <a href="http://adobe.github.io/web-platform/presentations/test-the-web-forward-tutorial/index.html">Learn how to create a W3C Ref and JS tests</a></li>
<li>Elika J. Etemad, <a href="http://fantasai.inkedblade.net/style/talks/filing-good-bugs/">How to File a Good Bug Report</a></li>
<br>
<li>Gerard Talbot, <a href="http://lists.w3.org/Archives/Public/public-css-testsuite/2012Nov/0037.html">background-size-[025-029]: available, improved replacements</a></li>
<li>Hakim El Hattab, <a href="https://github.com/hakimel/reveal.js">reveal.js</a></li>
</ul>
</section>
<section>
<h2>Ready? Go!</h2>
<ul>
<li>Let's start the Test Hackathon!</li>
<br>
<li>Write test cases for the 6 specs and beyond.</li>
<br>
<li>File good bug reports.</li>
</ul>
</section>
</div>
</div>
<script src="../../../lib/js/head.min.js"></script>
<script src="../../../js/reveal.min.js"></script>
<script>
// Full list of configuration options available here:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
controls: true,
progress: true,
history: true,
center: true,
theme: Reveal.getQueryHash().theme, // available themes are in /css/theme
transition: Reveal.getQueryHash().transition || 'default', // default/cube/page/concave/zoom/linear/fade/none
// Optional libraries used to extend on reveal.js
dependencies: [
{ src: '../../../lib/js/classList.js', condition: function() { return !document.body.classList; } },
{ src: '../../../plugin/markdown/marked.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: '../../../plugin/markdown/markdown.js', condition: function() { return !!document.querySelector( '[data-markdown]' ); } },
{ src: '../../../plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } },
{ src: '../../../plugin/zoom-js/zoom.js', async: true, condition: function() { return !!document.body.classList; } },
{ src: '../../../plugin/notes/notes.js', async: true, condition: function() { return !!document.body.classList; } }
// { src: '../../../plugin/leap/leap.js', async: true }
// { src: '../../../plugin/search/search.js', async: true, condition: function() { return !!document.body.classList; } }
// { src: '../../../plugin/remotes/remotes.js', async: true, condition: function() { return !!document.body.classList; } }
]
});
</script>
</body>
</html>
| {
"content_hash": "336ebc11311b8156dfc248a68f17aa20",
"timestamp": "",
"source": "github",
"line_count": 416,
"max_line_length": 368,
"avg_line_length": 47.10336538461539,
"alnum_prop": 0.5686654758867058,
"repo_name": "zqzhang/talk",
"id": "92d8c9f8cb20332cedac784e5a23cab2b3876675",
"size": "19595",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "2013/08/18/test-and-bug.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "107179"
},
{
"name": "HTML",
"bytes": "116960"
},
{
"name": "JavaScript",
"bytes": "109479"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
#endregion
namespace DotNetNuke.Services.Upgrade.Internals.InstallConfiguration
{
/// -----------------------------------------------------------------------------
/// <summary>
/// PortalConfig - A class that represents Install/DotNetNuke.Install.Config/Portals/Portal
/// </summary>
/// -----------------------------------------------------------------------------
public class PortalConfig
{
public string PortalName { get; set; }
public string AdminFirstName { get; set; }
public string AdminLastName { get; set; }
public string AdminUserName { get; set; }
public string AdminPassword { get; set; }
public string AdminEmail { get; set; }
public string Description { get; set; }
public string Keywords { get; set; }
public string TemplateFileName { get; set; }
public bool IsChild { get; set; }
public string HomeDirectory { get; set; }
public IList<string> PortAliases { get; set; }
public PortalConfig()
{
PortAliases = new List<string>();
}
}
}
| {
"content_hash": "44a1bf9dd00ce996c6db7cb8253a7f56",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 95,
"avg_line_length": 34.911764705882355,
"alnum_prop": 0.5256950294860994,
"repo_name": "robsiera/Dnn.Platform",
"id": "a7b1755d87a46aa8617cab8d1719136c47a79028",
"size": "2412",
"binary": false,
"copies": "2",
"ref": "refs/heads/development",
"path": "DNN Platform/Library/Services/Upgrade/Internals/InstallConfiguration/PortalConfig.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "572469"
},
{
"name": "Batchfile",
"bytes": "405"
},
{
"name": "C#",
"bytes": "21903627"
},
{
"name": "CSS",
"bytes": "1653926"
},
{
"name": "HTML",
"bytes": "528314"
},
{
"name": "JavaScript",
"bytes": "8361433"
},
{
"name": "PLpgSQL",
"bytes": "53478"
},
{
"name": "PowerShell",
"bytes": "10762"
},
{
"name": "Smalltalk",
"bytes": "2410"
},
{
"name": "TSQL",
"bytes": "56906"
},
{
"name": "Visual Basic",
"bytes": "139195"
},
{
"name": "XSLT",
"bytes": "11388"
}
],
"symlink_target": ""
} |
package com.hazelcast.map.impl.record;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotEquals;
import static org.mockito.Mockito.mock;
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelTest.class})
public class ObjectRecordWithStatsTest {
private static final Object VALUE = new Object();
private ObjectRecordWithStats record;
private ObjectRecordWithStats recordSameAttributes;
private ObjectRecordWithStats recordOtherLastStoredTime;
private ObjectRecordWithStats recordOtherExpirationTime;
private ObjectRecordWithStats recordOtherKeyAndValue;
private DataRecordWithStats dataRecord;
@Before
public void setUp() {
Data key = mock(Data.class);
Data otherKey = mock(Data.class);
Object otherValue = new Object();
record = new ObjectRecordWithStats(VALUE);
record.setKey(key);
recordSameAttributes = new ObjectRecordWithStats();
recordSameAttributes.setKey(key);
recordSameAttributes.setValue(VALUE);
recordOtherLastStoredTime = new ObjectRecordWithStats(VALUE);
recordOtherLastStoredTime.setKey(key);
recordOtherLastStoredTime.onStore();
recordOtherExpirationTime = new ObjectRecordWithStats(VALUE);
recordOtherExpirationTime.setKey(key);
recordOtherExpirationTime.setExpirationTime(2342);
recordOtherKeyAndValue = new ObjectRecordWithStats();
recordOtherKeyAndValue.setKey(otherKey);
recordOtherKeyAndValue.setValue(otherValue);
dataRecord = new DataRecordWithStats();
dataRecord.setKey(key);
dataRecord.setValue(key);
}
@Test
public void testGetValue() {
assertEquals(VALUE, record.getValue());
assertEquals(VALUE, recordSameAttributes.getValue());
assertNotEquals(VALUE, recordOtherKeyAndValue.getValue());
}
@Test
public void testGetCosts() {
assertEquals(0, record.getCost());
}
@Test
public void testEquals() {
assertEquals(record, record);
assertEquals(record, recordSameAttributes);
assertNotEquals(record, null);
assertNotEquals(record, new Object());
assertNotEquals(record, dataRecord);
assertNotEquals(record, recordOtherLastStoredTime);
assertNotEquals(record, recordOtherExpirationTime);
assertNotEquals(record, recordOtherKeyAndValue);
}
@Test
public void testHashCode() {
assertEquals(record.hashCode(), record.hashCode());
assertEquals(record.hashCode(), recordSameAttributes.hashCode());
assertNotEquals(record.hashCode(), dataRecord.hashCode());
assertNotEquals(record.hashCode(), recordOtherLastStoredTime.hashCode());
assertNotEquals(record.hashCode(), recordOtherExpirationTime.hashCode());
assertNotEquals(record.hashCode(), recordOtherKeyAndValue.hashCode());
}
}
| {
"content_hash": "c5ac3a82d76cca815b2a0d254c64b5fa",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 81,
"avg_line_length": 33.704081632653065,
"alnum_prop": 0.7293369663941871,
"repo_name": "dbrimley/hazelcast",
"id": "fc5e320ade28724b99030859ef9e8b11113a7f0e",
"size": "3928",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "hazelcast/src/test/java/com/hazelcast/map/impl/record/ObjectRecordWithStatsTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1449"
},
{
"name": "C",
"bytes": "344"
},
{
"name": "Java",
"bytes": "34610196"
},
{
"name": "Shell",
"bytes": "12362"
}
],
"symlink_target": ""
} |
<!--
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<resources>
<dimen name="margin_left_card_next_year_devfest_otherday">50dp</dimen>
<dimen name="margin_right_card_next_year_devfest_otherday">50dp</dimen>
<dimen name="margin_top_card_next_year_devfest_otherday">24dp</dimen>
<dimen name="margin_bottom_card_next_year_devfest_otherday">24dp</dimen>
</resources>
| {
"content_hash": "296b85ab9eb0e1e47c4048bb6e404afb",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 76,
"avg_line_length": 40.608695652173914,
"alnum_prop": 0.7441113490364025,
"repo_name": "ramonrabello/devfestnorte-app",
"id": "e42ad1e30a316f66e8179715b3902027c1368dd2",
"size": "934",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "android/src/main/res/values-w400dp/dimens.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2105"
},
{
"name": "HTML",
"bytes": "36389"
},
{
"name": "Java",
"bytes": "1597108"
},
{
"name": "Shell",
"bytes": "10536"
}
],
"symlink_target": ""
} |
"""
Broadcast a message, with or without a price.
Multiple messages per block are allowed. Bets are be made on the 'timestamp'
field, and not the block index.
An address is a feed of broadcasts. Feeds may be locked with a broadcast whose
text field is identical to ‘lock’ (case insensitive). Bets on a feed reference
the address that is the source of the feed in an output which includes the
(latest) required fee.
Broadcasts without a price may not be used for betting. Broadcasts about events
with a small number of possible outcomes (e.g. sports games), should be
written, for example, such that a price of 1 XLT means one outcome, 2 XLT means
another, etc., which schema should be described in the 'text' field.
fee_fraction: .05 XLT means 5%. It may be greater than 1, however; but
because it is stored as a four‐byte integer, it may not be greater than about
42.
"""
import struct
import decimal
D = decimal.Decimal
from fractions import Fraction
import logging
from . import (util, exceptions, config, litecoin)
from . import (bet)
FORMAT = '>IdI'
LENGTH = 4 + 8 + 4
ID = 30
# NOTE: Pascal strings are used for storing texts for backwards‐compatibility.
def validate (db, source, timestamp, value, fee_fraction_int, text, block_index):
problems = []
if fee_fraction_int > 4294967295:
problems.append('fee fraction greater than 42.94967295')
if timestamp < 0: problems.append('negative timestamp')
if not source:
problems.append('null source address')
# Check previous broadcast in this feed.
cursor = db.cursor()
broadcasts = list(cursor.execute('''SELECT * FROM broadcasts WHERE (status = ? AND source = ?) ORDER BY tx_index ASC''', ('valid', source)))
cursor.close()
if broadcasts:
last_broadcast = broadcasts[-1]
if last_broadcast['locked']:
problems.append('locked feed')
elif timestamp <= last_broadcast['timestamp']:
problems.append('feed timestamps not monotonically increasing')
if not (block_index >= 317500 or config.TESTNET): # Protocol change.
if len(text) > 52:
problems.append('text too long')
return problems
def compose (db, source, timestamp, value, fee_fraction, text):
# Store the fee fraction as an integer.
fee_fraction_int = int(fee_fraction * 1e8)
problems = validate(db, source, timestamp, value, fee_fraction_int, text, util.last_block(db)['block_index'])
if problems: raise exceptions.BroadcastError(problems)
data = struct.pack(config.TXTYPE_FORMAT, ID)
if len(text) <= 52:
curr_format = FORMAT + '{}p'.format(len(text) + 1)
else:
curr_format = FORMAT + '{}s'.format(len(text))
data += struct.pack(curr_format, timestamp, value, fee_fraction_int,
text.encode('utf-8'))
return (source, [], data)
def parse (db, tx, message):
cursor = db.cursor()
# Unpack message.
try:
if len(message) - LENGTH <= 52:
curr_format = FORMAT + '{}p'.format(len(message) - LENGTH)
else:
curr_format = FORMAT + '{}s'.format(len(message) - LENGTH)
timestamp, value, fee_fraction_int, text = struct.unpack(curr_format, message)
try:
text = text.decode('utf-8')
except UnicodeDecodeError:
text = ''
status = 'valid'
except (struct.error) as e:
timestamp, value, fee_fraction_int, text = 0, None, 0, None
status = 'invalid: could not unpack'
if status == 'valid':
# For SQLite3
timestamp = min(timestamp, config.MAX_INT)
value = min(value, config.MAX_INT)
problems = validate(db, tx['source'], timestamp, value, fee_fraction_int, text, tx['block_index'])
if problems: status = 'invalid: ' + '; '.join(problems)
# Lock?
lock = False
if text and text.lower() == 'lock':
lock = True
timestamp, value, fee_fraction_int, text = 0, None, None, None
else:
lock = False
# Add parsed transaction to message-type–specific table.
bindings = {
'tx_index': tx['tx_index'],
'tx_hash': tx['tx_hash'],
'block_index': tx['block_index'],
'source': tx['source'],
'timestamp': timestamp,
'value': value,
'fee_fraction_int': fee_fraction_int,
'text': text,
'locked': lock,
'status': status,
}
sql='insert into broadcasts values(:tx_index, :tx_hash, :block_index, :source, :timestamp, :value, :fee_fraction_int, :text, :locked, :status)'
cursor.execute(sql, bindings)
# Negative values (default to ignore).
if value == None or value < 0:
# Cancel Open Bets?
if value == -2:
cursor.execute('''SELECT * FROM bets \
WHERE (status = ? AND feed_address = ?)''',
('open', tx['source']))
for i in list(cursor):
bet.cancel_bet(db, i, 'dropped', tx['block_index'])
# Cancel Pending Bet Matches?
if value == -3:
cursor.execute('''SELECT * FROM bet_matches \
WHERE (status = ? AND feed_address = ?)''',
('pending', tx['source']))
for bet_match in list(cursor):
bet.cancel_bet_match(db, bet_match, 'dropped', tx['block_index'])
cursor.close()
return
# Handle bet matches that use this feed.
cursor.execute('''SELECT * FROM bet_matches \
WHERE (status=? AND feed_address=?)
ORDER BY tx1_index ASC, tx0_index ASC''',
('pending', tx['source']))
for bet_match in cursor.fetchall():
broadcast_bet_match_cursor = db.cursor()
bet_match_id = bet_match['tx0_hash'] + bet_match['tx1_hash']
bet_match_status = None
# Calculate total funds held in escrow and total fee to be paid if
# the bet match is settled. Escrow less fee is amount to be paid back
# to betters.
total_escrow = bet_match['forward_quantity'] + bet_match['backward_quantity']
fee_fraction = fee_fraction_int / config.UNIT
fee = int(fee_fraction * total_escrow) # Truncate.
escrow_less_fee = total_escrow - fee
# Get known bet match type IDs.
cfd_type_id = util.BET_TYPE_ID['BullCFD'] + util.BET_TYPE_ID['BearCFD']
equal_type_id = util.BET_TYPE_ID['Equal'] + util.BET_TYPE_ID['NotEqual']
# Get the bet match type ID of this bet match.
bet_match_type_id = bet_match['tx0_bet_type'] + bet_match['tx1_bet_type']
# Contract for difference, with determinate settlement date.
if bet_match_type_id == cfd_type_id:
# Recognise tx0, tx1 as the bull, bear (in the right direction).
if bet_match['tx0_bet_type'] < bet_match['tx1_bet_type']:
bull_address = bet_match['tx0_address']
bear_address = bet_match['tx1_address']
bull_escrow = bet_match['forward_quantity']
bear_escrow = bet_match['backward_quantity']
else:
bull_address = bet_match['tx1_address']
bear_address = bet_match['tx0_address']
bull_escrow = bet_match['backward_quantity']
bear_escrow = bet_match['forward_quantity']
leverage = Fraction(bet_match['leverage'], 5040)
initial_value = bet_match['initial_value']
bear_credit = bear_escrow - (value - initial_value) * leverage * config.UNIT
bull_credit = escrow_less_fee - bear_credit
bear_credit = round(bear_credit)
bull_credit = round(bull_credit)
# Liquidate, as necessary.
if bull_credit >= escrow_less_fee or bull_credit <= 0:
if bull_credit >= escrow_less_fee:
bull_credit = escrow_less_fee
bear_credit = 0
bet_match_status = 'settled: liquidated for bull'
util.credit(db, tx['block_index'], bull_address, config.XLT, bull_credit, action='bet {}'.format(bet_match_status), event=tx['tx_hash'])
elif bull_credit <= 0:
bull_credit = 0
bear_credit = escrow_less_fee
bet_match_status = 'settled: liquidated for bear'
util.credit(db, tx['block_index'], bear_address, config.XLT, bear_credit, action='bet {}'.format(bet_match_status), event=tx['tx_hash'])
# Pay fee to feed.
util.credit(db, tx['block_index'], bet_match['feed_address'], config.XLT, fee, action='feed fee', event=tx['tx_hash'])
# For logging purposes.
bindings = {
'bet_match_id': bet_match_id,
'bet_match_type_id': bet_match_type_id,
'block_index': tx['block_index'],
'settled': False,
'bull_credit': bull_credit,
'bear_credit': bear_credit,
'winner': None,
'escrow_less_fee': None,
'fee': fee
}
sql='insert into bet_match_resolutions values(:bet_match_id, :bet_match_type_id, :block_index, :settled, :bull_credit, :bear_credit, :winner, :escrow_less_fee, :fee)'
cursor.execute(sql, bindings)
# Settle (if not liquidated).
elif timestamp >= bet_match['deadline']:
bet_match_status = 'settled'
util.credit(db, tx['block_index'], bull_address, config.XLT, bull_credit, action='bet {}'.format(bet_match_status), event=tx['tx_hash'])
util.credit(db, tx['block_index'], bear_address, config.XLT, bear_credit, action='bet {}'.format(bet_match_status), event=tx['tx_hash'])
# Pay fee to feed.
util.credit(db, tx['block_index'], bet_match['feed_address'], config.XLT, fee, action='feed fee', event=tx['tx_hash'])
# For logging purposes.
bindings = {
'bet_match_id': bet_match_id,
'bet_match_type_id': bet_match_type_id,
'block_index': tx['block_index'],
'settled': True,
'bull_credit': bull_credit,
'bear_credit': bear_credit,
'winner': None,
'escrow_less_fee': None,
'fee': fee
}
sql='insert into bet_match_resolutions values(:bet_match_id, :bet_match_type_id, :block_index, :settled, :bull_credit, :bear_credit, :winner, :escrow_less_fee, :fee)'
cursor.execute(sql, bindings)
# Equal[/NotEqual] bet.
elif bet_match_type_id == equal_type_id and timestamp >= bet_match['deadline']:
# Recognise tx0, tx1 as the bull, bear (in the right direction).
if bet_match['tx0_bet_type'] < bet_match['tx1_bet_type']:
equal_address = bet_match['tx0_address']
notequal_address = bet_match['tx1_address']
else:
equal_address = bet_match['tx1_address']
notequal_address = bet_match['tx0_address']
# Decide who won, and credit appropriately.
if value == bet_match['target_value']:
winner = 'Equal'
bet_match_status = 'settled: for equal'
util.credit(db, tx['block_index'], equal_address, config.XLT, escrow_less_fee, action='bet {}'.format(bet_match_status), event=tx['tx_hash'])
else:
winner = 'NotEqual'
bet_match_status = 'settled: for notequal'
util.credit(db, tx['block_index'], notequal_address, config.XLT, escrow_less_fee, action='bet {}'.format(bet_match_status), event=tx['tx_hash'])
# Pay fee to feed.
util.credit(db, tx['block_index'], bet_match['feed_address'], config.XLT, fee, action='feed fee', event=tx['tx_hash'])
# For logging purposes.
bindings = {
'bet_match_id': bet_match_id,
'bet_match_type_id': bet_match_type_id,
'block_index': tx['block_index'],
'settled': None,
'bull_credit': None,
'bear_credit': None,
'winner': winner,
'escrow_less_fee': escrow_less_fee,
'fee': fee
}
sql='insert into bet_match_resolutions values(:bet_match_id, :bet_match_type_id, :block_index, :settled, :bull_credit, :bear_credit, :winner, :escrow_less_fee, :fee)'
cursor.execute(sql, bindings)
# Update the bet match’s status.
if bet_match_status:
bindings = {
'status': bet_match_status,
'bet_match_id': bet_match['tx0_hash'] + bet_match['tx1_hash']
}
sql='update bet_matches set status = :status where id = :bet_match_id'
cursor.execute(sql, bindings)
util.message(db, tx['block_index'], 'update', 'bet_matches', bindings)
broadcast_bet_match_cursor.close()
cursor.close()
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
| {
"content_hash": "f8d92e1a771288a2ca102d1ff7dddbf8",
"timestamp": "",
"source": "github",
"line_count": 309,
"max_line_length": 182,
"avg_line_length": 43.213592233009706,
"alnum_prop": 0.5667640230659777,
"repo_name": "Litetokens/litetokensd",
"id": "ec57dbc5e3fa9cf019e133ded5b8f5a6855df0c8",
"size": "13386",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/broadcast.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "392223"
}
],
"symlink_target": ""
} |
from win32clipboard import *
from pywin32_testutil import str2bytes # py3k-friendly helper
import win32con
import types
if not __debug__:
print "WARNING: The test code in this module uses assert"
print "This instance of Python has asserts disabled, so many tests will be skipped"
cf_names = {}
# Build map of CF_* constants to names.
for name, val in win32con.__dict__.items():
if name[:3]=="CF_" and name != "CF_SCREENFONTS": # CF_SCREEN_FONTS==CF_TEXT!?!?
cf_names[val] = name
def TestEmptyClipboard():
OpenClipboard()
try:
EmptyClipboard()
assert EnumClipboardFormats(0)==0, "Clipboard formats were available after emptying it!"
finally:
CloseClipboard()
def TestText():
OpenClipboard()
try:
text = "Hello from Python"
text_bytes = str2bytes(text)
SetClipboardText(text)
got = GetClipboardData(win32con.CF_TEXT)
# CF_TEXT always gives us 'bytes' back .
assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,)
finally:
CloseClipboard()
OpenClipboard()
try:
# CF_UNICODE text always gives unicode objects back.
got = GetClipboardData(win32con.CF_UNICODETEXT)
assert got == text, "Didnt get the correct result back - '%r'." % (got,)
assert type(got)==types.UnicodeType, "Didnt get the correct result back - '%r'." % (got,)
# CF_OEMTEXT is a bytes-based format.
got = GetClipboardData(win32con.CF_OEMTEXT)
assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,)
# Unicode tests
EmptyClipboard()
text = u"Hello from Python unicode"
text_bytes = str2bytes(text)
# Now set the Unicode value
SetClipboardData(win32con.CF_UNICODETEXT, text)
# Get it in Unicode.
got = GetClipboardData(win32con.CF_UNICODETEXT)
assert got == text, "Didnt get the correct result back - '%r'." % (got,)
assert type(got)==types.UnicodeType, "Didnt get the correct result back - '%r'." % (got,)
# Close and open the clipboard to ensure auto-conversions take place.
finally:
CloseClipboard()
OpenClipboard()
try:
# Make sure I can still get the text as bytes
got = GetClipboardData(win32con.CF_TEXT)
assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,)
# Make sure we get back the correct types.
got = GetClipboardData(win32con.CF_UNICODETEXT)
assert type(got)==types.UnicodeType, "Didnt get the correct result back - '%r'." % (got,)
got = GetClipboardData(win32con.CF_OEMTEXT)
assert got == text_bytes, "Didnt get the correct result back - '%r'." % (got,)
print "Clipboard text tests worked correctly"
finally:
CloseClipboard()
def TestClipboardEnum():
OpenClipboard()
try:
# Enumerate over the clipboard types
enum = 0
while 1:
enum = EnumClipboardFormats(enum)
if enum==0:
break
assert IsClipboardFormatAvailable(enum), "Have format, but clipboard says it is not available!"
n = cf_names.get(enum,"")
if not n:
try:
n = GetClipboardFormatName(enum)
except error:
n = "unknown (%s)" % (enum,)
print "Have format", n
print "Clipboard enumerator tests worked correctly"
finally:
CloseClipboard()
class Foo:
def __init__(self, **kw):
self.__dict__.update(kw)
def __cmp__(self, other):
return cmp(self.__dict__, other.__dict__)
def __eq__(self, other):
return self.__dict__==other.__dict__
def TestCustomFormat():
OpenClipboard()
try:
# Just for the fun of it pickle Python objects through the clipboard
fmt = RegisterClipboardFormat("Python Pickle Format")
import cPickle
pickled_object = Foo(a=1, b=2, Hi=3)
SetClipboardData(fmt, cPickle.dumps( pickled_object ) )
# Now read it back.
data = GetClipboardData(fmt)
loaded_object = cPickle.loads(data)
assert cPickle.loads(data) == pickled_object, "Didnt get the correct data!"
print "Clipboard custom format tests worked correctly"
finally:
CloseClipboard()
if __name__=='__main__':
TestEmptyClipboard()
TestText()
TestCustomFormat()
TestClipboardEnum()
# And leave it empty at the end!
TestEmptyClipboard()
| {
"content_hash": "4b050eb526a2ae5a903124178bb870f6",
"timestamp": "",
"source": "github",
"line_count": 131,
"max_line_length": 107,
"avg_line_length": 35.916030534351144,
"alnum_prop": 0.593836344314559,
"repo_name": "ntuecon/server",
"id": "ee94996f18260209f491b4b8dff9a3ec433f8939",
"size": "4776",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "pyenv/Lib/site-packages/win32/Demos/win32clipboardDemo.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "2209"
},
{
"name": "Batchfile",
"bytes": "1509"
},
{
"name": "C",
"bytes": "504013"
},
{
"name": "C++",
"bytes": "96440"
},
{
"name": "CSS",
"bytes": "133288"
},
{
"name": "GAP",
"bytes": "18122"
},
{
"name": "HTML",
"bytes": "150026"
},
{
"name": "JavaScript",
"bytes": "243314"
},
{
"name": "Objective-C",
"bytes": "1292"
},
{
"name": "PowerShell",
"bytes": "8325"
},
{
"name": "Python",
"bytes": "27048260"
},
{
"name": "Shell",
"bytes": "47820"
},
{
"name": "Tcl",
"bytes": "1237796"
},
{
"name": "Visual Basic",
"bytes": "949"
},
{
"name": "XSLT",
"bytes": "2113"
}
],
"symlink_target": ""
} |
package moonlightowl.openblocks.structure.action;
import moonlightowl.openblocks.Assets;
import moonlightowl.openblocks.Blocks;
import moonlightowl.openblocks.io.lua.Action;
import moonlightowl.openblocks.structure.Block;
import moonlightowl.openblocks.structure.Joint;
/**
* OpenBlocks.Forward
* Created by MoonlightOwl on 11/8/15.
* ===
* Tell your robot to swing with pickaxe
*/
public class Build extends Block {
public Build() {
super(0, 0, Blocks.Id.BUILD);
addJoint(new Joint(this, -37, 0, Joint.TO, 0).setMultiwired(true));
addJoint(new Joint(this, 37, 0, Joint.FROM, 1));
setIcon(Assets.blockIconsIndex.get("build.png"));
operator = new Action("robot.place()");
}
}
| {
"content_hash": "1d2382b77720545ee726e71cd9294c17",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 75,
"avg_line_length": 30.458333333333332,
"alnum_prop": 0.707250341997264,
"repo_name": "MoonlightOwl/OpenBlocks",
"id": "ed1a52634080cb546002f2c94c986304cafdc297",
"size": "731",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/moonlightowl/openblocks/structure/action/Build.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4817"
},
{
"name": "Java",
"bytes": "128878"
}
],
"symlink_target": ""
} |
<?php
namespace Cubiche\Domain\ProcessManager\Tests\Units;
use Cubiche\Core\Collections\ArrayCollection\ArrayHashMap;
use Cubiche\Domain\EventSourcing\EventStore\InMemoryEventStore;
use Cubiche\Domain\EventSourcing\Factory\AggregateRepositoryFactory;
use Cubiche\Domain\Repository\RepositoryInterface;
/**
* SettingWriteRepository trait.
*
* Generated by TestGenerator on 2017-09-13 at 12:50:27.
*/
trait SettingWriteRepositoryTrait
{
/**
* @var ArrayHashMap
*/
private $writeRepositories;
/**
* @param $className
*
* @return RepositoryInterface
*/
protected function writeRepository($className)
{
if ($this->writeRepositories === null) {
$this->writeRepositories = new ArrayHashMap();
}
if (!$this->writeRepositories->containsKey($className)) {
$factory = new AggregateRepositoryFactory(new InMemoryEventStore());
$this->writeRepositories->set($className, $factory->create($className));
}
return $this->writeRepositories->get($className);
}
}
| {
"content_hash": "2b8c8754a71af7748c737c9173e348ae",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 84,
"avg_line_length": 25.27906976744186,
"alnum_prop": 0.6826126954921803,
"repo_name": "cubiche/cubiche",
"id": "9a95f7d9d2a8af09c5b88418dd238923cf60949a",
"size": "1314",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Cubiche/Domain/ProcessManager/Tests/Units/SettingWriteRepositoryTrait.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "6103"
},
{
"name": "PHP",
"bytes": "2278687"
}
],
"symlink_target": ""
} |
package scutil.gui
import java.awt.Graphics
import java.awt.Window
import javax.imageio.ImageReader
import javax.imageio.ImageWriter
import scala.util.Using.Releasable
object instances {
given GraphicsReleasable[T<:Graphics]:Releasable[T] = _.dispose()
given ImageReaderReleasable[T<:ImageReader]:Releasable[T] = _.dispose()
given ImageWriterReleasable[T<:ImageWriter]:Releasable[T] = _.dispose()
given WindowReleasable[T<:Window]:Releasable[T] = _.dispose()
}
| {
"content_hash": "0ce67cbc3db1934833009bcf271322b7",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 72,
"avg_line_length": 31.533333333333335,
"alnum_prop": 0.7758985200845666,
"repo_name": "ritschwumm/scutil",
"id": "ccfebf9f83eee9c77f2a1bd3235275dd910cdeba",
"size": "473",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/gui/src/main/scala/scutil/gui/instances.scala",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Scala",
"bytes": "604632"
},
{
"name": "Shell",
"bytes": "46"
}
],
"symlink_target": ""
} |
DVBCWSD1 ;ALB/CMM SKIN DISEASES (Other Than Scars) WKS TEXT - 1 ; 6 MARCH 1997
;;2.7;AMIE;**12**;Apr 10, 1995
;
;
TXT ;
;;A. Review of Medical Records:
;;
;;
;;
;;B. Medical History (Subjective Complaints):
;;
;; Comment on:
;; 1. Onset of disease and course - intermittent, constant.
;;
;;
;; 2. Current treatment - include side effects.
;;
;;
;; 3. Symptoms - pruritus, pain, etc.
;;
;;
;;C. Physical Examination (Objective Findings):
;;
;; Address each of the following and fully describe current findings:
;; 1. Extent of disease - specify what exposed areas are involved
;; and how large they are.
;;
;;
;; 2. Ulceration, exfoliation, or crusting.
;;
;;
;; 3. Associated systemic or nervous manifestations.
;;
;;
;;D. Diagnostic and Clinical Tests:
;;
;;
;; 1. Biopsy, scrapings if indicated.
;; 2. Include results of all diagnostic and clinical tests conducted
;; in the examination report.
;;
;;
;;E. Diagnosis:
;;
;; 1. Take COLOR PHOTOGRAPHS if disfigurement or disfiguring scars
;; are present.
;;
;;
;;Signature: Date:
;;END
| {
"content_hash": "bcc119c7130bceba01dbd21969267012",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 78,
"avg_line_length": 23.64,
"alnum_prop": 0.5956006768189509,
"repo_name": "bradking/VistA-M",
"id": "1713761ede9b445ca9949417f9a38b6d19b6839f",
"size": "1182",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "Packages/Automated Medical Information Exchange/Routines/DVBCWSD1.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "M",
"bytes": "115491308"
},
{
"name": "Matlab",
"bytes": "2056256"
},
{
"name": "Mercury",
"bytes": "90179"
},
{
"name": "Objective-C",
"bytes": "233777"
}
],
"symlink_target": ""
} |
<section data-ng-controller="ChatroomController" data-ng-init="findOne()">
<div class="page-header">
<h1 data-ng-bind="chatroom.title"></h1>
</div>
<div class="pull-right" data-ng-show="authentication.user._id == chatroom.user._id">
<a class="btn btn-primary" href="/#!/chatroom/{{chatroom._id}}/edit">
<i class="glyphicon glyphicon-edit"></i>
</a>
<a class="btn btn-primary" data-ng-click="remove();">
<i class="glyphicon glyphicon-trash"></i>
</a>
</div>
<small>
<em class="text-muted">
Posted on
<span data-ng-bind="chatroom.created | date:'mediumDate'"></span>
by
<span data-ng-bind="chatroom.user.displayName"></span>
</em>
</small>
<p class="lead" data-ng-bind="chatroom.content"></p>
</section> | {
"content_hash": "3d17a68cb28113961fcdb8f77cffbfae",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 85,
"avg_line_length": 33.63636363636363,
"alnum_prop": 0.65,
"repo_name": "jeffreymendez1993/meanStart",
"id": "95859a9db21b318167cb28f82825078644d50f0f",
"size": "740",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "public/modules/chatroom/views/view-chatrooms.client.view.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3163"
},
{
"name": "HTML",
"bytes": "24643"
},
{
"name": "JavaScript",
"bytes": "100731"
},
{
"name": "Shell",
"bytes": "693"
}
],
"symlink_target": ""
} |
package jat.application.missionPlan;
import jat.core.ephemeris.DE405Frame.frame;
import jat.core.ephemeris.DE405Plus;
import jat.core.util.PathUtil;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
public class MissionPlanMain extends JApplet {
private static final long serialVersionUID = 1L;
public MissionPlanGUI mpGUI;
public MissionPlanPlot mpPlot;
public MissionPlanParameters mpParam;
static int appletwidth = 900; // Width of Applet
static int appletheight = 700;
static com.tornadolabs.j3dtree.Java3dTree m_Java3dTree = null;
private static boolean Java3dTree_debug = false;
Container level1_Pane;
JFrame sFrame;
List<Flight> flightList = new ArrayList<Flight>();
public JTextPane textPane;
public JTextArea textArea;
public void init() {
// Create a text pane.
textPane = new JTextPane();
// JScrollPane paneScrollPane = new JScrollPane(textPane);
// paneScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// paneScrollPane.setPreferredSize(new Dimension(300, 155));
// paneScrollPane.setMinimumSize(new Dimension(10, 10));
// getContentPane().add(paneScrollPane, BorderLayout.NORTH);
// Redirect stdout and stderr to the text pane
// MessageConsole mc = new MessageConsole(textPane);
// mc.redirectOut();
// mc.redirectErr(Color.RED, null);
// mc.setMessageLines(100);
textArea = new JTextArea(5, 20);
JScrollPane paneScrollPane = new JScrollPane(textArea);
paneScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
paneScrollPane.setPreferredSize(new Dimension(300, 155));
paneScrollPane.setMinimumSize(new Dimension(10, 10));
getContentPane().add(paneScrollPane, BorderLayout.NORTH);
//System.out.println("[MissionPlanMain]");
}
public void start() {
//Message console
// MissionPlanConsole E = new MissionPlanConsole();
// JFrame jf = new JFrame();
// jf.setSize(800, 400);
// jf.getContentPane().add(E);
// jf.setVisible(true);
// E.init();
mpParam = new MissionPlanParameters();
mpParam.path = new PathUtil(this,mpParam.messages);
mpParam.Eph = new DE405Plus(mpParam.path,mpParam.messages);
mpParam.Eph.setFrame(frame.HEE);
//mpParam.messages.printMessages();
mpGUI = new MissionPlanGUI(this);
mpPlot = new MissionPlanPlot(this);
level1_Pane = getContentPane();
level1_Pane.add(mpGUI, BorderLayout.WEST);
level1_Pane.add(mpPlot, BorderLayout.CENTER);
// if (debug)
// System.out.println("[PathUtilTest] Console created");
//System.out.println("[MissionPlanMain before starting timer]");
mpGUI.mpE.timer.start();
//mpParam.messages.printMessages();
//mpParam.messages.printMessagesToTextArea(textArea);
}
/**
* Used when run as an application
*/
// public static void main(String[] args) {
// MissionPlanMain mApplet = new MissionPlanMain();
// mApplet.init();
//
// mApplet.sFrame = new JFrame();
// mApplet.sFrame.setTitle("JAT Solar System Mission Planner");
// mApplet.sFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//
// // When running this file as a stand-alone app, add the applet to
// // the frame.
// mApplet.sFrame.getContentPane().add(mApplet, BorderLayout.CENTER);
// mApplet.sFrame.setSize(appletwidth, appletheight);
// mApplet.sFrame.setVisible(true);
//
// // sApplet.ssp.mouseZoom.setupCallback(sApplet.ssE);
// mApplet.mpPlot.requestFocusInWindow();
//
// // mApplet.mpGUI.mpE.timer.start();
// mApplet.start();
// if (Java3dTree_debug) {
// m_Java3dTree = new com.tornadolabs.j3dtree.Java3dTree();
// m_Java3dTree.recursiveApplyCapability(mApplet.mpPlot.jatScene);
// m_Java3dTree.updateNodes(mApplet.mpPlot.universe);
// }
// }// End of main()
}
| {
"content_hash": "bc16d9097c84960b33234f8707937b0b",
"timestamp": "",
"source": "github",
"line_count": 124,
"max_line_length": 85,
"avg_line_length": 31.653225806451612,
"alnum_prop": 0.7393630573248408,
"repo_name": "atmelino/JATexperimental",
"id": "7e5f5263f9d96d96240ed4077074286ee4f3ddac",
"size": "4552",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/jat/application/missionPlan/MissionPlanMain.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "4434850"
},
{
"name": "Matlab",
"bytes": "760"
},
{
"name": "Shell",
"bytes": "889"
}
],
"symlink_target": ""
} |
Put the "ocean" and "WEB-INF" folder inside a folder which is located in the tomcat\webapps folder.
To set up run ./Makefile.sh
| {
"content_hash": "2f52c952bcb204db3a3e1f89f211de1b",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 99,
"avg_line_length": 43,
"alnum_prop": 0.751937984496124,
"repo_name": "kobitoko/Project-Ocean",
"id": "f4dcaa7fc89a2d6a2e431c29721846f2f0a11e10",
"size": "146",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "626"
},
{
"name": "HTML",
"bytes": "14006"
},
{
"name": "Java",
"bytes": "144524"
},
{
"name": "JavaScript",
"bytes": "12330"
},
{
"name": "Shell",
"bytes": "298"
}
],
"symlink_target": ""
} |
"""
包含一些CTA因子的可视化函数
"""
import matplotlib
matplotlib.use('Qt4Agg')
import numpy as np
import pandas as pd
import seaborn as sns
#import matplotlib as mpl
#mpl.rcParams["font.sans-serif"] = ["Microsoft YaHei"]#
#mpl.rcParams['axes.unicode_minus'] = False
import matplotlib.pyplot as plt
from calcFunction import get_capital_np
#----------------------------------------------------------------------
def plotSigCaps(signals,markets,climit=4,wlimit=2,size=1,rate=0.0001,op=True):
"""
打印某一个信号的资金曲线
"""
plt.close()
pnls,poss = get_capital_np(markets,signals,size,rate,\
climit=climit, wlimit=wlimit,op=op)
caps = np.cumsum(pnls[pnls!=0])
return caps,poss
#----------------------------------------------------------------------
def plotSigHeats(signals,markets,start=0,step=2,size=1,iters=6):
"""
打印信号回测盈损热度图,寻找参数稳定岛
"""
sigMat = pd.DataFrame(index=range(iters),columns=range(iters))
for i in range(iters):
for j in range(iters):
climit = start + i*step
wlimit = start + j*step
caps,poss = plotSigCaps(signals,markets,climit=climit,wlimit=wlimit,size=size,op=False)
sigMat[i][j] = caps[-1]
sns.heatmap(sigMat.values.astype(np.float64),annot=True,fmt='.2f',annot_kws={"weight": "bold"})
xTicks = [i+0.5 for i in range(iters)]
yTicks = [iters-i-0.5 for i in range(iters)]
xyLabels = [str(start+i*step) for i in range(iters)]
_, labels = plt.yticks(yTicks,xyLabels)
plt.setp(labels, rotation=0)
_, labels = plt.xticks(xTicks,xyLabels)
plt.setp(labels, rotation=90)
plt.xlabel('Loss Stop @')
plt.ylabel('Profit Stop @')
return sigMat
| {
"content_hash": "1e4f68b260b0d9db58bacd61369740e1",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 99,
"avg_line_length": 35.229166666666664,
"alnum_prop": 0.6014192785334121,
"repo_name": "moonnejs/uiKLine",
"id": "8bbed72f388097273d3a7d08f8820484688ac87e",
"size": "1793",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ctaFunction/visFunction.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "32"
},
{
"name": "Python",
"bytes": "62267"
}
],
"symlink_target": ""
} |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Asterisk extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see https://codeigniter.com/user_guide/general/urls.html
*/
// Constructeur du contrôleur, il charge les différents modèles
public function __construct()
{
parent::__construct();
$models = array('utilisateur_model', 'ticket_model', 'technicien_model', 'client_model', 'enregistrementconversation_model','produit_model', 'satisfaction_model');
$this->load->model($models);
}
// Fonction qui charge la vue correspondant à la page d'accueil
public function index()
{
}
public function mauvaisNum($numTicket){
$resultat = $this->ticket_model->ticket_present($numTicket);
if($resultat == 0){
$reponse = 2;
}else{
$reponse = 1;
}
echo $reponse;
}
public function verifSerie($numSerie){
$resultat = $this->produit_model->produit_present($numSerie);
if($resultat == 0){
$reponse = 2;
}else{
$reponse = 1;
}
echo $reponse;
}
public function temps_attente($ticket){
$temps_attente = 0;
$techniciens_indisponibles = $this->technicien_model->get_techniciens_indisponibles();
if($techniciens_indisponibles != array()){
$nb_techniciens = count($techniciens_indisponibles);
$collection = array();
foreach($techniciens_indisponibles as $unTechnicien){
$collection[] = array("idtechnicien" => $unTechnicien['idtechnicien'], 'statut' => $unTechnicien['statut'], "tempscommunication" => $unTechnicien['tempscommunication']);
}
$temps_communication = array();
foreach ($collection as $unTechnicien){
$temps_communication[] = $unTechnicien['tempscommunication'];
}
array_multisort($temps_communication, SORT_DESC, $collection);
$temps_communication_moyen = $this->enregistrementconversation_model->get_moyenne_tempscomm()[0]['tempsappel'];
$file_attente = $this->ticket_model->get_ticket_en_cours();
foreach($file_attente as $key => $unTicket){
if($unTicket['idticket'] == $ticket){
$place_file_attente = $key+1;
}
}
if($place_file_attente%$nb_techniciens == 0){
$index = 0;
} else {
$index = $place_file_attente%$nb_techniciens-1;
}
$temps_communication_technicien = $this->technicien_model->get_temps_communication($techniciens_indisponibles[$index]['idtechnicien'])[0]['tempscommunication'];
$temps_attente = ((($place_file_attente/$nb_techniciens)*$temps_communication_moyen) - ($temps_communication_technicien));
}
echo $temps_attente;
}
public function insertion_ticket($type=" ",$probleme1,$probleme2,$num_serie){
switch ($probleme1){
case 1 :
$probleme1 = "Imprimante non allumée";
break;
case 2 :
$probleme1 = "Problème de cartouche";
break;
case 3 :
$probleme1 = "Papier bloqué";
break;
case 4 :
$probleme1 = "Autre";
break;
default :
$probleme1 = " ";
break;
}
switch ($probleme2){
case 11:
$probleme2 = "Imprimante branchée";
break;
case 12:
$probleme2 = "Imprimante non branchée";
break;
case 21:
$probleme2 = "Cartouche changée";
break;
case 22:
$probleme2 = "Cartouche non changée";
break;
case 31:
$probleme2 = "Cache démonté";
break;
case 32:
$probleme2 = "Cache non démonté";
break;
default:
$probleme2 = " ";
break;
}
$probleme = $probleme1."-".$probleme2;
$id_client = $this->client_model->get_id_client_recent();
if($num_serie == 0){
$serie = 0;
} else {
$serie = $num_serie;
}
if($type == " "){
$type_final = "inconnu";
} else {
$type_final = $type;
}
$this->client_model->creation_client();
$ticket = $this->ticket_model->creation_ticket($type_final,$serie,$probleme,$id_client+1);
$idticket = $this->ticket_model->get_id_ticket_recent();
echo $idticket;
}
public function reouverture_ticket($ticket){
$probleme = $this->ticket_model->reouverture_ticket($ticket);
$this->ticket_model->update_probleme($ticket,$probleme[0]['probleme'] . " / reouverture du ticket : ");
}
public function satisfaction($amabilite,$didactique,$rapidite,$idticket){
$this->satisfaction_model->insert_satisfaction($amabilite,$didactique,$rapidite,$idticket);
}
}
?> | {
"content_hash": "f93685a457f4ddecd0699c792aa19ae4",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 173,
"avg_line_length": 26.016393442622952,
"alnum_prop": 0.6427221172022685,
"repo_name": "NoPrejudiceNTolerance/sitejj",
"id": "a48a12ec8e04d0523ea7f0c5f2bc26d0fcc40a2b",
"size": "4776",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "application/controllers/Asterisk.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "240"
},
{
"name": "CSS",
"bytes": "398084"
},
{
"name": "HTML",
"bytes": "26067"
},
{
"name": "JavaScript",
"bytes": "652951"
},
{
"name": "PHP",
"bytes": "2277947"
}
],
"symlink_target": ""
} |
var kunstmaanbundles = kunstmaanbundles || {};
kunstmaanbundles.tooltip = (function(window, undefined) {
var init, initTooltip;
init = function() {
$('[data-toggle="tooltip"]').each(function() {
if(!$(this).hasClass('js-tooltip--enabled')) {
initTooltip($(this));
}
});
};
// Initialize
initTooltip = function($el) {
$el.addClass('js-tooltip--enabled');
$el.tooltip();
};
return {
init: init
};
}(window));
| {
"content_hash": "d292527286fdbb926ac090e49dafed2d",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 58,
"avg_line_length": 19.51851851851852,
"alnum_prop": 0.5142314990512334,
"repo_name": "mennowame/KunstmaanBundlesCMS",
"id": "8d49f5d9476e1555a8bb53b9a2040db3f5dbc72b",
"size": "527",
"binary": false,
"copies": "16",
"ref": "refs/heads/master",
"path": "src/Kunstmaan/AdminBundle/Resources/ui/js/_tooltip.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "130"
},
{
"name": "CSS",
"bytes": "561843"
},
{
"name": "Cucumber",
"bytes": "22143"
},
{
"name": "HTML",
"bytes": "657329"
},
{
"name": "JavaScript",
"bytes": "6395203"
},
{
"name": "PHP",
"bytes": "2492897"
},
{
"name": "PowerShell",
"bytes": "161"
},
{
"name": "Ruby",
"bytes": "2363"
},
{
"name": "Shell",
"bytes": "4014"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">
<HTML>
<HEAD>
<meta name="generator" content="JDiff v1.0.9">
<!-- Generated by the JDiff Javadoc doclet -->
<!-- (http://www.jdiff.org) -->
<meta name="description" content="JDiff is a Javadoc doclet which generates an HTML report of all the packages, classes, constructors, methods, and fields which have been removed, added or changed in any way, including their documentation, when two APIs are compared.">
<meta name="keywords" content="diff, jdiff, javadiff, java diff, java difference, API difference, difference between two APIs, API diff, Javadoc, doclet">
<TITLE>
org.apache.pig.backend.hadoop.executionengine.physicalLayer
</TITLE>
<LINK REL="stylesheet" TYPE="text/css" HREF="../stylesheet-jdiff.css" TITLE="Style">
</HEAD>
<BODY>
<!-- Start of nav bar -->
<TABLE summary="Navigation bar" BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<TABLE summary="Navigation bar" BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../api/org/apache/pig/backend/hadoop/executionengine/physicalLayer/package-summary.html" target="_top"><FONT CLASS="NavBarFont1"><B><tt>pig 0.7.0</tt></B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="changes-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="jdiff_statistics.html"><FONT CLASS="NavBarFont1"><B>Statistics</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="jdiff_help.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM><b>Generated by<br><a href="http://www.jdiff.org" class="staysblack" target="_top">JDiff</a></b></EM></TD>
</TR>
<TR>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="pkg_org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans.html"><B>PREV PACKAGE</B></A>
<A HREF="pkg_org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators.html"><B>NEXT PACKAGE</B></A>
<A HREF="../changes.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="pkg_org.apache.pig.backend.hadoop.executionengine.physicalLayer.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell3"><FONT SIZE="-2"> DETAIL:
REMOVED |
ADDED |
<a href="#Changed">CHANGED</a>
</FONT></TD>
</TR>
</TABLE>
<HR>
<!-- End of nav bar -->
<H2>
Package <A HREF="../../api/org/apache/pig/backend/hadoop/executionengine/physicalLayer/package-summary.html" target="_top"><tt>org.apache.pig.backend.hadoop.executionengine.physicalLayer</tt></A>
</H2>
<p>
<a NAME="Changed"></a>
<TABLE summary="Changed Classes" BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TD VALIGN="TOP" COLSPAN=2><FONT SIZE="+1"><B>Changed Classes</B></FONT></TD>
</TR>
<TR BGCOLOR="#FFFFFF" CLASS="TableRowColor">
<TD VALIGN="TOP" WIDTH="25%">
<A NAME="LogToPhyTranslationVisitor"></A>
<nobr><A HREF="org.apache.pig.backend.hadoop.executionengine.physicalLayer.LogToPhyTranslationVisitor.html">LogToPhyTranslationVisitor</A></nobr>
</TD>
<TD> </TD>
</TR>
<TR BGCOLOR="#FFFFFF" CLASS="TableRowColor">
<TD VALIGN="TOP" WIDTH="25%">
<A NAME="POStatus"></A>
<nobr><A HREF="org.apache.pig.backend.hadoop.executionengine.physicalLayer.POStatus.html">POStatus</A></nobr>
</TD>
<TD> </TD>
</TR>
<TR BGCOLOR="#FFFFFF" CLASS="TableRowColor">
<TD VALIGN="TOP" WIDTH="25%">
<A NAME="PhysicalOperator"></A>
<nobr><A HREF="org.apache.pig.backend.hadoop.executionengine.physicalLayer.PhysicalOperator.html">PhysicalOperator</A></nobr>
</TD>
<TD VALIGN="TOP">This is the base class for all operators.</TD>
</TR>
</TABLE>
<HR>
<!-- Start of nav bar -->
<TABLE summary="Navigation bar" BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<TABLE summary="Navigation bar" BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../api/org/apache/pig/backend/hadoop/executionengine/physicalLayer/package-summary.html" target="_top"><FONT CLASS="NavBarFont1"><B><tt>pig 0.7.0</tt></B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="changes-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Package</B></FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="jdiff_statistics.html"><FONT CLASS="NavBarFont1"><B>Statistics</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="jdiff_help.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3></TD>
</TR>
<TR>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="pkg_org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans.html"><B>PREV PACKAGE</B></A>
<A HREF="pkg_org.apache.pig.backend.hadoop.executionengine.physicalLayer.expressionOperators.html"><B>NEXT PACKAGE</B></A>
<A HREF="../changes.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="pkg_org.apache.pig.backend.hadoop.executionengine.physicalLayer.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
<TD BGCOLOR="0xFFFFFF" CLASS="NavBarCell3"></TD>
</TR>
</TABLE>
<HR>
<!-- End of nav bar -->
</BODY>
</HTML>
| {
"content_hash": "9299a76e8ad01bd93ed74da996102ca6",
"timestamp": "",
"source": "github",
"line_count": 111,
"max_line_length": 269,
"avg_line_length": 56.57657657657658,
"alnum_prop": 0.6815286624203821,
"repo_name": "hirohanin/pig7hadoop21",
"id": "8c980947fffa2d2d47fb8483e84510695db3e501",
"size": "6280",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/jdiff/changes/pkg_org.apache.pig.backend.hadoop.executionengine.physicalLayer.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
const bittrex = require('../node.bittrex.api');
/**
* a bare client
*/
var websocketsclient = bittrex.websockets.client();
/**
* the messages received must be parsed as json first e.g. via jsonic(message.utf8Data)
*/
websocketsclient.serviceHandlers.messageReceived = function (message) {
console.log(message);
}
/**
* all possible serviceHandlers:
*
* bound: function() { console.log("Websocket bound"); },
* connectFailed: function(error) { console.log("Websocket connectFailed: ", error); },
* connected: function(connection) { console.log("Websocket connected"); },
* disconnected: function() { console.log("Websocket disconnected"); },
* onerror: function (error) { console.log("Websocket onerror: ", error); },
* messageReceived: function (message) { console.log("Websocket messageReceived: ", message); return false; },
* bindingError: function (error) { console.log("Websocket bindingError: ", error); },
* connectionLost: function (error) { console.log("Connection Lost: ", error); },
* reconnecting: function (retry { inital: true/false, count: 0} ) {
* console.log("Websocket Retrying: ", retry);
* //return retry.count >= 3; // cancel retry true
* return true;
* }
*/
websocketsclient.serviceHandlers.onerror = function (error) {
console.log('some error occured', error);
}
| {
"content_hash": "adc4f1693abd66ed4d2b952bebd3aa62",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 111,
"avg_line_length": 38.4,
"alnum_prop": 0.6815476190476191,
"repo_name": "n0mad01/node.bittrex.api",
"id": "7a54d204185a3e9fb077a595b7bda772dbf84d7a",
"size": "1344",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "examples/bittrex.websockets.client.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "21392"
}
],
"symlink_target": ""
} |
import StreamInfo from '../../src/streaming/vo/StreamInfo';
import MediaInfo from '../../src/streaming/vo/MediaInfo';
import MpdHelper from './MPDHelper';
import SpecHelper from './SpecHelper';
import Representation from '../../src/dash/vo/Representation';
import FragmentRequest from '../../src/streaming/vo/FragmentRequest';
import {HTTPRequest} from '../../src/streaming/vo/metrics/HTTPRequest';
class VoHelper {
constructor() {
this.mpdHelper = new MpdHelper();
this.specHelper = new SpecHelper();
this.voRep = undefined;
this.voAdaptation = undefined;
this.unixTime = this.specHelper.getUnixTime();
this.adaptation = undefined;
this.defaultMpdType = 'static';
}
createMpd(type) {
var mpd = {};
mpd.manifest = this.mpdHelper.getMpd(type || this.defaultMpdType);
mpd.suggestedPresentationDelay = 0;
mpd.availabilityStartTime = this.unixTime;
mpd.availabilityEndTime = Number.POSITIVE_INFINITY;
mpd.timeShiftBufferDepth = 50;
mpd.maxSegmentDuration = 1;
return mpd;
}
createPeriod() {
var period = {};
period.mpd = this.createMpd();
period.start = 0;
period.id = 'id1';
period.index = 0;
period.duration = 100;
period.liveEdge = 50;
period.isClientServerTimeSyncCompleted = false;
period.clientServerTimeShift = 0;
return period;
}
createAdaptation(type) {
var adaptation = {};
adaptation.period = this.createPeriod();
adaptation.index = 0;
adaptation.type = type;
return adaptation;
}
createRepresentation(type) {
var rep = new Representation();
rep.id = null;
rep.index = 0;
rep.adaptation = this.createAdaptation(type);
rep.fragmentInfoType = null;
rep.initialization = 'http://dash.edgesuite.net/envivio/dashpr/clear/video4/Header.m4s';
rep.segmentDuration = 1;
rep.timescale = 1;
rep.startNumber = 1;
rep.indexRange = null;
rep.range = null;
rep.presentationTimeOffset = 10;
// Set the source buffer timeOffset to this
rep.MSETimeOffset = NaN;
rep.segmentAvailabilityRange = null;
rep.availableSegmentsNumber = 0;
return rep;
}
createRequest(type) {
var req = {};
req.action = FragmentRequest.ACTION_DOWNLOAD;
req.quality = 0;
req.mediaType = 'video';
req.type = type;
req.url = 'http://dash.edgesuite.net/envivio/dashpr/clear/video4/Header.m4s';
req.startTime = NaN;
req.duration = NaN;
if (type === HTTPRequest.MEDIA_SEGMENT_TYPE) {
req.url = 'http://dash.edgesuite.net/envivio/dashpr/clear/video4/0.m4s';
req.startTime = 0;
req.duration = 4;
req.index = 0;
} else if (type === FragmentRequest.ACTION_COMPLETE) {
req.action = type;
req.url = undefined;
req.quality = NaN;
}
return req;
}
getDummyRepresentation(type) {
return this.voRep || this.createRepresentation(type);
}
getDummyMpd(type) {
return this.createMpd(type);
}
getDummyPeriod() {
return this.createPeriod();
}
getMediaRequest() {
return this.createRequest(HTTPRequest.MEDIA_SEGMENT_TYPE);
}
getInitRequest() {
return this.createRequest(HTTPRequest.INIT_SEGMENT_TYPE);
}
getCompleteRequest() {
return this.createRequest(FragmentRequest.ACTION_COMPLETE);
}
getDummyStreamInfo() {
const streamInfo = new StreamInfo();
streamInfo.id = 'DUMMY_STREAM-01';
return streamInfo;
}
getDummyMediaInfo(type) {
const mediaInfo = new MediaInfo();
mediaInfo.id = 'DUMMY_MEDIA-01';
mediaInfo.type = type;
mediaInfo.bitrateList = [
{
bandwidth: 1000,
width: 480,
height: 360
},
{
bandwidth: 2000,
width: 640,
height: 480
},
{
bandwidth: 3000,
width: 1280,
height: 720
}
];
mediaInfo.representationCount = 3;
mediaInfo.streamInfo = this.getDummyStreamInfo();
return mediaInfo;
}
}
export default VoHelper;
| {
"content_hash": "e40ea4a9515ab3170de16c0b995fabd7",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 96,
"avg_line_length": 27.333333333333332,
"alnum_prop": 0.5751662971175167,
"repo_name": "cpoilly-astek/angularjs_dashjs_intergration",
"id": "8c34bf9cae502f2bceb1c14351ddc665896d6e56",
"size": "4510",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bower_components/dashjs/test/helpers/VOHelper.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3020"
},
{
"name": "HTML",
"bytes": "10360"
},
{
"name": "JavaScript",
"bytes": "14774"
}
],
"symlink_target": ""
} |
package org.jbpm.query;
import static org.jbpm.persistence.util.PersistenceUtil.cleanUp;
import static org.jbpm.persistence.util.PersistenceUtil.setupWithPoolingDataSource;
import static org.junit.Assert.fail;
import static org.kie.api.runtime.EnvironmentName.ENTITY_MANAGER_FACTORY;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManagerFactory;
import org.hibernate.tool.hbm2ddl.DatabaseMetadata;
import org.kie.internal.query.ExtendedParametrizedQueryBuilder;
import org.kie.internal.runtime.manager.audit.query.ProcessInstanceLogQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.Level;
public abstract class QueryBuilderCoverageTestUtil {
private static HashMap<String, Object> context;
private static EntityManagerFactory emf;
private static final Logger logger = LoggerFactory.getLogger(QueryBuilderCoverageTestUtil.class);
public static EntityManagerFactory beforeClass(String persistenceUnit) {
hackTheDatabaseMetadataLoggerBecauseTheresALogbackXmlInTheClasspath();
context = setupWithPoolingDataSource(persistenceUnit);
emf = (EntityManagerFactory) context.get(ENTITY_MANAGER_FACTORY);
return emf;
}
public static void afterClass() {
cleanUp(context);
}
public static void hackTheDatabaseMetadataLoggerBecauseTheresALogbackXmlInTheClasspath() {
String [] fieldName = { "LOG", "log", "logger" };
try {
Object loggerObj = null;
for( int i = 0; i < fieldName.length; ++i ) {
Field loggerField;
Class objClass = null;
if( loggerObj == null ) {
objClass = DatabaseMetadata.class;
} else {
objClass = loggerObj.getClass();
}
loggerField = objClass.getDeclaredField(fieldName[i]);
loggerField.setAccessible(true);
loggerObj = loggerField.get(loggerObj);
}
((ch.qos.logback.classic.Logger) loggerObj).setLevel(Level.OFF);
} catch( Exception e ) {
e.printStackTrace();
// do nothing
}
}
public static void queryBuilderCoverageTest(
ExtendedParametrizedQueryBuilder queryBuilder,
Class builderClass,
ModuleSpecificInputFiller inputFiller,
String... skipMethodName) {
Set<Method> queryMethodSet = new HashSet<Method>();
while( builderClass != null && ! builderClass.equals(ExtendedParametrizedQueryBuilder.class) ) {
queryMethodSet.addAll(Arrays.asList(builderClass.getMethods()));
builderClass = builderClass.getInterfaces()[0];
}
List<Method> queryMethods = new ArrayList<Method>(queryMethodSet);
String [] specialMethodsArr = {
"newGroup", "endGroup",
"equals", "identity",
"intersect", "union",
"and", "or",
"like", "regex", "equal",
"build", "clear",
"notify", "notifyAll", "wait"
};
Set<String> specialMethods = new HashSet<String>(Arrays.asList(specialMethodsArr));
specialMethods.addAll(Arrays.asList(skipMethodName));
Iterator<Method> iter = queryMethods.iterator();
while( iter.hasNext() ) {
Method method = iter.next();
if( specialMethods.contains(method.getName()) ) {
iter.remove();
}
}
Collections.sort(queryMethods, new Comparator<Method>() {
@Override
public int compare( Method m1, Method m2 ) {
if( m1 == m2 ) {
return 0;
} else if( m1 == null ) {
return -1;
} else if( m2 == null ) {
return 1;
} else {
return m1.getName().compareTo(m2.getName());
}
}
});
for( Method methodA : queryMethods ) {
for( Method methodB : queryMethods ) {
Object [] inputA = fillInput(methodA.getParameterTypes(), inputFiller);
Object [] inputB = fillInput(methodB.getParameterTypes(), inputFiller);
try {
// build query
StringBuffer testName = new StringBuffer(methodA.getName());
callMethod(methodA, queryBuilder, inputA);
testName.append(" | ");
queryBuilder.union();
testName.append(methodB.getName());
callMethod(methodB, queryBuilder, inputB);
logger.debug(testName.toString());
// try queryT
queryBuilder.build().getResultList();
queryBuilder.clear();
} catch( Throwable t) {
t.printStackTrace();
String msg = createTestName(methodA, inputA, methodB, inputB, queryBuilder.getClass());
fail(msg);
}
}
}
}
private static <T,S> String createTestName(Method methodA, T [] inputA, Method methodB, S [] inputB, Class builderClass) {
StringBuffer msg = new StringBuffer(getMethodName(methodA, inputA));
msg.append(" OR ");
msg.append(getMethodName(methodB, inputB));
msg.append(": " + builderClass.getSimpleName());
return msg.toString();
}
private static void callMethod(Method method, Object obj, Object input) {
boolean noArgs = false;
Object [] arrInput = null;
if( input.getClass().isArray() ) {
int length = Array.getLength(input);
if( length == 1 ) {
input = Array.get(input, 0);
} else if( length == 0 ) {
noArgs = true;
} else {
arrInput = (Object[]) input;
}
}
try {
if( noArgs ) {
method.invoke(obj);
} else {
if( arrInput != null ) {
method.invoke(obj, arrInput);
} else {
method.invoke(obj, input);
}
}
} catch( Exception e ) {
e.printStackTrace();
fail( "Method [" + method.getName() + ".(" + getInputAsString(input) + ")]");
}
}
private static <T> String getMethodName(Method method, T [] input) {
StringBuilder msg = new StringBuilder(method.getName());
msg.append("(");
if( input.length > 0 ) {
msg.append(getInputAsString(input[0]));
for( int j = 1; j < input.length; ++j ) {
msg.append(",").append(getInputAsString(input[j]));
}
}
msg.append(")");
return msg.toString();
}
private static <T> String getInputAsString(Object input) {
if( input.getClass().isArray()) {
if( Array.getLength(input) == 0 ) {
return "";
}
Class compType = input.getClass().getComponentType();
if( int.class.equals(compType) ) {
return Arrays.toString((int []) input);
} else if( long.class.equals(compType) ) {
return Arrays.toString((long []) input);
} else {
return Arrays.toString((Object []) input);
}
} else {
return input.toString();
}
}
public static interface ModuleSpecificInputFiller {
public Object fillInput(Class type);
}
private static Object [] fillInput(Type [] types, ModuleSpecificInputFiller inputFiller) {
Object [] result = new Object[types.length];
for( int i = 0; i< types.length; ++i ) {
Class type = (Class) types[i];
if( type.equals(int.class) ) {
result[i] = 23;
} else if( type.equals(boolean.class) ) {
result[i] = false;
} else if( type.equals(Date.class) ) {
result[i] = new Date();
} else if( type.equals(long.class) ) {
result[i] = 46l;
} else if( type.equals(Long.class) ) {
result[i] = 96l;
} else if( type.equals(String.class) ) {
result[i] = "that";
} else if( type.isArray() ) {
Class arrayType = type.getComponentType();
if( arrayType.equals(int.class) ) {
int [] intArr = { 1,3,5 };
result[i] = intArr;
} else if( arrayType.equals(long.class) ) {
long [] longArr = { 1,9,25 };
result[i] = longArr;
} else if( arrayType.equals(String.class) ) {
String [] strArr = { "blu", "red", "gro"};
result[i] = strArr;
} else if( arrayType.equals(Date.class) ) {
Date [] strArr = { new Date(), new Date() };
result[i] = strArr;
}
}
if( result[i] == null ) {
result[i] = inputFiller.fillInput(type);
}
if( result[i] == null ) {
throw new IllegalStateException("Add logic for type: " + types[i].toString());
}
}
return result;
}
} | {
"content_hash": "ebd4692123b528de79b277dae22b06a0",
"timestamp": "",
"source": "github",
"line_count": 271,
"max_line_length": 126,
"avg_line_length": 35.66051660516605,
"alnum_prop": 0.5501862582781457,
"repo_name": "lukenjmcd/jbpm",
"id": "22c5819c35e6da5817a03212f67ea18627557d80",
"size": "10213",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jbpm-query-jpa/src/test/java/org/jbpm/query/QueryBuilderCoverageTestUtil.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "14604"
},
{
"name": "HTML",
"bytes": "251"
},
{
"name": "Java",
"bytes": "10633041"
},
{
"name": "PLSQL",
"bytes": "5292"
},
{
"name": "Protocol Buffer",
"bytes": "6420"
},
{
"name": "Shell",
"bytes": "98"
}
],
"symlink_target": ""
} |
<?php
/**
* Class die een multipoint voorstelt.
*
* @package KVD.gis
* @subpackage geometry
* @since 23 jun 2006
* @copyright 2004-2006 {@link http://www.vioe.be Vlaams Instituut voor het Onroerend Erfgoed}
* @author Koen Van Daele <koen.vandaele@rwo.vlaanderen.be>
*/
class KVDgis_GeomMultiPoint extends KVDgis_GeomGeometry
{
/**
* @var array
*/
private $points = array( );
/**
* @param integer $srid
* @param array $points
*/
public function __construct ( $srid = -1, $points = null)
{
$this->setSrid($srid);
if ( $points != null && is_array( $points ) ) {
$this->setPoints( $points );
}
}
/**
* addPoint
*
* @param KVDgis_GeomPoint $point
* @return void
*/
public function addPoint( KVDgis_GeomPoint $point )
{
if ( $point->getX( ) == 0 && $point->getY( ) == 0 ) {
return;
}
$this->points[] = $point;
}
/**
* clearPoints
*
* @return void
*/
public function clearPoints( )
{
$this->points = array( );
}
/**
* setPoints
*
* @param array $points Een verzameling KVDgis_GeomPoint objecten.
* @return void
*/
public function setPoints( array $points )
{
foreach ( $points as $point ) {
$this->addPoint( $point );
}
}
/**
* getPoints
*
* @return array $points Een verzameling KVDgis_GeomPoint objecten.
*/
public function getPoints( )
{
return $this->points;
}
/**
*
* @see KVDgis_GeomGeometry::setGeometryFromText()
* @param string $wkt vb. MULTIPOINT((1 2), (4 5), (8 9)).
* Het ongeldige type dat postgis en de meeste
* andere paketten aanmaken kan ook gelezen worden.
* @throws <b>InvalidArgumentException</b> - Indien de wkt-string ongeldig is.
*/
public function setGeometryFromText ( $wkt )
{
if ( $wkt == 'EMPTY' ) {
$this->clearPoints( );
return;
}
if (substr($wkt, 0, 10) != 'MULTIPOINT') {
throw new InvalidArgumentException (
'Ongeldige Well-Known Text string: ' . $wkt .
"\n. De string zou moeten beginnen met 'MULTIPOINT'.");
}
$this->clearPoints( );
$stringMultiPoint = $this->getStringBetweenBraces($wkt);
$points = explode(",", $stringMultiPoint);
foreach ( $points as $point ) {
if ( strpos( $point, '(' ) === false ) {
$stringPoint = trim( $point );
} else {
$stringPoint = $this->getStringBetweenBraces( $point );
}
$punten = explode( " ", $stringPoint );
$pointObj = new KVDgis_GeomPoint( $this->getSrid( ) );
$pointObj->setX($punten['0']);
$pointObj->setY($punten['1']);
$this->addPoint( $pointObj );
}
}
/**
* @see KVDgis_GeomGeometry::getAsText()
* @return string
*/
public function getAsText()
{
if ( $this->isEmpty( ) ) {
return 'EMPTY';
}
$buffer = "MULTIPOINT(";
$pointArray = array( );
foreach ( $this->points as $point ) {
$pointArray[] = $point->getX( ) . " " . $point->getY( );
}
$buffer .= implode ( ', ', $pointArray);
$buffer .= ")";
return $buffer;
}
/**
* getAsJson
*
* @param boolean $encode
*
* @return mixed String of Object.
*/
public function getAsJson( $encode = true )
{
$json = new stdClass( );
$json->type = 'MultiPoint';
$json->coordinates = array( );
foreach ( $this->points as $point ) {
$json->coordinates[] = $point->getAsJson(false)->coordinates;
}
return $encode ? json_encode( $json ) : $json;
}
public function isEmpty( )
{
return count( $this->points ) == 0;
}
}
?>
| {
"content_hash": "0db41e4e0aeb87f5d2c3246a2a5c75db",
"timestamp": "",
"source": "github",
"line_count": 158,
"max_line_length": 95,
"avg_line_length": 25.829113924050635,
"alnum_prop": 0.4998774810095565,
"repo_name": "OnroerendErfgoed/kvd",
"id": "881a4e10357be5045874ad3493f60b5d40e55350",
"size": "4295",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "classes/gis/geometry/KVDgis_GeomMultiPoint.class.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "1211895"
},
{
"name": "PLpgSQL",
"bytes": "34877"
},
{
"name": "Smarty",
"bytes": "477"
},
{
"name": "XSLT",
"bytes": "397"
}
],
"symlink_target": ""
} |
package reactor.core.publisher;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.Callable;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.logging.Level;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.junit.jupiter.api.Test;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscription;
import reactor.core.CoreSubscriber;
import reactor.core.Exceptions;
import reactor.core.Scannable;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import reactor.test.StepVerifier;
import reactor.test.publisher.TestPublisher;
import reactor.test.subscriber.AssertSubscriber;
import reactor.util.context.Context;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* @author Stephane Maldini
*/
public class HooksTest {
void simpleFlux(){
Flux.just(1)
.map(d -> d + 1)
.doOnNext(d -> {throw new RuntimeException("test");})
.collectList()
.onErrorReturn(Collections.singletonList(2))
.block();
}
static final class TestException extends RuntimeException {
public TestException(String message) {
super(message);
}
}
@Test
public void staticActivationOfOperatorDebug() {
String oldProp = System.setProperty("reactor.trace.operatorStacktrace", "true");
//this will be reset by the ReactorTestExecutionListener
Hooks.GLOBAL_TRACE = Hooks.initStaticGlobalTrace();
try {
assertThat(Hooks.GLOBAL_TRACE).isTrue();
//would throw NPE due to https://github.com/reactor/reactor-core/issues/985
Mono.just("hello").subscribe();
}
finally {
if (oldProp != null) {
System.setProperty("reactor.trace.operatorStacktrace", oldProp);
}
}
}
@Test
public void getOnEachOperatorHooksIsUnmodifiable() {
assertThatExceptionOfType(UnsupportedOperationException.class)
.isThrownBy(Hooks.getOnEachOperatorHooks()::clear);
}
@Test
public void getOnLastOperatorHooksIsUnmodifiable() {
assertThatExceptionOfType(UnsupportedOperationException.class)
.isThrownBy(Hooks.getOnLastOperatorHooks()::clear);
}
@Test
public void getOnOperatorErrorHooksIsUnmodifiable() {
assertThatExceptionOfType(UnsupportedOperationException.class)
.isThrownBy(Hooks.getOnOperatorErrorHooks()::clear);
}
@Test
public void onEachOperatorSameLambdaSameNameAppliedOnce() {
AtomicInteger applied = new AtomicInteger();
Function<? super Publisher<Object>, ? extends Publisher<Object>> hook = p -> {
applied.incrementAndGet();
return p;
};
Hooks.onEachOperator(hook);
Hooks.onEachOperator(hook);
Hooks.onEachOperatorHook.apply(s -> {});
assertThat(applied).hasValue(1);
}
@Test
public void onEachOperatorSameLambdaDifferentNamesAppliedTwice() {
AtomicInteger applied = new AtomicInteger();
Function<? super Publisher<Object>, ? extends Publisher<Object>> hook = p -> {
applied.incrementAndGet();
return p;
};
Hooks.onEachOperator(hook);
Hooks.onEachOperator("other", hook);
Hooks.onEachOperatorHook.apply(s -> {});
assertThat(applied).hasValue(2);
}
@Test
public void onEachOperatorOneHookNoComposite() {
Function<? super Publisher<Object>, ? extends Publisher<Object>> hook = p -> p;
Hooks.onEachOperator(hook);
assertThat(Hooks.onEachOperatorHook).isSameAs(hook);
}
@Test
public void onEachOperatorNamedReplacesKeepsOrder() {
List<String> applied = new ArrayList<>(3);
Function<? super Publisher<Object>, ? extends Publisher<Object>> hook1 = p -> {
applied.add("h1");
return p;
};
Function<? super Publisher<Object>, ? extends Publisher<Object>> hook2 = p -> {
applied.add("h2");
return p;
};
Function<? super Publisher<Object>, ? extends Publisher<Object>> hook3 = p -> {
applied.add("h3");
return p;
};
Hooks.onEachOperator("1", hook1);
Hooks.onEachOperator("2", hook2);
Hooks.onEachOperatorHook.apply(s -> {});
assertThat(Hooks.getOnEachOperatorHooks())
.containsOnlyKeys("1", "2");
assertThat(Hooks.getOnEachOperatorHooks().values())
.containsExactly(hook1, hook2);
assertThat(applied).containsExactly("h1", "h2");
applied.clear();
Hooks.onEachOperator("1", hook3);
Hooks.onEachOperatorHook.apply(s -> {});
assertThat(Hooks.getOnEachOperatorHooks())
.containsOnlyKeys("1", "2");
assertThat(Hooks.getOnEachOperatorHooks().values())
.containsExactly(hook3, hook2);
assertThat(applied).containsExactly("h3", "h2");
}
@Test
public void onEachOperatorResetSpecific() {
List<String> applied = new ArrayList<>(3);
Function<? super Publisher<Object>, ? extends Publisher<Object>> hook1 = p -> {
applied.add("h1");
return p;
};
Function<? super Publisher<Object>, ? extends Publisher<Object>> hook2 = p -> {
applied.add("h2");
return p;
};
Hooks.onEachOperator("1", hook1);
Hooks.onEachOperator(hook2);
Hooks.onEachOperatorHook.apply(s -> {});
assertThat(Hooks.getOnEachOperatorHooks()).hasSize(2);
assertThat(applied).containsExactly("h1", "h2");
applied.clear();
Hooks.resetOnEachOperator("1");
Hooks.onEachOperatorHook.apply(s -> {});
assertThat(Hooks.getOnEachOperatorHooks()).hasSize(1);
assertThat(applied).containsExactly("h2");
}
@Test
public void onEachOperatorReset() {
Hooks.onEachOperator("some", p -> p);
assertThat(Hooks.onEachOperatorHook).isNotNull();
assertThat(Hooks.getOnEachOperatorHooks()).hasSize(1);
Hooks.resetOnEachOperator();
assertThat(Hooks.onEachOperatorHook).isNull();
assertThat(Hooks.getOnEachOperatorHooks()).isEmpty();
}
@Test
public void onEachOperatorClearByName() {
Hooks.onEachOperator("some", p -> p);
Hooks.onEachOperator("other", p -> p);
assertThat(Hooks.onEachOperatorHook).isNotNull();
assertThat(Hooks.getOnEachOperatorHooks()).hasSize(2);
Hooks.resetOnEachOperator("some");
assertThat(Hooks.onEachOperatorHook).isNotNull();
assertThat(Hooks.getOnEachOperatorHooks())
.hasSize(1)
.containsOnlyKeys("other");
Hooks.resetOnEachOperator("other");
assertThat(Hooks.onEachOperatorHook).isNull();
assertThat(Hooks.getOnEachOperatorHooks()).isEmpty();
}
@Test
public void onLastOperatorSameLambdaSameNameAppliedOnce() {
AtomicInteger applied = new AtomicInteger();
Function<? super Publisher<Object>, ? extends Publisher<Object>> hook = p -> {
applied.incrementAndGet();
return p;
};
Hooks.onLastOperator(hook);
Hooks.onLastOperator(hook);
Hooks.onLastOperatorHook.apply(s -> {});
assertThat(applied).hasValue(1);
}
@Test
public void onLastOperatorSameLambdaDifferentNamesAppliedTwice() {
AtomicInteger applied = new AtomicInteger();
Function<? super Publisher<Object>, ? extends Publisher<Object>> hook = p -> {
applied.incrementAndGet();
return p;
};
Hooks.onLastOperator(hook);
Hooks.onLastOperator("other", hook);
Hooks.onLastOperatorHook.apply(s -> {});
assertThat(applied).hasValue(2);
}
@Test
public void onLastOperatorOneHookNoComposite() {
Function<? super Publisher<Object>, ? extends Publisher<Object>> hook = p -> p;
Hooks.onLastOperator(hook);
assertThat(Hooks.onLastOperatorHook).isSameAs(hook);
}
@Test
public void onLastOperatorNamedReplacesKeepsOrder() {
List<String> applied = new ArrayList<>(3);
Function<? super Publisher<Object>, ? extends Publisher<Object>> hook1 = p -> {
applied.add("h1");
return p;
};
Function<? super Publisher<Object>, ? extends Publisher<Object>> hook2 = p -> {
applied.add("h2");
return p;
};
Function<? super Publisher<Object>, ? extends Publisher<Object>> hook3 = p -> {
applied.add("h3");
return p;
};
Hooks.onLastOperator("1", hook1);
Hooks.onLastOperator("2", hook2);
Hooks.onLastOperatorHook.apply(s -> {});
assertThat(Hooks.getOnLastOperatorHooks())
.containsOnlyKeys("1", "2");
assertThat(Hooks.getOnLastOperatorHooks().values())
.containsExactly(hook1, hook2);
assertThat(applied).containsExactly("h1", "h2");
applied.clear();
Hooks.onLastOperator("1", hook3);
Hooks.onLastOperatorHook.apply(s -> {});
assertThat(Hooks.getOnLastOperatorHooks())
.containsOnlyKeys("1", "2");
assertThat(Hooks.getOnLastOperatorHooks().values())
.containsExactly(hook3, hook2);
assertThat(applied).containsExactly("h3", "h2");
}
@Test
public void onLastOperatorResetSpecific() {
List<String> applied = new ArrayList<>(3);
Function<? super Publisher<Object>, ? extends Publisher<Object>> hook1 = p -> {
applied.add("h1");
return p;
};
Function<? super Publisher<Object>, ? extends Publisher<Object>> hook2 = p -> {
applied.add("h2");
return p;
};
Hooks.onLastOperator("1", hook1);
Hooks.onLastOperator(hook2);
Hooks.onLastOperatorHook.apply(s -> {});
assertThat(Hooks.getOnLastOperatorHooks()).hasSize(2);
assertThat(applied).containsExactly("h1", "h2");
applied.clear();
Hooks.resetOnLastOperator("1");
Hooks.onLastOperatorHook.apply(s -> {});
assertThat(Hooks.getOnLastOperatorHooks()).hasSize(1);
assertThat(applied).containsExactly("h2");
}
@Test
public void onLastOperatorReset() {
Hooks.onLastOperator("some", p -> p);
assertThat(Hooks.onLastOperatorHook).isNotNull();
assertThat(Hooks.getOnLastOperatorHooks()).hasSize(1);
Hooks.resetOnLastOperator();
assertThat(Hooks.onLastOperatorHook).isNull();
assertThat(Hooks.getOnLastOperatorHooks()).isEmpty();
}
@Test
public void onLastOperatorClearByName() {
Hooks.onLastOperator("some", p -> p);
Hooks.onLastOperator("other", p -> p);
assertThat(Hooks.onLastOperatorHook).isNotNull();
assertThat(Hooks.getOnLastOperatorHooks()).hasSize(2);
Hooks.resetOnLastOperator("some");
assertThat(Hooks.onLastOperatorHook).isNotNull();
assertThat(Hooks.getOnLastOperatorHooks())
.hasSize(1)
.containsOnlyKeys("other");
Hooks.resetOnLastOperator("other");
assertThat(Hooks.onLastOperatorHook).isNull();
assertThat(Hooks.getOnLastOperatorHooks()).isEmpty();
}
@Test
public void onOperatorErrorSameLambdaSameNameAppliedOnce() {
AtomicInteger applied = new AtomicInteger();
BiFunction<Throwable, Object, Throwable> hook = (t, s) -> {
applied.incrementAndGet();
return t;
};
Hooks.onOperatorError(hook);
Hooks.onOperatorError(hook);
Hooks.onOperatorErrorHook.apply(new IllegalStateException("boom"), "foo");
assertThat(applied).hasValue(1);
}
@Test
public void onOperatorErrorSameLambdaDifferentNamesAppliedTwice() {
AtomicInteger applied = new AtomicInteger();
BiFunction<Throwable, Object, Throwable> hook = (t, s) -> {
applied.incrementAndGet();
return t;
};
Hooks.onOperatorError(hook);
Hooks.onOperatorError("other", hook);
Hooks.onOperatorErrorHook.apply(new IllegalStateException("boom"), "foo");
assertThat(applied).hasValue(2);
}
@Test
public void onOperatorErrorOneHookNoComposite() {
BiFunction<Throwable, Object, Throwable> hook = (t, s) -> t;
Hooks.onOperatorError(hook);
assertThat(Hooks.onOperatorErrorHook).isSameAs(hook);
}
@Test
public void onOperatorErrorNamedReplacesKeepsOrder() {
List<String> applied = new ArrayList<>(3);
BiFunction<Throwable, Object, Throwable> hook1 = (t, s) -> {
applied.add("h1");
return t;
};
BiFunction<Throwable, Object, Throwable> hook2 = (t, s) -> {
applied.add("h2");
return t;
};
BiFunction<Throwable, Object, Throwable> hook3 = (t, s) -> {
applied.add("h3");
return t;
};
Hooks.onOperatorError("1", hook1);
Hooks.onOperatorError("2", hook2);
Hooks.onOperatorErrorHook.apply(new IllegalStateException("boom"), "foo");
assertThat(Hooks.getOnOperatorErrorHooks())
.containsOnlyKeys("1", "2");
assertThat(Hooks.getOnOperatorErrorHooks().values())
.containsExactly(hook1, hook2);
assertThat(applied).containsExactly("h1", "h2");
applied.clear();
Hooks.onOperatorError("1", hook3);
Hooks.onOperatorErrorHook.apply(new IllegalStateException("boom2"), "bar");
assertThat(Hooks.getOnOperatorErrorHooks())
.containsOnlyKeys("1", "2");
assertThat(Hooks.getOnOperatorErrorHooks().values())
.containsExactly(hook3, hook2);
assertThat(applied).containsExactly("h3", "h2");
}
@Test
public void onOperatorErrorResetSpecific() {
List<String> applied = new ArrayList<>(3);
BiFunction<Throwable, Object, Throwable> hook1 = (t, s) -> {
applied.add("h1");
return t;
};
BiFunction<Throwable, Object, Throwable> hook2 = (t, s) -> {
applied.add("h2");
return t;
};
Hooks.onOperatorError("1", hook1);
Hooks.onOperatorError(hook2);
Hooks.onOperatorErrorHook.apply(new IllegalStateException("boom"), "foo");
assertThat(Hooks.getOnOperatorErrorHooks()).hasSize(2);
assertThat(applied).containsExactly("h1", "h2");
applied.clear();
Hooks.resetOnOperatorError("1");
Hooks.onOperatorErrorHook.apply(new IllegalStateException("boom2"), "bar");
assertThat(Hooks.getOnOperatorErrorHooks()).hasSize(1);
assertThat(applied).containsExactly("h2");
}
@Test
public void onOperatorErrorReset() {
Hooks.onOperatorError("some", (t, v) -> t);
assertThat(Hooks.onOperatorErrorHook).isNotNull();
assertThat(Hooks.getOnOperatorErrorHooks()).hasSize(1);
Hooks.resetOnOperatorError();
assertThat(Hooks.onOperatorErrorHook).isNull();
assertThat(Hooks.getOnOperatorErrorHooks()).isEmpty();
}
@Test
public void onOperatorErrorClearByName() {
Hooks.onOperatorError("some", (t, v) -> t);
Hooks.onOperatorError("other", (t, v) -> t);
assertThat(Hooks.onOperatorErrorHook).isNotNull();
assertThat(Hooks.getOnOperatorErrorHooks()).hasSize(2);
Hooks.resetOnOperatorError("some");
assertThat(Hooks.onOperatorErrorHook).isNotNull();
assertThat(Hooks.getOnOperatorErrorHooks())
.hasSize(1)
.containsOnlyKeys("other");
Hooks.resetOnOperatorError("other");
assertThat(Hooks.onOperatorErrorHook).isNull();
assertThat(Hooks.getOnOperatorErrorHooks()).isEmpty();
}
@Test
public void errorHooks() throws Exception {
Hooks.onOperatorError((e, s) -> new TestException(s.toString()));
Hooks.onNextDropped(d -> {
throw new TestException(d.toString());
});
Hooks.onErrorDropped(e -> {
throw new TestException("errorDrop");
});
Throwable w = Operators.onOperatorError(null, new Exception(), "hello", Context.empty());
assertThat(w).isInstanceOf(TestException.class);
assertThat(w).hasMessage("hello");
assertThatExceptionOfType(TestException.class).isThrownBy(() -> {
Operators.onNextDropped("hello", Context.empty());
}).withMessage("hello");
assertThatExceptionOfType(TestException.class).isThrownBy(() -> {
Operators.onErrorDropped(new Exception(), Context.empty());
}).withMessage("errorDrop");
}
@Test
public void accumulatingHooks() throws Exception {
AtomicReference<String> ref = new AtomicReference<>();
Hooks.onNextDropped(d -> {
ref.set(d.toString());
});
Hooks.onNextDropped(d -> {
ref.set(ref.get()+"bar");
});
Operators.onNextDropped("foo", Context.empty());
assertThat(ref).hasValue("foobar");
Hooks.onErrorDropped(d -> {
ref.set(d.getMessage());
});
Hooks.onErrorDropped(d -> {
ref.set(ref.get()+"bar");
});
Operators.onErrorDropped(new Exception("foo"), Context.empty());
assertThat(ref).hasValue("foobar");
Hooks.resetOnErrorDropped();
Hooks.onOperatorError((error, d) -> {
ref.set(d.toString());
return new Exception("bar");
});
Hooks.onOperatorError((error, d) -> {
ref.set(ref.get()+error.getMessage());
return error;
});
Operators.onOperatorError(null, null, "foo", Context.empty());
assertThat(ref).hasValue("foobar");
Hooks.resetOnOperatorError();
AtomicReference<Publisher> hook = new AtomicReference<>();
AtomicReference<Object> hook2 = new AtomicReference<>();
Hooks.onEachOperator(h -> {
Flux<Object> publisher = Hooks.convertToFluxBypassingHooks(
TestPublisher.create());
hook.set(publisher);
return publisher;
});
Hooks.onEachOperator(h -> {
hook2.set(h);
return h;
});
Flux.just("test").filter(d -> true).subscribe();
assertThat(hook.get()).isNotNull().isEqualTo(hook2.get());
Hooks.resetOnEachOperator();
hook.set(null);
hook2.set(null);
Hooks.onLastOperator(h -> {
final Flux<Object> publisher = Hooks.convertToFluxBypassingHooks(
TestPublisher.create());
hook.set(publisher);
return publisher;
});
Hooks.onLastOperator(h -> {
hook2.set(h);
return h;
});
Flux.just("test").filter(d -> true).subscribe();
assertThat(hook.get()).isNotNull().isEqualTo(hook2.get());
}
@Test
public void parallelModeFused() {
Hooks.onOperatorDebug();
Hooks.onEachOperator(p -> {
System.out.println(Scannable.from(p).stepName());
return p;
});
Flux<Integer> source = Mono.just(1)
.flux()
.repeat(999)
.publish()
.autoConnect();
int ncpu = Math.max(8,
Runtime.getRuntime()
.availableProcessors());
Scheduler scheduler = Schedulers.newParallel("test", ncpu);
try {
Flux<Integer> result = ParallelFlux.from(source, ncpu)
.runOn(scheduler)
.map(v -> v + 1)
.log("test", Level.INFO, true, SignalType.ON_SUBSCRIBE)
.sequential();
AssertSubscriber<Integer> ts = AssertSubscriber.create();
result.subscribe(ts);
ts.await(Duration.ofSeconds(10));
ts.assertSubscribed()
.assertValueCount(1000)
.assertComplete()
.assertNoError();
}
finally {
scheduler.dispose();
}
}
@Test
public void verboseExtension() {
Queue<String> q = new LinkedTransferQueue<>();
Hooks.onEachOperator(p -> {
q.offer(p.toString());
return p;
});
Hooks.onOperatorDebug();
simpleFlux();
assertThat(q.toArray()).containsExactly(
"FluxJust",
"FluxMapFuseable",
"FluxPeekFuseable",
"MonoCollectList",
"MonoOnErrorReturn"
);
q.clear();
Hooks.resetOnEachOperator();
Hooks.onEachOperator(p -> {
q.offer(p.toString());
return p;
});
simpleFlux();
assertThat(q.toArray()).containsExactly(
"FluxJust",
"FluxMapFuseable",
"FluxPeekFuseable",
"MonoCollectList",
"MonoOnErrorReturn");
q.clear();
Hooks.resetOnEachOperator();
simpleFlux();
assertThat(q.toArray()).isEmpty();
}
@Test
public void testOnLastPublisher() throws Exception {
List<Publisher> l = new ArrayList<>();
Hooks.onLastOperator(p -> {
System.out.println(Scannable.from(p).parents().count());
System.out.println(Scannable.from(p).stepName());
l.add(p);
return p;
});
StepVerifier.create(Flux.just(1, 2, 3)
.map(m -> m)
.takeUntilOther(Mono.never())
.flatMap(d -> Mono.just(d).hide()))
.expectNext(1, 2, 3)
.verifyComplete();
Hooks.resetOnLastOperator();
assertThat(l).hasSize(5);
}
@Test
public void testMultiReceiver() {
Hooks.onOperatorDebug();
//this will avoid relying on exceptions surfacing from assertion in error handler
AssertionError[] assertionErrors = new AssertionError[3];
List<Throwable> assemblyExceptions = new ArrayList<>();
ConnectableFlux<?> t = Flux.empty()
.then(Mono.defer(() -> {
throw new RuntimeException();
})).flux().publish();
t.map(d -> d).subscribe(null, e -> {
assemblyExceptions.add(e.getSuppressed()[0]);
try {
//live evaluation, error hasn't been emitted everywhere so we only have one occurrence so far
assertThat(e.getSuppressed()[0]).hasMessageContaining("|_ Flux.publish ⇢ at reactor.core.publisher.HooksTest.testMultiReceiver(HooksTest.java:747)");
}
catch (AssertionError ae) {
assertionErrors[0] = ae;
}
});
t.filter(d -> true).subscribe(null, e -> {
assemblyExceptions.add(e.getSuppressed()[0]);
try {
//live evaluation, error hasn't been emitted everywhere so we only have two occurrences so far
assertThat(e.getSuppressed()[0]).hasMessageContaining("|_ Flux.publish ⇢ at reactor.core.publisher.HooksTest.testMultiReceiver(HooksTest.java:747) (observed 2 times)");
}
catch (AssertionError ae) {
assertionErrors[1] = ae;
}
});
t.distinct().subscribe(null, e -> {
assemblyExceptions.add(e.getSuppressed()[0]);
try {
//live evaluation, error has been emitted everywhere so we have the three occurrences now
// (note that the indentation has grown by 1 due to distinct operator getting in the mix)
assertThat(e.getSuppressed()[0]).hasMessageContaining("|_ Flux.publish ⇢ at reactor.core.publisher.HooksTest.testMultiReceiver(HooksTest.java:747) (observed 3 times)");
}
catch (AssertionError ae) {
assertionErrors[2] = ae;
}
});
t.connect();
assertThat(assertionErrors).allMatch(Objects::isNull);
assertThat(assemblyExceptions)
.hasSize(3)
.allMatch(Objects::nonNull)
.containsOnly(assemblyExceptions.get(0))
.first(InstanceOfAssertFactories.THROWABLE)
.hasMessageContaining("|_ Flux.publish ⇢ at reactor.core.publisher.HooksTest.testMultiReceiver(HooksTest.java:747) (observed 3 times)")
.hasMessageNotContainingAny("(observed 2 times)");
}
@Test
public void onNextDroppedFailReplaces() {
AtomicReference<Object> dropHook = new AtomicReference<>();
Publisher<Integer> p = s -> {
s.onSubscribe(Operators.emptySubscription());
s.onNext(1);
s.onNext(2);
s.onNext(3);
};
List<Integer> seen = new ArrayList<>();
try {
Hooks.onNextDropped(dropHook::set);
Hooks.onNextDroppedFail();
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> Flux.from(p).take(2, false).subscribe(seen::add))
.isInstanceOf(RuntimeException.class)
.matches(Exceptions::isCancel);
assertThat(seen).containsExactly(1, 2);
assertThat(dropHook.get()).isNull();
}
finally {
Hooks.resetOnNextDropped();
}
}
@Test
public void lastOperatorLiftsFlux() {
AtomicInteger liftCounter = new AtomicInteger();
Hooks.onLastOperator(Operators.lift((sc, sub) -> liftSubscriber(sc, sub, liftCounter)));
StepVerifier.create(Flux.just(1, 2, 3)
.log()
.log())
.expectNext(101, 102, 103)
.verifyComplete();
assertThat(liftCounter).hasValue(1);
}
@Test
public void lastOperatorLiftsMono() {
AtomicInteger liftCounter = new AtomicInteger();
Hooks.onLastOperator(Operators.lift((sc, sub) -> liftSubscriber(sc, sub, liftCounter)));
StepVerifier.create(Mono.just(1)
.log()
.log())
.expectNext(101)
.verifyComplete();
}
@Test
public void lastOperatorLiftsParallelFlux() {
AtomicInteger liftCounter = new AtomicInteger();
Hooks.onLastOperator(Operators.lift((sc, sub) -> liftSubscriber(sc, sub, liftCounter)));
StepVerifier.create(ParallelFlux.from(Mono.just(1), Mono.just(1))
.log()
.log())
.expectNext(101, 101)
.verifyComplete();
}
@Test
public void lastOperatorFilteredLiftFlux() {
AtomicInteger liftCounter = new AtomicInteger();
Hooks.onLastOperator(Operators.lift(sc -> sc.tags()
.anyMatch(t -> t.getT1().contains("metric")),
(sc, sub) -> liftSubscriber(sc, sub, liftCounter)));
StepVerifier.create(Flux.just(1, 2, 3)
.tag("metric", "test")
.log()
.log())
.expectNext(101, 102, 103)
.verifyComplete();
StepVerifier.create(Flux.just(1, 2, 3)
.log()
.log())
.expectNext(1, 2, 3)
.verifyComplete();
}
@Test
public void lastOperatorFilteredLiftMono() {
AtomicInteger liftCounter = new AtomicInteger();
Hooks.onLastOperator(Operators.lift(sc -> sc.tags()
.anyMatch(t -> t.getT1().contains("metric")),
(sc, sub) -> liftSubscriber(sc, sub, liftCounter)));
StepVerifier.create(Mono.just(1)
.tag("metric", "test")
.log()
.log())
.expectNext(101)
.verifyComplete();
StepVerifier.create(Mono.just(1)
.log()
.log())
.expectNext(1)
.verifyComplete();
}
@Test
public void lastOperatorFilteredLiftParallelFlux() {
AtomicInteger liftCounter = new AtomicInteger();
Hooks.onLastOperator(Operators.lift(sc -> sc.tags()
.anyMatch(t -> t.getT1().contains("metric")),
(sc, sub) -> liftSubscriber(sc, sub, liftCounter)));
StepVerifier.create(ParallelFlux.from(Mono.just(1), Mono.just(1))
.tag("metric", "test")
.log()
.log())
.expectNext(101, 101)
.verifyComplete();
StepVerifier.create(ParallelFlux.from(Mono.just(1), Mono.just(1))
.log()
.log())
.expectNext(1, 1)
.verifyComplete();
}
@Test
public void eachOperatorLiftsFlux() {
AtomicInteger liftCounter = new AtomicInteger();
Hooks.onEachOperator(Operators.lift((sc, sub) -> liftSubscriber(sc, sub, liftCounter)));
StepVerifier.create(Flux.just(1, 2, 3)
.log()
.log())
.expectNext(301, 302, 303)
.verifyComplete();
}
@Test
public void eachOperatorLiftsMono() {
AtomicInteger liftCounter = new AtomicInteger();
Hooks.onEachOperator(Operators.lift((sc, sub) -> liftSubscriber(sc, sub, liftCounter)));
StepVerifier.create(Mono.just(1)
.log()
.log())
.expectNext(301)
.verifyComplete();
}
@Test
public void eachOperatorLiftsParallelFlux() {
AtomicInteger liftCounter = new AtomicInteger();
Hooks.onEachOperator(Operators.lift((sc, sub) -> liftSubscriber(sc, sub, liftCounter)));
StepVerifier.create(ParallelFlux.from(Mono.just(1), Mono.just(1)) //internally converts each rail to a Flux using Flux.from
.log()
.log())
.expectNext(601, 601) //6x lifts => just,Flux.from,ParallelFlux.from,log,log, back to sequential (shared)
.verifyComplete();
assertThat(liftCounter).hasValue(11); //11x total lifts: 2xjust, 2xfrom, 2xparallelFrom,4xlog,sequential
}
@Test
public void fluxWrapFluxSourceDoesntCallAssemblyHook() {
final Flux<Integer> source = Flux.range(1, 10);
//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
AtomicInteger wrappedCount = new AtomicInteger();
Hooks.onEachOperator(p -> {
wrappedCount.incrementAndGet();
return p;
});
Hooks.convertToFluxBypassingHooks(source);
Flux.wrap(source);
Assertions.assertThat(wrappedCount).hasValue(0);
}
@Test
public void fluxWrapScalarJustDoesntCallAssemblyHook() {
final Mono<String> source = Mono.just("scalarJust");
//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
AtomicInteger wrappedCount = new AtomicInteger();
Hooks.onEachOperator(p -> {
wrappedCount.incrementAndGet();
return p;
});
Hooks.convertToFluxBypassingHooks(source);
Flux.wrap(source);
Assertions.assertThat(wrappedCount).hasValue(0);
}
@Test
public void fluxWrapScalarErrorDoesntCallAssemblyHook() {
final Mono<Object> source = Mono.error(new IllegalStateException("scalarError"));
//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
AtomicInteger wrappedCount = new AtomicInteger();
Hooks.onEachOperator(p -> {
wrappedCount.incrementAndGet();
return p;
});
Hooks.convertToFluxBypassingHooks(source);
Flux.wrap(source);
Assertions.assertThat(wrappedCount).hasValue(0);
}
@Test
public void fluxWrapScalarEmptyDoesntCallAssemblyHook() {
final Mono<Object> source = Mono.empty();
//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
AtomicInteger wrappedCount = new AtomicInteger();
Hooks.onEachOperator(p -> {
wrappedCount.incrementAndGet();
return p;
});
Hooks.convertToFluxBypassingHooks(source);
Flux.wrap(source);
Assertions.assertThat(wrappedCount).hasValue(0);
}
@Test
public void fluxWrapMonoFuseableDoesntCallAssemblyHook() {
Mono<String> source = Mono.just("monoFuseable").map(i -> i);
//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
AtomicInteger wrappedCount = new AtomicInteger();
Hooks.onEachOperator(p -> {
wrappedCount.incrementAndGet();
return p;
});
Hooks.convertToFluxBypassingHooks(source);
Flux.wrap(source);
Assertions.assertThat(wrappedCount).hasValue(0);
}
@Test
public void fluxWrapMonoNormalDoesntCallAssemblyHook() {
final Mono<String> source = Mono.just("monoNormal")
.hide()
.map(i -> i);
//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
AtomicInteger wrappedCount = new AtomicInteger();
Hooks.onEachOperator(p -> {
wrappedCount.incrementAndGet();
return p;
});
Hooks.convertToFluxBypassingHooks(source);
Flux.wrap(source);
Assertions.assertThat(wrappedCount).hasValue(0);
}
@Test
public void fluxWrapPublisherDoesntCallAssemblyHook() {
Publisher<String> publisher = sub -> sub.onSubscribe(Operators.emptySubscription());
//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
AtomicInteger wrappedCount = new AtomicInteger();
Hooks.onEachOperator(p -> {
wrappedCount.incrementAndGet();
return p;
});
Hooks.convertToFluxBypassingHooks(publisher);
Flux.wrap(publisher);
Assertions.assertThat(wrappedCount).hasValue(0);
}
@Test
public void monoWrapMonoDoesntCallAssemblyHook() {
final Mono<Integer> source = Mono.just(1);
//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
AtomicInteger wrappedCount = new AtomicInteger();
Hooks.onEachOperator(p -> {
wrappedCount.incrementAndGet();
return p;
});
Hooks.convertToMonoBypassingHooks(source, true);
Hooks.convertToMonoBypassingHooks(source, false);
Mono.wrap(source, true);
Mono.wrap(source, false);
Assertions.assertThat(wrappedCount).hasValue(0);
}
@Test
public void monoWrapFluxWrappingMonoDoesntCallAssemblyHook() {
final Flux<Integer> source = Flux.from(Mono.just(1).hide());
//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
AtomicInteger wrappedCount = new AtomicInteger();
Hooks.onEachOperator(p -> {
wrappedCount.incrementAndGet();
return p;
});
Hooks.convertToMonoBypassingHooks(source, true);
Hooks.convertToMonoBypassingHooks(source, false);
Mono.wrap(source, true);
Mono.wrap(source, false);
Assertions.assertThat(wrappedCount).hasValue(0);
}
@Test
public void monoWrapCallableFluxDoesntCallAssemblyHook() {
final Flux<Integer> source = Flux.just(1);
//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
AtomicInteger wrappedCount = new AtomicInteger();
Hooks.onEachOperator(p -> {
wrappedCount.incrementAndGet();
return p;
});
Hooks.convertToMonoBypassingHooks(source, true);
Hooks.convertToMonoBypassingHooks(source, false);
Mono.wrap(source, true);
Mono.wrap(source, false);
Assertions.assertThat(wrappedCount).hasValue(0);
}
@Test
public void monoWrapFluxDoesntCallAssemblyHook() {
final Flux<Integer> source = Flux.just(1).hide();
//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
AtomicInteger wrappedCount = new AtomicInteger();
Hooks.onEachOperator(p -> {
wrappedCount.incrementAndGet();
return p;
});
Hooks.convertToMonoBypassingHooks(source, true);
Hooks.convertToMonoBypassingHooks(source, false);
Mono.wrap(source, true);
Mono.wrap(source, false);
Assertions.assertThat(wrappedCount).hasValue(0);
}
@Test
public void monoWrapPublisherDoesntCallAssemblyHook() {
final Publisher<Integer> source = TestPublisher.create();
Assertions.assertThat(source).isNotInstanceOf(Flux.class); //smoke test this is a Publisher
//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
AtomicInteger wrappedCount = new AtomicInteger();
Hooks.onEachOperator(p -> {
wrappedCount.incrementAndGet();
return p;
});
Hooks.convertToMonoBypassingHooks(source, true);
Hooks.convertToMonoBypassingHooks(source, false);
Mono.wrap(source, true);
Mono.wrap(source, false);
Assertions.assertThat(wrappedCount).hasValue(0);
}
@Test
public void fluxWrapToMonoScalarEmptyDoesntCallAssemblyHook() {
@SuppressWarnings("unchecked")
Callable<Integer> source = (Callable<Integer>) Flux.empty();
//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
AtomicInteger wrappedCount = new AtomicInteger();
Hooks.onEachOperator(p -> {
wrappedCount.incrementAndGet();
return p;
});
Flux.wrapToMono(source);
Assertions.assertThat(wrappedCount).hasValue(0);
}
@Test
public void fluxWrapToMonoScalarValuedDoesntCallAssemblyHook() {
@SuppressWarnings("unchecked")
Callable<Integer> source = (Callable<Integer>) Flux.just(1);
//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
AtomicInteger wrappedCount = new AtomicInteger();
Hooks.onEachOperator(p -> {
wrappedCount.incrementAndGet();
return p;
});
Flux.wrapToMono(source);
Assertions.assertThat(wrappedCount).hasValue(0);
}
@Test
public void fluxWrapToMonoScalarErrorDoesntCallAssemblyHook() {
@SuppressWarnings("unchecked")
Callable<Integer> source = (Callable<Integer>) Flux.error(new IllegalStateException("boom"));
//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
AtomicInteger wrappedCount = new AtomicInteger();
Hooks.onEachOperator(p -> {
wrappedCount.incrementAndGet();
return p;
});
Flux.wrapToMono(source);
Assertions.assertThat(wrappedCount).hasValue(0);
}
@Test
public void fluxWrapToMonoVanillaCallableDoesntCallAssemblyHook() {
Callable<Integer> source = () -> 1;
//set the hook AFTER the original operators have been invoked (since they trigger assembly themselves)
AtomicInteger wrappedCount = new AtomicInteger();
Hooks.onEachOperator(p -> {
wrappedCount.incrementAndGet();
return p;
});
Flux.wrapToMono(source);
Assertions.assertThat(wrappedCount).hasValue(0);
}
private static CoreSubscriber<Object> liftSubscriber(Scannable scannable, CoreSubscriber<? super Object> sub, AtomicInteger liftCounter) {
liftCounter.incrementAndGet();
return new CoreSubscriber<Object>() {
@Override
public void onSubscribe(Subscription s) {
sub.onSubscribe(s);
}
@Override
public void onNext(Object o) {
System.out.println("Lifting " + o + " out of " + scannable.stepName());
sub.onNext((Integer) o + 100);
}
@Override
public void onError(Throwable t) {
sub.onError(t);
}
@Override
public void onComplete() {
sub.onComplete();
}
};
}
// https://github.com/reactor/reactor-core/issues/3137
@Test
public void reproduceClassCastExceptionWithHooks() {
Hooks.onLastOperator(objectPublisher -> {
if (objectPublisher instanceof Mono) {
return Hooks.convertToMonoBypassingHooks(objectPublisher, false)
.doFinally(signalType -> {
});
} else {
return objectPublisher;
}
});
try {
Mono.just(1)
.flatMap(fsm -> Mono.just(1)
.doOnSubscribe(subscription -> {
}))
.doOnSubscribe(subscription -> {
})
.block();
} finally {
Hooks.resetOnLastOperator();
}
}
}
| {
"content_hash": "0bcc70f172a20b644a8daaa43aff7252",
"timestamp": "",
"source": "github",
"line_count": 1267,
"max_line_length": 173,
"avg_line_length": 29.17600631412786,
"alnum_prop": 0.6827354866634204,
"repo_name": "reactor/reactor-core",
"id": "84ad1d9b647226b2671376bb32efd67e57788f4c",
"size": "37616",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "reactor-core/src/test/java/reactor/core/publisher/HooksTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "8647845"
}
],
"symlink_target": ""
} |
require_relative '../spec_helper'
describe Phoebo::Environment do
before(:all) {
@path = [
"#{File::SEPARATOR}a",
"#{File::SEPARATOR}b",
"#{File::SEPARATOR}c"
]
}
subject(:env) {
described_class.new({'PATH' => @path.join(File::PATH_SEPARATOR) })
}
context 'path lookup' do
it 'looks up path' do
allow(File).to receive(:executable?).with("#{@path[0]}#{File::SEPARATOR}bash").and_return(false)
allow(File).to receive(:executable?).with("#{@path[1]}#{File::SEPARATOR}bash").and_return(true)
allow(File).to receive(:executable?).with("#{@path[2]}#{File::SEPARATOR}bash").and_return(true)
expect(env.bash_path).to eq "#{@path[1]}#{File::SEPARATOR}bash"
end
it 'nil if not found' do
@path.each { |path|
allow(File).to receive(:executable?).with("#{path}#{File::SEPARATOR}git").and_return(false)
}
expect(env.git_path).to eq nil
end
end
end
| {
"content_hash": "aa48f3a2bdf203609dccb05b999561ce",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 102,
"avg_line_length": 30.516129032258064,
"alnum_prop": 0.6046511627906976,
"repo_name": "phoebo/image-builder",
"id": "1e62b89773be37972de7d1637758281711655d74",
"size": "946",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/phoebo/environment_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "54468"
},
{
"name": "Shell",
"bytes": "4596"
}
],
"symlink_target": ""
} |
'use strict';
//require the schema in the models dir
const Note = require('../models/note');
const Category = require('../models/category');
module.exports.edit = (req, res) => {
//find through mongoose.
Note.findById(req.params.id, (err, note) => {
if (err) throw err;
//passing the specific object into jade template
res.render('new-note', {note: note});
});
};
module.exports.update = (req, res) => {
Note.findByIdAndUpdate(req.params.id, req.body, (err, note) => {
if (err) throw err;
res.redirect(`/notes/${note._id}`);
});
};
module.exports.index = (req, res) => {
Note.find({}, (err, notes) => {
if (err) throw err;
res.render('notes-index', {notes: notes});
});
};
module.exports.newNote = (req, res) => {
Category.find({}, (err, categories) => {
if (err) throw err;
res.render('new-note', {
categories: categories
});
})
};
module.exports.show = (req, res) => {
Note.findById(req.params.id, (err, note) => {
if (err) throw err;
res.render('show-note', {note: note});
});
};
module.exports.create = (req, res) => {
Note.create(req.body, (err, note) => {
if (err) throw err;
res.redirect(`/notes/${note._id}`);
});
};
module.exports.destroy = (req, res) => {
Note.findByIdAndRemove(req.params.id, (err) => {
if (err) throw err;
res.redirect('/notes');
});
};
| {
"content_hash": "157b84e18101fcd02eb8412741d9b719",
"timestamp": "",
"source": "github",
"line_count": 65,
"max_line_length": 67,
"avg_line_length": 21.2,
"alnum_prop": 0.581277213352685,
"repo_name": "stephanieg0/evernode",
"id": "5c44a8510a82af2b8448d2b483ed1699fdcda13b",
"size": "1378",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "controllers/note.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1259"
},
{
"name": "JavaScript",
"bytes": "4596"
}
],
"symlink_target": ""
} |
package org.elasticsearch.benchmark.transport;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.Bytes;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.*;
import org.elasticsearch.transport.netty.NettyTransport;
import java.util.concurrent.CountDownLatch;
import static org.elasticsearch.transport.TransportRequestOptions.options;
/**
*
*/
public class BenchmarkNettyLargeMessages {
public static void main(String[] args) throws InterruptedException {
final ByteSizeValue payloadSize = new ByteSizeValue(10, ByteSizeUnit.MB);
final int NUMBER_OF_ITERATIONS = 100000;
final int NUMBER_OF_CLIENTS = 5;
final byte[] payload = new byte[(int) payloadSize.bytes()];
Settings settings = ImmutableSettings.settingsBuilder()
.build();
final ThreadPool threadPool = new ThreadPool();
final TransportService transportServiceServer = new TransportService(new NettyTransport(settings, threadPool), threadPool).start();
final TransportService transportServiceClient = new TransportService(new NettyTransport(settings, threadPool), threadPool).start();
final DiscoveryNode bigNode = new DiscoveryNode("big", new InetSocketTransportAddress("localhost", 9300));
// final DiscoveryNode smallNode = new DiscoveryNode("small", new InetSocketTransportAddress("localhost", 9300));
final DiscoveryNode smallNode = bigNode;
transportServiceClient.connectToNode(bigNode);
transportServiceClient.connectToNode(smallNode);
transportServiceServer.registerHandler("benchmark", new BaseTransportRequestHandler<BenchmarkMessage>() {
@Override
public BenchmarkMessage newInstance() {
return new BenchmarkMessage();
}
@Override
public String executor() {
return ThreadPool.Names.GENERIC;
}
@Override
public void messageReceived(BenchmarkMessage request, TransportChannel channel) throws Exception {
channel.sendResponse(request);
}
});
final CountDownLatch latch = new CountDownLatch(NUMBER_OF_CLIENTS);
for (int i = 0; i < NUMBER_OF_CLIENTS; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < NUMBER_OF_ITERATIONS; i++) {
BenchmarkMessage message = new BenchmarkMessage(1, payload);
transportServiceClient.submitRequest(bigNode, "benchmark", message, options().withLowType(), new BaseTransportResponseHandler<BenchmarkMessage>() {
@Override
public BenchmarkMessage newInstance() {
return new BenchmarkMessage();
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public void handleResponse(BenchmarkMessage response) {
}
@Override
public void handleException(TransportException exp) {
exp.printStackTrace();
}
}).txGet();
}
latch.countDown();
}
}).start();
}
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < NUMBER_OF_ITERATIONS; i++) {
BenchmarkMessage message = new BenchmarkMessage(2, Bytes.EMPTY_ARRAY);
long start = System.currentTimeMillis();
transportServiceClient.submitRequest(smallNode, "benchmark", message, options().withHighType(), new BaseTransportResponseHandler<BenchmarkMessage>() {
@Override
public BenchmarkMessage newInstance() {
return new BenchmarkMessage();
}
@Override
public String executor() {
return ThreadPool.Names.SAME;
}
@Override
public void handleResponse(BenchmarkMessage response) {
}
@Override
public void handleException(TransportException exp) {
exp.printStackTrace();
}
}).txGet();
long took = System.currentTimeMillis() - start;
System.out.println("Took " + took + "ms");
}
}
}).start();
latch.await();
}
}
| {
"content_hash": "e436d53f48ecf93ecf991b267474faff",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 171,
"avg_line_length": 41.31782945736434,
"alnum_prop": 0.5634146341463414,
"repo_name": "chanil1218/elasticsearch",
"id": "94378935ed1311d1fa01e849a78dd16456322ecc",
"size": "6135",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/org/elasticsearch/benchmark/transport/BenchmarkNettyLargeMessages.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FlowSharp
{
public static class SingleFlowPipe
{
private static SingleFlow<O> Parse<O>(this SingleFlow<O> flow)
{
if (flow.IsStopped)
flow.Stop(flow.Value);
return flow.Flow(flow.Value);
}
public static SingleFlow<O> I<O>(this SingleFlow<O> flow, Func<SingleFlow<O>> func)
{
if (flow.IsStopped)
return flow;
return Parse(func());
}
public static SingleFlow<O> I<O>(this SingleFlow<O> flow, Func<O, SingleFlow<O>> func)
{
if (flow.IsStopped)
return flow;
return Parse(func(flow.Value));
}
//public static ISingleFlow<O> Flow<I, O>(this ISingleFlow<I> flow, Func<ISingleFlow<O>> func, Func<I, O> convertFailure)
//{
// if (flow.IsStopped)
// return flow.Stop(convertFailure(flow.Value));
// return Flow(func());
//}
//public static ISingleFlow<O> Flow<I, O>(this ISingleFlow<I> flow, Func<I, ISingleFlow<O>> func, Func<I, O> convertFailure)
//{
// if (flow.IsStopped)
// return SingleFlow<O>.Stop(convertFailure(flow.Value));
// return Flow(func(flow.Value));
//}
//public static ISingleFlow<O> I<I, O>(this ISingleFlow<I> flow, Func<I, ISingleFlow<O>> func, Func<I, O> convertFailure)
//{
// if (flow.IsStopped)
// return SingleFlow<O>.Stop(convertFailure(flow.Value));
// return Flow(func(flow.Value));
//}
}
}
| {
"content_hash": "0c730dea286664601b7e230de89e32c1",
"timestamp": "",
"source": "github",
"line_count": 59,
"max_line_length": 132,
"avg_line_length": 29.440677966101696,
"alnum_prop": 0.5544041450777202,
"repo_name": "bazer/flowsharp",
"id": "dbe15ed3b8ac7ec93882af41ed5a549545d4d6ed",
"size": "1739",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/FlowSharp/SingleFlow/Pipe.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "45234"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>mathcomp-analysis: 4 m 40 s 🏆</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.9.0 / mathcomp-analysis - 0.2.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
mathcomp-analysis
<small>
0.2.0
<span class="label label-success">4 m 40 s 🏆</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-25 09:17:08 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-25 09:17:08 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.9.0 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.02.3 The OCaml compiler (virtual package)
ocaml-base-compiler 4.02.3 Official 4.02.3 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "pierre-yves@strub.nu"
homepage: "https://github.com/math-comp/analysis"
bug-reports: "https://github.com/math-comp/analysis/issues"
dev-repo: "git+https://github.com/math-comp/analysis.git"
license: "CeCILL-C"
authors: [
"Reynald Affeldt"
"Cyril Cohen"
"Assia Mahboubi"
"Damien Rouhling"
"Pierre-Yves Strub"
]
build: [
[make "INSTMODE=global" "config"]
[make "-j%{jobs}%"]
]
install: [
[make "install"]
]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/mathcomp/analysis"]
depends: [
"coq" { (>= "8.8" | = "dev") }
"coq-mathcomp-field" {(>= "1.8.0" & < "1.9.0~")}
"coq-mathcomp-bigenough" {(>= "1.0.0" & < "1.1.0~")}
"coq-mathcomp-finmap" {(>= "1.2.0" & < "1.3.0~")}
]
synopsis: "An analysis library for mathematical components"
description: """
This repository contains an experimental library for real analysis for
the Coq proof-assistant and using the Mathematical Components library.
It is inspired by the Coquelicot library.
"""
flags: light-uninstall
url {
src: "https://github.com/math-comp/analysis/archive/0.2.0.tar.gz"
checksum: "sha256=c84e5104c657bce16c2f04ff7602a0e53b7757e1b97262cf046bb6c41184d360"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-mathcomp-analysis.0.2.0 coq.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-mathcomp-analysis.0.2.0 coq.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>26 m 50 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-mathcomp-analysis.0.2.0 coq.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>4 m 40 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 28 M</p>
<ul>
<li>19 M <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/normedtype.vo</code></li>
<li>867 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/derive.vo</code></li>
<li>697 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/topology.vo</code></li>
<li>661 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/derive.glob</code></li>
<li>561 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/topology.glob</code></li>
<li>551 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/landau.vo</code></li>
<li>506 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/normedtype.glob</code></li>
<li>404 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/altreals/realsum.vo</code></li>
<li>397 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/altreals/realsum.glob</code></li>
<li>387 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/landau.glob</code></li>
<li>375 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/altreals/distr.glob</code></li>
<li>366 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/altreals/distr.vo</code></li>
<li>272 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/reals.vo</code></li>
<li>220 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/Rbar.vo</code></li>
<li>199 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/forms.vo</code></li>
<li>197 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/altreals/realseq.vo</code></li>
<li>183 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/reals.glob</code></li>
<li>166 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/Rstruct.vo</code></li>
<li>153 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/classical_sets.vo</code></li>
<li>146 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/forms.glob</code></li>
<li>139 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/altreals/realseq.glob</code></li>
<li>138 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/classical_sets.glob</code></li>
<li>117 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/Rstruct.glob</code></li>
<li>116 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/topology.v</code></li>
<li>116 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/Rbar.glob</code></li>
<li>104 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/boolp.vo</code></li>
<li>103 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/boolp.glob</code></li>
<li>93 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/altreals/discrete.vo</code></li>
<li>90 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/altreals/xfinmap.vo</code></li>
<li>83 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/posnum.vo</code></li>
<li>81 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/normedtype.v</code></li>
<li>72 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/summability.vo</code></li>
<li>64 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/landau.v</code></li>
<li>63 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/derive.v</code></li>
<li>45 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/altreals/realsum.v</code></li>
<li>43 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/altreals/xfinmap.glob</code></li>
<li>41 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/altreals/distr.v</code></li>
<li>37 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/altreals/discrete.glob</code></li>
<li>32 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/reals.v</code></li>
<li>31 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/classical_sets.v</code></li>
<li>23 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/boolp.v</code></li>
<li>23 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/forms.v</code></li>
<li>21 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/Rstruct.v</code></li>
<li>20 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/altreals/realseq.v</code></li>
<li>19 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/Rbar.v</code></li>
<li>18 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/posnum.glob</code></li>
<li>8 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/altreals/discrete.v</code></li>
<li>7 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/summability.glob</code></li>
<li>6 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/posnum.v</code></li>
<li>5 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/altreals/xfinmap.v</code></li>
<li>2 K <code>../ocaml-base-compiler.4.02.3/lib/coq/user-contrib/mathcomp/analysis/summability.v</code></li>
</ul>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-mathcomp-analysis.0.2.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "57386bcf1dff151f56d9c8e8da880ac3",
"timestamp": "",
"source": "github",
"line_count": 226,
"max_line_length": 159,
"avg_line_length": 60.43805309734513,
"alnum_prop": 0.5953583717695292,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "f4a8d460410142696a696f217913f196bee8217b",
"size": "13684",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.02.3-2.0.6/released/8.9.0/mathcomp-analysis/0.2.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
/**
* GLOBAL PARAMETERS FOR GENERIC COMPONENTS
* @type {number}
*/
var SA_JOB_TYPE = 'aCGHSurvivalAnalysis';
/**
* survival analysis acgh view instance
*/
var survivalAnalysisACGHView;
/**
* Buttons for Input Panel
* @type {Array}
*/
var _inputpanel_items = ['->',{ // '->' making it right aligned
xtype: 'button',
text: 'Run Analysis',
scale: 'medium',
iconCls: 'runbutton',
handler: function () {
survivalAnalysisACGHView.submitACGHSurvivalAnalysisJob();
}
}];
/**
* list of buttons for intermediate result grid
* @type {Array}
* @private
*/
var _resultgrid_items = [
'-',
{
xtype: 'button',
text: 'Download Result',
scale: 'medium',
iconCls: 'downloadbutton',
handler: function (b, e) {
// get job name
var jobName = survivalAnalysisACGHView.intermediateResultGrid.jobName;
return survivalAnalysisACGHView.intermediateResultGrid.downloadIntermediateResult(jobName);
}
},
{
xtype: 'button',
text: 'Show Survival Plot',
scale: 'medium',
iconCls: 'chartcurvebutton',
handler: function (b, e) {
// get selected regions
var selectedRows = survivalAnalysisACGHView.intermediateResultGrid.getSelectedRows();
if (selectedRows.length > 0) {
// invoke display survival plot
survivalAnalysisACGHView.intermediateResultGrid.displaySurvivalPlot(selectedRows);
} else {
// warn user if there's no row is selected
Ext.MessageBox.show({
title: 'No row is selected',
msg: 'To display the survival plot, you must select at least one region from the grid.',
buttons: Ext.MessageBox.OK,
icon: Ext.MessageBox.INFO
});
}
}
}];
/**
* list of result grid columns
* @type {Array}
* @private
*/
var _resultgrid_columns = [{
id: 'chromosome', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
header: "chromosome",
dataIndex: 'chromosome',
width: 400,
sortable: true
},{
header: "cytoband",
dataIndex: 'cytoband',
width: 100,
sortable: true
},{
header: "start",
dataIndex: 'start',
width: 100,
sortable: true
},{
header: "end",
dataIndex: 'end',
width: 100,
sortable: true
},{
header: "pvalue",
dataIndex: 'pvalue',
width: 100,
align: 'right',
sortable: true
},{
id: 'fdr',
header: "fdr",
dataIndex: 'fdr',
align: 'right',
width: 100,
sortable: true
}];
/**
* This object represents Input Bar in the Survival Analysis page
* @type {*|Object}
*/
var SurvivalAnalysisInputBar = Ext.extend(GenericAnalysisInputBar, {
regionPanel: null,
survivalPanel: null,
censoringPanel: null,
alterationPanel: null,
alterationRadioButtons: [
{boxLabel: 'GAIN vs NO GAIN', name: 'rb-alt', XValue:'1'},
{boxLabel: 'LOSS vs NO LOSS', name: 'rb-alt', XValue:'-1'},
{boxLabel: 'LOSS vs NORMAL vs GAIN', name: 'rb-alt', XValue:'0'}
],
constructor: function(config) {
SurvivalAnalysisInputBar.superclass.constructor.apply(this, arguments);
this.init();
},
init: function() {
// define child panel configs
var childPanelConfig = [{
title: 'Region',
id: 'sa-input-region',
isDroppable: true,
notifyFunc: dropOntoCategorySelection,
toolTipTitle: 'Tip: Region',
toolTipTxt: 'Drag and drop aCGH region here.'
},{
title: 'Survival Time',
id: 'sa-input-survival',
isDroppable: true,
notifyFunc: dropNumericOntoCategorySelection,
toolTipTitle: 'Tip: Survival Time',
toolTipTxt: 'Drag and drop phenodata with survival data.'
},{
title: 'Censoring Variable',
id: 'sa-input-censoring',
isDroppable: true,
notifyFunc: dropOntoCategorySelection,
toolTipTitle: 'Tip: Censoring Variable',
toolTipTxt: 'Drag and drop survival status (e.g alive or dead).'
},{
title: 'Alteration Type',
id: 'sa-input-alteration',
toolTipTitle: 'Tip: Alteration Type',
toolTipTxt: 'Select type of chromosomal alteration to test the association.'
}];
// create child panels
this.regionPanel = this.createChildPanel(childPanelConfig[0]);
this.survivalPanel = this.createChildPanel(childPanelConfig[1]);
this.censoringPanel = this.createChildPanel(childPanelConfig[2]);
this.alterationPanel = this.createChildPanel(childPanelConfig[3]);
// create check boxes
this.alterationPanel.add(this.createRadioBtnGroup(this.alterationRadioButtons, 'alteration-types-chk-group'));
// re-draw
this.doLayout();
}
});
/**
* This object represents the intermediate result grid
* @type {*|Object}
*/
var IntermediateResultGrid = Ext.extend(GenericAnalysisResultGrid, {
jobName : '',
constructor: function(config) {
IntermediateResultGrid.superclass.constructor.apply(this, arguments);
this.init();
},
init: function () {
},
/**
* Get selected rows from the grid
* @returns {*}
*/
getSelectedRows: function () {
return this.getSelectionModel().getSelections();
},
/**
* Display selected rows in tab panel
* @param selectedRegions
*/
displaySurvivalPlot: function (selectedRegions) {
var outer_scope = this;
// creating tab panel
if (this.plotCurvePanel == null) {
this.plotCurvePanel = new GenericTabPlotPanel({
id: 'plotResultCurve',
renderTo: 'plotResultWrapper'
});
}
// create tab as many as selected rows
for (var i = 0; i < selectedRegions.length ; i++) {
var imagePath = '';
var data = selectedRegions[i].data;
var _me = this;
// get image path
Ext.Ajax.request({
url: pageInfo.basePath+"/SurvivalAnalysisResult/imagePath",
method: 'POST',
success: function(result, request){
imagePath = result.responseText;
// compose tab_id form region name + cytoband + alteration type
var tab_id = 'survival_' + data.chromosome + '_' + data.start + '_' + data.end;
tab_id = tab_id.replace(/\s/g,''); // remove whitespaces
// Getting the template as blue print for survival curve plot.
// Template is defined in SurvivalAnalysisaCGH.gsp
var survivalPlotTpl = Ext.Template.from('template-survival-plot');
var translatedAlteration = survivalAnalysisACGHView.translateAlteration(
survivalAnalysisACGHView.jobInfo.jobInputsJson.aberrationType
);
var censoringVariable = survivalAnalysisACGHView.jobInfo.jobInputsJson.censoringVariable;
var censoringVariableHtml = censoringVariable ? censoringVariable.replace('|', '<br />') : '';
// create data instance
var region = {
jobName: survivalAnalysisACGHView.jobInfo.name,
startDate: survivalAnalysisACGHView.jobInfo.startDate,
runTime: survivalAnalysisACGHView.jobInfo.runTime,
inputRegion: survivalAnalysisACGHView.jobInfo.jobInputsJson.regionVariable,
inputSurvivalTime: survivalAnalysisACGHView.jobInfo.jobInputsJson.timeVariable,
inputCensoring: censoringVariableHtml,
inputCohort1: survivalAnalysisACGHView.jobInfo.jobInputsJson.result_instance_id1,
inputCohort2: survivalAnalysisACGHView.jobInfo.jobInputsJson.result_instance_id2,
inputAlteration: translatedAlteration,
chromosome: data.chromosome,
cytoband: data.cytoband,
start: data.start,
end: data.end,
pvalue: data.pvalue,
fdr: data.fdr,
filename: imagePath
};
//create tab title
var tab_title = 'Chr' + region.chromosome + ' (' + region.start + '-' + region.end + ')';
// add tab to the container
_me.plotCurvePanel.addTab(region, tab_id, survivalPlotTpl, tab_title);
},
failure: function(result, request){
Ext.Msg.alert('Status', 'Unable to get image');
},
timeout: '1800000',
params: {
jobName: this.jobName,
jobType: SA_JOB_TYPE,
chromosome: selectedRegions[i].data.chromosome,
start: selectedRegions[i].data.start,
end: selectedRegions[i].data.end,
alteration: selectedRegions[i].data.alteration
}
});
}
},
downloadIntermediateResult: function (jobName) {
// clean up
try {
Ext.destroy(Ext.get('downloadIframe'));
}
catch(e) {}
// get the file
Ext.DomHelper.append(document.body, {
tag: 'iframe',
id:'downloadIframe',
frameBorder: 0,
width: 0,
height: 0,
css: 'display:none;visibility:hidden;height:0px;',
src: pageInfo.basePath+"/survivalAnalysisResult/zipFile?jobName=" + jobName
});
}
});
/**
* This object represents the whole Survival Analysis Array CGH View
* @type {*|Object}
*/
var SurvivalAnalysisACGHView = Ext.extend(GenericAnalysisView, {
// input panel
inputBar : null,
// intermediate result panel
intermediateResultGrid : null,
// plot curve panel
plotCurvePanel : null,
// job info
jobInfo : null,
constructor: function () {
this.init();
},
redraw: function () {
this.inputBar.doLayout();
if (this.intermediateResultGrid) {
this.intermediateResultGrid.doLayout();
}
},
init: function() {
// first of all, let's reset all major components
this.resetAll();
// start drawing input panel
this.inputBar = new SurvivalAnalysisInputBar({
id: 'survivalAnalysisACGHInputBar',
title: 'Input Parameters',
iconCls: 'newbutton',
renderTo: 'analysisContainer',
bbar: this.createToolBar(_inputpanel_items)
});
},
resetAll: function () {
// destroy input bar
Ext.destroy(Ext.get('survivalAnalysisACGHInputBar'));
this.inputBar = null;
// and destroy the rest ..
this.resetResult();
},
resetResult: function () {
// destroy intermediate grid
Ext.destroy(Ext.get('intermediateGridPanel'));
this.intermediateResultGrid = null;
// destroy plot result curve
Ext.destroy(Ext.get('plotResultCurve'));
this.plotCurvePanel = null;
},
createToolBar: function(btnList) {
return new GenericAnalysisToolBar({
items: btnList
});
},
submitACGHSurvivalAnalysisJob: function() {
if (this.validateInputs()) {
console.log('LOG: submit survival analysis acgh job');
// get concept codes
var variablesConceptCode = '';
var regionVarConceptCode = this.inputBar.regionPanel.getConceptCode();
var survivalVarConceptCode = this.inputBar.survivalPanel.getConceptCode();
var censoringVarConceptCode = this.inputBar.censoringPanel.getConceptCodes();
// get alteration value
var alterationBtnGroup = this.inputBar.alterationPanel.getComponent('alteration-types-chk-group');
var alterationVal = alterationBtnGroup.getSelectedValue();
// create a string of all the concepts we need for the i2b2 data.
variablesConceptCode = regionVarConceptCode;
variablesConceptCode += survivalVarConceptCode != '' ? "|" + survivalVarConceptCode : "";
variablesConceptCode += censoringVarConceptCode != '' ? "|" + censoringVarConceptCode : "";
// compose params
var formParams = {
regionVariable : regionVarConceptCode,
timeVariable : survivalVarConceptCode,
censoringVariable : censoringVarConceptCode,
variablesConceptPaths: variablesConceptCode,
aberrationType:alterationVal,
confidenceIntervals:'',
jobType: SA_JOB_TYPE
};
// reset previous analysis result
this.resetResult();
// submit job
var job = this.submitJob(formParams, this.generateResultGrid, this);
}
},
validateInputs: function () {
var isValid = true;
var invalidInputs = [];
var regionVal;
var survivalAnalysisVal;
var censoringVal;
var alterationValues;
// check if region panel is empty
if (this.inputBar.regionPanel.isEmpty()) {
invalidInputs.push(this.inputBar.regionPanel.title);
isValid = false;
} else {
regionVal = this.inputBar.regionPanel.getInputEl();
}
// check if survival time panel is empty
if (this.inputBar.survivalPanel.isEmpty()) {
invalidInputs.push(this.inputBar.survivalPanel.title);
isValid = false;
} else {
survivalAnalysisVal = this.inputBar.survivalPanel.getInputEl();
}
// check censoring variable is empty (e.g status is dead or alive)
if (this.inputBar.censoringPanel.isEmpty()) {
invalidInputs.push(this.inputBar.censoringPanel.title);
isValid = false;
} else {
censoringVal = this.inputBar.censoringPanel.getInputEl();
}
//check if alteration values has been selected
var alterationChkGroup = this.inputBar.alterationPanel.getComponent('alteration-types-chk-group');
alterationValues = alterationChkGroup.getSelectedValue();
if (!alterationValues) {
isValid = false;
invalidInputs.push(this.inputBar.alterationPanel.title);
}
if (!isValid) {
var strErrMsg = 'Following needs to be defined: ';
invalidInputs.each(function (item) {
strErrMsg += '['+item + '] ';
})
// inform user on mandatory inputs need to be defined
Ext.MessageBox.show({
title: 'Missing mandatory inputs',
msg: strErrMsg,
buttons: Ext.MessageBox.OK,
icon: Ext.MessageBox.ERROR
});
}
return isValid;
},
/**
* generates intermediate result in grid panel
* @param data
*/
generateResultGrid: function (jobName, view) {
var _this = this;
Ext.Ajax.request ({
// retrieve information about the job (status, inputs, run-time, etc)
url: pageInfo.basePath+"/asyncJob/getjobbyname",
method: 'GET',
success: function (result, request) {
var resultJSON = JSON.parse(result.responseText);
_this.jobInfo = resultJSON.jobs[0];
// create store data
var store = new Ext.data.JsonStore({
root: 'result',
totalProperty: 'totalCount',
idProperty: 'threadid',
remoteSort: true, // can be enhanced with remote sort
baseParams: {jobName:jobName},
fields: [
'chromosome',
'cytoband',
{name: 'start', type: 'int'},
{name: 'end', type: 'int'},
{name: 'pvalue', type: 'float'},
{name: 'fdr', type: 'float'}
],
// load using script tags for cross domain, if the data in on the same domain as
// this page, an HttpProxy would be better
proxy: new Ext.data.HttpProxy({
url: "../SurvivalAnalysisResult/list"
})
});
store.setDefaultSort('chromosome', 'asc');
// create paging bar with related store
var pagingbar = new Ext.PagingToolbar({
pageSize: GEN_RESULT_GRID_LIMIT,
store: store,
displayInfo: true,
displayMsg: 'Displaying topics {0} - {1} of {2}',
emptyMsg: "No topics to display",
items: _resultgrid_items
});
// make sure no instance from previous job
Ext.destroy(Ext.get('intermediateGridPanel'));
// create new grid and render it
view.intermediateResultGrid = new IntermediateResultGrid({
id: 'intermediateGridPanel',
title: 'Intermediate Result - Job Name: ' + jobName ,
renderTo: 'intermediateResultWrapper',
trackMouseOver:false,
loadMask: true,
columns: _resultgrid_columns,
store: store,
bbar: pagingbar,
jobName: jobName
});
view.intermediateResultGrid.render();
// finally load the data
store.load({params:{start:0, limit:GEN_RESULT_GRID_LIMIT}});
},
failure: function (result, request) {
console.log('failure ....')
},
params: {
jobName: jobName
}
})
}
});
/**
*
* This function is called when user selects Survival Analysis aCGH from the Analysis combo box in the Dataset
* Explorer toolbar
*
*/
function loadACGHSurvivalAnalysisView() {
// everything starts here ..
survivalAnalysisACGHView = new SurvivalAnalysisACGHView();
}
| {
"content_hash": "d1308be907efb5dbdb3b71c1486a3f6b",
"timestamp": "",
"source": "github",
"line_count": 582,
"max_line_length": 118,
"avg_line_length": 32.43298969072165,
"alnum_prop": 0.5526594617503708,
"repo_name": "andrewtikhonov/rdc-rmodules-rcloud",
"id": "388aad440b29454f8b597cb471399abc3a70435b",
"size": "18876",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web-app/js/plugin/aCGHSurvivalAnalysis.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "18076"
},
{
"name": "Groovy",
"bytes": "396302"
},
{
"name": "HTML",
"bytes": "2192"
},
{
"name": "Java",
"bytes": "244416"
},
{
"name": "JavaScript",
"bytes": "309426"
},
{
"name": "R",
"bytes": "323012"
}
],
"symlink_target": ""
} |
Imports System
Imports System.Reflection
Imports System.Runtime.InteropServices
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
' Review the values of the assembly attributes
<Assembly: AssemblyTitle("RegistrationForm")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("RegistrationForm")>
<Assembly: AssemblyCopyright("Copyright © 2015")>
<Assembly: AssemblyTrademark("")>
<Assembly: ComVisible(False)>
'The following GUID is for the ID of the typelib if this project is exposed to COM
<Assembly: Guid("81f437c4-1c3d-46a0-8868-551e757072af")>
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Build and Revision Numbers
' by using the '*' as shown below:
' <Assembly: AssemblyVersion("1.0.*")>
<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly: AssemblyFileVersion("1.0.0.0")>
| {
"content_hash": "48cb35efaae7fb9536ef7f80f97a4512",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 83,
"avg_line_length": 33.705882352941174,
"alnum_prop": 0.7486910994764397,
"repo_name": "Emiliya93/TelerikAcademy",
"id": "e722ede70d97ea0baaca7f7f9ed573bfdf9bc0ef",
"size": "1149",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "HTML/Forms/RegistrationForm/My Project/AssemblyInfo.vb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "2183"
},
{
"name": "C",
"bytes": "991"
},
{
"name": "C#",
"bytes": "1313936"
},
{
"name": "CSS",
"bytes": "26060"
},
{
"name": "HTML",
"bytes": "163485"
},
{
"name": "JavaScript",
"bytes": "548828"
},
{
"name": "Python",
"bytes": "168390"
},
{
"name": "Smalltalk",
"bytes": "31868"
},
{
"name": "Visual Basic",
"bytes": "201175"
},
{
"name": "XSLT",
"bytes": "3112"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Microsoft.SharePoint.Client.NetCore.Runtime
{
public enum ClientAuthenticationMode
{
Default,
FormsAuthentication,
Anonymous
}
}
| {
"content_hash": "6063d690bbdc661487f48a1f40d6e28e",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 53,
"avg_line_length": 19.571428571428573,
"alnum_prop": 0.718978102189781,
"repo_name": "OneBitSoftware/NetCore.CSOM",
"id": "7b880f3f8ab86212ee2ad5620eae3b3a3c519711",
"size": "276",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Microsoft.SharePoint.Client.NetCore/Runtime/ClientAuthenticationMode.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1853437"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20220314200235 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE person DROP phone2, DROP phone2_label, DROP maiden_name');
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql('ALTER TABLE person ADD phone2 VARCHAR(30) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_unicode_ci`, ADD phone2_label VARCHAR(40) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_unicode_ci`, ADD maiden_name VARCHAR(40) CHARACTER SET utf8mb4 DEFAULT NULL COLLATE `utf8mb4_unicode_ci`');
}
}
| {
"content_hash": "43a2933878e3d6f8dc7f256f696c48f5",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 318,
"avg_line_length": 33.61290322580645,
"alnum_prop": 0.7149712092130518,
"repo_name": "naitsirch/ecgpb-memberlist",
"id": "1d4759bbb411fd9afb2c73c301e4d824734a664e",
"size": "1042",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "migrations/Version20220314200235.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "5129"
},
{
"name": "PHP",
"bytes": "193483"
},
{
"name": "SCSS",
"bytes": "367"
},
{
"name": "Shell",
"bytes": "2100"
},
{
"name": "Twig",
"bytes": "53021"
}
],
"symlink_target": ""
} |
using System;
using System.Drawing;
using ZXing;
using ZXing.CoreCompat.Rendering;
using ZXing.QrCode;
using ZXing.QrCode.Internal;
using ZXing.Rendering;
namespace UpnQR
{
public static class UpnQRBuilder
{
const string QR_ENCODING = "ISO-8859-2";
const int QR_VERSION = 15;
public static Bitmap GenerateUpnQR(UpnQRData qRData)
{
if (qRData == null)
throw new ArgumentException("QrData niz ni določen");
var barcodeWriter = new BarcodeWriter<Bitmap>();
//barcodeWriter.Renderer = new IBarcodeRenderer<Bitmap>()
barcodeWriter.Format = BarcodeFormat.QR_CODE;
barcodeWriter.Options = new QrCodeEncodingOptions()
{
DisableECI = false,
CharacterSet = QR_ENCODING,
QrVersion = QR_VERSION,
Height = 300,
Width = 300,
ErrorCorrection = ErrorCorrectionLevel.M
};
barcodeWriter.Renderer = new BitmapRenderer();
return barcodeWriter.Write(qRData.GetQrDataString());
}
}
}
| {
"content_hash": "b3b15225918f3b655df92a2d98648be9",
"timestamp": "",
"source": "github",
"line_count": 43,
"max_line_length": 69,
"avg_line_length": 26.627906976744185,
"alnum_prop": 0.5903930131004367,
"repo_name": "hozjanmarko/UpnQR",
"id": "2ba892210e0c8735b6951f879df731c74a8c5ea8",
"size": "1148",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "UpnQR/UpnQRBuilder.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "8419"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-us" xml:lang="en-us">
<!--
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.
-->
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<meta name="copyright" content="(C) Copyright 2005" />
<meta name="DC.rights.owner" content="(C) Copyright 2005" />
<meta content="public" name="security" />
<meta content="index,follow" name="Robots" />
<meta http-equiv="PICS-Label" content='(PICS-1.1 "http://www.icra.org/ratingsv02.html" l gen true r (cz 1 lz 1 nz 1 oz 1 vz 1) "http://www.rsac.org/ratingsv01.html" l gen true r (n 0 s 0 v 0 l 0) "http://www.classify.org/safesurf/" l gen true r (SS~~000 1))' />
<meta content="reference" name="DC.Type" />
<meta name="DC.Title" content="java.sql.CallableStatement interface" />
<meta name="abstract" content="Derby supports all methods of CallableStatement except setBlob, getBlob, setClob, and getClob." />
<meta name="description" content="Derby supports all methods of CallableStatement except setBlob, getBlob, setClob, and getClob." />
<meta content="java.sql.CallableStatement interface" name="DC.subject" />
<meta content="java.sql.CallableStatement interface" name="keywords" />
<meta scheme="URI" name="DC.Relation" content="crefjdbc12657.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc32052.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc34565.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc27734.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc15905.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc40794.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc29874.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc23502.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc38274.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc16643.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc30469.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbcrefsqlxml.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbcjavasqlsavepoint.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc20377.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc4_1summary.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc4_2summary.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc1020262.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjavcallstatout.html" />
<meta scheme="URI" name="DC.Relation" content="rrefjdbc75719.html" />
<meta content="XHTML" name="DC.Format" />
<meta content="rrefjdbc20485" name="DC.Identifier" />
<meta content="en-us" name="DC.Language" />
<link href="commonltr.css" type="text/css" rel="stylesheet" />
<title>java.sql.CallableStatement interface</title>
</head>
<body id="rrefjdbc20485"><a name="rrefjdbc20485"><!-- --></a>
<h1 class="topictitle1">java.sql.CallableStatement interface</h1>
<div><p><span>Derby</span> supports
all methods of <em>CallableStatement</em> except <em>setBlob</em>, <em>getBlob</em>,
<em>setClob</em>, and <em>getClob</em>.</p>
</div>
<div>
<ul class="ullinks">
<li class="ulchildlink"><strong><a href="rrefjavcallstatout.html">CallableStatements and OUT Parameters</a></strong><br />
Derby supports OUT parameters and CALL statements that return values, as in the following example.</li>
<li class="ulchildlink"><strong><a href="rrefjdbc75719.html">CallableStatements and INOUT parameters</a></strong><br />
INOUT parameters map to an array of the parameter type in the Java programming language. (The method must take an array as its parameter.) This conforms to the recommendations of the SQL standard.</li>
</ul>
<div class="familylinks">
<div class="parentlink"><strong>Parent topic:</strong> <a href="crefjdbc12657.html" title="This section provides reference information about Derby's implementation of the Java Database Connectivity (JDBC) API and documents the way it conforms to the JDBC APIs.">JDBC reference</a></div>
</div>
<div class="relref"><strong>Related reference</strong><br />
<div><a href="rrefjdbc32052.html" title="The class that loads Derby's local JDBC driver is the class org.apache.derby.jdbc.EmbeddedDriver. The class that loads Derby's network client driver is the class org.apache.derby.jdbc.ClientDriver.">java.sql.Driver interface</a></div>
<div><a href="rrefjdbc34565.html" title="A Java application that uses the JDBC API establishes a connection to a database by obtaining a Connection object. The standard way to obtain a Connection object is to call the method DriverManager.getConnection, which takes a String that contains a database connection URL.">java.sql.DriverManager.getConnection method</a></div>
<div><a href="rrefjdbc27734.html" title="A Derby Connection object is not garbage-collected until all other JDBC objects created from that connection are closed or are themselves garbage-collected.">java.sql.Connection interface</a></div>
<div><a href="rrefjdbc15905.html" title="Derby implements the java.sql.DatabaseMetaData interface.">java.sql.DatabaseMetaData interface</a></div>
<div><a href="rrefjdbc40794.html" title="Derby does not implement the setEscapeProcessing method of java.sql.Statement. In addition, the cancel method raises a "Feature not supported" exception.">java.sql.Statement interface</a></div>
<div><a href="rrefjdbc29874.html" title="Derby provides all the required JDBC type conversions and additionally allows use of the individual setXXX methods for each type as if a setObject(Value, JDBCTypeCode) invocation were made.">java.sql.PreparedStatement interface</a></div>
<div><a href="rrefjdbc23502.html" title="A positioned update or delete issued against a cursor being accessed through a ResultSet object modifies or deletes the current row of the ResultSet object.">java.sql.ResultSet interface</a></div>
<div><a href="rrefjdbc38274.html" title="Derby does not track the source or updatability of columns in ResultSets, and so always returns the constants shown for the methods listed in the following table.">java.sql.ResultSetMetaData interface</a></div>
<div><a href="rrefjdbc16643.html" title="Derby supplies values for the getMessage, getSQLState, and getErrorCode calls of SQLException.">java.sql.SQLException class</a></div>
<div><a href="rrefjdbc30469.html" title="Derby can generate a warning in certain circumstances. A warning is generated if, for example, you try to connect to a database with the create attribute set to true if the database already exists.">java.sql.SQLWarning class</a></div>
<div><a href="rrefjdbcrefsqlxml.html" title="The java.sql.SQLXML interface is the mapping for the SQL XML data type. However, Derby defines the XML data type and operators only in the SQL layer. There is no JDBC-side support for the XML data type and operators.">java.sql.SQLXML interface</a></div>
<div><a href="rrefjdbcjavasqlsavepoint.html" title="The Savepoint interface contains methods to set, release, or roll back a transaction to designated savepoints. Once a savepoint has been set, the transaction can be rolled back to that savepoint without affecting preceding work.">java.sql.Savepoint interface</a></div>
<div><a href="rrefjdbc20377.html" title="In Derby, the java.sql.Types are mapped to SQL data types.">Mapping of java.sql.Types to SQL types</a></div>
<div><a href="rrefjdbc4_1summary.html" title="JDBC 4.1 added some functionality to the core API. This section documents the JDBC 4.1 features supported by Derby.">Features supported on JDBC 4.1 and above</a></div>
<div><a href="rrefjdbc4_2summary.html" title="JDBC 4.2 adds some functionality to the core API. This section documents the JDBC 4.2 features supported by Derby.">JDBC 4.2-only features</a></div>
<div><a href="rrefjdbc1020262.html" title="JDBC provides a way of smoothing out some of the differences in the ways different DBMS vendors implement SQL. This is called escape syntax.">JDBC escape syntax</a></div>
</div>
</div>
</body>
</html>
| {
"content_hash": "c7a3166b85fcb25b039097535d32ffc6",
"timestamp": "",
"source": "github",
"line_count": 102,
"max_line_length": 370,
"avg_line_length": 87.32352941176471,
"alnum_prop": 0.7589536319748512,
"repo_name": "sadrayan/topic_web",
"id": "d2087c739bc8eb50b1e3b99966564ed6e664e78e",
"size": "8908",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "db/db-derby-10.13.1.1-bin/docs/html/ref/rrefjdbc20485.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "19783"
},
{
"name": "CSS",
"bytes": "115761"
},
{
"name": "HTML",
"bytes": "10366192"
},
{
"name": "Java",
"bytes": "205323"
},
{
"name": "JavaScript",
"bytes": "13265"
},
{
"name": "Shell",
"bytes": "44845"
}
],
"symlink_target": ""
} |
<?php
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads/v11/common/criteria.proto
namespace Google\Ads\GoogleAds\V11\Common;
use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;
/**
* A listing group criterion.
*
* Generated from protobuf message <code>google.ads.googleads.v11.common.ListingGroupInfo</code>
*/
class ListingGroupInfo extends \Google\Protobuf\Internal\Message
{
/**
* Type of the listing group.
*
* Generated from protobuf field <code>.google.ads.googleads.v11.enums.ListingGroupTypeEnum.ListingGroupType type = 1;</code>
*/
protected $type = 0;
/**
* Dimension value with which this listing group is refining its parent.
* Undefined for the root group.
*
* Generated from protobuf field <code>.google.ads.googleads.v11.common.ListingDimensionInfo case_value = 2;</code>
*/
protected $case_value = null;
/**
* Resource name of ad group criterion which is the parent listing group
* subdivision. Null for the root group.
*
* Generated from protobuf field <code>optional string parent_ad_group_criterion = 4;</code>
*/
protected $parent_ad_group_criterion = null;
/**
* Constructor.
*
* @param array $data {
* Optional. Data for populating the Message object.
*
* @type int $type
* Type of the listing group.
* @type \Google\Ads\GoogleAds\V11\Common\ListingDimensionInfo $case_value
* Dimension value with which this listing group is refining its parent.
* Undefined for the root group.
* @type string $parent_ad_group_criterion
* Resource name of ad group criterion which is the parent listing group
* subdivision. Null for the root group.
* }
*/
public function __construct($data = NULL) {
\GPBMetadata\Google\Ads\GoogleAds\V11\Common\Criteria::initOnce();
parent::__construct($data);
}
/**
* Type of the listing group.
*
* Generated from protobuf field <code>.google.ads.googleads.v11.enums.ListingGroupTypeEnum.ListingGroupType type = 1;</code>
* @return int
*/
public function getType()
{
return $this->type;
}
/**
* Type of the listing group.
*
* Generated from protobuf field <code>.google.ads.googleads.v11.enums.ListingGroupTypeEnum.ListingGroupType type = 1;</code>
* @param int $var
* @return $this
*/
public function setType($var)
{
GPBUtil::checkEnum($var, \Google\Ads\GoogleAds\V11\Enums\ListingGroupTypeEnum\ListingGroupType::class);
$this->type = $var;
return $this;
}
/**
* Dimension value with which this listing group is refining its parent.
* Undefined for the root group.
*
* Generated from protobuf field <code>.google.ads.googleads.v11.common.ListingDimensionInfo case_value = 2;</code>
* @return \Google\Ads\GoogleAds\V11\Common\ListingDimensionInfo|null
*/
public function getCaseValue()
{
return $this->case_value;
}
public function hasCaseValue()
{
return isset($this->case_value);
}
public function clearCaseValue()
{
unset($this->case_value);
}
/**
* Dimension value with which this listing group is refining its parent.
* Undefined for the root group.
*
* Generated from protobuf field <code>.google.ads.googleads.v11.common.ListingDimensionInfo case_value = 2;</code>
* @param \Google\Ads\GoogleAds\V11\Common\ListingDimensionInfo $var
* @return $this
*/
public function setCaseValue($var)
{
GPBUtil::checkMessage($var, \Google\Ads\GoogleAds\V11\Common\ListingDimensionInfo::class);
$this->case_value = $var;
return $this;
}
/**
* Resource name of ad group criterion which is the parent listing group
* subdivision. Null for the root group.
*
* Generated from protobuf field <code>optional string parent_ad_group_criterion = 4;</code>
* @return string
*/
public function getParentAdGroupCriterion()
{
return isset($this->parent_ad_group_criterion) ? $this->parent_ad_group_criterion : '';
}
public function hasParentAdGroupCriterion()
{
return isset($this->parent_ad_group_criterion);
}
public function clearParentAdGroupCriterion()
{
unset($this->parent_ad_group_criterion);
}
/**
* Resource name of ad group criterion which is the parent listing group
* subdivision. Null for the root group.
*
* Generated from protobuf field <code>optional string parent_ad_group_criterion = 4;</code>
* @param string $var
* @return $this
*/
public function setParentAdGroupCriterion($var)
{
GPBUtil::checkString($var, True);
$this->parent_ad_group_criterion = $var;
return $this;
}
}
| {
"content_hash": "30551db824a64e36c643b7a9c4a10bb1",
"timestamp": "",
"source": "github",
"line_count": 163,
"max_line_length": 129,
"avg_line_length": 31.085889570552148,
"alnum_prop": 0.6447602131438721,
"repo_name": "googleads/google-ads-php",
"id": "1b322c5f85da5588bc61f7ccaef1423c51ee2174",
"size": "5067",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/Google/Ads/GoogleAds/V11/Common/ListingGroupInfo.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "899"
},
{
"name": "PHP",
"bytes": "9952711"
},
{
"name": "Shell",
"bytes": "338"
}
],
"symlink_target": ""
} |
<?php
namespace KBackend\Libs;
/**
* KBackend
* PHP version 5
* @package Controller
* @license https://raw.github.com/Ashrey/KBackend/master/LICENSE.txt
* @author KumbiaPHP Development Team
*/
use \KumbiaAuth;
require_once CORE_PATH . 'kumbia/controller.php';
/*carga las configuraciones del backend*/
\KBackend\Libs\Config::read('backend');
class AuthController extends \Controller
{
/**
* variable que indica si las acciones del controller son protegidas
*
* Por defecto todas las acciones son protegidas
* para indicar que solo algunas acciones van a ser protegidas debe
* crearse un array con los nombres de dichas acciones, ejemplo:
*
* <code>
* protected $_protected_actions = array(
* 'ultimos_envios',
* 'editar',
* 'eliminar',
* 'activar',
* );
* </code>
*
* @var array
*/
protected $_protectedActions = array();
/**
* @var Object Objeto encargado de hacer el auth
*/
protected $_authACL = null;
/**
* Check if user have permission for the resource
*/
protected $_checkPermission = true;
/**
* Función que hace las veces de contructor de la clase.
*
*/
protected function initialize()
{
$class = Config::get('backend.security.auth');
$obj = new $class();
KumbiaAuth::inject(new Auth($obj));
$this->_authACL = AuthACL::getInstance();
if (empty($this->_protectedActions) || in_array($this->action_name , $this->_protectedActions)){
return $this->checkAuth();
}
}
/**
* Función que hace todos las validaciones necesarias para controladores
* y acciones protegidas.
*
* Verifica que el usuario esté logueado, si no es así le muestra el form de
* logueo.
*
* si está logueado verifica que tenga los permisos necesarios para acceder
* a la acción correspondiente.
*
* @return boolean devuelve TRUE si tiene acceso a la acción.
*
*/
protected function checkAuth(){
if (KumbiaAuth::isLogin()) {
return !$this->_checkPermission || $this->_isAllow();
} elseif (\Input::hasPost('login')) {
$this->_valid();
\Redirect::toAction(\Router::get('action'));
} else {
\View::select(null, 'logueo');
return FALSE;
}
}
/**
* Verifica si el usuario conectado tiene acceso a la acción actual
*
* @return boolean devuelve TRUE si tiene acceso a la acción.
*/
protected function _isAllow()
{
if (!$this->_authACL->check()) {
\Flash::error('No posees privilegios para acceder a ' . \Router::get('route'));
\View::select(null, 'forbidden');
return FALSE;
} else {
return TRUE;
}
}
/**
* Realiza la autenticacón con los datos enviados por formulario
*
* Si se realiza el logueo correctamente, se verifica que tenga permisos
* para entrar al recurso actual.
*
* @return boolean devuelve TRUE si se pudo loguear y tiene acceso a la acción.
*
*/
protected function _valid()
{
KumbiaAuth::login(\Input::post('login'));
if (KumbiaAuth::isLogin()) {
Event::fired('LoginSuccess');
return $this->_isAllow();
} else {
Event::fired('LoginFail');
\Flash::warning('Datos de acceso no válidos');
\View::select(null,'logueo');
return FALSE;
}
}
/**
* Acción para cerrar sesión en la app
*
* Cualquier controlador que herede de esta clase
* tiene acceso a esta acción.
*
*/
public function logout()
{
KumbiaAuth::logout();
return \Redirect::to('/');
}
/**
* Método que se ejecuta luego de ejecutada la acción y filtros
* del controlador.
*
*/
protected function finalize()
{
}
}
| {
"content_hash": "7cfcf81238e53dd8bb18ae437e137fb4",
"timestamp": "",
"source": "github",
"line_count": 150,
"max_line_length": 106,
"avg_line_length": 27.80666666666667,
"alnum_prop": 0.5538240230160633,
"repo_name": "Ashrey/KBackend",
"id": "84bf14ac8daa0423ed0a9bfb186fc7f519064907",
"size": "4188",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "backend/app/libs/AuthController.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "50652"
},
{
"name": "PHP",
"bytes": "88918"
},
{
"name": "Perl",
"bytes": "15"
},
{
"name": "SQL",
"bytes": "3031"
}
],
"symlink_target": ""
} |
<?php
if(!defined('BASEPATH')){
exit('No direct script access allowed');
}
class _ajax extends MX_Controller{
public function __construct(){
parent::__construct();
$this->lang->load('message');
}
function login(){
$data_array = array();
$data_array['msg'] = '0';
$data_array['msg_data'] = 'An error occurred!';
$this->form_validation->set_rules('login_email', '<strong>Email</strong>', 'clean|required|valid_email|max_length[255]');
$this->form_validation->set_rules('login_password', '<strong>Password</strong>', 'clean|required|max_length[255]');
if($this->form_validation->run() == FALSE){
$this->form_validation->set_error_delimiters('• ', '<br>');
$data_array['msg_data'] = validation_errors();
$data_array['error_array'] = $this->form_validation->error_array();
$data_array['field_data'] = $this->form_validation->field_data();
}
else{
$login_email = $this->input->post('login_email');
$login_password = $this->input->post('login_password');
$query = $this->db
->from('users')
->where('user_email', (string) $login_email)
->where('user_password', (string) md5('salty' . $login_password))
->limit(1)
->get();
if($query->num_rows() > 0){
$row = $query->row_array();
$this->session->set_userdata('user_id', $row['user_id']);
$this->session->set_userdata('user_firstname', $row['user_firstname']);
$this->session->set_userdata('user_admin', $row['user_admin']);
$data_array['name'] = $row['user_firstname'];
$data_array['msg'] = '1';
$data_array['msg_data'] = '<strong>Login successful!</strong>';
$data_array['msg_extra'] = $row['user_language'];
}
else{
$data_array['msg'] = '0';
$data_array['msg_data'] = 'Invalid login details!';
}
}
$data['msg'] = json_encode($data_array);
$this->load->view('_ajax/_blank', $data);
}
function save_profile(){
$data_array = array();
$data_array['msg'] = '0';
$data_array['msg_data'] = 'An error occurred!';
if($this->session->userdata('user_id') != ''){
$is_admin = is_admin($this);
$this->form_validation->set_rules('user_firstname', '<strong>Firstname</strong>', 'clean|required|max_length[255]');
$this->form_validation->set_rules('user_lastname', '<strong>Lastname</strong>', 'clean|required|max_length[255]');
if($is_admin){
$this->form_validation->set_rules('user_email', '<strong>Email</strong>', 'clean|required|valid_email|max_length[255]');
$this->form_validation->set_rules('user_password', '<strong>Password</strong>', 'clean|max_length[255]');
$required = ($this->input->post('user_password') != '' ? 'required|' : '');
$this->form_validation->set_rules('confirm_password', '<strong>Confirm Password</strong>', 'clean|' . $required . 'matches[user_password]|max_length[255]');
}
if($this->form_validation->run() == FALSE){
$this->form_validation->set_error_delimiters('• ', '<br>');
$data_array['msg_data'] = validation_errors();
$data_array['error_array'] = $this->form_validation->error_array();
$data_array['field_data'] = $this->form_validation->field_data();
}
else{
$data_array['field_data'] = $this->form_validation->field_data();
$this->db->set('user_firstname', $this->input->post('user_firstname'));
$this->db->set('user_lastname', $this->input->post('user_lastname'));
if($is_admin){
$user_password = $this->input->post('user_password');
$this->db->set('user_email', $this->input->post('user_email'));
if($user_password){
$this->db->set('user_password', md5('salty' . $user_password));
}
}
$this->db->set('user_modified', date('Y-m-d H:i:s'));
$this->db->where('user_id', (string) $this->session->userdata('user_id'));
$this->db->update('users');
$data_array['affected_rows'] = $this->db->affected_rows();
/* DB END */
$data_array['msg'] = '1';
$data_array['msg_data'] = '<strong>Saved successfully!</strong>';
}
}
$data['msg'] = json_encode($data_array);
$this->load->view('_ajax/_blank', $data);
}
function add_user(){
$data_array = array();
$data_array['msg'] = '0';
$data_array['msg_data'] = 'An error occurred!';
if($this->session->userdata('user_id') != ''){
$userinfo = $this->master->get_userinfo();
if($userinfo['user']['user_admin'] == '1'){
$user_email = $this->input->post('user_email');
$email_exists = $this->master->check_duplicate($user_email) > 0;
$this->form_validation->set_rules('user_firstname', '<strong>First Name</strong>', 'clean|required|max_length[255]');
$this->form_validation->set_rules('user_lastname', '<strong>Last Name</strong>', 'clean|required|max_length[255]');
$this->form_validation->set_rules('user_email', '<strong>Email</strong>', 'clean|required|valid_email|max_length[255]');
$this->form_validation->set_rules('user_password', '<strong>Password</strong>', 'clean|required|max_length[255]');
$validate = $this->form_validation->run();
if(! $validate && $email_exists){
$this->form_validation->set_error_delimiters('• ', '<br>');
$data_array['msg_data'] = '<strong>User exists with email ' . $user_email . '!</strong><br />' . validation_errors();
$data_array['error_array'] = $this->form_validation->error_array();
$data_array['field_data'] = $this->form_validation->field_data();
}
elseif(! $validate){
$this->form_validation->set_error_delimiters('• ', '<br>');
$data_array['msg_data'] = validation_errors();
$data_array['error_array'] = $this->form_validation->error_array();
$data_array['field_data'] = $this->form_validation->field_data();
}
elseif($email_exists){
$data_array['msg_data'] = '<strong>User exists with email ' . $user_email . '!</strong>';
$data_array['error_array'] = array();
$data_array['field_data'] = $this->form_validation->field_data();
}
else{
$user_firstname = $this->input->post('user_firstname');
$user_lastname = $this->input->post('user_lastname');
$user_email = $this->input->post('user_email');
$user_password = $this->input->post('user_password');
/* DB START */
$this->db->set('user_firstname', $user_firstname);
$this->db->set('user_lastname', $user_lastname);
$this->db->set('user_email', $user_email);
$this->db->set('user_password', md5('salty' . $user_password));
$this->db->set('user_created', date('Y-m-d H:i:s'));
$this->db->set('user_modified', date('Y-m-d H:i:s'));
$this->db->insert('users');
$data_array['insert_id'] = $this->db->insert_id();
/* DB END */
$data_array['msg'] = '1';
$data_array['msg_data'] = '<strong>Saved successfully!</strong>';
$this->session->set_flashdata('msg', $data_array['msg']);
$this->session->set_flashdata('msg_data', $data_array['msg_data']);
}
}
}
$data['msg'] = json_encode($data_array);
$this->load->view('_ajax/_blank', $data);
}
function save_user_details(){
$data_array = array();
$data_array['msg'] = '0';
$data_array['msg_data'] = 'An error occurred!';
if($this->session->userdata('user_id') != ''){
$userinfo = $this->master->get_userinfo();
if($userinfo['account']['account_admin'] == '1'){
$this->form_validation->set_rules('user_id', '<strong>User ID</strong>', 'clean|required');
$this->form_validation->set_rules('user_firstname', '<strong>First Name</strong>', 'clean|required|max_length[255]');
$this->form_validation->set_rules('user_lastname', '<strong>Last Name</strong>', 'clean|required|max_length[255]');
$this->form_validation->set_rules('user_email', '<strong>Email</strong>', 'clean|required|valid_email|max_length[255]');
if($this->form_validation->run() == FALSE){
$this->form_validation->set_error_delimiters('• ', '<br>');
$data_array['msg_data'] = validation_errors();
$data_array['error_array'] = $this->form_validation->error_array();
$data_array['field_data'] = $this->form_validation->field_data();
}
else{
$data_array['field_data'] = $this->form_validation->field_data();
$user_id = $this->input->post('user_id');
$user_firstname = $this->input->post('user_firstname');
$user_lastname = $this->input->post('user_lastname');
$user_email = $this->input->post('user_email');
$user_password = $this->input->post('user_password');
/* DB START */
$this->db->set('user_firstname', $user_firstname);
$this->db->set('user_lastname', $user_lastname);
$this->db->set('user_email', $user_email);
if($user_password != ''){
$this->db->set('user_password', md5('salty' . $user_password));
}
$this->db->where('user_id', (string) $user_id);
$this->db->update('users');
$data_array['affected_rows'] = $this->db->affected_rows();
/* DB END */
$data_array['msg'] = '1';
$data_array['msg_data'] = '<strong>Saved successfully!</strong>';
}
}
}
$data['msg'] = json_encode($data_array);
$this->load->view('_ajax/_blank', $data);
}
}
/* End of file _ajax.php */
/* Location: ./application/controllers/_ajax.php */ | {
"content_hash": "79d3625367fdece8053149fda6a7dc80",
"timestamp": "",
"source": "github",
"line_count": 203,
"max_line_length": 164,
"avg_line_length": 48.389162561576356,
"alnum_prop": 0.5645933014354066,
"repo_name": "shaheeda622/civzapp",
"id": "22fcbf4f5dc964e1798163dbd381b22f5fdb53ae",
"size": "10587",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "application/controllers/_ajax.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "750"
},
{
"name": "CSS",
"bytes": "1097667"
},
{
"name": "HTML",
"bytes": "15084"
},
{
"name": "JavaScript",
"bytes": "1464302"
},
{
"name": "PHP",
"bytes": "1853504"
}
],
"symlink_target": ""
} |
use std::io;
pub type BayerResult<T> = Result<T, BayerError>;
quick_error! {
#[derive(Debug)]
pub enum BayerError {
// Generic failure. Please try to make something more meaningful.
NoGood {
description("No good")
}
WrongResolution {
description("Wrong resolution")
}
WrongDepth {
description("Wrong depth")
}
Io(err: io::Error) {
from()
description(err.description())
display("IO error: {}", err)
cause(err)
}
}
}
| {
"content_hash": "39e15820a8e16845a8fc4cc09f857d9a",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 70,
"avg_line_length": 17.724137931034484,
"alnum_prop": 0.5739299610894941,
"repo_name": "wangds/libbayer",
"id": "5a75bfdeb012f5ce069671574b25353f90d5d586",
"size": "538",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/errcode.rs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1745"
},
{
"name": "Rust",
"bytes": "67426"
}
],
"symlink_target": ""
} |
'use strict';
let expect = require('chai').expect;
let Huejay = require('../lib/Huejay');
describe('Huejay', () => {
describe('version property', () => {
it('should be a string', () => {
expect(Huejay).to.have.property('version');
expect(Huejay.version).to.be.a('string');
});
});
describe('discover property', () => {
it('should be a function', () => {
expect(Huejay).to.have.property('discover');
expect(Huejay.discover).to.be.a('function');
});
});
describe('Client property', () => {
it('should be a function', () => {
expect(Huejay).to.have.property('Client');
expect(Huejay.Client).to.be.a('function');
});
});
describe('Error property', () => {
it('should be a function', () => {
expect(Huejay).to.have.property('Error');
expect(Huejay.Error).to.be.a('function');
});
});
});
| {
"content_hash": "66908b73670af9dbfd8b378986bd5134",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 50,
"avg_line_length": 26,
"alnum_prop": 0.5565610859728507,
"repo_name": "sqmk/huejay",
"id": "6ff85685b709b2e73ba9b0924df3fc96d845948b",
"size": "884",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/Huejay.spec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "221275"
}
],
"symlink_target": ""
} |
/**
* text: value: $(element).text(value)
* html: value: $(element).html(value)
* replaceWith: value: $(element).replaceWith(value)
* attr: {name:value}: $(element).attr(name, value)
* data: {name:value}: $(element).data(name, value)
* val: value: $(element).val(value)
* addClass: value: $(element).addClass(value);
* removeClass: value: $(element).removeClass(value);
* remove: : $(element).remove();
* modal: value: $(element).modal(value);
* popover: value: $(element).popover(value);
* append: value: $(element).append($(value));
* id: value - parameter of appendOnce
* appendOnce: value, id - append dialog
* appendModal: - append modal dialog
* reload: : location.reload();
* redirect: Редирект на страницу
* multiple: [{bindName: bindParams}]
* jquery: value: $(element)[value]()
*/
// region render binding
var bindings = {
/**
* Заглушка для передачи доп параметра в биндинг
* @param element
* @param value
* @param allBind
*/
id: function (element, value, allBind) {
},
/**
* Заглушка для передачи доп параметра в биндинг
* @param element
* @param value
* @param allBind
*/
options: function (element, value, allBind) {
},
/**
* text() из jquery
* @param element
* @param value
* @param allBind
*/
text: function (element, value, allBind) {
$(element).text(value);
},
hide: function (element, value, allBind) {
$(element).hide();
},
show: function (element, value, allBind) {
$(element).show();
},
html: function (element, value, allBind) {
$(element).html(value);
},
replaceWith: function (element, value, allBind) {
$(element).replaceWith(value);
},
attr: function (element, value, allBind) {
for (var name in value) {
$(element).attr(name, value[name]);
}
},
data: function (element, value, allBind) {
for (var name in value) {
$(element).data(name, value[name]);
}
},
val: function (element, value, allBind) {
$(element).val(value);
},
trigger: function (element, value, allBind) {
$(element).trigger(value);
},
addClass: function (element, value, allBind) {
$(element).addClass(value);
},
removeClass: function (element, value, allBind) {
$(element).removeClass(value);
},
remove: function (element, value, allBind) {
$(element).remove();
},
modal: function (element, value, allBind) {
$(element).modal(value);
},
popover: function (element, value, allBind) {
$(element).popover(value);
},
append: function (element, value, allBind) {
$(element).append($(value));
},
/**
* Добавляет html в элемент 1 раз.
* Доп параметры
* options.id = id контэйнера для проверки уникальности
* options.template = шаблон контэйнера, по умолчанию span
*
* @param element
* @param value
* @param allBind
*/
appendOnce: function (element, value, allBind) {
var o = {
id: allBind.id,
template: '<span></span>'
};
if (allBind.options) {
o = $.extend(o, allBind.options);
}
var container = $(element).find('[data-render-id=' + o.id + ']');
if (container.length == 0) {
container = $(o.template).attr('data-render-id', o.id).appendTo($(element));
}
container.html(value);
},
appendModal: function (element, value, allBind) {
var ids = [];
var id = null;
$(value).each(function () {
if ($(this).hasClass('modal')) {
if (id == null) {
id = $(this).attr('id');
}
ids.push($(this).attr('id'));
}
return true;
});
$('#' + ids.join(',#')).modal('hide').remove();
$(value).appendTo(element);
$('#' + id).modal('show');
$.each(ids, function (i, e) {
ko.applyBindings(viewModel, document.getElementById(e));
});
},
reload: function () {
location.reload();
},
redirect: function (element, value) {
location.href = value;
},
multiple: function (element, value, allBind) {
var bind = bindings[value.name];
$.each(value.values, function (i, e) {
bind(element, e, allBind);
});
},
jquery: function (element, value, allBind) {
if (typeof(value) == "object") {
$.each(value, function (i, e) {
if (typeof(e) == "object") {
console.log(e);
console.log(allBind);
// #todo
} else {
$(element)[i](e);
}
});
} else {
$(element)[value]();
}
}
};
$.bindings = bindings;
$.executeRenderBind = function (element, name, value, allBind) {
var bind = bindings[name];
try {
bind(element, value, allBind);
} catch (err) {
console.log(err);
console.log("Error binding " + name + ' ' + err.name);
}
}
$.executeRender = function (data) {
for (var i in data) {
//noinspection JSUnfilteredForInLoop
var value = data[i];
$(i).each(function (i, e) {
if (typeof(value) == 'object') {
for (var name in value) {
$.executeRenderBind(e, name, value[name], value);
}
} else {
$.executeRenderBind(e, value, null, {value: null});
}
});
}
}
// endregion render binding | {
"content_hash": "af5285d4317875f7907956ccea17c55d",
"timestamp": "",
"source": "github",
"line_count": 196,
"max_line_length": 88,
"avg_line_length": 29.301020408163264,
"alnum_prop": 0.5192408149051019,
"repo_name": "brother79/brother-common-bundle",
"id": "f8ec07322625a49b26dc464c45a846cfe28f38da",
"size": "5933",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Resources/public/js/binding.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3151"
},
{
"name": "JavaScript",
"bytes": "38379"
},
{
"name": "PHP",
"bytes": "226321"
},
{
"name": "Twig",
"bytes": "39116"
}
],
"symlink_target": ""
} |
package com.android.rs.test_compat;
import android.content.Context;
import android.content.res.Resources;
import android.support.v8.renderscript.*;
public class UT_clamp_relaxed extends UnitTest {
private Resources mRes;
protected UT_clamp_relaxed(RSTestCore rstc, Resources res, Context ctx) {
super(rstc, "Clamp (Relaxed)", ctx);
mRes = res;
}
public void run() {
RenderScript pRS = RenderScript.create(mCtx);
ScriptC_clamp_relaxed s =
new ScriptC_clamp_relaxed(pRS);
pRS.setMessageHandler(mRsMessage);
s.invoke_clamp_test();
pRS.finish();
waitForMessage();
pRS.destroy();
}
}
| {
"content_hash": "264044a92d2d9a5a346f9a00b699e88c",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 77,
"avg_line_length": 25.666666666666668,
"alnum_prop": 0.6435786435786436,
"repo_name": "blois/AndroidSDKCloneMin",
"id": "d880e68c58ab5e78aa06430d3c621ef106731187",
"size": "1312",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "sdk/sources/android-20/com/android/rs/test_compat/UT_clamp_relaxed.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "AppleScript",
"bytes": "0"
},
{
"name": "Assembly",
"bytes": "39964"
},
{
"name": "Awk",
"bytes": "50821"
},
{
"name": "C",
"bytes": "65602656"
},
{
"name": "C++",
"bytes": "32706569"
},
{
"name": "CSS",
"bytes": "301711"
},
{
"name": "Component Pascal",
"bytes": "110"
},
{
"name": "Emacs Lisp",
"bytes": "4737"
},
{
"name": "Groovy",
"bytes": "82931"
},
{
"name": "IDL",
"bytes": "11244"
},
{
"name": "Java",
"bytes": "102765797"
},
{
"name": "JavaScript",
"bytes": "27699"
},
{
"name": "Objective-C",
"bytes": "138688"
},
{
"name": "Perl",
"bytes": "20900909"
},
{
"name": "Prolog",
"bytes": "2842768"
},
{
"name": "Python",
"bytes": "17241370"
},
{
"name": "Rust",
"bytes": "9919"
},
{
"name": "Shell",
"bytes": "806338"
},
{
"name": "Visual Basic",
"bytes": "481"
},
{
"name": "XC",
"bytes": "200153"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "387d247eef2af59c86ac3204f78e1a06",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "feb1cef504cbc3bff37a21f3734726c89c93f234",
"size": "177",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Baccharis rodriguezii/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<?php
/* TwigBundle:Exception:error.xml.twig */
class __TwigTemplate_f423e4db66e9f64dfd833a9db036bd63e246468e1082dcb8d7bc91ce54ad26ed extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 1
echo "<?xml version=\"1.0\" encoding=\"";
echo twig_escape_filter($this->env, $this->env->getCharset(), "html", null, true);
echo "\" ?>
<error code=\"";
// line 3
echo twig_escape_filter($this->env, (isset($context["status_code"]) ? $context["status_code"] : null), "html", null, true);
echo "\" message=\"";
echo twig_escape_filter($this->env, (isset($context["status_text"]) ? $context["status_text"] : null), "html", null, true);
echo "\" />
";
}
public function getTemplateName()
{
return "TwigBundle:Exception:error.xml.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 25 => 3, 19 => 1,);
}
}
/* <?xml version="1.0" encoding="{{ _charset }}" ?>*/
/* */
/* <error code="{{ status_code }}" message="{{ status_text }}" />*/
/* */
| {
"content_hash": "2096d96bdde537d621103dffc791b7fc",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 131,
"avg_line_length": 27.16,
"alnum_prop": 0.56480117820324,
"repo_name": "malioret/ConnectedSoccerApi",
"id": "afd453cb1331bbfc06044acabf44c89757d9ee33",
"size": "1358",
"binary": false,
"copies": "1",
"ref": "refs/heads/origin2",
"path": "app/cache/prod/twig/12/12441521e4620fa2016cdf39c4a11d9535e61cd730266c3b96a8776be12ace06.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3606"
},
{
"name": "CSS",
"bytes": "142021"
},
{
"name": "HTML",
"bytes": "3898126"
},
{
"name": "JavaScript",
"bytes": "67098"
},
{
"name": "PHP",
"bytes": "272341"
}
],
"symlink_target": ""
} |
var cachedUnblock;
var originalSub = MeteorX.Session.prototype.protocol_handlers.sub;
MeteorX.Session.prototype.protocol_handlers.sub = function(msg, unblock) {
var self = this;
// cacheUnblock temporarly, so we can capture it later
// we will use unblock in current eventLoop, so this is safe
cachedUnblock = unblock;
originalSub.call(self, msg, unblock);
// cleaning cached unblock
cachedUnblock = null;
};
// We simply replace current implementation with a simple modification
// to add add the unblock
MeteorX.Session.prototype._startSubscription = function (handler, subId, params, name) {
var self = this;
var sub = new MeteorX.Subscription(self, handler, subId, params, name);
var unblockHander = cachedUnblock;
// _startSubscription may call from a lot places
// so cachedUnblock might be null in somecases
if(!unblockHander) {
unblockHander = function() {}
}
// assign the cachedUnblock
sub.unblock = unblockHander ;
if(subId) {
self._namedSubs[subId] = sub;
} else {
self._universalSubs.push(sub);
}
sub._runHandler();
};
// sometimes _runHandler will be called directly and
// we won't have the session context and cachedUnblock
// so, those situations, set a dummy function for unblock
// this happens often when logging in and out
var originalRunHandler = MeteorX.Subscription.prototype._runHandler;
MeteorX.Subscription.prototype._runHandler = function() {
if(!this.unblock) {
this.unblock = function() {};
}
originalRunHandler.call(this);
} | {
"content_hash": "64c4b1d6b2b81a840d2a695b120ac620",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 88,
"avg_line_length": 31.75,
"alnum_prop": 0.7296587926509186,
"repo_name": "meteorhacks/unblock",
"id": "f5cfc27a2862022c7f24b4b2e2cf03be9db9aae8",
"size": "1524",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/unblock.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "5100"
}
],
"symlink_target": ""
} |
actions :unpack
default_action :unpack
provides :msys_archive
attribute :source, kind_of: String, name_attribute: true
attribute :root_dir, kind_of: String, required: true
attribute :mingw, kind_of: [TrueClass, FalseClass], default: false
attribute :checksum, kind_of: String
| {
"content_hash": "540b658084755e8b01a2d7cf7e6f3798",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 66,
"avg_line_length": 34.625,
"alnum_prop": 0.776173285198556,
"repo_name": "enriko-iskandar/chef",
"id": "38c49ce270b58390c5a06067ff23afc7e1fa2b2a",
"size": "277",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "cookbooks/build-essential/resources/msys_archive.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "187369"
},
{
"name": "Perl",
"bytes": "82975"
},
{
"name": "Python",
"bytes": "1654898"
},
{
"name": "Ruby",
"bytes": "769796"
},
{
"name": "Shell",
"bytes": "8647"
}
],
"symlink_target": ""
} |
package uk.ac.ebi.spot.goci.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
/**
* Javadocs go here!
*
* @author Tony Burdett
* @date 03/02/15
*/
@Entity
public class GenomicContext {
@Id
@GeneratedValue
private Long id;
private Boolean isIntergenic;
private Boolean isUpstream;
private Boolean isDownstream;
private Long distance;
@ManyToOne
private SingleNucleotidePolymorphism snp;
@ManyToOne
private Gene gene;
@ManyToOne
private Location location;
private String source;
private String mappingMethod;
private Boolean isClosestGene;
// JPA no-args constructor
public GenomicContext() {
}
public GenomicContext(Long id){
this.id = id;
}
public GenomicContext(Boolean isIntergenic,
Boolean isUpstream,
Boolean isDownstream,
Long distance,
SingleNucleotidePolymorphism snp,
Gene gene,
Location location,
String source,
String mappingMethod, Boolean isClosestGene) {
this.isIntergenic = isIntergenic;
this.isUpstream = isUpstream;
this.isDownstream = isDownstream;
this.distance = distance;
this.snp = snp;
this.gene = gene;
this.location = location;
this.source = source;
this.mappingMethod = mappingMethod;
this.isClosestGene = isClosestGene;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Boolean getIsIntergenic() {
return isIntergenic;
}
public void setIsIntergenic(Boolean isIntergenic) {
this.isIntergenic = isIntergenic;
}
public Boolean getIsUpstream() {
return isUpstream;
}
public void setIsUpstream(Boolean isUpstream) {
this.isUpstream = isUpstream;
}
public Boolean getIsDownstream() {
return isDownstream;
}
public void setIsDownstream(Boolean isDownstream) {
this.isDownstream = isDownstream;
}
public Long getDistance() {
return distance;
}
public void setDistance(Long distance) {
this.distance = distance;
}
public SingleNucleotidePolymorphism getSnp() {
return snp;
}
public void setSnp(SingleNucleotidePolymorphism snp) {
this.snp = snp;
}
public Gene getGene() {
return gene;
}
public void setGene(Gene gene) {
this.gene = gene;
}
public String getMappingMethod() {
return mappingMethod;
}
public void setMappingMethod(String mappingMethod) {
this.mappingMethod = mappingMethod;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public Boolean getIsClosestGene() {
return isClosestGene;
}
public void setIsClosestGene(Boolean isClosestGene) {
this.isClosestGene = isClosestGene;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
}
| {
"content_hash": "17d7e86bf4fdad339c704d01daf14b06",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 72,
"avg_line_length": 21.446540880503143,
"alnum_prop": 0.6087976539589443,
"repo_name": "EBISPOT/goci",
"id": "b01fa8a15e25135557cc3443ff3538003ea1d456",
"size": "3410",
"binary": false,
"copies": "1",
"ref": "refs/heads/2.x-stable",
"path": "goci-core/goci-model/src/main/java/uk/ac/ebi/spot/goci/model/GenomicContext.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "57485"
},
{
"name": "Dockerfile",
"bytes": "1896"
},
{
"name": "HTML",
"bytes": "710010"
},
{
"name": "Java",
"bytes": "4474446"
},
{
"name": "JavaScript",
"bytes": "95941"
},
{
"name": "PLSQL",
"bytes": "114387"
},
{
"name": "Perl",
"bytes": "4356"
},
{
"name": "Python",
"bytes": "67067"
},
{
"name": "Shell",
"bytes": "10134"
}
],
"symlink_target": ""
} |
"""
.. module:: Downsample test
:platform: Unix
:synopsis: unittest test classes for plugins
.. moduleauthor:: Mark Basham <mark.basham@diamond.ac.uk>
"""
import unittest
from savu.test.plugin_test import PluginTest
class DownsampleTest(PluginTest):
def setUp(self):
self.plugin_name = "savu.plugins.downsample_filter"
if __name__ == "__main__":
unittest.main()
| {
"content_hash": "c10f516f5ace9fac2b93cc379d5a1a3d",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 59,
"avg_line_length": 18.666666666666668,
"alnum_prop": 0.6836734693877551,
"repo_name": "swtp1v07/Savu",
"id": "ec31e66eee3bf4fb1d9c778d2a4ed9b15d6d6d4b",
"size": "982",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "savu/test/downsample_plugin_test.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "84400"
},
{
"name": "C++",
"bytes": "509"
},
{
"name": "Makefile",
"bytes": "2126"
},
{
"name": "Python",
"bytes": "349231"
},
{
"name": "Shell",
"bytes": "6321"
}
],
"symlink_target": ""
} |
#import <XCTest/XCTest.h>
#import <Cronet/Cronet.h>
#import <RemoteTest/Messages.pbobjc.h>
#import <RemoteTest/Test.pbobjc.h>
#import <RemoteTest/Test.pbrpc.h>
#import <RxLibrary/GRXBufferedPipe.h>
#define NSStringize_helper(x) #x
#define NSStringize(x) @NSStringize_helper(x)
static NSString *const kRemoteSSLHost = NSStringize(HOST_PORT_REMOTE);
static NSString *const kLocalSSLHost = NSStringize(HOST_PORT_LOCALSSL);
static NSString *const kLocalCleartextHost = NSStringize(HOST_PORT_LOCAL);
static const NSTimeInterval TEST_TIMEOUT = 8000;
@interface RMTStreamingOutputCallRequest (Constructors)
+ (instancetype)messageWithPayloadSize:(NSNumber *)payloadSize
requestedResponseSize:(NSNumber *)responseSize;
@end
@implementation RMTStreamingOutputCallRequest (Constructors)
+ (instancetype)messageWithPayloadSize:(NSNumber *)payloadSize
requestedResponseSize:(NSNumber *)responseSize {
RMTStreamingOutputCallRequest *request = [self message];
RMTResponseParameters *parameters = [RMTResponseParameters message];
parameters.size = responseSize.intValue;
[request.responseParametersArray addObject:parameters];
request.payload.body = [NSMutableData dataWithLength:payloadSize.unsignedIntegerValue];
return request;
}
@end
@interface RMTStreamingOutputCallResponse (Constructors)
+ (instancetype)messageWithPayloadSize:(NSNumber *)payloadSize;
@end
@implementation RMTStreamingOutputCallResponse (Constructors)
+ (instancetype)messageWithPayloadSize:(NSNumber *)payloadSize {
RMTStreamingOutputCallResponse *response = [self message];
response.payload.type = RMTPayloadType_Compressable;
response.payload.body = [NSMutableData dataWithLength:payloadSize.unsignedIntegerValue];
return response;
}
@end
@interface InteropTestsMultipleChannels : XCTestCase
@end
dispatch_once_t initCronet;
@implementation InteropTestsMultipleChannels {
RMTTestService *_remoteService;
RMTTestService *_remoteCronetService;
RMTTestService *_localCleartextService;
RMTTestService *_localSSLService;
}
- (void)setUp {
[super setUp];
self.continueAfterFailure = NO;
// Default stack with remote host
_remoteService = [RMTTestService serviceWithHost:kRemoteSSLHost];
// Cronet stack with remote host
_remoteCronetService = [RMTTestService serviceWithHost:kRemoteSSLHost];
dispatch_once(&initCronet, ^{
[Cronet setHttp2Enabled:YES];
[Cronet start];
});
GRPCCallOptions *options = [[GRPCCallOptions alloc] init];
options.transportType = GRPCTransportTypeCronet;
options.cronetEngine = [Cronet getGlobalEngine];
_remoteCronetService.options = options;
// Local stack with no SSL
_localCleartextService = [RMTTestService serviceWithHost:kLocalCleartextHost];
options = [[GRPCCallOptions alloc] init];
options.transportType = GRPCTransportTypeInsecure;
_localCleartextService.options = options;
// Local stack with SSL
_localSSLService = [RMTTestService serviceWithHost:kLocalSSLHost];
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSString *certsPath =
[bundle pathForResource:@"TestCertificates.bundle/test-certificates" ofType:@"pem"];
NSError *error = nil;
NSString *certs =
[NSString stringWithContentsOfFile:certsPath encoding:NSUTF8StringEncoding error:&error];
XCTAssertNil(error);
options = [[GRPCCallOptions alloc] init];
options.transportType = GRPCTransportTypeChttp2BoringSSL;
options.PEMRootCertificates = certs;
options.hostNameOverride = @"foo.test.google.fr";
_localSSLService.options = options;
}
- (void)testEmptyUnaryRPC {
__weak XCTestExpectation *expectRemote = [self expectationWithDescription:@"Remote RPC finish"];
__weak XCTestExpectation *expectCronetRemote =
[self expectationWithDescription:@"Remote RPC finish"];
__weak XCTestExpectation *expectCleartext =
[self expectationWithDescription:@"Remote RPC finish"];
__weak XCTestExpectation *expectSSL = [self expectationWithDescription:@"Remote RPC finish"];
GPBEmpty *request = [GPBEmpty message];
void (^handler)(GPBEmpty *response, NSError *error) = ^(GPBEmpty *response, NSError *error) {
XCTAssertNil(error, @"Finished with unexpected error: %@", error);
id expectedResponse = [GPBEmpty message];
XCTAssertEqualObjects(response, expectedResponse);
};
[_remoteService emptyCallWithRequest:request
handler:^(GPBEmpty *response, NSError *error) {
handler(response, error);
[expectRemote fulfill];
}];
[_remoteCronetService emptyCallWithRequest:request
handler:^(GPBEmpty *response, NSError *error) {
handler(response, error);
[expectCronetRemote fulfill];
}];
[_localCleartextService emptyCallWithRequest:request
handler:^(GPBEmpty *response, NSError *error) {
handler(response, error);
[expectCleartext fulfill];
}];
[_localSSLService emptyCallWithRequest:request
handler:^(GPBEmpty *response, NSError *error) {
handler(response, error);
[expectSSL fulfill];
}];
[self waitForExpectationsWithTimeout:TEST_TIMEOUT handler:nil];
}
- (void)testFullDuplexRPC {
__weak XCTestExpectation *expectRemote = [self expectationWithDescription:@"Remote RPC finish"];
__weak XCTestExpectation *expectCronetRemote =
[self expectationWithDescription:@"Remote RPC finish"];
__weak XCTestExpectation *expectCleartext =
[self expectationWithDescription:@"Remote RPC finish"];
__weak XCTestExpectation *expectSSL = [self expectationWithDescription:@"Remote RPC finish"];
NSArray *requestSizes = @[ @100, @101, @102, @103 ];
NSArray *responseSizes = @[ @104, @105, @106, @107 ];
XCTAssertEqual([requestSizes count], [responseSizes count]);
NSUInteger kRounds = [requestSizes count];
NSMutableArray *requests = [NSMutableArray arrayWithCapacity:kRounds];
NSMutableArray *responses = [NSMutableArray arrayWithCapacity:kRounds];
for (int i = 0; i < kRounds; i++) {
requests[i] = [RMTStreamingOutputCallRequest messageWithPayloadSize:requestSizes[i]
requestedResponseSize:responseSizes[i]];
responses[i] = [RMTStreamingOutputCallResponse messageWithPayloadSize:responseSizes[i]];
}
__block NSMutableArray *steps = [NSMutableArray arrayWithCapacity:4];
__block NSMutableArray *requestsBuffers = [NSMutableArray arrayWithCapacity:4];
for (int i = 0; i < 4; i++) {
steps[i] = [NSNumber numberWithUnsignedInteger:0];
requestsBuffers[i] = [[GRXBufferedPipe alloc] init];
[requestsBuffers[i] writeValue:requests[0]];
}
BOOL (^handler)(int, BOOL, RMTStreamingOutputCallResponse *, NSError *) =
^(int index, BOOL done, RMTStreamingOutputCallResponse *response, NSError *error) {
XCTAssertNil(error, @"Finished with unexpected error: %@", error);
XCTAssertTrue(done || response, @"Event handler called without an event.");
if (response) {
NSUInteger step = [steps[index] unsignedIntegerValue];
XCTAssertLessThan(step, kRounds, @"More than %lu responses received.",
(unsigned long)kRounds);
XCTAssertEqualObjects(response, responses[step]);
step++;
steps[index] = [NSNumber numberWithUnsignedInteger:step];
GRXBufferedPipe *pipe = requestsBuffers[index];
if (step < kRounds) {
[pipe writeValue:requests[step]];
} else {
[pipe writesFinishedWithError:nil];
}
}
if (done) {
NSUInteger step = [steps[index] unsignedIntegerValue];
XCTAssertEqual(step, kRounds, @"Received %lu responses instead of %lu.", step, kRounds);
return YES;
}
return NO;
};
[_remoteService
fullDuplexCallWithRequestsWriter:requestsBuffers[0]
eventHandler:^(BOOL done,
RMTStreamingOutputCallResponse *_Nullable response,
NSError *_Nullable error) {
if (handler(0, done, response, error)) {
[expectRemote fulfill];
}
}];
[_remoteCronetService
fullDuplexCallWithRequestsWriter:requestsBuffers[1]
eventHandler:^(BOOL done,
RMTStreamingOutputCallResponse *_Nullable response,
NSError *_Nullable error) {
if (handler(1, done, response, error)) {
[expectCronetRemote fulfill];
}
}];
[_localCleartextService
fullDuplexCallWithRequestsWriter:requestsBuffers[2]
eventHandler:^(BOOL done,
RMTStreamingOutputCallResponse *_Nullable response,
NSError *_Nullable error) {
if (handler(2, done, response, error)) {
[expectCleartext fulfill];
}
}];
[_localSSLService
fullDuplexCallWithRequestsWriter:requestsBuffers[3]
eventHandler:^(BOOL done,
RMTStreamingOutputCallResponse *_Nullable response,
NSError *_Nullable error) {
if (handler(3, done, response, error)) {
[expectSSL fulfill];
}
}];
[self waitForExpectationsWithTimeout:TEST_TIMEOUT handler:nil];
}
@end
| {
"content_hash": "e5c8b80be1d0ade57e3bf5084f11ea72",
"timestamp": "",
"source": "github",
"line_count": 243,
"max_line_length": 98,
"avg_line_length": 42.04938271604938,
"alnum_prop": 0.6351536504208259,
"repo_name": "carl-mastrangelo/grpc",
"id": "b0d4e4883a39d2b14f7c4b510f7e97a8a81146bd",
"size": "10820",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/objective-c/tests/InteropTestsMultipleChannels/InteropTestsMultipleChannels.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "32274"
},
{
"name": "C",
"bytes": "1677470"
},
{
"name": "C#",
"bytes": "1905512"
},
{
"name": "C++",
"bytes": "30667850"
},
{
"name": "CMake",
"bytes": "624762"
},
{
"name": "CSS",
"bytes": "1519"
},
{
"name": "DTrace",
"bytes": "147"
},
{
"name": "Dockerfile",
"bytes": "153845"
},
{
"name": "Go",
"bytes": "34791"
},
{
"name": "HTML",
"bytes": "14"
},
{
"name": "Java",
"bytes": "6907"
},
{
"name": "JavaScript",
"bytes": "53044"
},
{
"name": "M4",
"bytes": "46911"
},
{
"name": "Makefile",
"bytes": "1151674"
},
{
"name": "Objective-C",
"bytes": "441626"
},
{
"name": "Objective-C++",
"bytes": "37623"
},
{
"name": "PHP",
"bytes": "471571"
},
{
"name": "Python",
"bytes": "2754606"
},
{
"name": "Ruby",
"bytes": "993806"
},
{
"name": "Shell",
"bytes": "429791"
},
{
"name": "Swift",
"bytes": "3516"
},
{
"name": "XSLT",
"bytes": "9673"
}
],
"symlink_target": ""
} |
layout: page
title: Mann - Best Wedding
date: 2016-05-24
author: Tiffany Flowers
tags: weekly links, java
status: published
summary: Nullam viverra hendrerit mollis. Ut odio nisi.
banner: images/banner/leisure-03.jpg
booking:
startDate: 08/20/2016
endDate: 08/22/2016
ctyhocn: CLEMEHX
groupCode: MBW
published: true
---
Integer volutpat tortor a urna faucibus pellentesque. Donec rutrum varius faucibus. Nulla facilisi. Donec ornare, leo ac sodales sollicitudin, quam eros varius justo, vel volutpat neque mauris ut ipsum. Integer non augue vitae metus condimentum aliquam. Morbi bibendum a velit ut euismod. Nunc sodales, ex et tincidunt dapibus, ante enim tempus mi, nec elementum ante libero in est.
* Sed ut nisl sed elit rutrum vehicula eget vitae quam
* Morbi condimentum orci in maximus tristique
* Aliquam molestie augue a ipsum dapibus tincidunt
* Duis convallis purus nec massa sagittis, nec semper augue maximus
* Fusce blandit turpis ac laoreet sodales.
Pellentesque a fringilla mi. In euismod quam ac nunc luctus, eleifend maximus eros dignissim. Ut tincidunt augue nunc, quis vestibulum nunc porttitor vel. Ut tincidunt consequat blandit. Phasellus tincidunt justo eget enim viverra vehicula. Vivamus congue lectus eget urna laoreet tempus. Nullam elementum sagittis tortor, et dapibus ipsum lacinia eget. Curabitur sed dapibus neque. Curabitur faucibus mi aliquam semper lobortis. Suspendisse potenti.
Nulla facilisi. Praesent placerat laoreet suscipit. Pellentesque fermentum luctus velit id dignissim. In risus tellus, vulputate a efficitur eu, venenatis non neque. Integer consequat risus vitae auctor feugiat. Vivamus nec lorem vel nisl placerat aliquam. Nulla dapibus non nunc at molestie. Etiam ut lacus iaculis, facilisis magna vel, volutpat ipsum.
| {
"content_hash": "ae2c8e3998490e7bffa3ccfd1e132504",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 450,
"avg_line_length": 71.24,
"alnum_prop": 0.8090960134755755,
"repo_name": "KlishGroup/prose-pogs",
"id": "63848e5d5ae25dcdf5151d4d9b3ed51a45143762",
"size": "1785",
"binary": false,
"copies": "1",
"ref": "refs/heads/gh-pages",
"path": "pogs/C/CLEMEHX/MBW/index.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
/**
*/
package org.eclipse.xtext.example.domainmodel.domainmodel;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.xtype.XImportSection;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Domain Model</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.eclipse.xtext.example.domainmodel.domainmodel.DomainModel#getImportSection <em>Import Section</em>}</li>
* <li>{@link org.eclipse.xtext.example.domainmodel.domainmodel.DomainModel#getElements <em>Elements</em>}</li>
* </ul>
* </p>
*
* @see org.eclipse.xtext.example.domainmodel.domainmodel.DomainmodelPackage#getDomainModel()
* @model
* @generated
*/
public interface DomainModel extends EObject
{
/**
* Returns the value of the '<em><b>Import Section</b></em>' containment reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Import Section</em>' containment reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Import Section</em>' containment reference.
* @see #setImportSection(XImportSection)
* @see org.eclipse.xtext.example.domainmodel.domainmodel.DomainmodelPackage#getDomainModel_ImportSection()
* @model containment="true"
* @generated
*/
XImportSection getImportSection();
/**
* Sets the value of the '{@link org.eclipse.xtext.example.domainmodel.domainmodel.DomainModel#getImportSection <em>Import Section</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Import Section</em>' containment reference.
* @see #getImportSection()
* @generated
*/
void setImportSection(XImportSection value);
/**
* Returns the value of the '<em><b>Elements</b></em>' containment reference list.
* The list contents are of type {@link org.eclipse.xtext.example.domainmodel.domainmodel.AbstractElement}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Elements</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Elements</em>' containment reference list.
* @see org.eclipse.xtext.example.domainmodel.domainmodel.DomainmodelPackage#getDomainModel_Elements()
* @model containment="true"
* @generated
*/
EList<AbstractElement> getElements();
} // DomainModel
| {
"content_hash": "5c7e97ef94d802dfde31a443198ca411",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 162,
"avg_line_length": 35.80555555555556,
"alnum_prop": 0.6873545384018619,
"repo_name": "adrian-herscu/experiments",
"id": "0624e3ca727674ed022573a856e06480884bdb6b",
"size": "2578",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "language-workbenches/xtext/org.eclipse.xtext.example.domainmodel/src-gen/org/eclipse/xtext/example/domainmodel/domainmodel/DomainModel.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "15855"
},
{
"name": "GAP",
"bytes": "1004389"
},
{
"name": "Java",
"bytes": "9518470"
},
{
"name": "JavaScript",
"bytes": "18171"
},
{
"name": "Xtend",
"bytes": "46322"
}
],
"symlink_target": ""
} |
#import <objc/runtime.h>
#import "SBJSON.h"
#import "KrollObject.h"
#import "KrollMethod.h"
#import "KrollCallback.h"
#import "KrollMethodDelegate.h"
#import "KrollPropertyDelegate.h"
#import "KrollContext.h"
#import "KrollBridge.h"
#ifdef KROLL_COVERAGE
# import "KrollCoverage.h"
#endif
#import "TiApp.h"
TiClassRef KrollObjectClassRef = NULL;
TiClassRef JSObjectClassRef = NULL;
/*
* Since TiStringRefs are not tied to any particular context, and are
* immutable, they are threadsafe and more importantly, ones that are in
* constant use never need to garbage collected, but can be reused.
*/
TiStringRef kTiStringGetTime;
TiStringRef kTiStringLength;
TiStringRef kTiStringNewObject;
TiStringRef kTiStringTiPropertyKey;
TiStringRef kTiStringPropertyKey;
TiStringRef kTiStringEventKey;
id TiValueToId(KrollContext* context, TiValueRef v);
//
// function to determine if the object passed is a JS Date
//
BOOL IsDateLike(TiContextRef jsContext, TiObjectRef object, TiValueRef *v)
{
BOOL result = NO;
if (TiObjectHasProperty(jsContext, object, kTiStringGetTime))
{
TiValueRef fn = TiObjectGetProperty(jsContext, object, kTiStringGetTime, NULL);
TiObjectRef fnObj = TiValueToObject(jsContext, fn, NULL);
if (TiObjectIsFunction(jsContext, fnObj))
{
*v = TiObjectCallAsFunction(jsContext,fnObj,object,0,NULL,NULL);
result = YES;
}
}
return result;
}
//
// function for converting a TiValueRef into a NSDictionary*
//
NSDictionary* TiValueToDict(KrollContext *context, TiValueRef value)
{
TiContextRef jsContext = [context context];
TiObjectRef obj = TiValueToObject(jsContext, value, NULL);
TiPropertyNameArrayRef props = TiObjectCopyPropertyNames(jsContext,obj);
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
size_t count = TiPropertyNameArrayGetCount(props);
for (size_t i = 0; i < count; i++)
{
TiStringRef jsString = TiPropertyNameArrayGetNameAtIndex(props, i);
TiValueRef v = TiObjectGetProperty(jsContext, obj, jsString, NULL);
NSString* jsonkey = [NSString stringWithCharacters:TiStringGetCharactersPtr(jsString) length:TiStringGetLength(jsString)];
id jsonvalue = TiValueToId(context,v);
if (jsonvalue && jsonkey) {
[dict setObject:jsonvalue forKey:jsonkey];
}
}
TiPropertyNameArrayRelease(props);
return [dict autorelease];
}
//
// function for converting a TiValueRef into a JSON string as NSString*
//
NSString* TiValueToJSON(KrollContext *context, TiValueRef value)
{
return [SBJSON stringify:TiValueToId(context,value)];
}
//
// function for converting a TiValueRef into an NSObject* (as ID)
//
id TiValueToId(KrollContext *context, TiValueRef v)
{
id result = nil;
if (v) {
TiContextRef jsContext = [context context];
TiType tt = TiValueGetType(jsContext, v);
switch (tt) {
case kTITypeUndefined:{
result = nil;
break;
}
case kTITypeNull: {
result = [NSNull null];
break;
}
case kTITypeBoolean: {
result = [NSNumber numberWithBool:TiValueToBoolean(jsContext, v)];
break;
}
case kTITypeNumber: {
result = [NSNumber numberWithDouble:TiValueToNumber(jsContext, v, NULL)];
break;
}
case kTITypeString: {
TiStringRef stringRefValue = TiValueToStringCopy(jsContext, v, NULL);
result = [(NSString *)TiStringCopyCFString
(kCFAllocatorDefault,stringRefValue) autorelease];
TiStringRelease(stringRefValue);
break;
}
case kTITypeObject: {
TiObjectRef obj = TiValueToObject(jsContext, v, NULL);
id privateObject = (id)TiObjectGetPrivate(obj);
if ([privateObject isKindOfClass:[KrollObject class]]) {
result = [privateObject target];
break;
}
if (TiValueIsArray(jsContext,obj)) {
TiValueRef length = TiObjectGetProperty(jsContext, obj, kTiStringLength, NULL);
double len = TiValueToNumber(jsContext, length, NULL);
NSMutableArray* resultArray = [[NSMutableArray alloc] initWithCapacity:len];
for (size_t c=0; c<len; ++c)
{
TiValueRef valueRef = TiObjectGetPropertyAtIndex(jsContext, obj, c, NULL);
id value = TiValueToId(context,valueRef);
//TODO: This is a temprorary workaround for the time being. We have to properly take care of [undefined] objects.
if(value == nil){
[resultArray addObject:[NSNull null]];
}
else{
[resultArray addObject:value];
}
}
result = [resultArray autorelease];
break;
}
if (TiValueIsDate(jsContext, obj)) {
TiValueRef fn = TiObjectGetProperty(jsContext, obj, kTiStringGetTime, NULL);
TiObjectRef fnObj = TiValueToObject(jsContext, fn, NULL);
TiValueRef resultDate = TiObjectCallAsFunction(jsContext,fnObj,obj,0,NULL,NULL);
double value = TiValueToNumber(jsContext, resultDate, NULL);
result = [NSDate dateWithTimeIntervalSince1970:value/1000]; // ms for JS, sec for Obj-C
break;
}
if (TiObjectIsFunction(jsContext,obj)) {
result = [[[KrollCallback alloc] initWithCallback:obj thisObject:TiContextGetGlobalObject(jsContext) context:context] autorelease];
} else {
result = TiValueToDict(context,v);
}
break;
}
default: {
break;
}
}
}
return result;
}
//
// function for converting a TiValue to an NSObject* (as ID)
//
TiValueRef ConvertIdTiValue(KrollContext *context, id obj)
{
TiContextRef jsContext = [context context];
if ([obj isKindOfClass:[NSNull class]])
{
return TiValueMakeNull(jsContext);
}
else if (obj == nil)
{
return TiValueMakeUndefined(jsContext);
}
else if ([obj isKindOfClass:[NSURL class]])
{
NSString* urlString = [obj absoluteString];
TiStringRef jsString = TiStringCreateWithCFString((CFStringRef) urlString);
TiValueRef result = TiValueMakeString(jsContext,jsString);
TiStringRelease(jsString);
return result;
}
else if ([obj isKindOfClass:[NSString class]])
{
TiStringRef jsString = TiStringCreateWithCFString((CFStringRef) obj);
TiValueRef result = TiValueMakeString(jsContext,jsString);
TiStringRelease(jsString);
return result;
}
else if ([obj isKindOfClass:[NSNumber class]])
{
const char *ch = [obj objCType];
if ('c' == ch[0])
{
return TiValueMakeBoolean(jsContext, [obj boolValue]);
}
else
{
return TiValueMakeNumber(jsContext, [obj doubleValue]);
}
}
else if ([obj isKindOfClass:[NSArray class]])
{
size_t count = [obj count];
TiValueRef args[count];
for (size_t c=0;c<count;c++)
{
args[c]=ConvertIdTiValue(context,[obj objectAtIndex:c]);
}
return TiObjectMakeArray(jsContext, count, args, NULL);
}
else if ([obj isKindOfClass:[NSDictionary class]])
{
//Why not just make a blank object?
TiValueRef value = TiEvalScript(jsContext, kTiStringNewObject, NULL, NULL, 0, NULL);
TiObjectRef objRef = TiValueToObject(jsContext, value, NULL);
for (id prop in obj)
{
TiStringRef key = TiStringCreateWithCFString((CFStringRef) prop);
TiValueRef value = ConvertIdTiValue(context,[obj objectForKey:prop]);
TiObjectSetProperty(jsContext, objRef, key, value, 0, NULL);
TiStringRelease(key);
}
return objRef;
}
else if ([obj isKindOfClass:[NSException class]])
{
TiStringRef jsString = TiStringCreateWithCFString((CFStringRef) [obj reason]);
TiValueRef result = TiValueMakeString(jsContext,jsString);
TiStringRelease(jsString);
return TiObjectMakeError(jsContext, 1, &result, NULL);
}
else if ([obj isKindOfClass:[KrollMethod class]])
{
KrollContext * ourContext = [(KrollMethod *)obj context];
if (context == ourContext)
{
return [(KrollMethod *)obj jsobject];
}
return TiObjectMake(jsContext,KrollMethodClassRef,obj);
}
else if ([obj isKindOfClass:[KrollWrapper class]])
{
if ([KrollBridge krollBridgeExists:[(KrollWrapper *)obj bridge]])
{
return [(KrollWrapper *)obj jsobject];
}
//Otherwise, this flows to null.
}
else if ([obj isKindOfClass:[KrollObject class]])
{
KrollContext * ourContext = [(KrollObject *)obj context];
TiObjectRef ourJsObject = [(KrollObject *)obj jsobject];
if ((context == ourContext) && (ourJsObject != NULL))
{
return ourJsObject;
}
return TiObjectMake(jsContext,KrollObjectClassRef,obj);
}
else if ([obj isKindOfClass:[KrollCallback class]])
{
return [(KrollCallback*)obj function];
}
else if ([obj isKindOfClass:[NSDate class]])
{
NSDate *date = (NSDate*)obj;
double number = [date timeIntervalSince1970]*1000; // JS is ms
TiValueRef args [1];
args[0] = TiValueMakeNumber(jsContext,number);
return TiObjectMakeDate(jsContext,1,args,NULL);
}
else
{
KrollBridge * ourBridge = (KrollBridge *)[context delegate];
if (ourBridge != nil)
{
if (![ourBridge usesProxy:obj])
{
if (![context isKJSThread])
{
NSLog(@"[WARN] Creating %@ in a different context than the calling function.",obj);
ourBridge = [KrollBridge krollBridgeForThreadName:[[NSThread currentThread] name]];
}
return [[ourBridge registerProxy:obj] jsobject];
}
KrollObject * objKrollObject = [ourBridge krollObjectForProxy:obj];
return [objKrollObject jsobject];
}
NSLog(@"[WARN] Generating a new TiObject for KrollObject %@ because the contexts %@ and its context %@ differed.",obj,context,ourBridge);
#ifdef KROLL_COVERAGE
KrollObject *o = [[[KrollCoverageObject alloc] initWithTarget:obj context:context] autorelease];
#else
KrollObject *o = [[[KrollObject alloc] initWithTarget:obj context:context] autorelease];
#endif
return TiObjectMake(jsContext,KrollObjectClassRef,o);
}
return TiValueMakeNull(jsContext);
}
//
// callback for handling finalization (in JS land)
//
void KrollFinalizer(TiObjectRef ref)
{
waitForMemoryPanicCleared();
id o = (KrollObject*)TiObjectGetPrivate(ref);
if ((o==nil) || [o isKindOfClass:[KrollContext class]])
{
return;
}
if (![o isKindOfClass:[KrollObject class]])
{
NSLog(@"[WARN] object: %@ was not of the right class: %@",o,[o class]);
return;
}
#if KOBJECT_MEMORY_DEBUG == 1
NSLog(@"KROLL FINALIZER: %@, retain:%d",o,[o retainCount]);
#endif
[(KrollObject *)o setFinalized:YES];
if ([o isMemberOfClass:[KrollObject class]])
{
KrollBridge * ourBridge = [(KrollObject *)o bridge];
if ([KrollBridge krollBridgeExists:ourBridge])
{
TiProxy * ourTarget = [o target];
if ((ourTarget != nil) && ([ourBridge krollObjectForProxy:ourTarget] == o))
{
[ourBridge unregisterProxy:ourTarget];
}
}
}
[o release];
o = nil;
}
bool KrollDeleteProperty(TiContextRef ctx, TiObjectRef object, TiStringRef propertyName, TiValueRef* exception)
{
waitForMemoryPanicCleared();
KrollObject* o = (KrollObject*) TiObjectGetPrivate(object);
if ([o isKindOfClass:[KrollObject class]])
{
NSString* name = (NSString*)TiStringCopyCFString(kCFAllocatorDefault, propertyName);
[o deleteKey:name];
[o forgetObjectForTiString:propertyName context:ctx];
[name release];
}
return true;
}
//
// callback for handling creation (in JS land)
//
void KrollInitializer(TiContextRef ctx, TiObjectRef object)
{
waitForMemoryPanicCleared();
KrollObject * o = (KrollObject*)TiObjectGetPrivate(object);
if ([o isKindOfClass:[KrollContext class]])
{
return;
}
#if KOBJECT_MEMORY_DEBUG == 1
NSLog(@"KROLL RETAINER: %@ (%@), retain:%d",o,[o class],[o retainCount]);
#endif
if ([o isKindOfClass:[KrollObject class]])
{
[o retain];
TiObjectRef propsObject = TiObjectMake(ctx, NULL, NULL);
TiObjectSetProperty(ctx, object, kTiStringTiPropertyKey, propsObject, kTiPropertyAttributeDontEnum, NULL);
[o setPropsObject:propsObject];
}
else {
NSLog(@"[DEBUG] initializer for %@",[o class]);
}
}
//
// callback for handling retrieving an objects property (in JS land)
//
//TODO: We should fetch from the props object and shortcut some of this. Especially now that callbacks are CURRENTLY write-only.
TiValueRef KrollGetProperty(TiContextRef jsContext, TiObjectRef object, TiStringRef prop, TiValueRef* exception)
{
waitForMemoryPanicCleared();
KrollObject* o = (KrollObject*) TiObjectGetPrivate(object);
@try
{
if(TiStringIsEqual(prop,kTiStringTiPropertyKey))
{
return NULL;
}
NSString* name = (NSString*)TiStringCopyCFString(kCFAllocatorDefault, prop);
[name autorelease];
id result = [o valueForKey:name];
TiObjectRef cachedObject = [o objectForTiString:prop context:jsContext];
if ([result isKindOfClass:[KrollWrapper class]])
{
if (![KrollBridge krollBridgeExists:[(KrollWrapper *)result bridge]])
{
//This remote object no longer exists.
[o deleteKey:name];
result = nil;
}
else
{
TiObjectRef remoteFunction = [(KrollWrapper *)result jsobject];
if ((cachedObject != NULL) && (cachedObject != remoteFunction))
{
[o forgetObjectForTiString:prop context:jsContext]; //Clean up the old property.
}
if (remoteFunction != NULL)
{
[o noteObject:remoteFunction forTiString:prop context:jsContext];
}
return remoteFunction;
}
}
TiValueRef jsResult = ConvertIdTiValue([o context],result);
if ([result isKindOfClass:[KrollObject class]] &&
![result isKindOfClass:[KrollCallback class]] && [[result target] isKindOfClass:[TiProxy class]])
{
[o noteObject:(TiObjectRef)jsResult forTiString:prop context:jsContext];
}
else
{
[o forgetObjectForTiString:prop context:jsContext];
}
#if KOBJECT_DEBUG == 1
NSLog(@"KROLL GET PROPERTY: %@=%@",name,result);
#endif
return jsResult;
}
@catch (NSException * ex)
{
*exception = [KrollObject toValue:[o context] value:ex];
}
return TiValueMakeUndefined(jsContext);
}
//
// callback for handling a setter (in JS land)
//
bool KrollSetProperty(TiContextRef jsContext, TiObjectRef object, TiStringRef prop, TiValueRef value, TiValueRef* exception)
{
waitForMemoryPanicCleared();
KrollObject* o = (KrollObject*) TiObjectGetPrivate(object);
@try
{
if(TiStringIsEqual(prop,kTiStringTiPropertyKey))
{
return false;
}
NSString* name = (NSString*)TiStringCopyCFString(kCFAllocatorDefault, prop);
[name autorelease];
id v = TiValueToId([o context], value);
#if KOBJECT_DEBUG == 1
NSLog(@"KROLL SET PROPERTY: %@=%@ against %@",name,v,o);
#endif
if ([v isKindOfClass:[TiProxy class]])
{
[o noteObject:(TiObjectRef)value forTiString:prop context:jsContext];
}
else
{
[o forgetObjectForTiString:prop context:jsContext];
}
[o setValue:v forKey:name];
return true;
}
@catch (NSException * ex)
{
*exception = [KrollObject toValue:[o context] value:ex];
}
return false;
}
// forward declare these
//@interface SplitViewSampleWithCommonJSObject : NSObject
//@end
@interface SplitViewSampleWithCommonJSObject (Private)
-(NSDictionary*)modules;
@end
//@interface TiProxy : NSObject
//@end
//
// handle property names which makes the object iterable
//
void KrollPropertyNames(TiContextRef ctx, TiObjectRef object, TiPropertyNameAccumulatorRef propertyNames)
{
KrollObject* o = (KrollObject*) TiObjectGetPrivate(object);
if (o)
{
id target = [o target];
if ([o isKindOfClass:[SplitViewSampleWithCommonJSObject class]])
{
for (NSString *key in [[(SplitViewSampleWithCommonJSObject*)o modules] allKeys])
{
TiStringRef value = TiStringCreateWithUTF8CString([key UTF8String]);
TiPropertyNameAccumulatorAddName(propertyNames,value);
TiStringRelease(value);
}
}
else if ([target isKindOfClass:[TiProxy class]])
{
for (NSString *key in [target allKeys])
{
TiStringRef value = TiStringCreateWithUTF8CString([key UTF8String]);
TiPropertyNameAccumulatorAddName(propertyNames,value);
TiStringRelease(value);
}
}
}
}
//
// support casting
//
bool KrollHasInstance(TiContextRef ctx, TiObjectRef constructor, TiValueRef possibleInstance, TiValueRef* exception)
{
KrollObject* o1 = (KrollObject*) TiObjectGetPrivate(constructor);
if (o1)
{
TiValueRef ex = NULL;
TiObjectRef objTarget = TiValueToObject(ctx, possibleInstance, &ex);
if (!ex)
{
KrollObject* o2 = (KrollObject*) TiObjectGetPrivate(objTarget);
if (o2)
{
id t1 = [o1 target];
id t2 = [o2 target];
Class c1 = [t1 class];
Class c2 = [t2 class];
Class ti = [TiProxy class];
while (c1!=c2 && c1!=nil && c2!=nil && c1!=ti && c2!=ti)
{
// if the proxies are the same class, we can cast
if (c1 == c2)
{
return true;
}
// if the target is a kind of class that matches this superclass, we can cast
if ([t2 isKindOfClass:c1])
{
return true;
}
c1 = [c1 superclass];
c2 = [c2 superclass];
}
}
}
}
return false;
}
@implementation KrollObject
@synthesize propsObject, finalized, bridge;
+(void)initialize
{
if (KrollObjectClassRef==NULL)
{
TiClassDefinition classDef = kTiClassDefinitionEmpty;
classDef.className = "Object";
classDef.initialize = KrollInitializer;
classDef.finalize = KrollFinalizer;
classDef.setProperty = KrollSetProperty;
classDef.getProperty = KrollGetProperty;
classDef.deleteProperty = KrollDeleteProperty;
classDef.getPropertyNames = KrollPropertyNames;
classDef.hasInstance = KrollHasInstance;
KrollObjectClassRef = TiClassCreate(&classDef);
kTiStringGetTime = TiStringCreateWithUTF8CString("getTime");
kTiStringLength = TiStringCreateWithUTF8CString("length");
kTiStringNewObject = TiStringCreateWithUTF8CString("new Object()");
kTiStringTiPropertyKey = TiStringCreateWithUTF8CString("__TI");
kTiStringPropertyKey = TiStringCreateWithUTF8CString("__PR");
kTiStringEventKey = TiStringCreateWithUTF8CString("__EV");
}
}
+(TiClassRef)jsClassRef
{
return KrollObjectClassRef;
}
-(id)initWithTarget:(id)target_ context:(KrollContext*)context_
{
if (self = [self init])
{
#if DEBUG
//TODO: See if this actually happens, and if not, remove this extra check.
if ([(KrollBridge *)[context_ delegate] usesProxy:target_] && [self isMemberOfClass:[KrollObject class]])
{
NSLog(@"[WARN] %@ already has %@!",[context_ delegate],target_);
}
if (![context_ isKJSThread])
{
NSLog(@"[WARN] %@->%@ is being made in a thread not owned by %@",self,target_,context_);
}
#endif
target = [target_ retain];
context = context_; // don't retain
bridge = (KrollBridge*)[context_ delegate];
jsobject = TiObjectMake([context context],[[self class] jsClassRef],self);
targetable = [target conformsToProtocol:@protocol(KrollTargetable)];
}
return self;
}
-(TiObjectRef)jsobject
{
return jsobject;
}
-(void)invalidateJsobject;
{
propsObject = NULL;
jsobject = NULL;
context = nil;
}
- (BOOL)isEqual:(id)anObject
{
if ([anObject isKindOfClass:[KrollObject class]])
{
TiObjectRef ref1 = jsobject;
TiObjectRef ref2 = [(KrollObject*)anObject jsobject];
return TiValueIsStrictEqual([context context],ref1,ref2);
}
return NO;
}
-(void)dealloc
{
#if KOBJECT_MEMORY_DEBUG == 1
NSLog(@"DEALLOC KROLLOBJECT: %@",[self description]);
#endif
RELEASE_TO_NIL(properties);
RELEASE_TO_NIL(target);
RELEASE_TO_NIL(statics);
// [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
[super dealloc];
}
#if KOBJECT_MEMORY_DEBUG == 1
-(id)description
{
return [NSString stringWithFormat:@"KrollObject[%@] held:%d",target,[target retainCount]];
}
#endif
-(KrollContext*)context
{
return context;
}
-(id)target
{
return target;
}
//
// create a JS TiValueRef from a NSObject* (as ID)
//
+(TiValueRef)create:(id)object context:(KrollContext*)context
{
#ifdef KROLL_COVERAGE
KrollObject *ko = [[[KrollCoverageObject alloc] initWithTarget:object context:context] autorelease];
#else
KrollObject *ko = [[[KrollObject alloc] initWithTarget:object context:context] autorelease];
#endif
return [ko jsobject];
}
//
// convert TiValueRef to ID
//
+(id)toID:(KrollContext*)context value:(TiValueRef) ref
{
return TiValueToId(context,ref);
}
+(id)nonNull:(id)value
{
if (value == nil || value == [NSNull null])
{
return nil;
}
return value;
}
//
// convert ID to TiValueRef
//
+(TiValueRef)toValue:(KrollContext*)context value:(id)obj
{
return ConvertIdTiValue(context,obj);
}
-(NSString*)propercase:(NSString*)name index:(int)index
{
if (index > 0)
{
NSString *result = [name substringFromIndex:index];
return [NSString stringWithFormat:@"%@%@", [[result substringToIndex:1] lowercaseString], [result length] > 1 ? [result substringFromIndex:1] : @""];
}
else
{
return [NSString stringWithFormat:@"%@%@", [[name substringToIndex:1] uppercaseString], [name length] > 1 ? [name substringFromIndex:1] : @""];
}
}
-(NSString*)_propertyGetterSetterKey:(NSString *)key
{
NSString *newkey = [key substringFromIndex:3];
return [NSString stringWithFormat:@"%@%@",[[newkey substringToIndex:1] lowercaseString], [newkey length]>1 ? [newkey substringFromIndex:1]: @""];
}
-(id)_valueForKey:(NSString *)key
{
//TODO: need to consult property_getAttributes to make sure we're not hitting readonly, etc. but do this
//only for non-production builds
if ([key hasPrefix:@"set"] && ([key length]>=4) &&
[[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[key characterAtIndex:3]])
{
// this is a request for a setter method
// a.setFoo('bar')
SEL selector;
// setter can also have a special 2nd parameter, let's check that
// right now we only support 2 but easy to add more
// form is foo.setFoo('bar','foo')
NSString * propertyKey = [self _propertyGetterSetterKey:key];
#ifdef KROLL_COVERAGE
KrollMethod * result = [[KrollCoverageMethod alloc] initWithTarget:target context:[self context] parent:self];
#else
KrollMethod * result = [[KrollMethod alloc] initWithTarget:target context:[self context]];
#endif
[result setArgcount:1];
[result setPropertyKey:propertyKey];
[result setType:KrollMethodSetter];
[result setUpdatesProperty:[(TiProxy *)target retainsJsObjectForKey:propertyKey]];
selector = NSSelectorFromString([key stringByAppendingString:@":withObject:"]);
if ([target respondsToSelector:selector])
{
[result setArgcount:2];
[result setSelector:selector];
}
else
{
selector = NSSelectorFromString([key stringByAppendingString:@":"]);
if ([target respondsToSelector:selector])
{
[result setSelector:selector];
}
else
{
[result setType:KrollMethodPropertySetter];
[result setName:propertyKey];
}
}
return [result autorelease]; // we simply return a method delegator against the target to set the property directly on the target
}
else if ([key hasPrefix:@"get"])
{
#ifdef KROLL_COVERAGE
KrollMethod * result = [[KrollCoverageMethod alloc] initWithTarget:target context:[self context] parent:self];
#else
KrollMethod * result = [[KrollMethod alloc] initWithTarget:target context:[self context]];
#endif
NSString * propertyKey = [self _propertyGetterSetterKey:key];
[result setPropertyKey:propertyKey];
[result setArgcount:1];
[result setUpdatesProperty:[(TiProxy *)target retainsJsObjectForKey:propertyKey]];
//first make sure we don't have a method with the fullname
SEL fullSelector = NSSelectorFromString([NSString stringWithFormat:@"%@:",key]);
if ([target respondsToSelector:fullSelector])
{
[result setSelector:fullSelector];
[result setType:KrollMethodInvoke];
return [result autorelease];
}
// this is a request for a getter method
// a.getFoo()
NSString *partkey = [self propercase:key index:3];
SEL selector = NSSelectorFromString(partkey);
if ([target respondsToSelector:selector])
{
[result setSelector:selector];
[result setType:KrollMethodGetter];
return [result autorelease];
}
// see if its an actual method that takes an arg instead
selector = NSSelectorFromString([NSString stringWithFormat:@"%@:",partkey]);
if ([target respondsToSelector:selector])
{
[result setSelector:selector];
[result setType:KrollMethodGetter];
return [result autorelease];
}
[result setName:propertyKey];
[result setArgcount:0];
[result setType:KrollMethodPropertyGetter];
return [result autorelease];
}
else
{
// property accessor - need to determine if its a objc property of method
objc_property_t p = class_getProperty([target class], [key UTF8String]);
if (p==NULL)
{
if ([key isEqualToString:@"toString"] || [key isEqualToString:@"valueOf"])
{
return [[[KrollMethod alloc] initWithTarget:target selector:@selector(toString:) argcount:0 type:KrollMethodInvoke name:nil context:[self context]] autorelease];
}
SEL selector = NSSelectorFromString([NSString stringWithFormat:@"%@:",key]);
if ([target respondsToSelector:selector])
{
#ifdef KROLL_COVERAGE
return [[[KrollCoverageMethod alloc] initWithTarget:target selector:selector
argcount:1 type:KrollMethodInvoke name:nil context:[self context] parent:self] autorelease];
#else
return [[[KrollMethod alloc] initWithTarget:target selector:selector
argcount:1 type:KrollMethodInvoke name:nil context:[self context]] autorelease];
#endif
}
// attempt a function that has no args (basically a non-property property)
selector = NSSelectorFromString([NSString stringWithFormat:@"%@",key]);
if ([target respondsToSelector:selector])
{
#ifdef KROLL_COVERAGE
id<KrollCoverage> cSelf = (id<KrollCoverage>)self;
[cSelf increment:key coverageType:COVERAGE_TYPE_GET apiType:API_TYPE_PROPERTY];
#endif
return [target performSelector:selector];
}
id result = [target valueForKey:key];
if (result!=nil)
{
if ([result isKindOfClass:[KrollMethodDelegate class]])
{
int argcount = [result args] ? 1 : 0;
#ifdef KROLL_COVERAGE
return [[[KrollCoverageMethod alloc] initWithTarget:[result target] selector:[result selector]
argcount:argcount type:KrollMethodInvoke name:key context:[self context] parent:self] autorelease];
#else
return [[[KrollMethod alloc] initWithTarget:[result target] selector:[result selector]
argcount:argcount type:KrollMethodInvoke name:key context:[self context]] autorelease];
#endif
}
else if ([result isKindOfClass:[KrollPropertyDelegate class]])
{
KrollPropertyDelegate *d = (KrollPropertyDelegate*)result;
return [[d target] performSelector:[d selector]];
}
return result;
}
// see if this is a create factory which we can do dynamically
if ([key hasPrefix:@"create"])
{
SEL selector = @selector(createProxy:forName:context:);
if ([target respondsToSelector:selector])
{
#ifdef KROLL_COVERAGE
return [[[KrollCoverageMethod alloc] initWithTarget:target selector:selector argcount:2
type:KrollMethodFactory name:key context:[self context] parent:self] autorelease];
#else
return [[[KrollMethod alloc] initWithTarget:target selector:selector argcount:2
type:KrollMethodFactory name:key context:[self context]] autorelease];
#endif
}
}
}
else
{
#ifdef KROLL_COVERAGE
id<KrollCoverage> cSelf = (id<KrollCoverage>)self;
[cSelf increment:key coverageType:COVERAGE_TYPE_GET apiType:API_TYPE_PROPERTY];
#endif
NSString *attributes = [NSString stringWithCString:property_getAttributes(p) encoding:NSUTF8StringEncoding];
SEL selector = NSSelectorFromString([NSString stringWithCString:property_getName(p) encoding:NSUTF8StringEncoding]);
if ([attributes hasPrefix:@"T@"])
{
// this means its a return type of id
return [target performSelector:selector];
}
else
{
// it's probably a primitive type - check for them
NSMethodSignature *methodSignature = [target methodSignatureForSelector:selector];
IMP methodFunction = [target methodForSelector:selector];
if ([attributes hasPrefix:@"Td,"])
{
double d;
typedef double (*dIMP)(id, SEL, ...);
d = ((dIMP)methodFunction)(target,selector);
return [NSNumber numberWithDouble:d];
}
else if ([attributes hasPrefix:@"Tf,"])
{
float f;
typedef float (*fIMP)(id, SEL, ...);
f = ((fIMP)methodFunction)(target,selector);
return [NSNumber numberWithFloat:f];
}
else if ([attributes hasPrefix:@"Ti,"])
{
int i;
typedef int (*iIMP)(id, SEL, ...);
i = ((iIMP)methodFunction)(target,selector);
return [NSNumber numberWithInt:i];
}
else if ([attributes hasPrefix:@"Tl,"])
{
long l;
typedef long (*lIMP)(id, SEL, ...);
l = ((lIMP)methodFunction)(target,selector);
return [NSNumber numberWithLong:l];
}
else if ([attributes hasPrefix:@"Tc,"])
{
char c;
typedef char (*cIMP)(id, SEL, ...);
c = ((cIMP)methodFunction)(target,selector);
return [NSNumber numberWithChar:c];
}
else if ([attributes hasPrefix:@"TQ,"])
{
unsigned long long ull;
typedef unsigned long long (*ullIMP)(id, SEL, ...);
ull = ((ullIMP)methodFunction)(target,selector);
return [NSNumber numberWithUnsignedLongLong:ull];
}
else
{
// let it fall through and return undefined
NSLog(@"[WARN] unsupported property: %@ for %@, attributes = %@",key,target,attributes);
}
}
}
}
return nil;
}
-(id)valueForKey:(NSString *)key
{
BOOL executionSet = NO;
@try
{
// first consult our statics
if (statics!=nil)
{
id result = [statics objectForKey:key];
if (result!=nil)
{
return result;
}
}
// second consult our fixed properties dictionary if we have one
if (properties!=nil)
{
id result = [properties objectForKey:key];
if (result!=nil)
{
return result;
}
}
if (targetable)
{
executionSet = YES;
[target setExecutionContext:context.delegate];
}
id result = [self _valueForKey:key];
// we can safely cache method objects
if ([result isKindOfClass:[KrollObject class]])
{
[self setStaticValue:result forKey:key purgable:YES];
}
return result;
}
@finally
{
if (executionSet)
{
[target setExecutionContext:nil];
}
}
}
-(void)deleteKey:(NSString*)key
{
[target deleteKey:key];
}
-(void)setValue:(id)value forKey:(NSString *)key
{
BOOL executionSet = NO;
if ([target conformsToProtocol:@protocol(KrollTargetable)])
{
executionSet = YES;
[target setExecutionContext:context.delegate];
}
@try
{
if (value == [NSNull null])
{
value = nil;
}
NSString *name = [self propercase:key index:0];
SEL selector = NSSelectorFromString([NSString stringWithFormat:@"set%@:withObject:",name]);
if ([target respondsToSelector:selector])
{
[target performSelector:selector withObject:value withObject:nil];
return;
}
selector = NSSelectorFromString([NSString stringWithFormat:@"set%@:",name]);
if ([target respondsToSelector:selector] && ![name isEqualToString:@"ZIndex"])//TODO: Quick hack is quick.
{
[target performSelector:selector withObject:value];
}
else
{
[target setValue:value forKey:key];
}
#ifdef KROLL_COVERAGE
id<KrollCoverage> cSelf = (id<KrollCoverage>) self;
[cSelf increment:key coverageType:COVERAGE_TYPE_SET apiType:API_TYPE_PROPERTY];
#endif
}
@finally
{
if (executionSet)
{
[target setExecutionContext:nil];
}
}
}
-(void)setStaticValue:(id)value forKey:(NSString*)key purgable:(BOOL)purgable
{
if (purgable)
{
if (properties == nil)
{
properties = [[NSMutableDictionary alloc] initWithCapacity:3];
}
[properties setValue:value forKey:key];
}
else
{
if (statics==nil)
{
statics = [[NSMutableDictionary alloc] initWithCapacity:2];
}
[statics setValue:value forKey:key];
}
}
-(void)protectJsobject
{
if (protecting)
{
return;
}
TiContextRef jscontext = [context context];
if (finalized || (jscontext == NULL) || (jsobject == NULL))
{
return;
}
if (![context isKJSThread])
{
NSOperation * safeProtect = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(protectJsobject) object:nil];
[context enqueue:safeProtect];
[safeProtect release];
return;
}
protecting = YES;
TiValueProtect(jscontext,jsobject);
}
-(void)unprotectJsobject
{
if (!protecting)
{
return;
}
TiContextRef jscontext = [context context];
if (finalized || (jscontext == NULL) || (jsobject == NULL))
{
return;
}
if (![context isKJSThread])
{
NSOperation * safeUnprotect = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(unprotectJsobject) object:nil];
[context enqueue:safeUnprotect];
[safeUnprotect release];
return;
}
protecting = NO;
TiValueUnprotect(jscontext,jsobject);
}
TI_INLINE TiStringRef TiStringCreateWithPointerValue(int value)
{
/*
* When we note proxies, we need to come up with a property name
* that is unique. We previously did an nsstring with format
* of __PX%X, but this method is so often called, and allocating a string
* can be a waste, so it's better to jump straight to something hardwired
*
* No sense in doing hex when so many more characters are valid property
* characters. So we do it in chunks of 6 bits, from '<' (60) to '{' (123)
*/
char result[10];
result[0]='_';
result[1]='_';
result[2]=':';
result[3]='<' + (value & 0x3F);
result[4]='<' + ((value >> 6) & 0x3F);
result[5]='<' + ((value >> 12) & 0x3F);
result[6]='<' + ((value >> 18) & 0x3F);
result[7]='<' + ((value >> 24) & 0x3F);
result[8]='<' + ((value >> 30) & 0x3F);
result[9]=0;
return TiStringCreateWithUTF8CString(result);
}
-(void)noteKeylessKrollObject:(KrollObject *)value
{
if ([value finalized])
{
return;
}
if (![context isKJSThread])
{
NSOperation * safeProtect = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(noteKeylessKrollObject:) object:value];
[context enqueue:safeProtect];
[safeProtect release];
return;
}
TiStringRef nameRef = TiStringCreateWithPointerValue((int)value);
[self noteObject:[value jsobject] forTiString:nameRef context:[context context]];
TiStringRelease(nameRef);
}
-(void)forgetKeylessKrollObject:(KrollObject *)value
{
if (![context isKJSThread])
{
NSOperation * safeUnprotect = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(forgetKeylessKrollObject:) object:value];
[context enqueue:safeUnprotect];
[safeUnprotect release];
return;
}
TiStringRef nameRef = TiStringCreateWithPointerValue((int)value);
[self forgetObjectForTiString:nameRef context:[context context]];
TiStringRelease(nameRef);
}
-(void)noteCallback:(KrollCallback *)eventCallback forKey:(NSString *)key
{
if (![context isKJSThread])
{
NSLog(@"[WARN] %@ tried to note the callback for %@ in the wrong thead.",target,key);
NSOperation * safeInvoke = [[ExpandedInvocationOperation alloc]
initWithTarget:self selector:_cmd object:eventCallback object:key];
[context enqueue:safeInvoke];
[safeInvoke release];
return;
}
TiStringRef nameRef = TiStringCreateWithCFString((CFStringRef)key);
[self noteObject:[eventCallback function] forTiString:nameRef context:[context context]];
TiStringRelease(nameRef);
}
-(void)forgetCallbackForKey:(NSString *)key
{
if (![context isKJSThread])
{
NSOperation * safeForget = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(forgetCallbackForKey:) object:key];
[context enqueue:safeForget];
[safeForget release];
return;
}
TiStringRef nameRef = TiStringCreateWithCFString((CFStringRef)key);
[self forgetObjectForTiString:nameRef context:[context context]];
TiStringRelease(nameRef);
}
-(void)invokeCallbackForKey:(NSString *)key withObject:(NSDictionary *)eventData thisObject:(id)thisObject
{
if (finalized)
{
return;
}
if (![context isKJSThread])
{
NSOperation * safeInvoke = [[ExpandedInvocationOperation alloc]
initWithTarget:self selector:_cmd object:key object:eventData object:thisObject];
[context enqueue:safeInvoke];
[safeInvoke release];
return;
}
if (![thisObject isKindOfClass:[KrollObject class]])
{
thisObject = [(KrollBridge *)[context delegate] registerProxy:thisObject];
}
TiValueRef exception=NULL;
TiContextRef jsContext = [context context];
TiObjectRef jsProxyHash = (TiObjectRef)TiObjectGetProperty(jsContext, propsObject, kTiStringPropertyKey, &exception);
jsProxyHash = TiValueToObject(jsContext, jsProxyHash, &exception);
if ((jsProxyHash == NULL) || (TiValueGetType(jsContext,jsProxyHash) != kTITypeObject))
{
return;
}
TiStringRef nameRef = TiStringCreateWithCFString((CFStringRef)key);
TiObjectRef jsCallback = (TiObjectRef)TiObjectGetProperty(jsContext, jsProxyHash, nameRef, NULL);
TiStringRelease(nameRef);
if ((jsCallback == NULL) || (TiValueGetType(jsContext,jsCallback) != kTITypeObject))
{
return;
}
TiValueRef jsEventData = ConvertIdTiValue(context, eventData);
TiObjectCallAsFunction(jsContext, jsCallback, [thisObject jsobject], 1, &jsEventData,&exception);
}
-(void)noteKrollObject:(KrollObject *)value forKey:(NSString *)key
{
if ([value finalized])
{
return;
}
if (![context isKJSThread])
{
NSLog(@"[WARN] %@ tried to note the callback for %@ in the wrong thead.",target,key);
NSOperation * safeInvoke = [[ExpandedInvocationOperation alloc]
initWithTarget:self selector:_cmd object:value object:key];
[context enqueue:safeInvoke];
[safeInvoke release];
return;
}
TiStringRef nameRef = TiStringCreateWithCFString((CFStringRef)key);
[self noteObject:[value jsobject] forTiString:nameRef context:[context context]];
TiStringRelease(nameRef);
}
-(void)forgetKrollObjectforKey:(NSString *)key;
{
if (![context isKJSThread])
{
NSOperation * safeForget = [[NSInvocationOperation alloc] initWithTarget:self
selector:_cmd object:key];
[context enqueue:safeForget];
[safeForget release];
return;
}
TiStringRef nameRef = TiStringCreateWithCFString((CFStringRef)key);
[self forgetObjectForTiString:nameRef context:[context context]];
TiStringRelease(nameRef);
}
-(void)noteObject:(TiObjectRef)storedJSObject forTiString:(TiStringRef) keyString context:(TiContextRef) jsContext
{
if ((propsObject == NULL) || (storedJSObject == NULL) || finalized)
{
return;
}
TiValueRef exception=NULL;
TiObjectRef jsProxyHash = (TiObjectRef)TiObjectGetProperty(jsContext, propsObject, kTiStringPropertyKey, &exception);
if ((jsProxyHash == NULL) || (TiValueGetType(jsContext,jsProxyHash) != kTITypeObject))
{
jsProxyHash = TiObjectMake(jsContext, NULL, &exception);
TiObjectSetProperty(jsContext, propsObject, kTiStringPropertyKey, jsProxyHash,
kTiPropertyAttributeDontEnum , &exception);
}
TiObjectSetProperty(jsContext, jsProxyHash, keyString, storedJSObject,
kTiPropertyAttributeDontEnum , &exception);
}
-(void)forgetObjectForTiString:(TiStringRef) keyString context:(TiContextRef) jsContext
{
if ((propsObject == NULL) || finalized)
{
return;
}
TiValueRef exception=NULL;
TiObjectRef jsProxyHash = (TiObjectRef)TiObjectGetProperty(jsContext, propsObject, kTiStringPropertyKey, &exception);
if ((jsProxyHash == NULL) || (TiValueGetType(jsContext,jsProxyHash) != kTITypeObject))
{
return;
}
TiObjectDeleteProperty(jsContext, jsProxyHash, keyString, &exception);
}
-(TiObjectRef)objectForTiString:(TiStringRef) keyString context:(TiContextRef) jsContext
{
if(finalized){
return NULL;
}
TiValueRef exception=NULL;
TiObjectRef jsProxyHash = (TiObjectRef)TiObjectGetProperty(jsContext, propsObject, kTiStringPropertyKey, &exception);
if ((jsProxyHash == NULL) || (TiValueGetType(jsContext,jsProxyHash) != kTITypeObject))
{
return NULL;
}
TiObjectRef result = (TiObjectRef)TiObjectGetProperty(jsContext, jsProxyHash, keyString, NULL);
if ((result == NULL) || (TiValueGetType(jsContext,result) != kTITypeObject))
{
return NULL;
}
return result;
}
-(void)storeListener:(KrollCallback *)eventCallback forEvent:(NSString *)eventName
{
if ((propsObject == NULL) || finalized)
{
return;
}
TiValueRef exception=NULL;
TiContextRef jsContext = [context context];
TiObjectRef jsEventHash = (TiObjectRef)TiObjectGetProperty(jsContext, propsObject, kTiStringEventKey, &exception);
jsEventHash = TiValueToObject(jsContext, jsEventHash, &exception);
if ((jsEventHash == NULL) || (TiValueGetType(jsContext,jsEventHash) != kTITypeObject))
{
jsEventHash = TiObjectMake(jsContext, NULL, &exception);
TiObjectSetProperty(jsContext, propsObject, kTiStringEventKey, jsEventHash,
kTiPropertyAttributeDontEnum , &exception);
}
TiStringRef jsEventTypeString = TiStringCreateWithCFString((CFStringRef) eventName);
TiObjectRef jsCallbackArray = (TiObjectRef)TiObjectGetProperty(jsContext, jsEventHash, jsEventTypeString, &exception);
TiObjectRef callbackFunction = [eventCallback function];
jsCallbackArray = TiValueToObject(jsContext, jsCallbackArray, &exception);
if ((jsCallbackArray == NULL) || (TiValueGetType(jsContext,jsCallbackArray) != kTITypeObject))
{
jsCallbackArray = TiObjectMakeArray(jsContext, 1, (TiValueRef*)&callbackFunction, &exception);
TiObjectSetProperty(jsContext, jsEventHash, jsEventTypeString, jsCallbackArray,
kTiPropertyAttributeDontEnum , &exception);
}
else
{
TiValueRef jsCallbackArrayLength = TiObjectGetProperty(jsContext, jsCallbackArray, kTiStringLength, &exception);
int arrayLength = (int)TiValueToNumber(jsContext, jsCallbackArrayLength, &exception);
TiObjectSetPropertyAtIndex(jsContext, jsCallbackArray, arrayLength, callbackFunction, &exception);
}
//TODO: Call back to the proxy?
TiStringRelease(jsEventTypeString);
}
-(void)removeListener:(KrollCallback *)eventCallback forEvent:(NSString *)eventName
{
if (finalized || (propsObject == NULL))
{
return;
}
TiContextRef jsContext = [context context];
TiObjectRef jsEventHash = (TiObjectRef)TiObjectGetProperty(jsContext, propsObject, kTiStringEventKey, NULL);
if ((jsEventHash == NULL) || (TiValueGetType(jsContext,jsEventHash) != kTITypeObject))
{
return;
}
TiStringRef jsEventTypeString = TiStringCreateWithCFString((CFStringRef) eventName);
TiObjectRef jsCallbackArray = (TiObjectRef)TiObjectGetProperty(jsContext, jsEventHash, jsEventTypeString, NULL);
TiStringRelease(jsEventTypeString);
TiObjectRef callbackFunction = [eventCallback function];
if ((jsCallbackArray == NULL) || (TiValueGetType(jsContext,jsCallbackArray) != kTITypeObject))
{
return;
}
TiValueRef jsCallbackArrayLength = TiObjectGetProperty(jsContext, jsCallbackArray, kTiStringLength, NULL);
int arrayLength = (int)TiValueToNumber(jsContext, jsCallbackArrayLength, NULL);
if (arrayLength < 1)
{
return;
}
for (int currentCallbackIndex=0; currentCallbackIndex<arrayLength; currentCallbackIndex++)
{
TiValueRef currentCallback = TiObjectGetPropertyAtIndex(jsContext, jsCallbackArray, currentCallbackIndex, NULL);
if (currentCallback == callbackFunction)
{
TiValueRef undefined = TiValueMakeUndefined(jsContext);
TiObjectSetPropertyAtIndex(jsContext, jsCallbackArray, currentCallbackIndex, undefined, NULL);
}
}
}
-(void)triggerEvent:(NSString *)eventName withObject:(NSDictionary *)eventData thisObject:(KrollObject *)thisObject
{
if (finalized || [thisObject finalized] || (propsObject == NULL))
{
return;
}
TiContextRef jsContext = [context context];
TiObjectRef jsEventHash = (TiObjectRef)TiObjectGetProperty(jsContext, propsObject, kTiStringEventKey, NULL);
if ((jsEventHash == NULL) || (TiValueGetType(jsContext,jsEventHash) != kTITypeObject))
{ //We did not have any event listeners on this proxy. Perfectly normal.
return;
}
TiStringRef jsEventTypeString = TiStringCreateWithCFString((CFStringRef) eventName);
TiObjectRef jsCallbackArray = (TiObjectRef)TiObjectGetProperty(jsContext, jsEventHash, jsEventTypeString, NULL);
TiStringRelease(jsEventTypeString);
if ((jsCallbackArray == NULL) || (TiValueGetType(jsContext,jsCallbackArray) != kTITypeObject))
{ //We did not have any event listeners on this proxy. Perfectly normal.
return;
}
TiValueRef jsCallbackArrayLength = TiObjectGetProperty(jsContext, jsCallbackArray, kTiStringLength, NULL);
int arrayLength = (int)TiValueToNumber(jsContext, jsCallbackArrayLength, NULL);
if (arrayLength < 1)
{
return;
}
TiValueRef jsEventData = ConvertIdTiValue(context, eventData);
for (int currentCallbackIndex=0; currentCallbackIndex<arrayLength; currentCallbackIndex++)
{
TiValueRef currentCallback = TiObjectGetPropertyAtIndex(jsContext, jsCallbackArray, currentCallbackIndex, NULL);
currentCallback = TiValueToObject(jsContext, currentCallback, NULL);
if ((currentCallback == NULL) || !TiObjectIsFunction(jsContext,(TiObjectRef)currentCallback))
{
continue;
}
TiValueRef exception = NULL;
TiObjectCallAsFunction(jsContext, (TiObjectRef)currentCallback, [thisObject jsobject], 1, &jsEventData,&exception);
if (exception!=NULL)
{
NSLog(@"[WARN] Exception in event callback. %@",[KrollObject toID:context value:exception]);
}
}
}
@end
| {
"content_hash": "da0f446a8fca01149833bd40ceb87b93",
"timestamp": "",
"source": "github",
"line_count": 1536,
"max_line_length": 165,
"avg_line_length": 29.139973958333332,
"alnum_prop": 0.718738130878706,
"repo_name": "prock13/SplitViewSampleWithCommonJS",
"id": "0ffba7ba9708223dba2c8b5f72b761c424246579",
"size": "45096",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "build/iphone/Classes/KrollObject.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "176678"
},
{
"name": "C++",
"bytes": "47528"
},
{
"name": "D",
"bytes": "772117"
},
{
"name": "JavaScript",
"bytes": "3997"
},
{
"name": "Objective-C",
"bytes": "3060569"
},
{
"name": "Shell",
"bytes": "146"
}
],
"symlink_target": ""
} |
<!-- Forward Shading Pipeline -->
<Pipeline>
<CommandQueue>
<Stage id="Geometry" link="pipelines/globalSettings.material.xml">
<ClearTarget depthBuf="true" colBuf0="true" />
<DrawGeometry context="AMBIENT" class="~Translucent" />
<DoForwardLightLoop class="~Translucent" />
<DrawGeometry context="TRANSLUCENT" class="Translucent" order="BACK_TO_FRONT" />
</Stage>
<Stage id="Overlays">
<DrawOverlays context="OVERLAY" />
</Stage>
</CommandQueue>
</Pipeline> | {
"content_hash": "627458e44fb6c94abe3a85117531719a",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 83,
"avg_line_length": 29,
"alnum_prop": 0.6855983772819473,
"repo_name": "dansamargiu/TemporalLookbackGame",
"id": "0994a8830eec57a0bb3564b87dd95c61dee824f7",
"size": "493",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Content/pipelines/forward.pipeline.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "28119"
},
{
"name": "C++",
"bytes": "35054"
}
],
"symlink_target": ""
} |
[Prerequisites](https://github.com/Dickurt/vscode-php-formatter/wiki/Prerequisites)
[Setup](https://github.com/Dickurt/vscode-php-formatter/wiki/Setup)
[Configuration](https://github.com/Dickurt/vscode-php-formatter/wiki/Configuration)
[Commands](https://github.com/Dickurt/vscode-php-formatter/wiki/Commands)
[Troubleshooting](https://github.com/Dickurt/vscode-php-formatter/wiki/Troubleshooting) | {
"content_hash": "6be2753cd78cbe42f17fc9216329d792",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 87,
"avg_line_length": 44.55555555555556,
"alnum_prop": 0.8054862842892768,
"repo_name": "Dickurt/vscode-php-formatter",
"id": "28d16a345f0a0680b63a4a883472d1396efd7ae3",
"size": "419",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "wiki/_Sidebar-Installation.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1751"
},
{
"name": "TypeScript",
"bytes": "14970"
}
],
"symlink_target": ""
} |
<PMML version="4.1" xsi:schemaLocation="http://www.dmg.org/PMML-4_1 http://www.dmg.org/v4-1/pmml-4-1.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.dmg.org/PMML-4_1">
<Header copyright="JBoss" description="Clustering Test"/>
<DataDictionary numberOfFields="3">
<DataField dataType="string" name="fld0" optype="categorical">
<Value value="x"/>
<Value value="y"/>
<Value value="z"/>
</DataField>
<DataField dataType="double" name="fld1" optype="continuous"/>
<DataField dataType="double" name="fld2" optype="continuous">
<Value property="missing" value="-1"/>
<Value property="valid" value="0.3"/>
<Value property="valid" value="0.4"/>
<Value property="valid" value="0.5"/>
<Value property="valid" value="0.6"/>
<Value property="valid" value="0.7"/>
</DataField>
</DataDictionary>
<ClusteringModel functionName="clustering" modelClass="centerBased" modelName="CenterClustering" numberOfClusters="2">
<MiningSchema>
<MiningField name="fld0"/>
<MiningField name="fld1"/>
<MiningField name="fld2"/>
</MiningSchema>
<LocalTransformations>
<DerivedField dataType="double" name="fld3" optype="continuous">
<NormDiscrete field="fld0" value="x"/>
</DerivedField>
<DerivedField dataType="double" name="fld4" optype="continuous">
<NormDiscrete field="fld0" value="y"/>
</DerivedField>
<DerivedField dataType="double" name="fld5" optype="continuous">
<NormDiscrete field="fld0" value="z"/>
</DerivedField>
</LocalTransformations>
<ComparisonMeasure compareFunction="absDiff" kind="distance">
<squaredEuclidean/>
</ComparisonMeasure>
<ClusteringField field="fld1" fieldWeight="0.8" isCenterField="true"/>
<ClusteringField compareFunction="gaussSim" field="fld2" isCenterField="true" similarityScale="0.99"/>
<ClusteringField compareFunction="equal" field="fld3" isCenterField="true"/>
<ClusteringField compareFunction="delta" field="fld4" fieldWeight="0.6"/>
<ClusteringField compareFunction="table" field="fld5">
<Comparisons>
<Matrix diagDefault="-1" kind="symmetric" nbCols="3" nbRows="3" offDiagDefault="99">
<MatCell col="1" row="1">4.0</MatCell>
<MatCell col="2" row="1">5.0</MatCell>
<MatCell col="2" row="2">6.0</MatCell>
</Matrix>
</Comparisons>
</ClusteringField>
<MissingValueWeights>
<Array n="5" type="real">1 0.5 1 1 1</Array>
</MissingValueWeights>
<Cluster name="Klust1">
<KohonenMap coord1="3" coord3="7"/>
<Array n="5" type="real">0.5 0.4 0.1 0.3 1</Array>
</Cluster>
<Cluster name="Klust2">
<Array n="5" type="real">0.7 0.4 0.5 0.1 2</Array>
</Cluster>
</ClusteringModel>
</PMML> | {
"content_hash": "80fe14c725e5b4d6b0c243f3110dc153",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 196,
"avg_line_length": 45.01587301587302,
"alnum_prop": 0.6452750352609309,
"repo_name": "bernardator/drools-chance",
"id": "4b572893b4c6ddc9b80e6f20f62c198c2bf34cc0",
"size": "2836",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "drools-pmml/src/test/resources/org/drools/pmml/pmml_4_1/test_clustering.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2712410"
},
{
"name": "Web Ontology Language",
"bytes": "597230"
}
],
"symlink_target": ""
} |
[org.apache.struts.taglib.logic](../../../../../org/apache/struts/taglib/logic/package-summary.html.md)
|------------------------------------------------------------------------------------------------|
| Classes
[CompareTagBase](CompareTagBase.html.md "class in org.apache.struts.taglib.logic")
[ConditionalTagBase](ConditionalTagBase.html.md "class in org.apache.struts.taglib.logic")
[EmptyTag](EmptyTag.html.md "class in org.apache.struts.taglib.logic")
[EqualTag](EqualTag.html.md "class in org.apache.struts.taglib.logic")
[ForwardTag](ForwardTag.html.md "class in org.apache.struts.taglib.logic")
[GreaterEqualTag](GreaterEqualTag.html.md "class in org.apache.struts.taglib.logic")
[GreaterThanTag](GreaterThanTag.html.md "class in org.apache.struts.taglib.logic")
[IterateTag](IterateTag.html.md "class in org.apache.struts.taglib.logic")
[IterateTei](IterateTei.html.md "class in org.apache.struts.taglib.logic")
[LessEqualTag](LessEqualTag.html.md "class in org.apache.struts.taglib.logic")
[LessThanTag](LessThanTag.html.md "class in org.apache.struts.taglib.logic")
[MatchTag](MatchTag.html.md "class in org.apache.struts.taglib.logic")
[MessagesNotPresentTag](MessagesNotPresentTag.html.md "class in org.apache.struts.taglib.logic")
[MessagesPresentTag](MessagesPresentTag.html.md "class in org.apache.struts.taglib.logic")
[NotEmptyTag](NotEmptyTag.html.md "class in org.apache.struts.taglib.logic")
[NotEqualTag](NotEqualTag.html.md "class in org.apache.struts.taglib.logic")
[NotMatchTag](NotMatchTag.html.md "class in org.apache.struts.taglib.logic")
[NotPresentTag](NotPresentTag.html.md "class in org.apache.struts.taglib.logic")
[PresentTag](PresentTag.html.md "class in org.apache.struts.taglib.logic")
[RedirectTag](RedirectTag.html.md "class in org.apache.struts.taglib.logic") |
| {
"content_hash": "09a97799e89c2702112dfa72e46766b4",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 103,
"avg_line_length": 92.96,
"alnum_prop": 0.5796041308089501,
"repo_name": "ExclamationLabs/struts-1.3.10_docs",
"id": "1e63e7436a50ec6cc1346da311017169a848398e",
"size": "2325",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "apidocs/org/apache/struts/taglib/logic/package-frame.html.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "2487"
},
{
"name": "CSS",
"bytes": "165112"
},
{
"name": "JavaScript",
"bytes": "18038"
}
],
"symlink_target": ""
} |
package peco
import (
"testing"
"unicode/utf8"
"github.com/mattn/go-runewidth"
"github.com/nsf/termbox-go"
)
type dummyScreen struct {
*interceptor
width int
height int
pollCh chan termbox.Event
}
func (d dummyScreen) Init() error {
return nil
}
func (d dummyScreen) Close() error {
return nil
}
func (d dummyScreen) SendEvent(e termbox.Event) {
d.pollCh <- e
}
func setDummyScreen() (*interceptor, func()) {
i := newInterceptor()
old := screen
guard := func() { screen = old }
screen = dummyScreen{
i,
100,
100,
make(chan termbox.Event, 256), // chan has a biiiig buffer, so we avoid blocking
}
return i, guard
}
func (d dummyScreen) SetCell(x, y int, ch rune, fg, bg termbox.Attribute) {
d.record("SetCell", interceptorArgs{x, y, ch, fg, bg})
}
func (d dummyScreen) Flush() error {
d.record("Flush", interceptorArgs{})
return nil
}
func (d dummyScreen) PollEvent() chan termbox.Event {
return d.pollCh
}
func (d dummyScreen) Size() (int, int) {
return d.width, d.height
}
func TestLayoutType(t *testing.T) {
layouts := []struct {
value LayoutType
expectOK bool
}{
{LayoutTypeTopDown, true},
{LayoutTypeBottomUp, true},
{"foobar", false},
}
for _, l := range layouts {
valid := IsValidLayoutType(l.value)
if valid != l.expectOK {
t.Errorf("LayoutType %s, expected IsValidLayoutType to return %t, but got %t",
l.value,
l.expectOK,
valid,
)
}
}
}
func TestPrintScreen(t *testing.T) {
i, guard := setDummyScreen()
defer guard()
makeVerifier := func(initX, initY int, fill bool) func(string) {
return func(msg string) {
i.reset()
t.Logf("Checking printScreen(%d, %d, %s, %t)", initX, initY, msg, fill)
width := utf8.RuneCountInString(msg)
printScreen(initX, initY, termbox.ColorDefault, termbox.ColorDefault, msg, fill)
events := i.events["SetCell"]
if !fill {
if len(events) != width {
t.Errorf("Expected %d SetCell events, got %d",
width,
len(events),
)
}
return
}
// fill == true
w, _ := screen.Size()
if rw := runewidth.StringWidth(msg); rw != width {
w -= rw - width
}
if len(events) != w {
t.Errorf("Expected %d SetCell events, got %d",
w,
len(events),
)
return
}
}
}
verify := makeVerifier(0, 0, false)
verify("Hello, World!")
verify("日本語")
verify = makeVerifier(0, 0, true)
verify("Hello, World!")
verify("日本語")
}
func TestStatusBar(t *testing.T) {
i, guard := setDummyScreen()
defer guard()
st := NewStatusBar(NewCtx(nil), AnchorBottom, 0)
st.PrintStatus("Hello, World!", 0)
events := i.events
if l := len(events["Flush"]); l != 1 {
t.Errorf("Expected 1 Flush event, got %d", l)
return
}
}
func TestMergeAttribute(t *testing.T) {
colors := stringToFg
// merge colors
tests := [][]string{
{"red", "green", "yellow"},
{"red", "blue", "magenta"},
{"green", "blue", "cyan"},
{"yellow", "blue", "white"},
{"magenta", "green", "white"},
{"cyan", "red", "white"},
{"yellow", "magenta", "white"},
{"magenta", "cyan", "white"},
{"cyan", "yellow", "white"},
}
for _, c := range tests {
if m := mergeAttribute(colors[c[0]], colors[c[1]]); m != colors[c[2]] {
t.Errorf("(%s + %s) expected %d(%s), got %d", c[0], c[1], colors[c[2]], c[2], m)
}
}
// merge with white
for _, c := range colors {
if m := mergeAttribute(c, colors["white"]); m != colors["white"] {
t.Errorf("expected white(%d), got %d", colors["white"], m)
}
}
// merge attributes
if m := mergeAttribute(termbox.AttrBold|colors["red"], termbox.AttrUnderline|colors["cyan"]); m != termbox.AttrBold|termbox.AttrUnderline|colors["white"] {
t.Errorf("expected %d, got %d", termbox.AttrBold|termbox.AttrUnderline|colors["white"], m)
}
}
| {
"content_hash": "13ce32ec2485322bc829554a92182c0e",
"timestamp": "",
"source": "github",
"line_count": 171,
"max_line_length": 156,
"avg_line_length": 21.94736842105263,
"alnum_prop": 0.6195043964828137,
"repo_name": "ukitazume/peco",
"id": "7be79483995ba72ad99421236b42974f4f5c4481",
"size": "3765",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "layout_test.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Go",
"bytes": "158440"
}
],
"symlink_target": ""
} |
layout: "docs_api"
version: "1.0.0-beta.8"
versionHref: "/docs/1.0.0-beta.8"
path: "api/directive/ionList/"
title: "ion-list"
header_sub_title: "Directive in module ionic"
doc: "ionList"
docType: "directive"
---
<div class="improve-docs">
<a href='http://github.com/driftyco/ionic/tree/master/js/angular/directive/list.js#L1'>
View Source
</a>
<a href='http://github.com/driftyco/ionic/edit/master/js/angular/directive/list.js#L1'>
Improve this doc
</a>
</div>
<h1 class="api-title">
ion-list
<br/>
<small>
Delegate: <a href="/docs/api/service/$ionicListDelegate/"><code>$ionicListDelegate</code></a>
</small>
</h1>
{% include codepen.html id="JsHjf" %}
The List is a widely used interface element in almost any mobile app, and can include
content ranging from basic text all the way to buttons, toggles, icons, and thumbnails.
Both the list, which contains items, and the list items themselves can be any HTML
element. The containing element requires the `list` class and each list item requires
the `item` class.
However, using the ionList and ionItem directives make it easy to support various
interaction modes such as swipe to edit, drag to reorder, and removing items.
Related: <a href="/docs/api/directive/ionItem/"><code>ionItem</code></a>, <a href="/docs/api/directive/ionOptionButton/"><code>ionOptionButton</code></a>
<a href="/docs/api/directive/ionReorderButton/"><code>ionReorderButton</code></a>, <a href="/docs/api/directive/ionDeleteButton/"><code>ionDeleteButton</code></a>, [`list CSS documentation`](/docs/components/#list).
<h2 id="usage">Usage</h2>
Basic Usage:
```html
<ion-list>
<ion-item ng-repeat="item in items">
{% raw %}Hello, {{item}}!{% endraw %}
</ion-item>
</ion-list>
```
Advanced Usage: Thumbnails, Delete buttons, Reordering, Swiping
```html
<ion-list ng-controller="MyCtrl"
show-delete="shouldShowDelete"
show-reorder="shouldShowReorder"
can-swipe="true">
<ion-item ng-repeat="item in items"
class="item-thumbnail-left">
{% raw %}<img ng-src="{{item.img}}">
<h2>{{item.title}}</h2>
<p>{{item.description}}</p>{% endraw %}
<ion-option-button class="button-positive"
ng-click="share(item)">
Share
</ion-option-button>
<ion-option-button class="button-info"
ng-click="edit(item)">
Edit
</ion-option-button>
<ion-delete-button class="ion-minus-circled"
ng-click="items.splice($index, 1)">
</ion-delete-button>
<ion-reorder-button class="ion-navicon"
on-reorder="reorderItem(item, $fromIndex, $toIndex)">
</ion-reorder-button>
</ion-item>
</ion-list>
```
<h2 id="api" style="clear:both;">API</h2>
<table class="table" style="margin:0;">
<thead>
<tr>
<th>Attr</th>
<th>Type</th>
<th>Details</th>
</tr>
</thead>
<tbody>
<tr>
<td>
delegate-handle
<div><em>(optional)</em></div>
</td>
<td>
<code>string</code>
</td>
<td>
<p>The handle used to identify this list with
<a href="/docs/api/service/$ionicListDelegate/"><code>$ionicListDelegate</code></a>.</p>
</td>
</tr>
<tr>
<td>
show-delete
<div><em>(optional)</em></div>
</td>
<td>
<code>boolean</code>
</td>
<td>
<p>Whether the delete buttons for the items in the list are
currently shown or hidden.</p>
</td>
</tr>
<tr>
<td>
show-reorder
<div><em>(optional)</em></div>
</td>
<td>
<code>boolean</code>
</td>
<td>
<p>Whether the reorder buttons for the items in the list are
currently shown or hidden.</p>
</td>
</tr>
<tr>
<td>
can-swipe
<div><em>(optional)</em></div>
</td>
<td>
<code>boolean</code>
</td>
<td>
<p>Whether the items in the list are allowed to be swiped to reveal
option buttons. Default: true.</p>
</td>
</tr>
</tbody>
</table>
| {
"content_hash": "f41847d97d65f02f5d5db754b464bc59",
"timestamp": "",
"source": "github",
"line_count": 204,
"max_line_length": 215,
"avg_line_length": 20.279411764705884,
"alnum_prop": 0.5975344452501813,
"repo_name": "matheusrocha89/ionic-site",
"id": "062d30240e44211add24526700735df2db891a5a",
"size": "4141",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/1.0.0-beta.8/api/directive/ionList/index.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "994486"
},
{
"name": "JavaScript",
"bytes": "1109062"
},
{
"name": "Shell",
"bytes": "1000"
}
],
"symlink_target": ""
} |
<HTML>
<HEAD>
<TITLE>3rd Party ROBOTC Drivers</TITLE>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</HEAD>
<BODY bgcolor="#ffffff" link="#000000" vlink="#000000">
<table width="100%" bgcolor="navy" cellspacing=0 cellpadding=1 border=0>
<tr><td><table width="100%" bgcolor="#EEEEDD" cellspacing=0 cellpadding=3 border=0>
<tr>
<td width="33%" align="left"> <img src="images/LOGO_NXT.gif" width=266 height=44 border="0" alt="Mindstorms"></td>
<td><b><font size="+3" color="navy">3rd Party ROBOTC Drivers</font></b></td>
<td align="right"> <img src="images/logo.png" width=44 height=44 border="0" alt="RobotC"></td>
</tr>
<tr bgcolor="#cccc99" align="right">
<td colspan=3> <font face="arial" size="-1"> [<a href=main.html>Home</a>] [<a target=_top href="https://sourceforge.net/projects/rdpartyrobotcdr/">Download</a>] [<a target=_top href="http://apps.sourceforge.net/mantisbt/rdpartyrobotcdr/my_view_page.php">Submit a bug/suggestion</a>] [<a target=_top href="http://www.robotc.net/forums/">ROBOTC Forums</a>] [<a target=_top href="http://botbench.com">Blog</a>] [<a target=_top href="http://sourceforge.net/donate/index.php?group_id=257238">Support this project</a>]</font> </td>
</tr>
</table></td></tr>
</table>
<!-- Generated by Doxygen 1.7.2 -->
<div class="header">
<div class="headertitle">
<h1>mindsensors-lineleader-test2.c</h1> </div>
</div>
<div class="contents">
<div class="fragment"><pre class="fragment"><span class="preprocessor">#pragma config(Sensor, S1, LLEADER, sensorI2CCustom9V)</span>
<span class="preprocessor"></span><span class="comment">//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//</span>
<span class="comment">/*</span>
<span class="comment"> * $Id: mindsensors-lineleader-test2.c 133 2013-03-10 15:15:38Z xander $</span>
<span class="comment"> */</span>
<span class="comment"></span>
<span class="comment">/**</span>
<span class="comment"> * mindsensors-lineleader.h provides an API for the Mindsensors LineLeader Sensor. This program</span>
<span class="comment"> * demonstrates how to use that API.</span>
<span class="comment"> *</span>
<span class="comment"> * Changelog:</span>
<span class="comment"> * - 0.1: Initial release</span>
<span class="comment"> * - 0.2: More comments</span>
<span class="comment"> *</span>
<span class="comment"> * Credits:</span>
<span class="comment"> * - Big thanks to Mindsensors for providing me with the hardware necessary to write and test this.</span>
<span class="comment"> *</span>
<span class="comment"> * License: You may use this code as you wish, provided you give credit where it's due.</span>
<span class="comment"> *</span>
<span class="comment"> * THIS CODE WILL ONLY WORK WITH ROBOTC VERSION 3.59 AND HIGHER. </span>
<span class="comment"></span>
<span class="comment"> * Xander Soldaat (xander_at_botbench.com)</span>
<span class="comment"> * 28 November 2009</span>
<span class="comment"> * version 0.2</span>
<span class="comment"> */</span>
<span class="preprocessor">#include "<a class="code" href="mindsensors-lineleader_8h.html" title="Mindsensors Line Tracking Sensor.">drivers/mindsensors-lineleader.h</a>"</span>
task main {
byte sensor = 0;
<a name="a0"></a><a class="code" href="group__common.html#gaa172ef131853460e5b9f5c6db81d30f4">tByteArray</a> signalstr;
<span class="keywordflow">while</span> (<span class="keyword">true</span>) {
<span class="comment">// Fetch the data from the sensor</span>
sensor = <a name="a1"></a><a class="code" href="group__msll.html#ga7dd78212c25b63c0349b8f4c61e11e1b">LLreadResult</a>(LLEADER);
<span class="comment">// Re75ad the raw sensor data (8 bit data)</span>
<a name="a2"></a><a class="code" href="group__msll.html#ga60491a411576c00b70909e1f295919db">LLreadSensorRaw</a>(LLEADER, signalstr);
<span class="comment">// This clears the entire area occupied by the small rectangles</span>
nxtEraseRect(6,62, 91, 43);
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i < 8; i++) {
<span class="comment">// Draw the rectangles for the signal strength first</span>
nxtDrawRect(6+(i*11),62, 14+(i*11), 50);
nxtFillRect(6+(i*11),51+signalstr[i]/10, 14+(i*11), 50);
<span class="comment">// Draw a black rectangle if the sensor has detected the line,</span>
<span class="comment">// a hollow one when nothing has been detected.</span>
<span class="keywordflow">if</span> ((sensor >> i) & 1) {
nxtFillRect(6+(i*11),48, 14+(i*11), 43);
} <span class="keywordflow">else</span> {
nxtDrawRect(6+(i*11),48, 14+(i*11), 43);
}
}
<span class="comment">// Display the actual signal strength for each sensor</span>
<span class="keywordflow">for</span> (<span class="keywordtype">int</span> i = 0; i < 7; i+=2) {
nxtDisplayTextLine(i/2+3, <span class="stringliteral">"S: %3d S: %3d"</span>, (<span class="keywordtype">int</span>)signalstr[i], (<span class="keywordtype">int</span>)signalstr[i+1]);
}
wait1Msec(50);
}
}
<span class="comment">/*</span>
<span class="comment"> * $Id: mindsensors-lineleader-test2.c 133 2013-03-10 15:15:38Z xander $</span>
<span class="comment"> */</span>
</pre></div> </div>
</div>
<hr class="footer"/><address class="footer"><small>Generated on Wed Mar 13 2013 19:56:42 for ROBOTC Drivers by 
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.2 </small></address>
</body>
</html>
| {
"content_hash": "b38af09e21cbecdb799f5ba2c770717d",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 537,
"avg_line_length": 58.01020408163265,
"alnum_prop": 0.6678979771328056,
"repo_name": "balthorium/coloradobots",
"id": "2db538c2c64cf85150cd5ae1aea9d4d41510dc29",
"size": "5685",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "rdpartyrobotcdr-3.3.1/html/mindsensors-lineleader-test2_8c-example.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "750274"
},
{
"name": "C++",
"bytes": "324704"
},
{
"name": "CSS",
"bytes": "11651"
},
{
"name": "Objective-C",
"bytes": "13886"
},
{
"name": "Python",
"bytes": "7957"
}
],
"symlink_target": ""
} |
//
// CHGTabItem.m
// CHGGridViewSample
//
// Created by Hogan on 2017/3/3.
// Copyright © 2017年 Hogan. All rights reserved.
//
#import "CHGTabItem.h"
@implementation CHGTabItem
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
+(id)initWithNibName:(NSString*) nibName {
NSArray * views = [[NSBundle mainBundle] loadNibNamed:nibName owner:nil options:nil];
id view = [views objectAtIndex:0];
// CHGGridViewCell * cell = (CHGGridViewCell*)view;
return view;
}
///此方法会返回当前tabitem需要的数据 如果子类重写此方法 需调用父类的方法,如果不调用则 data不能正确赋值
-(void)setItemData:(id)data position:(NSInteger)position {
self.position = position;
self.data = data;
}
/////当item被点击后此方法会被调用 selected == true 表示被调用, 此方法中写 item被选中后和选择前的变化
////-(void)setSelected_:(BOOL)selected {
////
////}
//-(void)setCurryItemSelected:(BOOL)curryItemSelected {
//
//}
///变化率
-(void)onTabScrollRateChange:(CGFloat)rateChange {
}
@end
| {
"content_hash": "bccfc1326a9c931ed0ba7d2830eb4f41",
"timestamp": "",
"source": "github",
"line_count": 47,
"max_line_length": 89,
"avg_line_length": 22.680851063829788,
"alnum_prop": 0.6979362101313321,
"repo_name": "chenhaigang888/CHGGridView",
"id": "8c47fb29eacefd9b9f743b5432da81db8561edcb",
"size": "1227",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CHGGridView/CHGTabPageView/CHGTabItem.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "86284"
}
],
"symlink_target": ""
} |
@ECHO OFF
REM Command file for Sphinx documentation
if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set BUILDDIR=build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source
set I18NSPHINXOPTS=%SPHINXOPTS% source
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^<target^>` where ^<target^> is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. singlehtml to make a single large HTML file
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. devhelp to make HTML files and a Devhelp project
echo. epub to make an epub
echo. epub3 to make an epub3
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. text to make text files
echo. man to make manual pages
echo. texinfo to make Texinfo files
echo. gettext to make PO message catalogs
echo. changes to make an overview over all changed/added/deprecated items
echo. xml to make Docutils-native XML files
echo. pseudoxml to make pseudoxml-XML files for display purposes
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
echo. coverage to run coverage check of the documentation if enabled
echo. dummy to check syntax errors of document sources
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
REM Check if sphinx-build is available and fallback to Python version if any
%SPHINXBUILD% 1>NUL 2>NUL
if errorlevel 9009 goto sphinx_python
goto sphinx_ok
:sphinx_python
set SPHINXBUILD=python -m sphinx.__init__
%SPHINXBUILD% 2> nul
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.http://sphinx-doc.org/
exit /b 1
)
:sphinx_ok
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "singlehtml" (
%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\qytz-notes.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\qytz-notes.ghc
goto end
)
if "%1" == "devhelp" (
%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
if errorlevel 1 exit /b 1
echo.
echo.Build finished.
goto end
)
if "%1" == "epub" (
%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub file is in %BUILDDIR%/epub.
goto end
)
if "%1" == "epub3" (
%SPHINXBUILD% -b epub3 %ALLSPHINXOPTS% %BUILDDIR%/epub3
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The epub3 file is in %BUILDDIR%/epub3.
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
if errorlevel 1 exit /b 1
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdf" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf
cd %~dp0
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "latexpdfja" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
cd %BUILDDIR%/latex
make all-pdf-ja
cd %~dp0
echo.
echo.Build finished; the PDF files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "text" (
%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The text files are in %BUILDDIR%/text.
goto end
)
if "%1" == "man" (
%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The manual pages are in %BUILDDIR%/man.
goto end
)
if "%1" == "texinfo" (
%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
goto end
)
if "%1" == "gettext" (
%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
if errorlevel 1 exit /b 1
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
if errorlevel 1 exit /b 1
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
if errorlevel 1 exit /b 1
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
if "%1" == "coverage" (
%SPHINXBUILD% -b coverage %ALLSPHINXOPTS% %BUILDDIR%/coverage
if errorlevel 1 exit /b 1
echo.
echo.Testing of coverage in the sources finished, look at the ^
results in %BUILDDIR%/coverage/python.txt.
goto end
)
if "%1" == "xml" (
%SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The XML files are in %BUILDDIR%/xml.
goto end
)
if "%1" == "pseudoxml" (
%SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml
if errorlevel 1 exit /b 1
echo.
echo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.
goto end
)
if "%1" == "dummy" (
%SPHINXBUILD% -b dummy %ALLSPHINXOPTS% %BUILDDIR%/dummy
if errorlevel 1 exit /b 1
echo.
echo.Build finished. Dummy builder generates no files.
goto end
)
:end
| {
"content_hash": "418016f3541b5e9c413c80818beb7a57",
"timestamp": "",
"source": "github",
"line_count": 281,
"max_line_length": 79,
"avg_line_length": 27.576512455516013,
"alnum_prop": 0.6785391663440444,
"repo_name": "qytz/qytz-notes",
"id": "f56d853972d93881979f382b08ec7a7e50d5b924",
"size": "7749",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "make.bat",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "15481"
},
{
"name": "Makefile",
"bytes": "15237"
},
{
"name": "Python",
"bytes": "23815"
}
],
"symlink_target": ""
} |
// Package docsnoretest contains a Prow plugin which manages a label indicating
// whether a given pull requests only changes documentation. In such cases it
// would not need to be retested.
package docsnoretest
import (
"fmt"
"path"
"regexp"
"k8s.io/test-infra/prow/github"
"k8s.io/test-infra/prow/pluginhelp"
"k8s.io/test-infra/prow/plugins"
)
const (
pluginName = "docs-no-retest"
labelSkipRetest = "retest-not-required-docs-only"
)
var (
docFilesRegex = regexp.MustCompile(`^.*\.(md|png|svg|dia)$`)
ownersFilesRegex = regexp.MustCompile(`^OWNERS$`)
licenseFilesRegex = regexp.MustCompile(`^LICENSE$`)
)
func init() {
plugins.RegisterPullRequestHandler(pluginName, handlePullRequest, helpProvider)
}
func helpProvider(config *plugins.Configuration, enabledRepos []string) (*pluginhelp.PluginHelp, error) {
// The {WhoCanUse, Usage, Examples, Config} fields are omitted because this plugin cannot be
// manually triggered and is not configurable.
return &pluginhelp.PluginHelp{
Description: `The docs-no-retest plugin applies the '` + labelSkipRetest + `' label to pull requests that only touch documentation type files and thus do not need to be retested against the latest master commit before merging.
<br>Files extensions '.md', '.png', '.svg', and '.dia' are considered documentation.`,
},
nil
}
func handlePullRequest(pc plugins.PluginClient, pe github.PullRequestEvent) error {
return handlePR(pc.GitHubClient, pe)
}
// Strict subset of *github.Client methods.
type githubClient interface {
AddLabel(owner, repo string, number int, label string) error
RemoveLabel(owner, repo string, number int, label string) error
GetIssueLabels(org, repo string, number int) ([]github.Label, error)
GetPullRequestChanges(org, repo string, number int) ([]github.PullRequestChange, error)
}
func handlePR(gc githubClient, pe github.PullRequestEvent) error {
var (
owner = pe.PullRequest.Base.Repo.Owner.Login
repo = pe.PullRequest.Base.Repo.Name
num = pe.PullRequest.Number
)
if pe.Action != github.PullRequestActionOpened &&
pe.Action != github.PullRequestActionReopened &&
pe.Action != github.PullRequestActionSynchronize {
return nil
}
changes, err := gc.GetPullRequestChanges(owner, repo, num)
if err != nil {
return fmt.Errorf("cannot get pull request changes for docs-no-retest plugin: %v", err)
}
docsOnly := true
for _, change := range changes {
_, basename := path.Split(change.Filename)
if docFilesRegex.MatchString(basename) {
continue
}
if ownersFilesRegex.MatchString(basename) {
continue
}
if licenseFilesRegex.MatchString(basename) {
continue
}
docsOnly = false
break
}
labels, err := gc.GetIssueLabels(owner, repo, num)
if err != nil {
return fmt.Errorf("cannot get labels for docs-no-retest plugin: %v", err)
}
hasTargetLabel := false
for _, label := range labels {
if label.Name == labelSkipRetest {
hasTargetLabel = true
break
}
}
if docsOnly && !hasTargetLabel {
if err := gc.AddLabel(owner, repo, num, labelSkipRetest); err != nil {
return fmt.Errorf("error adding label to %s/%s#%d: %v", owner, repo, num, err)
}
} else if !docsOnly && hasTargetLabel {
if err := gc.RemoveLabel(owner, repo, num, labelSkipRetest); err != nil {
return fmt.Errorf("error removing label from %s/%s#%d: %v", owner, repo, num, err)
}
}
return nil
}
| {
"content_hash": "999fb49d2de97a9f9b8d95e4f4e88b72",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 229,
"avg_line_length": 29.991150442477878,
"alnum_prop": 0.7208616110947182,
"repo_name": "foxish/test-infra",
"id": "f5fd49ba1b6fb11f275fd18534a6702a8cbbfdc3",
"size": "3958",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "prow/plugins/docs-no-retest/docs-no-retest.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "26680"
},
{
"name": "Go",
"bytes": "3516095"
},
{
"name": "HTML",
"bytes": "73212"
},
{
"name": "JavaScript",
"bytes": "207614"
},
{
"name": "Makefile",
"bytes": "61977"
},
{
"name": "Python",
"bytes": "958919"
},
{
"name": "Roff",
"bytes": "5462"
},
{
"name": "Shell",
"bytes": "96590"
},
{
"name": "Smarty",
"bytes": "516"
}
],
"symlink_target": ""
} |
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* AdditiveRegression.java
* Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.classifiers.meta;
import java.util.Enumeration;
import java.util.Vector;
import weka.classifiers.Classifier;
import weka.classifiers.IteratedSingleClassifierEnhancer;
import weka.classifiers.rules.ZeroR;
import weka.core.AdditionalMeasureProducer;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.TechnicalInformation;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
import weka.core.WeightedInstancesHandler;
/**
<!-- globalinfo-start -->
* Meta classifier that enhances the performance of a regression base classifier. Each iteration fits a model to the residuals left by the classifier on the previous iteration. Prediction is accomplished by adding the predictions of each classifier. Reducing the shrinkage (learning rate) parameter helps prevent overfitting and has a smoothing effect but increases the learning time.<br/>
* <br/>
* For more information see:<br/>
* <br/>
* J.H. Friedman (1999). Stochastic Gradient Boosting.
* <p/>
<!-- globalinfo-end -->
*
<!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @techreport{Friedman1999,
* author = {J.H. Friedman},
* institution = {Stanford University},
* title = {Stochastic Gradient Boosting},
* year = {1999},
* PS = {http://www-stat.stanford.edu/\~jhf/ftp/stobst.ps}
* }
* </pre>
* <p/>
<!-- technical-bibtex-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -S
* Specify shrinkage rate. (default = 1.0, ie. no shrinkage)
* </pre>
*
* <pre> -I <num>
* Number of iterations.
* (default 10)</pre>
*
* <pre> -D
* If set, classifier is run in debug mode and
* may output additional info to the console</pre>
*
* <pre> -W
* Full name of base classifier.
* (default: weka.classifiers.trees.DecisionStump)</pre>
*
* <pre>
* Options specific to classifier weka.classifiers.trees.DecisionStump:
* </pre>
*
* <pre> -D
* If set, classifier is run in debug mode and
* may output additional info to the console</pre>
*
<!-- options-end -->
*
* @author Mark Hall (mhall@cs.waikato.ac.nz)
* @version $Revision: 8034 $
*/
public class AdditiveRegression
extends IteratedSingleClassifierEnhancer
implements OptionHandler,
AdditionalMeasureProducer,
WeightedInstancesHandler,
TechnicalInformationHandler {
/** for serialization */
static final long serialVersionUID = -2368937577670527151L;
/**
* Shrinkage (Learning rate). Default = no shrinkage.
*/
protected double m_shrinkage = 1.0;
/** The number of successfully generated base classifiers. */
protected int m_NumIterationsPerformed;
/** The model for the mean */
protected ZeroR m_zeroR;
/** whether we have suitable data or nor (if not, ZeroR model is used) */
protected boolean m_SuitableData = true;
/**
* Returns a string describing this attribute evaluator
* @return a description of the evaluator suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return " Meta classifier that enhances the performance of a regression "
+"base classifier. Each iteration fits a model to the residuals left "
+"by the classifier on the previous iteration. Prediction is "
+"accomplished by adding the predictions of each classifier. "
+"Reducing the shrinkage (learning rate) parameter helps prevent "
+"overfitting and has a smoothing effect but increases the learning "
+"time.\n\n"
+"For more information see:\n\n"
+ getTechnicalInformation().toString();
}
/**
* Returns an instance of a TechnicalInformation object, containing
* detailed information about the technical background of this class,
* e.g., paper reference or book this class is based on.
*
* @return the technical information about this class
*/
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result;
result = new TechnicalInformation(Type.TECHREPORT);
result.setValue(Field.AUTHOR, "J.H. Friedman");
result.setValue(Field.YEAR, "1999");
result.setValue(Field.TITLE, "Stochastic Gradient Boosting");
result.setValue(Field.INSTITUTION, "Stanford University");
result.setValue(Field.PS, "http://www-stat.stanford.edu/~jhf/ftp/stobst.ps");
return result;
}
/**
* Default constructor specifying DecisionStump as the classifier
*/
public AdditiveRegression() {
this(new weka.classifiers.trees.DecisionStump());
}
/**
* Constructor which takes base classifier as argument.
*
* @param classifier the base classifier to use
*/
public AdditiveRegression(Classifier classifier) {
m_Classifier = classifier;
}
/**
* String describing default classifier.
*
* @return the default classifier classname
*/
protected String defaultClassifierString() {
return "weka.classifiers.trees.DecisionStump";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
public Enumeration listOptions() {
Vector newVector = new Vector(4);
newVector.addElement(new Option(
"\tSpecify shrinkage rate. "
+"(default = 1.0, ie. no shrinkage)\n",
"S", 1, "-S"));
Enumeration enu = super.listOptions();
while (enu.hasMoreElements()) {
newVector.addElement(enu.nextElement());
}
return newVector.elements();
}
/**
* Parses a given list of options. <p/>
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -S
* Specify shrinkage rate. (default = 1.0, ie. no shrinkage)
* </pre>
*
* <pre> -I <num>
* Number of iterations.
* (default 10)</pre>
*
* <pre> -D
* If set, classifier is run in debug mode and
* may output additional info to the console</pre>
*
* <pre> -W
* Full name of base classifier.
* (default: weka.classifiers.trees.DecisionStump)</pre>
*
* <pre>
* Options specific to classifier weka.classifiers.trees.DecisionStump:
* </pre>
*
* <pre> -D
* If set, classifier is run in debug mode and
* may output additional info to the console</pre>
*
<!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
public void setOptions(String[] options) throws Exception {
String optionString = Utils.getOption('S', options);
if (optionString.length() != 0) {
Double temp = Double.valueOf(optionString);
setShrinkage(temp.doubleValue());
}
super.setOptions(options);
}
/**
* Gets the current settings of the Classifier.
*
* @return an array of strings suitable for passing to setOptions
*/
public String [] getOptions() {
String [] superOptions = super.getOptions();
String [] options = new String [superOptions.length + 2];
int current = 0;
options[current++] = "-S"; options[current++] = "" + getShrinkage();
System.arraycopy(superOptions, 0, options, current,
superOptions.length);
current += superOptions.length;
while (current < options.length) {
options[current++] = "";
}
return options;
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String shrinkageTipText() {
return "Shrinkage rate. Smaller values help prevent overfitting and "
+ "have a smoothing effect (but increase learning time). "
+"Default = 1.0, ie. no shrinkage.";
}
/**
* Set the shrinkage parameter
*
* @param l the shrinkage rate.
*/
public void setShrinkage(double l) {
m_shrinkage = l;
}
/**
* Get the shrinkage rate.
*
* @return the value of the learning rate
*/
public double getShrinkage() {
return m_shrinkage;
}
/**
* Returns default capabilities of the classifier.
*
* @return the capabilities of this classifier
*/
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
// class
result.disableAllClasses();
result.disableAllClassDependencies();
result.enable(Capability.NUMERIC_CLASS);
result.enable(Capability.DATE_CLASS);
return result;
}
/**
* Build the classifier on the supplied data
*
* @param data the training data
* @throws Exception if the classifier could not be built successfully
*/
public void buildClassifier(Instances data) throws Exception {
super.buildClassifier(data);
// can classifier handle the data?
getCapabilities().testWithFail(data);
// remove instances with missing class
Instances newData = new Instances(data);
newData.deleteWithMissingClass();
double sum = 0;
double temp_sum = 0;
// Add the model for the mean first
m_zeroR = new ZeroR();
m_zeroR.buildClassifier(newData);
// only class? -> use only ZeroR model
if (newData.numAttributes() == 1) {
System.err.println(
"Cannot build model (only class attribute present in data!), "
+ "using ZeroR model instead!");
m_SuitableData = false;
return;
}
else {
m_SuitableData = true;
}
newData = residualReplace(newData, m_zeroR, false);
for (int i = 0; i < newData.numInstances(); i++) {
sum += newData.instance(i).weight() *
newData.instance(i).classValue() * newData.instance(i).classValue();
}
if (m_Debug) {
System.err.println("Sum of squared residuals "
+"(predicting the mean) : " + sum);
}
m_NumIterationsPerformed = 0;
do {
temp_sum = sum;
// Build the classifier
m_Classifiers[m_NumIterationsPerformed].buildClassifier(newData);
newData = residualReplace(newData, m_Classifiers[m_NumIterationsPerformed], true);
sum = 0;
for (int i = 0; i < newData.numInstances(); i++) {
sum += newData.instance(i).weight() *
newData.instance(i).classValue() * newData.instance(i).classValue();
}
if (m_Debug) {
System.err.println("Sum of squared residuals : "+sum);
}
m_NumIterationsPerformed++;
} while (((temp_sum - sum) > Utils.SMALL) &&
(m_NumIterationsPerformed < m_Classifiers.length));
}
/**
* Classify an instance.
*
* @param inst the instance to predict
* @return a prediction for the instance
* @throws Exception if an error occurs
*/
public double classifyInstance(Instance inst) throws Exception {
double prediction = m_zeroR.classifyInstance(inst);
// default model?
if (!m_SuitableData) {
return prediction;
}
for (int i = 0; i < m_NumIterationsPerformed; i++) {
double toAdd = m_Classifiers[i].classifyInstance(inst);
toAdd *= getShrinkage();
prediction += toAdd;
}
return prediction;
}
/**
* Replace the class values of the instances from the current iteration
* with residuals ater predicting with the supplied classifier.
*
* @param data the instances to predict
* @param c the classifier to use
* @param useShrinkage whether shrinkage is to be applied to the model's output
* @return a new set of instances with class values replaced by residuals
* @throws Exception if something goes wrong
*/
private Instances residualReplace(Instances data, Classifier c,
boolean useShrinkage) throws Exception {
double pred,residual;
Instances newInst = new Instances(data);
for (int i = 0; i < newInst.numInstances(); i++) {
pred = c.classifyInstance(newInst.instance(i));
if (useShrinkage) {
pred *= getShrinkage();
}
residual = newInst.instance(i).classValue() - pred;
newInst.instance(i).setClassValue(residual);
}
// System.err.print(newInst);
return newInst;
}
/**
* Returns an enumeration of the additional measure names
* @return an enumeration of the measure names
*/
public Enumeration enumerateMeasures() {
Vector newVector = new Vector(1);
newVector.addElement("measureNumIterations");
return newVector.elements();
}
/**
* Returns the value of the named measure
* @param additionalMeasureName the name of the measure to query for its value
* @return the value of the named measure
* @throws IllegalArgumentException if the named measure is not supported
*/
public double getMeasure(String additionalMeasureName) {
if (additionalMeasureName.compareToIgnoreCase("measureNumIterations") == 0) {
return measureNumIterations();
} else {
throw new IllegalArgumentException(additionalMeasureName
+ " not supported (AdditiveRegression)");
}
}
/**
* return the number of iterations (base classifiers) completed
* @return the number of iterations (same as number of base classifier
* models)
*/
public double measureNumIterations() {
return m_NumIterationsPerformed;
}
/**
* Returns textual description of the classifier.
*
* @return a description of the classifier as a string
*/
public String toString() {
StringBuffer text = new StringBuffer();
// only ZeroR model?
if (!m_SuitableData) {
StringBuffer buf = new StringBuffer();
buf.append(this.getClass().getName().replaceAll(".*\\.", "") + "\n");
buf.append(this.getClass().getName().replaceAll(".*\\.", "").replaceAll(".", "=") + "\n\n");
buf.append("Warning: No model could be built, hence ZeroR model is used:\n\n");
buf.append(m_zeroR.toString());
return buf.toString();
}
if (m_NumIterations == 0) {
return "Classifier hasn't been built yet!";
}
text.append("Additive Regression\n\n");
text.append("ZeroR model\n\n" + m_zeroR + "\n\n");
text.append("Base classifier "
+ getClassifier().getClass().getName()
+ "\n\n");
text.append("" + m_NumIterationsPerformed + " models generated.\n");
for (int i = 0; i < m_NumIterationsPerformed; i++) {
text.append("\nModel number " + i + "\n\n" +
m_Classifiers[i] + "\n");
}
return text.toString();
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision: 8034 $");
}
/**
* Main method for testing this class.
*
* @param argv should contain the following arguments:
* -t training file [-T test file] [-c class index]
*/
public static void main(String [] argv) {
runClassifier(new AdditiveRegression(), argv);
}
}
| {
"content_hash": "4f1a0b673b7b5a1ad8c12d2d4cfd9657",
"timestamp": "",
"source": "github",
"line_count": 535,
"max_line_length": 389,
"avg_line_length": 29.357009345794392,
"alnum_prop": 0.6640774226410289,
"repo_name": "tdelev/MULLAN",
"id": "c68b1770611bf653970118dab062a434a093b37b",
"size": "15706",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "MULLANWrappers/src/weka/classifiers/meta/AdditiveRegression.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "13900418"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html ng-app="demoapp">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="../bower_components/angular/angular.min.js"></script>
<script src="../bower_components/leaflet/dist/leaflet.js"></script>
<script src="../bower_components/leaflet-plugins/layer/Marker.Rotate.js"></script>
<script src="../dist/angular-leaflet-directive.min.js"></script>
<link rel="stylesheet" href="../bower_components/leaflet/dist/leaflet.css" />
<script>
var app = angular.module("demoapp", ["leaflet-directive"]);
app.controller('MarkersRotationController', [ '$scope', function($scope) {
var markers = {
m1: {
lat: 41.95,
lng: -87.65,
message: "I'm a static marker at 0 degrees",
focus: false,
iconAngle: 0
},
m2: {
lat: 41.85,
lng: -87.95,
message: "I'm a static marker at 270 degrees",
focus: false,
iconAngle: 270
},
m3: {
lat: 41.85,
lng: -87.05,
message: "I'm a static marker at 90 degrees",
focus: false,
iconAngle: 90
},
m4: {
lat: 41.35,
lng: -87.65,
message: "I'm a static marker at 180 degrees",
focus: false,
iconAngle: 180
}
};
angular.extend($scope, {
chicago: {
lat: 41.85,
lng: -87.65,
zoom: 8
},
markers: markers
});
} ]);
</script>
</head>
<body ng-controller="MarkersRotationController">
<leaflet lf-center="chicago" markers="markers" height="480px" width="100%"></leaflet>
<h1>Changing Icon Rotation</h1>
</div>
</body>
</html>
| {
"content_hash": "10300f77cf78fbeb34630e018afdef2e",
"timestamp": "",
"source": "github",
"line_count": 60,
"max_line_length": 91,
"avg_line_length": 37.71666666666667,
"alnum_prop": 0.4206805125939019,
"repo_name": "vomc/csr-mapping-engine",
"id": "23399e81e2dd69380a52c885130c954e2fd39919",
"size": "2263",
"binary": false,
"copies": "6",
"ref": "refs/heads/master",
"path": "leaflet_amman_backup/node_modules/angular-leaflet-directive/examples/0507-markers-rotation-example.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "34432"
},
{
"name": "HTML",
"bytes": "68823"
},
{
"name": "JavaScript",
"bytes": "77130"
}
],
"symlink_target": ""
} |
package monix.catnap
package cancelables
import cats.effect.IO
import minitest.SimpleTestSuite
object BooleanCancelableFSuite extends SimpleTestSuite {
test("apply") {
var effect = 0
val task = IO { effect += 1 }
val ref = BooleanCancelableF[IO](task)
val cf = ref.unsafeRunSync()
assert(!cf.isCanceled.unsafeRunSync(), "!cf.isCanceled")
assertEquals(effect, 0)
cf.cancel.unsafeRunSync()
assert(cf.isCanceled.unsafeRunSync(), "cf.isCanceled")
assertEquals(effect, 1)
cf.cancel.unsafeRunSync()
assert(cf.isCanceled.unsafeRunSync(), "cf.isCanceled")
assertEquals(effect, 1)
// Referential transparency test
val cf2 = ref.unsafeRunSync()
assert(!cf2.isCanceled.unsafeRunSync(), "!cf2.isCanceled")
assertEquals(effect, 1)
cf2.cancel.unsafeRunSync()
assert(cf2.isCanceled.unsafeRunSync(), "cf2.isCanceled")
assertEquals(effect, 2)
cf2.cancel.unsafeRunSync()
assert(cf2.isCanceled.unsafeRunSync(), "cf2.isCanceled")
assertEquals(effect, 2)
}
test("alreadyCanceled") {
val cf = BooleanCancelableF.alreadyCanceled[IO]
assert(cf.isCanceled.unsafeRunSync(), "cf.isCanceled")
cf.cancel.unsafeRunSync()
cf.cancel.unsafeRunSync()
assert(cf.isCanceled.unsafeRunSync(), "cf.isCanceled")
}
test("dummy") {
val cf = BooleanCancelableF.dummy[IO]
assert(!cf.isCanceled.unsafeRunSync(), "!cf.isCanceled")
cf.cancel.unsafeRunSync()
cf.cancel.unsafeRunSync()
assert(!cf.isCanceled.unsafeRunSync(), "!cf.isCanceled")
}
}
| {
"content_hash": "29ad92d15f1ccb3f83d6f44285c5c698",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 62,
"avg_line_length": 29.73076923076923,
"alnum_prop": 0.703104786545925,
"repo_name": "monixio/monix",
"id": "97e0caad55479725793d942d9037b9b883d05297",
"size": "2219",
"binary": false,
"copies": "2",
"ref": "refs/heads/series/4.x",
"path": "monix-catnap/shared/src/test/scala/monix/catnap/cancelables/BooleanCancelableFSuite.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "108987"
},
{
"name": "Scala",
"bytes": "2315190"
},
{
"name": "Shell",
"bytes": "2950"
}
],
"symlink_target": ""
} |
@interface ETTopAlignedLabel : UILabel
@end
| {
"content_hash": "fd4dc8b25e78d20cb4d220daa1fc1f6a",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 38,
"avg_line_length": 15,
"alnum_prop": 0.8,
"repo_name": "iosttpl/TTPLLibrary",
"id": "ca63c83eaa2d9fe9349713bf5b46b84045885286",
"size": "215",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "Example/Categories/ETTopAlignedLabel.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "138915"
},
{
"name": "Ruby",
"bytes": "1460"
}
],
"symlink_target": ""
} |
package com.huawei.esdk.fusionmanager.local.model.common;
import com.huawei.esdk.fusionmanager.local.model.FMSDKResponse;
/**
* 操作可用分区,当前支持恢复使用、暂停使用返回消息。
*
* @since eSDK Cloud V100R003C30
*/
public class ActionAvailableZoneResp extends FMSDKResponse
{
}
| {
"content_hash": "6f995ce2d7845c0a560cd0048db13af8",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 63,
"avg_line_length": 20.46153846153846,
"alnum_prop": 0.7706766917293233,
"repo_name": "eSDK/esdk_cloud_fm_r3_native_java",
"id": "053ca11dd7af1771518f2ee11448ca3d137d1f4d",
"size": "316",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "source/FM/V1R5/esdk_fm_neadp_1.5_native_java/src/main/java/com/huawei/esdk/fusionmanager/local/model/common/ActionAvailableZoneResp.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "66248"
},
{
"name": "HTML",
"bytes": "464839"
},
{
"name": "Java",
"bytes": "7087779"
},
{
"name": "JavaScript",
"bytes": "417865"
}
],
"symlink_target": ""
} |
<?php
namespace Cacic\CommonBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Cacic\CommonBundle\Entity\Acao;
use Cacic\CommonBundle\Entity\AcaoRede;
use Cacic\CommonBundle\Entity\AcaoSo;
use Cacic\CommonBundle\Entity\AcaoExcecao;
use Doctrine\Common\Util\Debug;
class ModuloController extends Controller
{
/**
*
* Tela de exibição dos módulos do CACIC
*/
public function indexAction()
{
$usuario = $this->getUser()->getIdUsuario();
$nivel = $this->getDoctrine()->getRepository('CacicCommonBundle:Usuario' )->nivel($usuario);
$local = $this->getUser()->getIdLocal(); // Recupera o Local da sessão do usuário logado
$modulos = $this->getDoctrine()->getRepository('CacicCommonBundle:Acao')->listarModulosOpcionais( $nivel, $local->getIdLocal() );
$totalRedes = $this->getDoctrine()->getRepository('CacicCommonBundle:Rede')->countByLocal( $local->getIdLocal() );
//Debug::dump($modulos);die;
return $this->render(
'CacicCommonBundle:Modulo:index.html.twig',
array('modulos'=>$modulos, 'local'=>$local, 'totalRedes'=>$totalRedes)
);
}
/**
*
* Tela de configuração do módulo informado
* @todo Verificar padrão de codificação do Symfony
* @param int $idAcao
* @param Request $request
*/
public function editarAction( $idAcao, Request $request )
{
$usuario = $this->getUser()->getIdUsuario();
$nivel = $this->getDoctrine()->getRepository('CacicCommonBundle:Usuario' )->nivel($usuario);
$modulo = $this->getDoctrine()->getRepository( 'CacicCommonBundle:Acao' )->find( $idAcao );
if ( ! $modulo )
throw $this->createNotFoundException( 'Página não encontrada' );
if($nivel[0]['teGrupoUsuarios'] != "Administração")
{
$local = $this->getUser()->getIdLocal(); /* @todo Em caso de usuário administrativo, escolher o Local */
$redes = $this->getDoctrine()->getRepository( 'CacicCommonBundle:Rede' )->listarPorLocal( $local );
}else
{
$local = $this->getDoctrine()->getManager()->getRepository('CacicCommonBundle:Local')->findAll();
$redes = $this->getDoctrine()->getRepository( 'CacicCommonBundle:Rede' )->listarPorLocalADM();
}
if ( $request->isMethod('POST') )
{
$_data = $request->get('modulo');
$novasRedes = array_key_exists( 'rede', $_data ) ? $_data['rede'] : array();
$this->getDoctrine()->getRepository( 'CacicCommonBundle:AcaoRede' )->atualizarPorLocal( $idAcao, $local, $novasRedes );
// if ( $novasRedes )
// throw $this->createNotFoundException( 'Subrede não encontrado' );
$novosSO = array_key_exists( 'so', $_data ) ? $_data['so'] : array();
$this->getDoctrine()->getRepository( 'CacicCommonBundle:AcaoSo' )->atualizarPorLocal( $idAcao, $local, $novasRedes, $novosSO );
// if ( $novosSO )
// throw $this->createNotFoundException( 'Subrede não encontrado' );
$novasExcecoes = array_key_exists( 'mac', $_data ) ? explode(',', $_data['mac'] ) : array();
$this->getDoctrine()->getRepository( 'CacicCommonBundle:AcaoExcecao' )->atualizarPorLocal( $idAcao, $local, $novasRedes, $novasExcecoes );
$this->get('session')->getFlashBag()->add('success', 'Dados salvos com sucesso!');
return $this->redirect( $this->generateUrl( 'cacic_modulo_editar', array('idAcao'=>$idAcao) ) );
}
$so = $this->getDoctrine()->getRepository( 'CacicCommonBundle:So' )->listar(); // Recupera a lista de SOs cadastrados
$redesSelecionadas = array_keys( // Recupera as Redes já associadas à Ação
$this->getDoctrine()->getRepository( 'CacicCommonBundle:AcaoRede' )->getArrayChaveValorRedesPorAcao( $idAcao )
);
$soSelecionados = array_keys( // Recupera os SOs já associados à Ação
$this->getDoctrine()->getRepository( 'CacicCommonBundle:AcaoSo' )->getArrayChaveValorSoPorAcao( $idAcao )
);
$excecoes = $this->getDoctrine()->getRepository( 'CacicCommonBundle:AcaoExcecao' )->getArrayExcecoesPorAcao( $idAcao ); // Recupera a lista de excecoes
return $this->render(
'CacicCommonBundle:Modulo:editar.html.twig',
array(
'modulo' => $modulo,
'redes' => $redes,
'so' => $so,
'redesSelecionadas' => $redesSelecionadas,
'soSelecionados' => $soSelecionados,
'excecoesCadastradas' => $excecoes
)
);
}
}
| {
"content_hash": "837133475f8f15fcaafc9c48b7e788b0",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 153,
"avg_line_length": 39,
"alnum_prop": 0.6657590197413207,
"repo_name": "davialcantara/gerente",
"id": "fa9f2562048b1fb15858143b3f6ea7d7aebec8d2",
"size": "4433",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Cacic/CommonBundle/Controller/ModuloController.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "15796"
},
{
"name": "CSS",
"bytes": "987291"
},
{
"name": "CoffeeScript",
"bytes": "97304"
},
{
"name": "Erlang",
"bytes": "7427"
},
{
"name": "Go",
"bytes": "31652"
},
{
"name": "JavaScript",
"bytes": "3188958"
},
{
"name": "PHP",
"bytes": "1102012"
},
{
"name": "Perl",
"bytes": "37131"
},
{
"name": "Python",
"bytes": "10791"
},
{
"name": "Shell",
"bytes": "11554"
}
],
"symlink_target": ""
} |
<?php
#**************************************************************************
# openSIS is a free student information system for public and non-public
# schools from Open Solutions for Education, Inc. web: www.os4ed.com
#
# openSIS is web-based, open source, and comes packed with features that
# include student demographic info, scheduling, grade book, attendance,
# report cards, eligibility, transcripts, parent portal,
# student portal and more.
#
# Visit the openSIS web site at http://www.opensis.com to learn more.
# If you have question regarding this system or the license, please send
# an email to info@os4ed.com.
#
# This program is released under the terms of the GNU General Public License as
# published by the Free Software Foundation, version 2 of the License.
# See license.txt.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#***************************************************************************************
//error_reporting(1);
function HackingLog()
{
echo "You're not allowed to use this program! This attempted violation has been logged and your IP address was captured.";
Warehouse('footer');
if ($_SERVER['HTTP_X_FORWARDED_FOR']){
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
if($openSISNotifyAddress)
mail($openSISNotifyAddress,'HACKING ATTEMPT',"INSERT INTO hacking_log (HOST_NAME,IP_ADDRESS,LOGIN_DATE,VERSION,PHP_SELF,DOCUMENT_ROOT,SCRIPT_NAME,MODNAME,USERNAME) values('$_SERVER[SERVER_NAME]','$ip','".date('Y-m-d')."','$openSISVersion','$_SERVER[PHP_SELF]','$_SERVER[DOCUMENT_ROOT]','$_SERVER[SCRIPT_NAME]','$_REQUEST[modname]','".User('USERNAME')."')");
/*if($openSISNotifyAddress)
mail($openSISNotifyAddress,'HACKING ATTEMPT',"INSERT INTO hacking_log (HOST_NAME,IP_ADDRESS,LOGIN_DATE,VERSION,PHP_SELF,DOCUMENT_ROOT,SCRIPT_NAME,MODNAME,USERNAME) values('$_SERVER[SERVER_NAME]','$_SERVER[REMOTE_ADDR]','".date('Y-m-d')."','$openSISVersion','$_SERVER[PHP_SELF]','$_SERVER[DOCUMENT_ROOT]','$_SERVER[SCRIPT_NAME]','$_REQUEST[modname]','".User('USERNAME')."')");*/
if(false && function_exists('mysql_query'))
{
if ($_SERVER['HTTP_X_FORWARDED_FOR']){
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
$link = @mysql_connect('os4ed.com','openSIS_log','openSIS_log');
@mysql_select_db('openSIS_log');
@mysql_query('INSERT INTO hacking_log (HOST_NAME,IP_ADDRESS,LOGIN_DATE,VERSION,PHP_SELF,DOCUMENT_ROOT,SCRIPT_NAME,MODNAME,USERNAME) values(\''.$_SERVER[SERVER_NAME].'\',\''.$ip.'\',\''.date('Y-m-d').'\',\''.$openSISVersion.'\',\''.$_SERVER[PHP_SELF].'\',\''.$_SERVER[DOCUMENT_ROOT].'\',\''.$_SERVER[SCRIPT_NAME].'\',\''.$_REQUEST[modname].'\',\''.User('USERNAME').'\')');
@mysql_close($link);
/*$link = @mysql_connect('os4ed.com','openSIS_log','openSIS_log');
@mysql_select_db('openSIS_log');
@mysql_query("INSERT INTO hacking_log (HOST_NAME,IP_ADDRESS,LOGIN_DATE,VERSION,PHP_SELF,DOCUMENT_ROOT,SCRIPT_NAME,MODNAME,USERNAME) values('$_SERVER[SERVER_NAME]','$_SERVER[REMOTE_ADDR]','".date('Y-m-d')."','$openSISVersion','$_SERVER[PHP_SELF]','$_SERVER[DOCUMENT_ROOT]','$_SERVER[SCRIPT_NAME]','$_REQUEST[modname]','".User('USERNAME')."')");
@mysql_close($link);*/
}
}
?> | {
"content_hash": "e2a915db6d2874a1c4c9becc338e8b04",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 381,
"avg_line_length": 54.455882352941174,
"alnum_prop": 0.638131244936538,
"repo_name": "shamim8888/SMSlib-ParallelPort",
"id": "2e2efc5bcfc3ec12894d43c70040f780bbb46258",
"size": "3703",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "opensis1/functions/HackingLog.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "32369"
},
{
"name": "CSS",
"bytes": "377271"
},
{
"name": "Java",
"bytes": "1596773"
},
{
"name": "JavaScript",
"bytes": "958712"
},
{
"name": "Makefile",
"bytes": "504"
},
{
"name": "PHP",
"bytes": "9860477"
},
{
"name": "Perl",
"bytes": "41696"
},
{
"name": "Ruby",
"bytes": "88985"
},
{
"name": "Rust",
"bytes": "101"
},
{
"name": "Scala",
"bytes": "362"
},
{
"name": "Shell",
"bytes": "23973"
}
],
"symlink_target": ""
} |
import json
from mock import patch
from onadata.apps.api.tests.viewsets.test_abstract_viewset import\
TestAbstractViewSet
from onadata.apps.api.viewsets.user_profile_viewset import UserProfileViewSet
from onadata.apps.main.models import UserProfile
from django.contrib.auth.models import User
from onadata.libs.serializers.user_profile_serializer import (
_get_first_last_names
)
def _profile_data():
return {
'username': u'deno',
'first_name': u'Dennis',
'last_name': u'erama',
'email': u'deno@columbia.edu',
'city': u'Denoville',
'country': u'US',
'organization': u'Dono Inc.',
'website': u'deno.com',
'twitter': u'denoerama',
'require_auth': False,
'password': 'denodeno',
'is_org': False,
'name': u'Dennis erama'
}
class TestUserProfileViewSet(TestAbstractViewSet):
def setUp(self):
super(self.__class__, self).setUp()
self.view = UserProfileViewSet.as_view({
'get': 'list',
'post': 'create',
'patch': 'partial_update',
'put': 'update'
})
def test_profiles_list(self):
request = self.factory.get('/', **self.extra)
response = self.view(request)
self.assertNotEqual(response.get('Last-Modified'), None)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data, [self.user_profile_data()])
def test_profiles_get(self):
"""Test get user profile"""
view = UserProfileViewSet.as_view({
'get': 'retrieve'
})
request = self.factory.get('/', **self.extra)
response = view(request)
self.assertEqual(response.status_code, 400)
self.assertEqual(
response.data, {'detail': 'Expected URL keyword argument `user`.'})
# by username
response = view(request, user='bob')
self.assertNotEqual(response.get('Last-Modified'), None)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data, self.user_profile_data())
# by pk
response = view(request, user=self.user.pk)
self.assertNotEqual(response.get('Last-Modified'), None)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data, self.user_profile_data())
def test_profiles_get_anon(self):
view = UserProfileViewSet.as_view({
'get': 'retrieve'
})
request = self.factory.get('/')
response = view(request)
self.assertEqual(response.status_code, 400)
self.assertEqual(
response.data, {'detail': 'Expected URL keyword argument `user`.'})
request = self.factory.get('/')
response = view(request, user='bob')
data = self.user_profile_data()
del data['email']
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data, data)
self.assertNotIn('email', response.data)
def test_profiles_get_org_anon(self):
self._org_create()
self.client.logout()
view = UserProfileViewSet.as_view({
'get': 'retrieve'
})
request = self.factory.get('/')
response = view(request, user=self.company_data['org'])
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data['first_name'],
self.company_data['name'])
self.assertIn('is_org', response.data)
self.assertEqual(response.data['is_org'], True)
def test_profile_create(self):
request = self.factory.get('/', **self.extra)
response = self.view(request)
self.assertEqual(response.status_code, 200)
data = _profile_data()
del data['name']
request = self.factory.post(
'/api/v1/profiles', data=json.dumps(data),
content_type="application/json", **self.extra)
response = self.view(request)
self.assertEqual(response.status_code, 201)
del data['password']
profile = UserProfile.objects.get(user__username=data['username'])
data['id'] = profile.user.pk
data['gravatar'] = profile.gravatar
data['url'] = 'http://testserver/api/v1/profiles/deno'
data['user'] = 'http://testserver/api/v1/users/deno'
data['metadata'] = {}
data['joined_on'] = profile.user.date_joined
data['name'] = "%s %s" % ('Dennis', 'erama')
self.assertEqual(response.data, data)
user = User.objects.get(username='deno')
self.assertTrue(user.is_active)
def test_profile_create_anon(self):
data = _profile_data()
request = self.factory.post(
'/api/v1/profiles', data=json.dumps(data),
content_type="application/json")
response = self.view(request)
self.assertEqual(response.status_code, 201)
del data['password']
del data['email']
profile = UserProfile.objects.get(user__username=data['username'])
data['id'] = profile.user.pk
data['gravatar'] = profile.gravatar
data['url'] = 'http://testserver/api/v1/profiles/deno'
data['user'] = 'http://testserver/api/v1/users/deno'
data['metadata'] = {}
data['joined_on'] = profile.user.date_joined
self.assertEqual(response.data, data)
self.assertNotIn('email', response.data)
def test_profile_create_missing_name_field(self):
request = self.factory.get('/', **self.extra)
response = self.view(request)
self.assertEqual(response.status_code, 200)
data = _profile_data()
del data['first_name']
del data['name']
request = self.factory.post(
'/api/v1/profiles', data=json.dumps(data),
content_type="application/json", **self.extra)
response = self.view(request)
response.render()
self.assertContains(response,
'Either name or first_name should be provided',
status_code=400)
def test_split_long_name_to_first_name_and_last_name(self):
name = "(CPLTGL) Centre Pour la Promotion de la Liberte D'Expression "\
"et de la Tolerance Dans La Region de"
first_name, last_name = _get_first_last_names(name)
self.assertEqual(first_name, "(CPLTGL) Centre Pour la Promot")
self.assertEqual(last_name, "ion de la Liberte D'Expression")
def test_partial_updates(self):
self.assertEqual(self.user.profile.country, u'US')
country = u'KE'
metadata = {u'computer': u'mac'}
json_metadata = json.dumps(metadata)
data = {'country': country, 'metadata': json_metadata}
request = self.factory.patch('/', data=data, **self.extra)
response = self.view(request, user=self.user.username)
profile = UserProfile.objects.get(user=self.user)
self.assertEqual(response.status_code, 200)
self.assertEqual(profile.country, country)
self.assertEqual(profile.metadata, metadata)
def test_partial_update_metadata_field(self):
metadata = {u"zebra": {u"key1": "value1", u"key2": "value2"}}
json_metadata = json.dumps(metadata)
data = {
'metadata': json_metadata,
}
request = self.factory.patch('/', data=data, **self.extra)
response = self.view(request, user=self.user.username)
profile = UserProfile.objects.get(user=self.user)
self.assertEqual(response.status_code, 200)
self.assertEqual(profile.metadata, metadata)
# create a new key/value object if it doesn't exist
data = {
'metadata': '{"zebra": {"key3": "value3"}}',
'overwrite': u'false'
}
request = self.factory.patch('/', data=data, **self.extra)
response = self.view(request, user=self.user.username)
profile = UserProfile.objects.get(user=self.user)
self.assertEqual(response.status_code, 200)
self.assertEqual(
profile.metadata, {u"zebra": {
u"key1": "value1", u"key2": "value2", u"key3": "value3"}})
# update an existing key/value object
data = {
'metadata': '{"zebra": {"key2": "second"}}', 'overwrite': u'false'}
request = self.factory.patch('/', data=data, **self.extra)
response = self.view(request, user=self.user.username)
profile = UserProfile.objects.get(user=self.user)
self.assertEqual(response.status_code, 200)
self.assertEqual(
profile.metadata, {u"zebra": {
u"key1": "value1", u"key2": "second", u"key3": "value3"}})
# add a new key/value object if the key doesn't exist
data = {
'metadata': '{"animal": "donkey"}', 'overwrite': u'false'}
request = self.factory.patch('/', data=data, **self.extra)
response = self.view(request, user=self.user.username)
profile = UserProfile.objects.get(user=self.user)
self.assertEqual(response.status_code, 200)
self.assertEqual(
profile.metadata, {
u"zebra": {
u"key1": "value1", u"key2": "second", u"key3": "value3"},
u'animal': u'donkey'})
# don't pass overwrite param
data = {'metadata': '{"b": "caah"}'}
request = self.factory.patch('/', data=data, **self.extra)
response = self.view(request, user=self.user.username)
profile = UserProfile.objects.get(user=self.user)
self.assertEqual(response.status_code, 200)
self.assertEqual(
profile.metadata, {u'b': u'caah'})
# pass 'overwrite' param whose value isn't false
data = {'metadata': '{"b": "caah"}', 'overwrite': u'falsey'}
request = self.factory.patch('/', data=data, **self.extra)
response = self.view(request, user=self.user.username)
profile = UserProfile.objects.get(user=self.user)
self.assertEqual(response.status_code, 200)
self.assertEqual(
profile.metadata, {u'b': u'caah'})
def test_put_update(self):
data = _profile_data()
# create profile
request = self.factory.post(
'/api/v1/profiles', data=json.dumps(data),
content_type="application/json", **self.extra)
response = self.view(request)
self.assertEqual(response.status_code, 201)
# edit username with existing different user's username
data['username'] = 'bob'
request = self.factory.put(
'/api/v1/profiles', data=json.dumps(data),
content_type="application/json", **self.extra)
response = self.view(request, user='deno')
self.assertEqual(response.status_code, 400)
# update
data['username'] = 'roger'
data['city'] = 'Nairobi'
request = self.factory.put(
'/api/v1/profiles', data=json.dumps(data),
content_type="application/json", **self.extra)
response = self.view(request, user='deno')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data['city'], data['city'])
def test_profile_create_mixed_case(self):
request = self.factory.get('/', **self.extra)
response = self.view(request)
self.assertEqual(response.status_code, 200)
data = _profile_data()
request = self.factory.post(
'/api/v1/profiles', data=json.dumps(data),
content_type="application/json", **self.extra)
response = self.view(request)
self.assertEqual(response.status_code, 201)
del data['password']
profile = UserProfile.objects.get(
user__username=data['username'].lower())
data['id'] = profile.user.pk
data['gravatar'] = unicode(profile.gravatar)
data['url'] = 'http://testserver/api/v1/profiles/deno'
data['user'] = 'http://testserver/api/v1/users/deno'
data['username'] = u'deno'
data['metadata'] = {}
data['joined_on'] = profile.user.date_joined
self.assertEqual(response.data, data)
data['username'] = u'deno'
data['joined_on'] = str(profile.user.date_joined)
request = self.factory.post(
'/api/v1/profiles', data=json.dumps(data),
content_type="application/json", **self.extra)
response = self.view(request)
self.assertEqual(response.status_code, 400)
self.assertIn("%s already exists" %
data['username'], response.data['username'])
def test_change_password(self):
view = UserProfileViewSet.as_view(
{'post': 'change_password'})
current_password = "bobbob"
new_password = "bobbob1"
post_data = {'current_password': current_password,
'new_password': new_password}
request = self.factory.post('/', data=post_data, **self.extra)
response = view(request, user='bob')
user = User.objects.get(username__iexact=self.user.username)
self.assertEqual(response.status_code, 200)
self.assertTrue(user.check_password(new_password))
def test_change_password_wrong_current_password(self):
view = UserProfileViewSet.as_view(
{'post': 'change_password'})
current_password = "wrong_pass"
new_password = "bobbob1"
post_data = {'current_password': current_password,
'new_password': new_password}
request = self.factory.post('/', data=post_data, **self.extra)
response = view(request, user='bob')
user = User.objects.get(username__iexact=self.user.username)
self.assertEqual(response.status_code, 400)
self.assertFalse(user.check_password(new_password))
def test_profile_create_with_name(self):
data = {
'username': u'deno',
'name': u'Dennis deno',
'email': u'deno@columbia.edu',
'city': u'Denoville',
'country': u'US',
'organization': u'Dono Inc.',
'website': u'deno.com',
'twitter': u'denoerama',
'require_auth': False,
'password': 'denodeno',
'is_org': False,
}
request = self.factory.post(
'/api/v1/profiles', data=json.dumps(data),
content_type="application/json", **self.extra)
response = self.view(request)
self.assertEqual(response.status_code, 201)
del data['password']
profile = UserProfile.objects.get(user__username=data['username'])
data['id'] = profile.user.pk
data['first_name'] = 'Dennis'
data['last_name'] = 'deno'
data['gravatar'] = profile.gravatar
data['url'] = 'http://testserver/api/v1/profiles/deno'
data['user'] = 'http://testserver/api/v1/users/deno'
data['metadata'] = {}
data['joined_on'] = profile.user.date_joined
self.assertEqual(response.data, data)
user = User.objects.get(username='deno')
self.assertTrue(user.is_active)
def test_twitter_username_validation(self):
data = {
'username': u'deno',
'name': u'Dennis deno',
'email': u'deno@columbia.edu',
'city': u'Denoville',
'country': u'US',
'organization': u'Dono Inc.',
'website': u'deno.com',
'twitter': u'denoerama',
'require_auth': False,
'password': 'denodeno',
'is_org': False,
}
request = self.factory.post(
'/api/v1/profiles', data=json.dumps(data),
content_type="application/json", **self.extra)
response = self.view(request)
self.assertEqual(response.status_code, 201)
data['twitter'] = 'denoerama'
data = {
'username': u'deno',
'name': u'Dennis deno',
'email': u'deno@columbia.edu',
'city': u'Denoville',
'country': u'US',
'organization': u'Dono Inc.',
'website': u'deno.com',
'twitter': u'denoeramaddfsdsl8729320392ujijdswkp--22kwklskdsjs',
'require_auth': False,
'password': 'denodeno',
'is_org': False,
}
request = self.factory.post(
'/api/v1/profiles', data=json.dumps(data),
content_type="application/json", **self.extra)
response = self.view(request)
self.assertEqual(response.status_code, 400)
self.assertEqual(response.data['twitter'],
[u'Invalid twitter username'])
user = User.objects.get(username='deno')
self.assertTrue(user.is_active)
def test_put_patch_method_on_names(self):
data = _profile_data()
# create profile
request = self.factory.post(
'/api/v1/profiles', data=json.dumps(data),
content_type="application/json", **self.extra)
response = self.view(request)
self.assertEqual(response.status_code, 201)
# update
data['first_name'] = 'Tom'
del data['name']
request = self.factory.put(
'/api/v1/profiles', data=json.dumps(data),
content_type="application/json", **self.extra)
response = self.view(request, user='deno')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data['first_name'], data['first_name'])
first_name = u'Henry'
last_name = u'Thierry'
data = {'first_name': first_name, 'last_name': last_name}
request = self.factory.patch('/', data=data, **self.extra)
response = self.view(request, user=self.user.username)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data['first_name'], data['first_name'])
self.assertEqual(response.data['last_name'], data['last_name'])
@patch('django.core.mail.EmailMultiAlternatives.send')
def test_send_email_activation_api(self, mock_send_mail):
request = self.factory.get('/', **self.extra)
response = self.view(request)
self.assertEqual(response.status_code, 200)
data = _profile_data()
del data['name']
request = self.factory.post(
'/api/v1/profiles', data=json.dumps(data),
content_type="application/json", **self.extra)
response = self.view(request)
self.assertEqual(response.status_code, 201)
# Activation email not sent
self.assertFalse(mock_send_mail.called)
user = User.objects.get(username='deno')
self.assertTrue(user.is_active)
def test_partial_update_email(self):
self.assertEqual(self.user.profile.country, u'US')
data = {'email': 'user@example.com'}
request = self.factory.patch('/', data=data, **self.extra)
response = self.view(request, user=self.user.username)
profile = UserProfile.objects.get(user=self.user)
self.assertEqual(response.status_code, 200)
self.assertEqual(profile.user.email, 'user@example.com')
data = {'email': 'user@example'}
request = self.factory.patch('/', data=data, **self.extra)
response = self.view(request, user=self.user.username)
self.assertEqual(response.status_code, 400)
def test_partial_update_unique_email_api(self):
data = {'email': 'example@gmail.com'}
request = self.factory.patch(
'/api/v1/profiles', data=json.dumps(data),
content_type="application/json", **self.extra)
response = self.view(request, user=self.user.username)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data['email'], data['email'])
# create User
request = self.factory.post(
'/api/v1/profiles', data=json.dumps(_profile_data()),
content_type="application/json", **self.extra)
response = self.view(request)
self.assertEqual(response.status_code, 201)
user = User.objects.get(username='deno')
# Update email
request = self.factory.patch(
'/api/v1/profiles', data=json.dumps(data),
content_type="application/json", **self.extra)
response = self.view(request, user=user.username)
self.assertEqual(response.status_code, 400)
| {
"content_hash": "43a66d7b2cf9bbad23f31e99f5797533",
"timestamp": "",
"source": "github",
"line_count": 511,
"max_line_length": 79,
"avg_line_length": 40.08023483365949,
"alnum_prop": 0.5895708217372199,
"repo_name": "qlands/onadata",
"id": "559d8d3e099de89ee92afac2c3211cd9b21bdbb5",
"size": "20481",
"binary": false,
"copies": "5",
"ref": "refs/heads/20151009",
"path": "onadata/apps/api/tests/viewsets/test_user_profile_viewset.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "70153"
},
{
"name": "HTML",
"bytes": "248525"
},
{
"name": "JavaScript",
"bytes": "904742"
},
{
"name": "Makefile",
"bytes": "2286"
},
{
"name": "Python",
"bytes": "2817195"
},
{
"name": "Shell",
"bytes": "14149"
}
],
"symlink_target": ""
} |
import json
import utils
import logger
import problemdb
import teamdb
from decorators import api_wrapper
from flask import Blueprint, request, session, jsonify, make_response
from decorators import admins_only
api = Blueprint("api", __name__)
@api.route("/api/register", methods=["POST"])
@api_wrapper
def register():
team = request.form["team"]
password = request.form["password"]
password2 = request.form["password2"]
if password != password2:
return {"message": "Passwords do not match"}
if len(password) < 4:
return {"message": "Passwords should be at least 4 characters long"}
if teamdb.team_exists(team):
return {"message": "Team already exists"}
else:
response = teamdb.add_team(team, password)
if "Success" in response:
logger.log("registrations", logger.INFO, "%s has registered" % team)
return {"message": response}
@api.route("/api/login", methods=["POST"])
@api_wrapper
def login():
team = request.form["team"]
password = request.form["password"]
stored_team_password = teamdb.get_team_password(team)
if utils.check_password(stored_team_password, password):
session["tid"] = team
session["logged_in"] = True
if teamdb.is_admin(team):
session["admin"] = True
logger.log("logins", logger.WARNING, "%s logged as admin" % team)
else:
logger.log("logins", logger.INFO, "%s logged in" % team)
return {"success": 1, "message": "Success!"}
else:
return {"success": 0, "message": "Invalid credentials"}
@api.route("/api/add_problem", methods=["POST"])
@admins_only
@api_wrapper
def add_problem():
name = request.form["problem_name"]
desc = request.form["problem_desc"]
hint = request.form["problem_hint"]
category = request.form["problem_category"]
value = request.form["problem_value"]
flag = request.form["problem_flag"]
response = problemdb.add_problem(name, desc, hint, category, value, flag)
return {"message": response}
@api.route("/api/submit_flag", methods=["POST"])
@api_wrapper
def submit_flag():
flag = request.form["flag"]
pid = request.form["pid"]
team = session["tid"]
response = problemdb.submit_flag(team, pid, flag)
return {"message": response}
@api.route("/api/remove_problem", methods=["POST"])
@admins_only
@api_wrapper
def remove_problem():
pid = request.form["pid"]
response = problemdb.remove_problem(pid)
return {"message": response}
@api.route("/api/update_problem", methods=["POST"])
@admins_only
@api_wrapper
def update_problem():
pid = request.form["pid"]
name = request.form["name"]
desc = request.form["description"]
hint = request.form["hint"]
category = request.form["category"]
points = request.form["points"]
flag = request.form["flag"]
response = problemdb.update_problem(pid, name, desc, hint, category, points, flag)
return {"message": response}
@api.route("/api/top/<count>", methods=["GET", "POST"])
def top(count):
data = {}
teams = teamdb.get_scoreboard_data(5)
scoreboard = []
for team in teams:
jason = {}
jason["name"] = team[0]
jason["score"] = team[2]
jason["last_solve"] = team[5]
jason["progression"] = team[6] + ",%s,%s" % (team[2], utils.get_time_since_epoch()) # Add current time score to make graph look nicer
scoreboard.append(jason)
data["scoreboard"] = scoreboard
return jsonify(data=data)
@api.route("/api/export_data", methods=["GET", "POST"])
@admins_only
def export_data():
data = {}
form = request.form
if "problems" in form:
problem_list = []
problems = problemdb.get_problems()
for problem in problems:
jason = {}
jason["pid"] = problem[0]
jason["name"] = problem[1]
jason["description"] = problem[2]
jason["hint"] = problem[3]
jason["category"] = problem[4]
jason["points"] = problem[5]
jason["flag"] = problem[6]
problem_list.append(jason)
data["problems"] = problem_list
if "scoreboard" in form:
scoreboard = []
teams = teamdb.get_scoreboard_data()
for team in teams:
jason = {}
jason["name"] = team[0]
jason["score"] = team[2]
jason["solves"] = [problemdb.get_name_from_pid(pid) for pid in team[4].split(",")[1:]]
jason["last_solve"] = team[5]
jason["progression"] = team[6] + ",%s,%s" % (team[2], utils.get_time_since_epoch()) # Add current time score to make graph look nicer
scoreboard.append(jason)
data["scoreboard"] = scoreboard
if "teams" in form:
team_list = []
teams = teamdb.get_teams()
for team in teams:
jason = {}
jason["name"] = team[0]
jason["password"] = team[1]
jason["score"] = team[2]
jason["admin"] = team[3]
jason["solves"] = [problemdb.get_name_from_pid(pid) for pid in team[4].split(",")[1:]]
jason["last_solve"] = team[5]
jason["progression"] = team[6]
team_list.append(jason)
data["teams"] = team_list
data = json.dumps(data, indent=4)
if "download" in form:
response = make_response(data)
response.headers["Content-Disposition"] = "attachment; filename=data.json"
return response
return jsonify(data=json.loads(data))
| {
"content_hash": "bd35aabf8c0ab8141dab2623d3e53e73",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 145,
"avg_line_length": 34.21604938271605,
"alnum_prop": 0.5987732274941368,
"repo_name": "james9909/IntroCTF",
"id": "9dd6ddb879ccc123066e7ccd9bd9bfcdbd764eec",
"size": "5543",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "api.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1646"
},
{
"name": "HTML",
"bytes": "21714"
},
{
"name": "JavaScript",
"bytes": "7518"
},
{
"name": "Makefile",
"bytes": "118"
},
{
"name": "PHP",
"bytes": "6995"
},
{
"name": "Python",
"bytes": "40825"
},
{
"name": "Shell",
"bytes": "4260"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8" ?>
<!--======================================================================================
Copyright 2015 Sitecore Corporation A/S
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.
======================================================================================-->
<xamlControls
xmlns:x="http://www.sitecore.net/xaml"
xmlns:ajax="http://www.sitecore.net/ajax"
xmlns:rest="http://www.sitecore.net/rest"
xmlns:r="http://www.sitecore.net/renderings"
xmlns:xmlcontrol="http://www.sitecore.net/xmlcontrols"
xmlns:p="http://schemas.sitecore.net/Visual-Studio-Intellisense"
xmlns:asp="http://www.sitecore.net/microsoft/webcontrols"
xmlns:html="http://www.sitecore.net/microsoft/htmlcontrols"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<Sitecore.Ecommerce.Shell.Applications.Catalogs.Catalog x:inherits="Sitecore.Ecommerce.Shell.Applications.Catalogs.Views.CatalogView, Sitecore.Ecommerce.Shell">
<x:register assembly="System.Web" namespace="System.Web.UI.HtmlControls" />
<x:register assembly="ComponentArt.Web.UI" namespace="ComponentArt.Web.UI" />
<x:register assembly="Sitecore.Kernel" namespace="Sitecore.Web.UI.WebControls.Ribbons" />
<Sitecore.Controls.HtmlPage runat="server">
<Stylesheet runat="server" Src="Content Manager.css" DeviceDependant="true" x:placeholder="Stylesheets" />
<Stylesheet runat="server" Src="Ribbon.css" DeviceDependant="true" x:placeholder="Stylesheets" />
<Stylesheet runat="server" Src="IDE.css" DeviceDependant="true" x:placeholder="Stylesheets" />
<Stylesheet runat="server" Src="Grid.css" DeviceDependant="true" />
<Stylesheet runat="server" Src="/sitecore/Shell/Applications/Modules/Ecommerce/Catalog/Catalog.css" />
<AjaxScriptManager runat="server"/>
<ContinuationManager runat="server" />
<Script runat="server" Src="/sitecore/shell/Controls/Sitecore.Runtime.js"/>
<Script runat="server" Src="/sitecore/shell/controls/SitecoreKeyboard.js"/>
<Script runat="server" Src="/sitecore/shell/Applications/Content Manager/Content Editor.js"/>
<Script runat="server" Src="/sitecore/Shell/Applications/Modules/Ecommerce/Catalog/Catalog.js" />
<Script runat="server">
<![CDATA[
function beforeCallback() {
Grid.CallbackPrefix = Grid.CallbackPrefix + scCatalog.getSearchQuery();
}
function afterCallback() {
Grid.CallbackPrefix = Grid.CallbackPrefix.replace(scCatalog.getSearchQuery(), "");
}
function doubleClick(item) {
scCatalog.gridRowDoubleClick(item);
}
function itemSelect(item)
{
scCatalog.gridRowSelect(item);
return true;
}
]]>
</Script>
<div style="overflow:scroll;height:100%;">
<table id="ContentEditor" width="100%" border="0" cellpadding="0" cellspacing="0" style="table-layout:fixed">
<tr>
<td>
<div runat="server" ID="RibbonPanel" style="display:none">
<Border ID="RibbonContainer" runat="server" style="display: none">
<Ribbon ID="Ribbon" runat="server" />
</Border>
</div>
</td>
</tr>
<tr>
<td>
<div id="Page">
<table id="ContentEditor" width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<div id="Shadow">
<GridPanel runat="server" autoHeight="false" class="GridPanel">
<Border runat="server" Class="scSearchArea">
<GridPanel runat="server">
<Border ID="TextBoxContainer" runat="server">
<Literal runat="server" Text="Search" Style="font-weight: bold; width: 50px;" />
</Border>
<Border ID="ChecklistContainer" runat="server" Class="scBorder" />
</GridPanel>
</Border>
<Border runat="server" Style="padding-top:12px;padding-bottom:12px">
<HtmlButton ID="SearchButton" runat="server" class="scButton" onclick="javascript:Grid.scHandler.refresh(); return false;" />
</Border>
<Border runat="server" GridPanel.ColSpan="2">
<Grid ID="Grid" runat="server"
ClientSideOnBeforeCallback="beforeCallback"
ClientSideOnAfterCallback="afterCallback"
ClientSideOnDoubleClick="doubleClick"
AutoFocusSearchBox="false"
RunningMode="Callback"
CssClass="Grid"
ShowHeader="true"
HeaderCssClass="GridHeader"
AutoAdjustPageSize="true"
FillContainer="false"
FooterCssClass="GridFooter"
GroupByCssClass="GroupByCell"
GroupByTextCssClass="GroupByText"
GroupBySortAscendingImageUrl="group_asc.gif"
GroupBySortDescendingImageUrl="group_desc.gif"
GroupBySortImageWidth="10"
GroupBySortImageHeight="10"
GroupingNotificationTextCssClass="GridHeaderText"
GroupingPageSize="5"
ManualPaging ="true"
PageSize="10"
PagerStyle="Slider"
PagerTextCssClass="GridFooterText"
PagerButtonWidth="41"
PagerButtonHeight="22"
PagerImagesFolderUrl="/sitecore/shell/themes/standard/componentart/grid/pager/"
ShowSearchBox="false"
SearchTextCssClass="GridHeaderText"
SearchBoxCssClass="SearchBox"
SliderHeight="20"
SliderWidth="150"
SliderGripWidth="9"
SliderPopupOffsetX="20"
SliderPopupClientTemplateId="SliderTemplate"
TreeLineImagesFolderUrl="/sitecore/shell/themes/standard/componentart/grid/lines/"
TreeLineImageWidth="22"
TreeLineImageHeight="19"
PreExpandOnGroup="false"
ImagesBaseUrl="/sitecore/shell/themes/standard/componentart/grid/"
IndentCellWidth="22"
LoadingPanelClientTemplateId="LoadingFeedbackTemplate"
LoadingPanelPosition="MiddleCenter"
AllowScroll="false"
height="50%"
>
<Levels>
<GridLevel runat="server"
AllowSorting="false"
DataKeyField="scGridID"
ShowTableHeading="false"
ShowSelectorCells="false"
RowCssClass="Row"
ColumnReorderIndicatorImageUrl="reorder.gif"
DataCellCssClass="DataCell"
HeadingCellCssClass="HeadingCell"
HeadingCellHoverCssClass="HeadingCellHover"
HeadingCellActiveCssClass="HeadingCellActive"
HeadingRowCssClass="HeadingRow"
HeadingTextCssClass="HeadingCellText"
SelectedRowCssClass="SelectedRow"
GroupHeadingCssClass="GroupHeading"
SortAscendingImageUrl="asc.gif"
SortDescendingImageUrl="desc.gif"
SortImageWidth="13"
SortImageHeight="13">
</GridLevel>
</Levels>
<ClientTemplates>
<ClientTemplate ID="LoadingFeedbackTemplate" runat="server">
<table cellspacing="0" cellpadding="0" border="0">
<tr>
<td style="font-size:10px;">
<asp:Literal Text="Loading..." runat="server" />;
</td>
<td>
<img src="/sitecore/shell/themes/standard/componentart/grid/spinner.gif" width="16" height="16" border="0" />
</td>
</tr>
</table>
</ClientTemplate>
<ClientTemplate ID="SliderTemplate" runat="server">
<table class="SliderPopup" cellspacing="0" cellpadding="0" border="0">
<tr>
<td>
<div style="padding:4px;font:8pt tahoma;white-space:nowrap;overflow:hidden">
## DataItem.GetMember('Title').Value ##
</div>
</td>
</tr>
<tr>
<td style="height:14px;background-color:#666666;padding:1px 8px 1px 8px;color:white">
## DataItem.PageIndex + 1 ## / ## Grid.PageCount ##
</td>
</tr>
</table>
</ClientTemplate>
</ClientTemplates>
</Grid>
</Border>
</GridPanel>
</div>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</div>
</Sitecore.Controls.HtmlPage>
</Sitecore.Ecommerce.Shell.Applications.Catalogs.Catalog>
</xamlControls> | {
"content_hash": "4b99c6b710acbe172c77025e6f70b750",
"timestamp": "",
"source": "github",
"line_count": 228,
"max_line_length": 162,
"avg_line_length": 50.69736842105263,
"alnum_prop": 0.4701963837702223,
"repo_name": "rhamille/SES-8.0",
"id": "46bfe0cb1f505bf2fb9a9131ea0556ea9f40b6a8",
"size": "11561",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "code/Examples/Sitecore.Ecommerce.WebSite/sitecore/shell/Applications/Modules/Ecommerce/Catalog/Catalog.xaml.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "130615"
},
{
"name": "C#",
"bytes": "3763614"
},
{
"name": "CSS",
"bytes": "64931"
},
{
"name": "JavaScript",
"bytes": "27304"
},
{
"name": "XSLT",
"bytes": "119659"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.