text stringlengths 2 1.04M | meta dict |
|---|---|
if(!dojo._hasResource["dojox.editor.plugins.UploadImage"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
dojo._hasResource["dojox.editor.plugins.UploadImage"] = true;
dojo.provide("dojox.editor.plugins.UploadImage");
dojo.require("dijit._editor._Plugin");
dojo.require("dojox.form.FileUploader");
dojo.experimental("dojox.editor.plugins.UploadImage");
dojo.declare("dojox.editor.plugins.UploadImage",
dijit._editor._Plugin,
{
//summary:
// Adds an icon to the Editor toolbar that when clicked, opens a system dialog
// Although the toolbar icon is a tiny "image" the uploader could be used for
// any file type
tempImageUrl: "",
iconClassPrefix: "editorIcon",
useDefaultCommand: false,
uploadUrl: "",
button:null,
label:"Upload",
setToolbar: function(toolbar){
this.button.destroy();
this.createFileInput();
toolbar.addChild(this.button);
},
_initButton: function(){
this.command = "uploadImage";
this.editor.commands[this.command] = "Upload Image";
this.inherited("_initButton", arguments);
delete this.command;
},
createFileInput: function(){
var node = dojo.create('span', {innerHTML:"."}, document.body)
dojo.style(node, {
width:"40px",
height:"20px",
paddingLeft:"8px",
paddingRight:"8px"
})
this.button = new dojox.form.FileUploader({
isDebug:true,
//force:"html",
uploadUrl:this.uploadUrl,
uploadOnChange:true,
selectMultipleFiles:false,
baseClass:"dojoxEditorUploadNorm",
hoverClass:"dojoxEditorUploadHover",
activeClass:"dojoxEditorUploadActive",
disabledClass:"dojoxEditorUploadDisabled"
}, node);
this.connect(this.button, "onChange", "insertTempImage");
this.connect(this.button, "onComplete", "onComplete");
},
onComplete: function(data,ioArgs,widgetRef){
data = data[0];
// Image is ready to insert
var tmpImgNode = dojo.withGlobal(this.editor.window, "byId", dojo, [this.currentImageId]);
var file;
// download path is mainly used so we can access a PHP script
// not relative to this file. The server *should* return a qualified path.
if(this.downloadPath){
file = this.downloadPath+data.name
}else{
file = data.file;
}
tmpImgNode.src = file;
dojo.attr(tmpImgNode,'_djrealurl',file);
if(data.width){
tmpImgNode.width = data.width;
tmpImgNode.height = data.height;
}
},
insertTempImage: function(){
// inserting a "busy" image to show something is hapening
// during upload and download of the image.
this.currentImageId = "img_"+(new Date().getTime());
var iTxt = '<img id="'+this.currentImageId+'" src="'+this.tempImageUrl+'" width="32" height="32"/>';
this.editor.execCommand('inserthtml', iTxt);
}
}
);
dojo.subscribe(dijit._scopeName + ".Editor.getPlugin",null,function(o){
if(o.plugin){ return; }
switch(o.args.name){
case "uploadImage":
o.plugin = new dojox.editor.plugins.UploadImage({url: o.args.url});
}
});
}
| {
"content_hash": "ad9c019f568765e7c1b07e9a57847772",
"timestamp": "",
"source": "github",
"line_count": 103,
"max_line_length": 144,
"avg_line_length": 30.339805825242717,
"alnum_prop": 0.66272,
"repo_name": "sonatype/owf",
"id": "8a1be058c421d0b501f64d820275e33bf83e430e",
"size": "3323",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "web-app/js-lib/dojo-release-1.5.0/dojox/editor/plugins/UploadImage.js",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
require 'rails_helper'
describe HasFriendship::Friendship do
let(:user){ User.create(name: "Jessie") }
let(:friend){ User.create(name: "Heisenberg") }
describe "associations" do
it { should belong_to(:friendable) }
it { should belong_to(:friend).with_foreign_key(:friend_id) } # Why can't I use '.class_name('Friendable')'?
end
describe "class methods" do
describe ".exist?" do
it "should be provided" do
expect(HasFriendship::Friendship).to respond_to(:exist?)
end
context "when a friendship exists between user and friend" do
it "returns true" do
create_friendship(user, friend)
expect(HasFriendship::Friendship.exist?(user, friend)).to be true
end
end
context "when a friendship does not exists" do
it "returns false" do
expect(HasFriendship::Friendship.exist?(user, friend)).to be false
end
end
end
describe ".find_unblocked_friendship" do
it "should be provided" do
expect(HasFriendship::Friendship).to respond_to(:find_unblocked_friendship)
end
it "should find friendship" do
create_request(user, friend)
friendship = HasFriendship::Friendship.find_by(friendable_id: user.id, friendable_type: user.class.base_class.name, friend_id: friend.id)
expect(HasFriendship::Friendship.find_unblocked_friendship(user, friend)).to eq friendship
end
end
describe ".find_blocked_friendship" do
it "should find a blocked friendship" do
create_friendship(user, friend, status: 'blocked', blocker_id: user.id)
friendship = find_friendship_record(user, friend)
expect(HasFriendship::Friendship.find_blocked_friendship(user, friend)).to eq friendship
end
end
describe '.find_one_side' do
it 'finds a friendship record' do
create_request(user, friend)
friendship = find_friendship_record(user, friend)
expect(HasFriendship::Friendship.find_one_side(user, friend)).to eq friendship
end
end
end
end
| {
"content_hash": "4979e5d3ea2c996d13572515c92a8e7d",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 145,
"avg_line_length": 33.04761904761905,
"alnum_prop": 0.665225744476465,
"repo_name": "tkubicek3/my_has_friendships",
"id": "a128627d00d1bbf799cd5db72e3668ceed0ebc14",
"size": "2082",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "spec/has_friendship/friendship_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "683"
},
{
"name": "HTML",
"bytes": "4886"
},
{
"name": "JavaScript",
"bytes": "599"
},
{
"name": "Ruby",
"bytes": "49840"
}
],
"symlink_target": ""
} |
class Vote < ActiveRecord::Base
belongs_to :user
belongs_to :post
validates :value, inclusion: { in: [-1, 1], message: "%{value} is not a valid vote." }
after_save :update_post
def up_vote?
value == 1
end
def down_vote?
value == -1
end
private
def update_post
post.update_rank
end
end
| {
"content_hash": "2159f2876a353f13bced8ddc44fa4897",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 88,
"avg_line_length": 15.571428571428571,
"alnum_prop": 0.617737003058104,
"repo_name": "erstrong/bloccit",
"id": "cccb46e694b085d66c805dbfc1244c975f8c4e86",
"size": "327",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/vote.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "616191"
},
{
"name": "CoffeeScript",
"bytes": "844"
},
{
"name": "HTML",
"bytes": "29151"
},
{
"name": "JavaScript",
"bytes": "835552"
},
{
"name": "Ruby",
"bytes": "82545"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2014 The Android Open Source Project
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.
-->
<android.support.v7.internal.widget.ActionBarOverlayLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/decor_content_parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<include layout="@layout/abc_screen_content_include"/>
<android.support.v7.internal.widget.ActionBarContainer
android:id="@+id/action_bar_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
style="?attr/actionBarStyle"
android:touchscreenBlocksFocus="true"
android:gravity="top">
<android.support.v7.widget.Toolbar
android:id="@+id/action_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:navigationContentDescription="@string/abc_action_bar_up_description"
style="?attr/toolbarStyle"/>
<android.support.v7.internal.widget.ActionBarContextView
android:id="@+id/action_context_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone"
android:theme="?attr/actionBarTheme"
style="?attr/actionModeStyle"/>
</android.support.v7.internal.widget.ActionBarContainer>
</android.support.v7.internal.widget.ActionBarOverlayLayout>
<!-- From: file:/usr/local/google/buildbot/repo_clients/https___googleplex-android.googlesource.com_a_platform_manifest.git/lmp-mr1-supportlib-release/frameworks/support/v7/appcompat/res/layout/abc_screen_toolbar.xml --><!-- From: file:/Users/miraclewong/AndroidStudioProjects/HelloWorld/app/build/intermediates/exploded-aar/com.android.support/appcompat-v7/22.2.1/res/layout/abc_screen_toolbar.xml --> | {
"content_hash": "f134dd637553fd23c3c7d4d6f3872236",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 402,
"avg_line_length": 49.98148148148148,
"alnum_prop": 0.6824749907373101,
"repo_name": "MiracleWong/HelloWorld",
"id": "ac97686dfe188fdb4f8ba63d7395d495c1c5f121",
"size": "2699",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/build/intermediates/res/debug/layout/abc_screen_toolbar.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "2265229"
}
],
"symlink_target": ""
} |
<?xml version="1.0"?>
<config>
<modules>
<Genmato_Payment>
<version>15.292.1</version>
</Genmato_Payment>
</modules>
<global>
<models>
<genmato_payment>
<class>Genmato_Payment_Model</class>
</genmato_payment>
</models>
<helpers>
<genmato_payment>
<class>Genmato_Payment_Helper</class>
</genmato_payment>
</helpers>
<events>
<sales_model_service_quote_submit_after>
<observers>
<genmato_payment_model_observer>
<type>singleton</type>
<class>Genmato_Payment_Model_Observer</class>
<method>autoCreateInvoice</method>
</genmato_payment_model_observer>
</observers>
</sales_model_service_quote_submit_after>
</events>
</global>
</config> | {
"content_hash": "1c0094b06f7810381626dc4e115fd8bd",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 69,
"avg_line_length": 27.13888888888889,
"alnum_prop": 0.48311156601842375,
"repo_name": "Genmato/Payment",
"id": "78beaf4328583dd5d7792c49fe739aef892836c7",
"size": "977",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/code/community/Genmato/Payment/etc/config.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "7660"
}
],
"symlink_target": ""
} |
# -*- coding: utf-8 -*-
# script.module.python.koding.aio
# Python Koding AIO (c) by whufclee (info@totalrevolution.tv)
# Python Koding AIO is licensed under a
# Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.
# You should have received a copy of the license along with this
# work. If not, see http://creativecommons.org/licenses/by-nc-nd/4.0.
# IMPORTANT: If you choose to use the special noobsandnerds features which hook into their server
# please make sure you give approptiate credit in your add-on description (noobsandnerds.com)
#
# Please make sure you've read and understood the license, this code can NOT be used commercially
# and it can NOT be modified and redistributed. If you're found to be in breach of this license
# then any affected add-ons will be blacklisted and will not be able to work on the same system
# as any other add-ons which use this code. Thank you for your cooperation.
import sys
import urllib
import xbmc
import xbmcaddon
import xbmcgui
import xbmcplugin
dialog = xbmcgui.Dialog()
mode = ''
#----------------------------------------------------------------
# TUTORIAL #
def Add_Dir(name, url='', mode='', folder=False, icon='', fanart='', description='', info_labels={}, set_art={}, set_property={}, content_type='', context_items=None, context_override=False, playable=False):
"""
This allows you to create a list item/folder inside your add-on.
Please take a look at your addon default.py comments for more information
(presuming you created one at http://totalrevolution.tv)
TOP TIP: If you want to send multiple variables through to a function just
send through as a dictionary encapsulated in quotation marks. In the function
you can then use the following code to access them:
params = eval(url)
^ That will then give you a dictionary where you can just pull each variable and value from.
CODE: Add_Dir(name, url, mode, [folder, icon, fanart, description, info_labels, content_type, context_items, context_override, playable])
AVAILABLE PARAMS:
(*) name - This is the name you want to show for the list item
url - If the route (mode) you're calling requires extra paramaters
to be sent through then this is where you add them. If the function is
only expecting one item then you can send through as a simple string.
Unlike many other Add_Dir functions Python Koding does allow for multiple
params to be sent through in the form of a dictionary so let's say your
function is expecting the 2 params my_time & my_date. You would send this info
through as a dictionary like this:
url={'my_time':'10:00', 'my_date':'01.01.1970'}
If you send through a url starting with plugin:// the item will open up into
that plugin path so for example:
url='plugin://plugin.video.youtube/play/?video_id=FTI16i7APhU'
mode - The mode you want to open when this item is clicked, this is set
in your master_modes dictionary (see template add-on linked above)
folder - This is an optional boolean, by default it's set to False.
True will open into a folder rather than an executable command
icon - The path to the thumbnail you want to use for this list item
fanart - The path to the fanart you want to use for this list item
description - A description of your list item, it's skin dependant but this
usually appears below the thumbnail
info_labels - You can send through any number of info_labels via this option.
For full details on the infolabels available please check the pydocs here:
http://mirrors.kodi.tv/docs/python-docs/16.x-jarvis/xbmcgui.html#ListItem-setInfo
When passing through infolabels you need to use a dictionary in this format:
{"genre":"comedy", "title":"test video"}
set_art - Using the same format as info_labels you can set your artwork via
a dictionary here. Full details can be found here:
http://mirrors.kodi.tv/docs/python-docs/16.x-jarvis/xbmcgui.html#ListItem-setArt
set_property - Using the same format as info_labels you can set your artwork via
a dictionary here. Full details can be found here:
http://kodi.wiki/view/InfoLabels#ListItem
content_type - By default this will set the content_type for kodi to a blank string
which is what Kodi expects for generic category listings. There are plenty of different
types though and when set Kodi will perform different actions (such as access the
database looking for season/episode information for the list item).
WARNING: Setting the wrong content type for your listing can cause the system to
log thousands of error reports in your log, cause the system to lag and make
thousands of unnecessary db calls - sometimes resulting in a crash. You can find
details on the content_types available here: http://forum.kodi.tv/showthread.php?tid=299107
context_items - Add context items to your directory. The params you need to send through
need to be in a list format of [(label, action,),] look at the example code below for
more details.
context_override - By default your context items will be added to the global context
menu items but you can override this by setting this to True and then only your
context menu items will show.
playable - By default this is set to False but if set to True kodi will just try
and play this item natively with no extra fancy functions.
EXAMPLE:
my_context = [('Music','xbmc.executebuiltin("ActivateWindow(music)")'),('Programs','xbmc.executebuiltin("ActivateWindow(programs)")')]
# ^ This is our two basic context menu items (music and programs)
Add_Dir(name='TEST DIRECTORY', url='', mode='test_directory', folder=True, context_items=my_context, context_override=True)
# ^ This will add a folder AND a context menu item for when bring up the menu (when focused on this directory).
# ^^ The context_override is set to True which means it will override the default Kodi context menu items.
Add_Dir(name='TEST ITEM', url='', mode='test_item', folder=False, context_items=my_context, context_override=False)
# ^ This will add an item to the list AND a context menu item for when bring up the menu (when focused on this item).
# ^^ The context_override is set to False which means the new items will appear alongside the default Kodi context menu items.
~"""
from systemtools import Data_Type
from vartools import Convert_Special
module_id = 'script.module.python.koding.aio'
this_module = xbmcaddon.Addon(id=module_id)
addon_handle = int(sys.argv[1])
# Check we're in an appropriate section for the content type set
song_only_modes = ['songs','artist','album','song','music']
video_only_modes = ['sets','tvshows','seasons','actors','directors','unknown','video','set','movie','tvshow','season','episode']
if xbmc.getInfoLabel('Window.Property(xmlfile)') == 'MyVideoNav.xml' and content_type in song_only_modes:
content_type = ''
if xbmc.getInfoLabel('Window.Property(xmlfile)') == 'MyMusicNav.xml' and content_type in video_only_modes:
content_type = ''
if description == '':
description = this_module.getLocalizedString(30837)
if Data_Type(url) == 'dict':
url = repr(url)
if Data_Type(info_labels) != 'dict':
dialog.ok('WRONG INFO LABELS', 'Please check documentation, these should be sent through as a dictionary.')
if Data_Type(set_art) != 'dict':
dialog.ok('WRONG SET_ART', 'Please check documentation, these should be sent through as a dictionary.')
if Data_Type(set_property) != 'dict':
dialog.ok('WRONG SET_PROPERTY', 'Please check documentation, these should be sent through as a dictionary.')
# Set the default title, filename and plot if not sent through already via info_labels
try:
title = info_labels["Title"]
if title == '':
info_labels["Title"] = name
except:
info_labels["Title"] = name
try:
filename = info_labels["FileName"]
# if filename == '':
# info_labels["FileName"] = name
except:
info_labels["FileName"] = name
try:
plot = info_labels["plot"]
if plot == '':
info_labels["plot"] = description
except:
info_labels["plot"] = description
# Set default thumbnail image used for listing (if not sent through via set_art)
try:
set_art["icon"]
except:
set_art["icon"] = icon
# Set default Fanart if not already sent through via set_property
try:
set_property["Fanart_Image"]
except:
set_property["Fanart_Image"] = fanart
# Set the main listitem properties
liz = xbmcgui.ListItem(label=str(name), iconImage=str(icon), thumbnailImage=str(icon))
# Set the infolabels
liz.setInfo(type=content_type, infoLabels=info_labels)
# Set the artwork
liz.setArt(set_art)
# Loop through the set_property list and set each item in there
for item in set_property.items():
liz.setProperty(item[0], item[1])
# Add a context item (if details for context items are sent through)
if context_items:
liz.addContextMenuItems(context_items, context_override)
u = sys.argv[0]
u += "?mode=" +str(mode)
u += "&url=" +Convert_Special(url,string=True)
u += "&name=" +urllib.quote_plus(name)
u += "&iconimage=" +urllib.quote_plus(icon)
u += "&fanart=" +urllib.quote_plus(fanart)
u += "&description=" +urllib.quote_plus(description)
if url.startswith('plugin://'):
xbmcplugin.addDirectoryItem(handle=addon_handle,url=url,listitem=liz,isFolder=True)
elif folder:
xbmcplugin.addDirectoryItem(handle=addon_handle,url=u,listitem=liz,isFolder=True)
elif playable:
liz.setProperty('IsPlayable', 'true')
xbmcplugin.addDirectoryItem(handle=addon_handle,url=url,listitem=liz,isFolder=False)
else:
xbmcplugin.addDirectoryItem(handle=addon_handle,url=u,listitem=liz,isFolder=False)
#----------------------------------------------------------------
def Default_Mode():
""" internal command ~"""
dialog = xbmcgui.Dialog()
dialog.ok('MODE ERROR','You\'ve tried to call Add_Dir() without a valid mode, check you\'ve added the mode into the master_modes dictionary')
#----------------------------------------------------------------
# TUTORIAL #
def Grab_Params(extras, keys = '', separator = '<~>'):
"""
This will allow you to send multiple values through as a string and
split at a common separator. The return will be a dictionary you can
easily access the values from.
CODE: Grab_Params(extras, keys, [separator]))
AVAILABLE PARAMS:
(*) extras - This is the string you want to split into a list of values.
Each value needs to be split by <~> (unless a different separator is sent through).
A good example of sending through name, DOB and sex would be: 'Mark<~>01.02.1976<~>male'
(*) keys - These are the keys (variable names) you want to assign the split
extras to. They need to be comma separated so using the above extras example
you could use something like this: key='name,DOB,sex'.
separator - This is optional, if you want to change the default separator you can do
so here. Make sure it's something unique not used anywhere else in the string.
EXAMPLE CODE:
raw_string = 'Mark<~>01.02.1976<~>male'
vars = 'name,DOB,sex'
params = koding.Grab_Params(extras=raw_string, keys=vars)
dialog.ok('RAW STRING','We\'re going to send through the following string','[COLOR=dodgerblue]%s[/COLOR]'%raw_string,'Click OK to see the results.')
dialog.ok('GRAB PARAMS RESULTS','Name: %s'%params["name"], 'DOB: %s'%params["DOB"], 'Sex: %s'%params["sex"])
~"""
params_array = {}
keyerror = False
keys = keys.replace(' ','').strip()
if keys.endswith(','):
keys = keys[:-1]
if ',' in keys:
keys = keys.split(',')
keylen = len(keys)
elif keys != '':
keyerror = True
else:
dialog.ok('KEY ERROR','You\'ve called the Grab_Params function but not provided any keys')
return
if separator in extras and not keyerror:
split_url = extras.split(separator)
if len(split_url) == keylen:
counter = 0
for item in split_url:
params_array[keys[counter]] = item
counter += 1
return params_array
else:
keyerror = True
else:
keyerror = True
if keyerror:
dialog.ok('KEY ERROR','You\'ve called Grab_Params() but there\'s no need. The url you passed through does not contain '
'any instances of %s which means there\'s nothing to split. Remove the Grab_Params function and just access url directly.'%separator)
return
#----------------------------------------------------------------
# TUTORIAL #
def Populate_List(url, start_point=r'<li+.<a href="', end_point=r'</a+.</li>', separator = r">", skip=['..','.','Parent Directory']):
"""
If you have a basic index web page or a webpage with a common
format for displaying links (on all pages) then you can use this
to populate an add-on. It's capable of cleverly working out what
needs to be sent through as a directory and what's a playable item.
CODE: Populate_List(url, [start_point, end_point, separator, skip]):
AVAILABLE PARAMS:
(*) url - The start page of where to pull the first links from
start_point - Send through the code tags you want to search for in the
webpage. By default it's setup for a standard indexed site so the start_point
is '<li+.<a href="'. The code will then grab every instance of start_point to end_point.
end_point - Send through the code tags you want to search for in the
webpage. By default it's setup for a standard indexed site so the end_point
is '</a+.</li>'. The code will then grab every instance of start_point to end_point.
separator - This is the point in the grabbed links (from above) where you want
to split the string into a url and a display name. The default is ">".
skip - By default this is set to ['..', '.', 'Parent Directory']. This is
a list of links you don't want to appear in your add-on listing.
EXAMPLE CODE:
link ='http://totalrevolution.tv/videos/'
sp ='<a href="'
ep ='</a>'
sep = '">'
koding.Populate_List(url=link, start_point=sp, end_point=ep, separator=sep)
~"""
import re
import urlparse
from __init__ import dolog
from vartools import Find_In_Text, Cleanup_String
from video import Play_Video
from web import Open_URL, Get_Extension, Cleanup_URL
badlist = []
if '<~>' in url:
params = Grab_Params(extras=url,keys='url,start,end,separator,skip')
url = params['url']
start_point = params['start']
end_point = params['end']
separator = params['separator']
skip = params['skip']
raw_content = Open_URL(url).replace('\n','').replace('\r','').replace('\t','')
raw_list = Find_In_Text(content=raw_content,start=start_point,end=end_point,show_errors=False)
if raw_list != None:
for item in raw_list:
cont = True
try:
dolog('ITEM: %s'%item)
new_sep = re.search(separator, item).group()
link, title = item.split(new_sep)
except:
dolog('^ BAD ITEM, adding to badlist')
badlist.append(item)
cont = False
# break
if cont:
title = Cleanup_String(title)
if title not in skip:
# Make sure the link we've grabbed isn't a full web address
if not '://' in link:
link = urlparse.urljoin(url, link)
link = Cleanup_URL(link)
extension = Get_Extension(link)
if not link.endswith('/') and extension == '':
link = link+'/'
if extension == '' and not 'mms://' in link:
Add_Dir(name=title, url=link+'<~>%s<~>%s<~>%s<~>%s'%(start_point,end_point,separator,skip),mode='populate_list',folder=True)
else:
Add_Dir(name=title, url=link,mode='play_video',folder=False)
else:
Add_Dir(name='Link 1', url=params["url"],mode='play_video',folder=False)
if len(badlist)>0:
dialog.ok('ERROR IN REGEX','The separator used is not working, an example raw match from the web page has now been printed to the log.')
for item in badlist:
dolog('BADLIST ITEM: %s'%item)
| {
"content_hash": "f1ab33af018a4f96e119a156b5a64b75",
"timestamp": "",
"source": "github",
"line_count": 375,
"max_line_length": 207,
"avg_line_length": 44.922666666666665,
"alnum_prop": 0.6534488899442004,
"repo_name": "TheWardoctor/Wardoctors-repo",
"id": "89a53674eb59b0b10c3cdd3e34ebe91cdb9ff3d9",
"size": "16848",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "script.module.python.koding.aio/lib/koding/directory.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "3208"
},
{
"name": "JavaScript",
"bytes": "115722"
},
{
"name": "Python",
"bytes": "34405207"
},
{
"name": "Shell",
"bytes": "914"
}
],
"symlink_target": ""
} |
import React from 'react';
import {shallow} from 'enzyme';
import ReactDOM from 'react-dom';
import {withDefaultNowContext, testContext} from '../testing/NowContainer';
import HomeInsights from './HomeInsights';
import CheckStudentsWithLowGrades from './CheckStudentsWithLowGrades';
import CheckStudentsWithHighAbsences from './CheckStudentsWithHighAbsences';
jest.mock('./CheckStudentsWithLowGrades');
jest.mock('./CheckStudentsWithHighAbsences');
function testProps(props = {}) {
return {
educatorId: 9999,
educatorLabels: [],
...props
};
}
it('renders without crashing', () => {
const props = testProps();
const el = document.createElement('div');
ReactDOM.render(withDefaultNowContext(<HomeInsights {...props} />), el);
});
it('shallow renders', () => {
const props = testProps();
const context = testContext();
const wrapper = shallow(<HomeInsights {...props} />, {context});
expect(wrapper.contains(<CheckStudentsWithHighAbsences educatorId={9999} />)).toEqual(true);
expect(wrapper.find(CheckStudentsWithLowGrades).length).toEqual(0);
});
it('shallow renders low grades box when correct label is set', () => {
const props = testProps({ educatorLabels: ['should_show_low_grades_box'] });
const context = testContext();
const wrapper = shallow(<HomeInsights {...props} />, {context});
expect(wrapper.contains(<CheckStudentsWithLowGrades educatorId={9999} />)).toEqual(true);
}); | {
"content_hash": "a156b2c2d8497f556e838d809ff01e89",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 94,
"avg_line_length": 35.725,
"alnum_prop": 0.7200839748075577,
"repo_name": "studentinsights/studentinsights",
"id": "a8886e2b4f8cb5784ee00b0bedd30903cdd9b7d6",
"size": "1429",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/assets/javascripts/home/HomeInsights.test.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8550"
},
{
"name": "HTML",
"bytes": "67602"
},
{
"name": "JavaScript",
"bytes": "2068243"
},
{
"name": "Procfile",
"bytes": "173"
},
{
"name": "Ruby",
"bytes": "1879416"
},
{
"name": "SCSS",
"bytes": "16368"
},
{
"name": "Shell",
"bytes": "30425"
}
],
"symlink_target": ""
} |
<!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>@uirouter/core/state/stateBuilder | @uirouter/angular</title>
<meta name="description" content="Documentation for @uirouter/angular">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../assets/css/main.css">
</head>
<body>
<header>
<div class="tsd-page-toolbar">
<div class="container">
<div class="table-wrap">
<div class="table-cell" id="tsd-search" data-index="../assets/js/search.json" data-base="..">
<div class="field">
<label for="tsd-search-field" class="tsd-widget search no-caption">Search</label>
<input id="tsd-search-field" type="text" />
</div>
<ul class="results">
<li class="state loading">Preparing search index...</li>
<li class="state failure">The search index is not available</li>
</ul>
<a href="../index.html" class="title">@uirouter/angular</a>
</div>
<div class="table-cell" id="tsd-widgets">
<div id="tsd-filter">
<a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a>
<div class="tsd-filter-group">
<div class="tsd-select" id="tsd-filter-visibility">
<span class="tsd-select-label">All</span>
<ul class="tsd-select-list">
<li data-value="public">Public</li>
<li data-value="protected">Public/Protected</li>
<li data-value="private" class="selected">All</li>
</ul>
</div>
<input type="checkbox" id="tsd-filter-inherited" checked />
<label class="tsd-widget" for="tsd-filter-inherited">Inherited</label>
<input type="checkbox" id="tsd-filter-externals" checked />
<label class="tsd-widget" for="tsd-filter-externals">Externals</label>
</div>
</div>
<a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a>
</div>
</div>
</div>
</div>
<div class="tsd-page-title">
<div class="container">
<ul class="tsd-breadcrumb">
<li>
<a href="../index.html">@uirouter/angular</a>
</li>
<li>
<a href="_uirouter_core_state_statebuilder.html">@uirouter/core/state/stateBuilder</a>
</li>
</ul>
<h1>Module @uirouter/core/state/stateBuilder</h1>
</div>
</div>
</header>
<div class="container container-main">
<div class="row">
<div class="col-8 col-content">
<section class="tsd-panel-group tsd-index-group">
<h2>Index</h2>
<section class="tsd-panel tsd-index-panel">
<div class="tsd-index-content">
<section class="tsd-index-section tsd-is-external">
<h3>Classes</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-class tsd-parent-kind-module tsd-is-external"><a href="../classes/_uirouter_core_state_statebuilder.statebuilder.html" class="tsd-kind-icon">State<wbr>Builder</a></li>
</ul>
</section>
<section class="tsd-index-section tsd-is-external">
<h3>Type aliases</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-type-alias tsd-parent-kind-module tsd-is-external"><a href="_uirouter_core_state_statebuilder.html#builderfunction" class="tsd-kind-icon">Builder<wbr>Function</a></li>
</ul>
</section>
<section class="tsd-index-section tsd-is-external">
<h3>Functions</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-function tsd-parent-kind-module tsd-is-external"><a href="_uirouter_core_state_statebuilder.html#resolvablesbuilder" class="tsd-kind-icon">resolvables<wbr>Builder</a></li>
</ul>
</section>
</div>
</section>
</section>
<section class="tsd-panel-group tsd-member-group tsd-is-external">
<h2>Type aliases</h2>
<section class="tsd-panel tsd-member tsd-kind-type-alias tsd-parent-kind-module tsd-is-external">
<a name="builderfunction" class="tsd-anchor"></a>
<h3>Builder<wbr>Function</h3>
<div class="tsd-signature tsd-kind-icon">Builder<wbr>Function<span class="tsd-signature-symbol">:</span> <span class="tsd-signature-symbol">(</span>state<span class="tsd-signature-symbol">: </span><a href="../classes/_uirouter_core_state_stateobject.stateobject.html" class="tsd-signature-type">StateObject</a>, parent<span class="tsd-signature-symbol">?: </span><a href="_uirouter_core_state_statebuilder.html#builderfunction" class="tsd-signature-type">BuilderFunction</a><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol"> => </span><span class="tsd-signature-type">any</span></div>
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/3d8c4a8/src/state/stateBuilder.ts#L34">@uirouter/core/src/state/stateBuilder.ts:34</a></li>
</ul>
</aside>
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>A function that builds the final value for a specific field on a <a href="../classes/_uirouter_core_state_stateobject.stateobject.html">StateObject</a>.</p>
</div>
<p>A series of builder functions for a given field are chained together.
The final value returned from the chain of builders is applied to the built <a href="../classes/_uirouter_core_state_stateobject.stateobject.html">StateObject</a>.
Builder functions should call the [[parent]] function either first or last depending on the desired composition behavior.</p>
<dl class="tsd-comment-tags">
<dt>param</dt>
<dd><p>the <em>partially built</em> <a href="../classes/_uirouter_core_state_stateobject.stateobject.html">StateObject</a>. The <a href="../interfaces/_uirouter_core_state_interface.statedeclaration.html">StateDeclaration</a> can be inspected via <a href="../classes/_uirouter_core_state_stateobject.stateobject.html#self">StateObject.self</a></p>
</dd>
<dt>param</dt>
<dd><p>the previous builder function in the series.</p>
</dd>
</dl>
</div>
<div class="tsd-type-declaration">
<h4>Type declaration</h4>
<ul class="tsd-parameters">
<li class="tsd-parameter-signature">
<ul class="tsd-signatures tsd-kind-type-literal tsd-parent-kind-type-alias">
<li class="tsd-signature tsd-kind-icon"><span class="tsd-signature-symbol">(</span>state<span class="tsd-signature-symbol">: </span><a href="../classes/_uirouter_core_state_stateobject.stateobject.html" class="tsd-signature-type">StateObject</a>, parent<span class="tsd-signature-symbol">?: </span><a href="_uirouter_core_state_statebuilder.html#builderfunction" class="tsd-signature-type">BuilderFunction</a><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><span class="tsd-signature-type">any</span></li>
</ul>
<ul class="tsd-descriptions">
<li class="tsd-description">
<h4 class="tsd-parameters-title">Parameters</h4>
<ul class="tsd-parameters">
<li>
<h5>state: <a href="../classes/_uirouter_core_state_stateobject.stateobject.html" class="tsd-signature-type">StateObject</a></h5>
</li>
<li>
<h5><span class="tsd-flag ts-flagOptional">Optional</span> parent: <a href="_uirouter_core_state_statebuilder.html#builderfunction" class="tsd-signature-type">BuilderFunction</a></h5>
</li>
</ul>
<h4 class="tsd-returns-title">Returns <span class="tsd-signature-type">any</span></h4>
</li>
</ul>
</li>
</ul>
</div>
</section>
</section>
<section class="tsd-panel-group tsd-member-group tsd-is-external">
<h2>Functions</h2>
<section class="tsd-panel tsd-member tsd-kind-function tsd-parent-kind-module tsd-is-external">
<a name="resolvablesbuilder" class="tsd-anchor"></a>
<h3>resolvables<wbr>Builder</h3>
<ul class="tsd-signatures tsd-kind-function tsd-parent-kind-module tsd-is-external">
<li class="tsd-signature tsd-kind-icon">resolvables<wbr>Builder<span class="tsd-signature-symbol">(</span>state<span class="tsd-signature-symbol">: </span><a href="../classes/_uirouter_core_state_stateobject.stateobject.html" class="tsd-signature-type">StateObject</a><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><a href="../classes/_uirouter_core_resolve_resolvable.resolvable.html" class="tsd-signature-type">Resolvable</a><span class="tsd-signature-symbol">[]</span></li>
</ul>
<ul class="tsd-descriptions">
<li class="tsd-description">
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/ui-router/core/blob/3d8c4a8/src/state/stateBuilder.ts#L156">@uirouter/core/src/state/stateBuilder.ts:156</a></li>
</ul>
</aside>
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>This is a <a href="../classes/_uirouter_core_state_statebuilder.statebuilder.html#builder">StateBuilder.builder</a> function for the <code>resolve:</code> block on a <a href="../interfaces/_uirouter_core_state_interface.statedeclaration.html">StateDeclaration</a>.</p>
</div>
<p>When the <a href="../classes/_uirouter_core_state_statebuilder.statebuilder.html">StateBuilder</a> builds a <a href="../classes/_uirouter_core_state_stateobject.stateobject.html">StateObject</a> object from a raw <a href="../interfaces/_uirouter_core_state_interface.statedeclaration.html">StateDeclaration</a>, this builder
validates the <code>resolve</code> property and converts it to a <a href="../classes/_uirouter_core_resolve_resolvable.resolvable.html">Resolvable</a> array.</p>
<p>resolve: input value can be:</p>
<p>{
// analyzed but not injected
myFooResolve: function() { return "myFooData"; },</p>
<p> // function.toString() parsed, "DependencyName" dep as string (not min-safe)
myBarResolve: function(DependencyName) { return DependencyName.fetchSomethingAsPromise() },</p>
<p> // Array split; "DependencyName" dep as string
myBazResolve: [ "DependencyName", function(dep) { return dep.fetchSomethingAsPromise() },</p>
<p> // Array split; DependencyType dep as token (compared using ===)
myQuxResolve: [ DependencyType, function(dep) { return dep.fetchSometingAsPromise() },</p>
<p> // val.$inject used as deps
// where:
// corgeResolve.$inject = ["DependencyName"];
// function corgeResolve(dep) { dep.fetchSometingAsPromise() }
// then "DependencyName" dep as string
myCorgeResolve: corgeResolve,</p>
<p> // inject service by name
// When a string is found, desugar creating a resolve that injects the named service
myGraultResolve: "SomeService"
}</p>
<p>or:</p>
<p>[
new Resolvable("myFooResolve", function() { return "myFooData" }),
new Resolvable("myBarResolve", function(dep) { return dep.fetchSomethingAsPromise() }, [ "DependencyName" ]),
{ provide: "myBazResolve", useFactory: function(dep) { dep.fetchSomethingAsPromise() }, deps: [ "DependencyName" ] }
]</p>
</div>
<h4 class="tsd-parameters-title">Parameters</h4>
<ul class="tsd-parameters">
<li>
<h5>state: <a href="../classes/_uirouter_core_state_stateobject.stateobject.html" class="tsd-signature-type">StateObject</a></h5>
</li>
</ul>
<h4 class="tsd-returns-title">Returns <a href="../classes/_uirouter_core_resolve_resolvable.resolvable.html" class="tsd-signature-type">Resolvable</a><span class="tsd-signature-symbol">[]</span></h4>
</li>
</ul>
</section>
</section>
</div>
<div class="col-4 col-menu menu-sticky-wrap menu-highlight">
<nav class="tsd-navigation primary">
<ul>
<li class="label ">
<span></span>
</li>
<li class="current tsd-kind-class tsd-parent-kind-module tsd-is-external">
<a href="../classes/_uirouter_core_router.uirouter.html">UIRouter</a>
</li>
<li class="label ">
<span>Services</span>
</li>
<li class="current tsd-kind-class tsd-parent-kind-module tsd-is-external">
<a href="../classes/_uirouter_core_state_stateservice.stateservice.html">State<wbr>Service</a>
</li>
<li class="current tsd-kind-class tsd-parent-kind-module tsd-is-external">
<a href="../classes/_uirouter_core_state_stateregistry.stateregistry.html">State<wbr>Registry</a>
</li>
<li class="current tsd-kind-class tsd-parent-kind-module tsd-is-external">
<a href="../classes/_uirouter_core_transition_transitionservice.transitionservice.html">Transition<wbr>Service</a>
</li>
<li class="current tsd-kind-class tsd-parent-kind-module tsd-is-external">
<a href="../classes/_uirouter_core_url_urlservice.urlservice.html">Url<wbr>Service</a>
</li>
<li class="current tsd-kind-class tsd-parent-kind-module tsd-is-external">
<a href="../classes/_uirouter_core_url_urlconfig.urlconfig.html">Url<wbr>Config</a>
</li>
<li class="current tsd-kind-class tsd-parent-kind-module tsd-is-external">
<a href="../classes/_uirouter_core_url_urlrules.urlrules.html">Url<wbr>Rules</a>
</li>
<li class="label ">
<span>Interfaces</span>
</li>
<li class="current tsd-kind-interface tsd-parent-kind-module tsd-is-external">
<a href="../interfaces/_interface_.ng2statedeclaration.html">Ng2<wbr>State<wbr>Declaration</a>
</li>
<li class="current tsd-kind-interface tsd-parent-kind-module tsd-is-external">
<a href="../interfaces/_interface_.uionparamschanged.html">Ui<wbr>OnParams<wbr>Changed</a>
</li>
<li class="current tsd-kind-interface tsd-parent-kind-module tsd-is-external">
<a href="../interfaces/_interface_.uionexit.html">Ui<wbr>OnExit</a>
</li>
<li class="label ">
<span>Components</span>
</li>
<li class="current tsd-kind-class tsd-parent-kind-module tsd-is-external">
<a href="../classes/_directives_uiview_.uiview.html">UIView</a>
</li>
<li class="current tsd-kind-class tsd-parent-kind-module tsd-is-external">
<a href="../classes/_directives_uisref_.uisref.html">UISref</a>
</li>
<li class="current tsd-kind-class tsd-parent-kind-module tsd-is-external">
<a href="../classes/_directives_uisrefactive_.uisrefactive.html">UISref<wbr>Active</a>
</li>
<li class="label ">
<span>Other</span>
</li>
<li class="current tsd-kind-class tsd-parent-kind-module tsd-is-external">
<a href="../classes/_uirouter_core_transition_transition.transition.html">Transition</a>
</li>
<li class="current tsd-kind-class tsd-parent-kind-module tsd-is-external">
<a href="../classes/_uirouter_core_common_trace.trace.html">Trace</a>
</li>
</ul>
</nav>
<nav class="tsd-navigation secondary menu-sticky">
<ul class="before-current">
<li class=" tsd-kind-class tsd-parent-kind-module tsd-is-external">
<a href="../classes/_uirouter_core_state_statebuilder.statebuilder.html" class="tsd-kind-icon">State<wbr>Builder</a>
</li>
<li class=" tsd-kind-type-alias tsd-parent-kind-module tsd-is-external">
<a href="_uirouter_core_state_statebuilder.html#builderfunction" class="tsd-kind-icon">Builder<wbr>Function</a>
</li>
<li class=" tsd-kind-function tsd-parent-kind-module tsd-is-external">
<a href="_uirouter_core_state_statebuilder.html#resolvablesbuilder" class="tsd-kind-icon">resolvables<wbr>Builder</a>
</li>
</ul>
</nav>
</div>
</div>
</div>
<footer class="with-border-bottom">
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
</div>
</div>
</footer>
<div class="container tsd-generator">
<p>Generated using <a href="https://typedoc.org/" target="_blank">TypeDoc</a></p>
</div>
<div class="overlay"></div>
<script src="../assets/js/main.js"></script>
</body>
</html> | {
"content_hash": "50ef90de1803b9edb2baf83517fc5847",
"timestamp": "",
"source": "github",
"line_count": 299,
"max_line_length": 620,
"avg_line_length": 54.147157190635454,
"alnum_prop": 0.6568252007411983,
"repo_name": "ui-router/ui-router.github.io",
"id": "6548f717470f3be1aad0461b9b1b14d311b4b672",
"size": "16198",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "_ng2_docs/7.0.0/modules/_uirouter_core_state_statebuilder.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4640890"
},
{
"name": "HTML",
"bytes": "276915023"
},
{
"name": "JavaScript",
"bytes": "831953"
},
{
"name": "Ruby",
"bytes": "140"
},
{
"name": "SCSS",
"bytes": "66332"
},
{
"name": "Shell",
"bytes": "5090"
}
],
"symlink_target": ""
} |
package org.apache.druid.segment.filter;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
import org.apache.druid.java.util.common.StringUtils;
import org.apache.druid.query.BitmapResultFactory;
import org.apache.druid.query.extraction.ExtractionFn;
import org.apache.druid.query.filter.BitmapIndexSelector;
import org.apache.druid.query.filter.DruidDoublePredicate;
import org.apache.druid.query.filter.DruidFloatPredicate;
import org.apache.druid.query.filter.DruidLongPredicate;
import org.apache.druid.query.filter.DruidPredicateFactory;
import org.apache.druid.query.filter.Filter;
import org.apache.druid.query.filter.FilterTuning;
import org.apache.druid.query.filter.ValueMatcher;
import org.apache.druid.query.filter.vector.VectorValueMatcher;
import org.apache.druid.query.filter.vector.VectorValueMatcherColumnStrategizer;
import org.apache.druid.segment.ColumnSelector;
import org.apache.druid.segment.ColumnSelectorFactory;
import org.apache.druid.segment.DimensionHandlerUtils;
import org.apache.druid.segment.vector.VectorColumnSelectorFactory;
import java.util.Set;
/**
*/
public class DimensionPredicateFilter implements Filter
{
private final String dimension;
private final DruidPredicateFactory predicateFactory;
private final String basePredicateString;
private final ExtractionFn extractionFn;
private final FilterTuning filterTuning;
public DimensionPredicateFilter(
final String dimension,
final DruidPredicateFactory predicateFactory,
final ExtractionFn extractionFn
)
{
this(dimension, predicateFactory, extractionFn, null);
}
public DimensionPredicateFilter(
final String dimension,
final DruidPredicateFactory predicateFactory,
final ExtractionFn extractionFn,
final FilterTuning filterTuning
)
{
Preconditions.checkNotNull(predicateFactory, "predicateFactory");
this.dimension = Preconditions.checkNotNull(dimension, "dimension");
this.basePredicateString = predicateFactory.toString();
this.extractionFn = extractionFn;
this.filterTuning = filterTuning;
if (extractionFn == null) {
this.predicateFactory = predicateFactory;
} else {
this.predicateFactory = new DruidPredicateFactory()
{
final Predicate<String> baseStringPredicate = predicateFactory.makeStringPredicate();
@Override
public Predicate<String> makeStringPredicate()
{
return input -> baseStringPredicate.apply(extractionFn.apply(input));
}
@Override
public DruidLongPredicate makeLongPredicate()
{
return input -> baseStringPredicate.apply(extractionFn.apply(input));
}
@Override
public DruidFloatPredicate makeFloatPredicate()
{
return input -> baseStringPredicate.apply(extractionFn.apply(input));
}
@Override
public DruidDoublePredicate makeDoublePredicate()
{
return input -> baseStringPredicate.apply(extractionFn.apply(input));
}
};
}
}
@Override
public <T> T getBitmapResult(BitmapIndexSelector selector, BitmapResultFactory<T> bitmapResultFactory)
{
return Filters.matchPredicate(dimension, selector, bitmapResultFactory, predicateFactory.makeStringPredicate());
}
@Override
public ValueMatcher makeMatcher(ColumnSelectorFactory factory)
{
return Filters.makeValueMatcher(factory, dimension, predicateFactory);
}
@Override
public VectorValueMatcher makeVectorMatcher(final VectorColumnSelectorFactory factory)
{
return DimensionHandlerUtils.makeVectorProcessor(
dimension,
VectorValueMatcherColumnStrategizer.instance(),
factory
).makeMatcher(predicateFactory);
}
@Override
public boolean canVectorizeMatcher()
{
return true;
}
@Override
public Set<String> getRequiredColumns()
{
return ImmutableSet.of(dimension);
}
@Override
public boolean supportsBitmapIndex(BitmapIndexSelector selector)
{
return selector.getBitmapIndex(dimension) != null;
}
@Override
public boolean shouldUseBitmapIndex(BitmapIndexSelector selector)
{
return Filters.shouldUseBitmapIndex(this, selector, filterTuning);
}
@Override
public boolean supportsSelectivityEstimation(ColumnSelector columnSelector, BitmapIndexSelector indexSelector)
{
return Filters.supportsSelectivityEstimation(this, dimension, columnSelector, indexSelector);
}
@Override
public double estimateSelectivity(BitmapIndexSelector indexSelector)
{
return Filters.estimateSelectivity(
dimension,
indexSelector,
predicateFactory.makeStringPredicate()
);
}
@Override
public String toString()
{
if (extractionFn != null) {
return StringUtils.format("%s(%s) = %s", extractionFn, dimension, basePredicateString);
} else {
return StringUtils.format("%s = %s", dimension, basePredicateString);
}
}
}
| {
"content_hash": "303896ed001730969bdf1dd93a86cf39",
"timestamp": "",
"source": "github",
"line_count": 165,
"max_line_length": 116,
"avg_line_length": 30.587878787878786,
"alnum_prop": 0.7501486031305726,
"repo_name": "deltaprojects/druid",
"id": "6029db54e5458e367be48f209c9eb402b3b36694",
"size": "5854",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "processing/src/main/java/org/apache/druid/segment/filter/DimensionPredicateFilter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "4575"
},
{
"name": "CSS",
"bytes": "101151"
},
{
"name": "Dockerfile",
"bytes": "7491"
},
{
"name": "HTML",
"bytes": "20210"
},
{
"name": "Java",
"bytes": "25726182"
},
{
"name": "JavaScript",
"bytes": "356973"
},
{
"name": "Makefile",
"bytes": "659"
},
{
"name": "PostScript",
"bytes": "5"
},
{
"name": "Python",
"bytes": "53060"
},
{
"name": "R",
"bytes": "17002"
},
{
"name": "Roff",
"bytes": "3617"
},
{
"name": "Shell",
"bytes": "49585"
},
{
"name": "TSQL",
"bytes": "8021"
},
{
"name": "TeX",
"bytes": "399508"
},
{
"name": "Thrift",
"bytes": "1003"
},
{
"name": "TypeScript",
"bytes": "847969"
}
],
"symlink_target": ""
} |
/**
*
*/
package com.sivalabs.jcart.admin.security;
/**
* @author Siva
*
*/
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, proxyTargetClass = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService customUserDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/resources/**", "/webjars/**","/assets/**").permitAll()
.antMatchers("/", "/forgotPwd","/resetPwd").permitAll()
//.antMatchers(HttpMethod.POST,"/api","/api/**").hasRole("ROLE_ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.failureUrl("/login?error")
.permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
//.logoutUrl("/logout")
.permitAll()
.and()
.exceptionHandling().accessDeniedPage("/403");
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(customUserDetailsService)
.passwordEncoder(passwordEncoder());
}
}
| {
"content_hash": "a7e4d319ada029d9932c5dacee3ac376",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 107,
"avg_line_length": 38.36363636363637,
"alnum_prop": 0.7010268562401264,
"repo_name": "sivaprasadreddy/jcart",
"id": "a8bc9b2bb365d99728ac3713a7244552ed63b7c9",
"size": "2532",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jcart-admin/src/main/java/com/sivalabs/jcart/admin/security/WebSecurityConfig.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "31046"
},
{
"name": "HTML",
"bytes": "115907"
},
{
"name": "Java",
"bytes": "121418"
},
{
"name": "JavaScript",
"bytes": "11305"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using 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.
[assembly: AssemblyTitle("03.GroupNumbers")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("03.GroupNumbers")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d1636b98-7705-4903-8f2e-3c26ff85fb12")]
// 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": "499699ab32983a649c589fb019ce47c0",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 84,
"avg_line_length": 38.833333333333336,
"alnum_prop": 0.7474964234620887,
"repo_name": "krasiymihajlov/Soft-Uni-practices",
"id": "ce51ce1e74fa82f060637ddaeb2eb594882fe6c2",
"size": "1401",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "C# Advanced/03. Matrices/Matrices - Lab/03.GroupNumbers/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1012199"
},
{
"name": "HTML",
"bytes": "568"
}
],
"symlink_target": ""
} |
// This file is automatically generated.
package adila.db;
/*
* Polaroid Infinite
*
* DEVICE: MID1324
* MODEL: MID 1324
*/
final class mid1324_mid201324 {
public static final String DATA = "Polaroid|Infinite|";
}
| {
"content_hash": "b6ea9ba431538ce419b0d149c438b0d3",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 59,
"avg_line_length": 17.23076923076923,
"alnum_prop": 0.6964285714285714,
"repo_name": "karim/adila",
"id": "a7e08161f0a956bce1d06985277b24d392eaaa79",
"size": "224",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "database/src/main/java/adila/db/mid1324_mid201324.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "2903103"
},
{
"name": "Prolog",
"bytes": "489"
},
{
"name": "Python",
"bytes": "3280"
}
],
"symlink_target": ""
} |
import { browserHistory } from 'react-router';
export const history = browserHistory;
| {
"content_hash": "ca82ecf2ec029bde01043332ff79915d",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 46,
"avg_line_length": 29,
"alnum_prop": 0.7701149425287356,
"repo_name": "tiberiusuciu/rpg-io",
"id": "3ae2ab6a47715030c71a5faf6eb43031c084ead0",
"size": "87",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "app/services.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1404"
},
{
"name": "HTML",
"bytes": "332"
},
{
"name": "JavaScript",
"bytes": "40079"
}
],
"symlink_target": ""
} |
A Ruby gem for managing version numbers in a project.
## Installation
Add this line to your application's Gemfile:
gem 'aversion'
And then execute:
$ bundle
Or install it yourself as:
$ gem install aversion
## Usage
Add the following line to your capistrano recipe:
require 'aversion/capistrano'
## Contributing
1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request
| {
"content_hash": "f3f8f6ca3d468642df71c265a411311e",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 64,
"avg_line_length": 19.344827586206897,
"alnum_prop": 0.7201426024955436,
"repo_name": "westarete/aversion",
"id": "cd10baa2f5f3a0af68d36c013b93e56114009b94",
"size": "573",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "1583"
}
],
"symlink_target": ""
} |
namespace ShadowPanelTest
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.shadowPanel1 = new ShadowPanel.ShadowPanel();
this.SuspendLayout();
//
// shadowPanel1
//
this.shadowPanel1.BackColor = System.Drawing.Color.Transparent;
this.shadowPanel1.BorderColor = System.Drawing.Color.Black;
this.shadowPanel1.Location = new System.Drawing.Point(12, 12);
this.shadowPanel1.Name = "shadowPanel1";
this.shadowPanel1.PanelColor = System.Drawing.Color.FromArgb(((int)(((byte)(216)))), ((int)(((byte)(232)))), ((int)(((byte)(254)))));
this.shadowPanel1.Size = new System.Drawing.Size(282, 131);
this.shadowPanel1.TabIndex = 0;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(311, 160);
this.Controls.Add(this.shadowPanel1);
this.Name = "Form1";
this.Text = "Drop shadow";
this.ResumeLayout(false);
}
#endregion
private ShadowPanel.ShadowPanel shadowPanel1;
}
}
| {
"content_hash": "011603c03938b9d3d75fe569537aafe3",
"timestamp": "",
"source": "github",
"line_count": 62,
"max_line_length": 145,
"avg_line_length": 35.403225806451616,
"alnum_prop": 0.564009111617312,
"repo_name": "flysnoopy1984/DDZ_Live",
"id": "ea7c6549a53a985959c3d9c881f51c0dc48c4973",
"size": "2195",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ReferenceCode/shadowpanel/ShadowPanel/ShadowPanelTest/Form1.Designer.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1135357"
},
{
"name": "CSS",
"bytes": "9423"
},
{
"name": "XSLT",
"bytes": "37041"
}
],
"symlink_target": ""
} |
package Dec2020Leetcode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
public class _0957PrisonCellsAfterNDays {
public static void main(String[] args) {
System.out.println(Arrays.toString(prisonAfterNDays(new int[] { 0, 1, 0, 1, 1, 0, 0, 1 }, 7)));
System.out.println(Arrays.toString(prisonAfterNDays(new int[] { 1, 0, 0, 1, 0, 0, 1, 0 }, 1000000000)));
}
public static int[] prisonAfterNDays(int[] cells, int N) {
HashMap<Integer, int[]> intStrMap = new HashMap<Integer, int[]>();
HashMap<String, Integer> strIntMap = new HashMap<String, Integer>();
HashSet<String> set = new HashSet<String>();
int[] prevState = cells;
for (int i = 0; i < N; i++) {
String prevStr = Arrays.toString(prevState);
if (set.contains(prevStr)) {
int repLength = set.size();
int extra = N % repLength;
return intStrMap.get(extra+1);
} else {
set.add(prevStr);
strIntMap.put(prevStr, i);
intStrMap.put(i, prevState);
int[] nextState = new int[cells.length];
for (int j = 1; j < nextState.length - 1; j++) {
int count = prevState[j - 1] + prevState[j + 1];
nextState[j] = count == 1 ? 0 : 1;
}
prevState = nextState;
}
}
return prevState;
}
}
| {
"content_hash": "8b97473ebaa1eaae6c6a88cb34eea1ed",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 106,
"avg_line_length": 31.76923076923077,
"alnum_prop": 0.6408393866020985,
"repo_name": "darshanhs90/Java-Coding",
"id": "f505c9176e4c015c3a262c858164267a7c99a4b7",
"size": "1239",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/Dec2020Leetcode/_0957PrisonCellsAfterNDays.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "1895320"
}
],
"symlink_target": ""
} |
'use strict';
_.sum = function(arr) { return _.reduce(arr, function(a, b) { return a+b; }, 0); };
_.average = function(arr) { return _.sum(arr) / arr.length; };
_.clamp = function(value, min, max) { return Math.min(max, Math.max(min, value)); };
angular.module('audioVizApp')
.constant('BLEND_DURATION', 1000)
.constant('SWITCH_FREQUENCY', 5000)
.service('TerrainModel', function(FakeRandom, BLEND_DURATION) {
function interpolate(a, b, t) { return a + (b-a) * t; }
function easeOutCubic(a, b, t) { t--; return a + (b-a) * (t*t*t-1); }
function createModel(options, random_function) {
options.size = options.size || 64;
options.smoothness = options.smoothness || 1.0;
//options.zScale = options.zScale || 200;
return generateTerrain(options.size, options.size, options.smoothness, random_function);
}
function modifyMesh(mesh, size, f) {
mesh.geometry.verticesNeedUpdate = true;
var vertices = mesh.geometry.vertices;
for (var i = 0; i < size; ++i) {
for (var j = 0; j < size; ++j) {
vertices[i * size + j].z = f(i, j);
}
}
return mesh;
}
var constructor = function(options) {
options = angular.copy(options);
var randomGen = FakeRandom.new(),
model = createModel(options, randomGen.next),
peaks = getPeaks(model, 5),
target_model = model,
blank_mesh = getTerrainMesh(model, 10),
service = {},
since_blend_start = 0;
service.update = function(new_options, delta_time) {
since_blend_start += delta_time;
if (new_options.size !== options.size || new_options.smoothness !== options.smoothness) {
randomGen.seek(0);
target_model = createModel(new_options, randomGen.next);
model = target_model;
peaks = getPeaks(target_model, 5);
blank_mesh = getTerrainMesh(model, new_options.zScale);
options = angular.copy(new_options);
}
};
var prevZ = 1;
service.getMesh = function(zScale) {
var t = 0.8;
var newZ = prevZ * (1-t) + t * zScale;
var a = _.clamp(since_blend_start/BLEND_DURATION, 0, 1);
modifyMesh(blank_mesh, model.length, function(i, j) {
return interpolate(model[i][j], target_model[i][j], a) * newZ;
});
prevZ = newZ;
return blank_mesh;
};
service.generateNextTarget = function() {
randomGen = FakeRandom.new();
model = target_model;
target_model = createModel(options, randomGen.next);
peaks = getPeaks(target_model, 5);
since_blend_start = 0;
};
service.peaks = peaks;
service.peakPosition = function(peak) {
var size = model.length;
var i = peak[0]*size+peak[1];
window.mesh = blank_mesh;
console.log(i, size, blank_mesh.geometry.vertices.length, blank_mesh.geometry.vertices[i]);
return blank_mesh.geometry.vertices[i];
};
return service;
};
return { new: constructor };
})
.controller('Terrain', function($scope, AudioService, TerrainModel, Dancer, SWITCH_FREQUENCY) {
$scope.Dancer = Dancer;
var scene, camera, cameraControls, composer, mesh;
$scope.camera = {
fov: 45,
near: 1,
far: 5000
};
$scope.modelOpts = {
size: 64,
smoothness: 1.0,
zScale: 200
};
$scope.anim = {
switchEveryBeat: false
};
$scope.scene_init = function(renderer, width, height) {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera($scope.camera.fov, width / height,
$scope.camera.near, $scope.camera.far);
camera.position.y = 400;
// transparently support window resize
//THREEx.WindowResize.bind(renderer, camera);
composer = new THREE.EffectComposer( renderer );
renderer.autoClear = false;
$scope.model = TerrainModel.new($scope.modelOpts);
mesh = $scope.model.getMesh($scope.modelOpts.zScale);
setupLights();
scene.add(mesh);
console.log(mesh);
};
function setupLights() {
var ambientLight = new THREE.AmbientLight(0xffffff, 0.1);
//scene.add(ambientLight);
var mainLight = new THREE.SpotLight(0xffffff, 1.0);
mainLight.position.set(500, 500, 500);
mainLight.castShadow = true;
scene.add(mainLight);
var auxLight = new THREE.SpotLight(0xffffff, 1.0);
auxLight.position.set(-300, 500, -400);
auxLight.castShadow = true;
scene.add(auxLight);
}
var sinceLastChange = 0;
$scope.render = function(renderer, time_delta) {
var timer = new Date().getTime() * 0.0001;
camera.position.x = Math.cos(timer) * 800;
camera.position.z = Math.sin(timer) * 200;
camera.lookAt(scene.position);
$scope.model.update($scope.modelOpts, time_delta);
//scene.remove(mesh);
var new_mesh = $scope.model.getMesh($scope.modelOpts.zScale);
if (new_mesh.uuid != mesh.uuid) {
scene.remove(mesh);
mesh = new_mesh;
scene.add(mesh);
}
sinceLastChange += time_delta;
var spectrum = AudioService.spectrum();
//if (Dancer.is_beat) {
//renderer.clear();
//return;
//}
if ((sinceLastChange >= SWITCH_FREQUENCY || $scope.anim.switchEveryBeat) && Dancer.is_beat) {
console.log('Switching layout', sinceLastChange);
sinceLastChange = 0;
$scope.model.generateNextTarget();
}
$scope.modelOpts.zScale = Math.min(1000, 1000 * AudioService.volume());
renderer.clear();
renderer.render(scene, camera);
};
// $scope.$watch('modelOpts.size', function(newOpt) {
// $scope.model.update($scope.modelOpts);
// scene.remove(mesh);
// mesh = $scope.model.getMesh($scope.modelOpts.zScale);
// scene.add(mesh);
// });
}); | {
"content_hash": "8d9edc6b96cf946436c89c8239145a0f",
"timestamp": "",
"source": "github",
"line_count": 181,
"max_line_length": 99,
"avg_line_length": 32.8232044198895,
"alnum_prop": 0.5940077428042417,
"repo_name": "UIKit0/WebGL-Audio-Visualization",
"id": "5491e3795aa971372b1f32c09535aad41fe819a9",
"size": "5941",
"binary": false,
"copies": "4",
"ref": "refs/heads/gh-pages",
"path": "js/controllers/Terrain.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "1083"
},
{
"name": "Batchfile",
"bytes": "1211"
},
{
"name": "C++",
"bytes": "85345"
},
{
"name": "CSS",
"bytes": "64832"
},
{
"name": "CoffeeScript",
"bytes": "88497"
},
{
"name": "GLSL",
"bytes": "591"
},
{
"name": "Groff",
"bytes": "18182"
},
{
"name": "HTML",
"bytes": "2864187"
},
{
"name": "JavaScript",
"bytes": "4075302"
},
{
"name": "Makefile",
"bytes": "7163"
},
{
"name": "Python",
"bytes": "256669"
},
{
"name": "Ruby",
"bytes": "281"
},
{
"name": "Shell",
"bytes": "12630"
}
],
"symlink_target": ""
} |
<?php
namespace PHPSocketIO\Event;
use Symfony\Component\EventDispatcher\Event;
use PHPSocketIO\ConnectionInterface;
/**
* Description of MessageEvent
*
* @author ricky
*/
class MessageEvent extends Event
{
protected $message;
protected $connection;
protected $endpoint;
public function getEndpoint()
{
return $this->endpoint;
}
public function setEndpoint($endpoint)
{
return $this->endpoint = $endpoint;
}
public function setMessage($message)
{
$this->message = $message;
return true;
}
public function setConnection(ConnectionInterface $connection)
{
$this->connection = $connection;
return true;
}
public function getConnection()
{
return $this->connection;
}
public function getMessage()
{
return $this->message;
}
}
| {
"content_hash": "9971349577ee415d7c1910ac116b542d",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 66,
"avg_line_length": 16.425925925925927,
"alnum_prop": 0.6268320180383314,
"repo_name": "yiliaofan/phpsocket.io",
"id": "c34aa67ffc341cd422270d0a25a728cef9caf897",
"size": "887",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/PHPSocketIO/Event/MessageEvent.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1952"
},
{
"name": "JavaScript",
"bytes": "70641"
},
{
"name": "PHP",
"bytes": "75200"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?><!--
~ Copyright 2016 "Henry Tao <hi@henrytao.me>"
~
~ 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.
-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
style="@style/MdToolbar" />
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="@dimen/mdLayoutSpacing">
<TextView
android:text="Display 4"
style="@style/MdText.Display4" />
<TextView
android:text="Display 3"
style="@style/MdText.Display3" />
<TextView
android:text="Display 2"
style="@style/MdText.Display2" />
<TextView
android:text="Display 1"
style="@style/MdText.Display1" />
<TextView
android:text="Headline"
style="@style/MdText.Headline" />
<TextView
android:text="Title"
style="@style/MdText.Title" />
<TextView
android:text="Subheading"
style="@style/MdText.Subhead1" />
<TextView
android:text="Body 2"
style="@style/MdText.Body2" />
<TextView
android:text="Body 1"
style="@style/MdText.Body1" />
<TextView
android:text="Caption"
style="@style/MdText.Caption" />
<TextView
android:text="Button"
style="@style/MdText.Button" />
<TextView
android:text="Custom font"
app:mdTypography="fonts/custom/Cookie-Regular.ttf"
tools:ignore="MissingPrefix"
style="@style/MdText.Display1" />
<View style="@style/MdDivider" />
<TextView
android:text="@string/sample_others"
style="@style/MdText.Display2" />
<TextView
android:text="@string/sample_science"
style="@style/MdText.Subhead1" />
<TextView
android:text="@string/sample_others"
style="@style/MdText.Headline" />
<TextView
android:text="@string/sample_science"
style="@style/MdText.Body1" />
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
</LinearLayout> | {
"content_hash": "57e361591a75d578dfa4f7ba2f857648",
"timestamp": "",
"source": "github",
"line_count": 108,
"max_line_length": 76,
"avg_line_length": 28.77777777777778,
"alnum_prop": 0.638030888030888,
"repo_name": "henrytao-me/android-md-core",
"id": "0d45f96fa08f51d1a69ffdf3d8129835257ddbea",
"size": "3108",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sample/src/main/res/layout/activity_typography.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "119011"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Euro+Med Plantbase
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "c0e591540a546bd1e46198aa1d38953c",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 18,
"avg_line_length": 8.692307692307692,
"alnum_prop": 0.6814159292035398,
"repo_name": "mdoering/backbone",
"id": "45e6f531c7c59d00286d7d3a5010275e7afd8b8b",
"size": "186",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Aster/Aster indamellus/Aster amellus bessarabicus/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
module Aqua
module Initializers
def self.included( klass )
klass.class_eval do
include InstanceMethods
extend ClassMethods
unless methods.include?( :transient_attr )
include Aqua::Pack::HiddenAttributes
end
end
end
module InstanceMethods
def to_aqua( path = '' )
rat = Aqua::Translator::Rat.new( { 'class' => to_aqua_class } )
init_rat = to_aqua_init( path )
rat.hord(init_rat, 'init')
ivar_rat = _pack_instance_vars( path )
rat.eat( ivar_rat ) if ivar_rat && ivar_rat.pack['ivars'] && !ivar_rat.pack['ivars'].empty?
rat
end
def to_aqua_class
self.class.to_s
end
def _pack_instance_vars( path )
rat = Aqua::Translator::Rat.new
ivar_rat = Translator.pack_ivars( self )
ivar_rat.pack.empty? ? rat : rat.hord( ivar_rat, 'ivars' )
end
def to_aqua_init( path )
Aqua::Translator::Rat.new( self.to_s )
end
end # InstanceMethods
module ClassMethods
end # ClassMethods
end # Initializers
end
[ TrueClass, FalseClass, Symbol, Time, Date, Fixnum, Bignum, Float, Rational, Hash, Array, OpenStruct, Range, File, Tempfile, String, NilClass].each do |klass|
klass.class_eval { include Aqua::Initializers }
end
class String
def from_aqua( path='')
self
end
def to_aqua( path='' )
Aqua::Translator::Rat.new( self )
end
end
class TrueClass
def from_aqua( path='')
true
end
def to_aqua( path='')
Aqua::Translator::Rat.new( true )
end
end
class FalseClass
def from_aqua( path='')
false
end
def to_aqua( path='' )
Aqua::Translator::Rat.new( false )
end
end
class NilClass
def self.aqua_init( init, opts=Aqua::Translator::Opts.new )
nil
end
end
class Symbol
def self.aqua_init( init, opts=Aqua::Translator::Opts.new )
init.to_sym
end
def _pack_instance_vars( path='')
nil
end
end
class Date
transient_attr :sg, :of, :ajd
def self.aqua_init( init, opts=Aqua::Translator::Opts.new )
parse( init )
end
def _pack_instance_vars( path='')
nil
end
end
class Time
def self.aqua_init( init, opts=Aqua::Translator::Opts.new )
parse( init )
end
end
class Fixnum
def self.aqua_init( init, opts=Aqua::Translator::Opts.new )
init.to_i
end
end
class Bignum
def self.aqua_init( init, opts=Aqua::Translator::Opts.new )
init.to_i
end
end
class Float
def self.aqua_init( init, opts=Aqua::Translator::Opts.new )
init.to_f
end
end
class Rational
def to_aqua_init( path='')
Aqua::Translator::Rat.new( self.to_s.match(/(\d*)\/(\d*)/).to_a.slice(1,2) )
end
def self.aqua_init( init, opts=Aqua::Translator::Opts.new )
Rational( init[0].to_i, init[1].to_i )
end
def _pack_instance_vars( path='')
nil
end
end
class Range
# todo: make this work for non int objects, time, date, etc ...
def self.aqua_init( init, opts=Aqua::Translator::Opts.new )
eval( init )
end
end
class Array
def to_aqua_init( path = '' )
rat = Aqua::Translator::Rat.new([])
self.each_with_index do |obj, index|
local_path = path + "[#{index}]"
obj_rat = Aqua::Translator.pack_object( obj, local_path )
rat.eat( obj_rat )
end
rat
end
def self.aqua_init( init, opts=Aqua::Translator::Opts.new )
# todo: make opts opts.path follow the path through the base object
array_init = init.map{ |obj| Aqua::Translator.unpack_object(obj, opts) }
# new is neccessary to make sure array derivatives maintain their class
# without having to override aqua_init!
self == Array ? array_init : new( array_init )
end
end
class Hash
def to_aqua_init( path='')
rat = Aqua::Translator::Rat.new
self.each do |raw_key, value|
key_class = raw_key.class
if key_class == String
key = raw_key
else # key is an object
index = aqua_next_object_index( rat.pack )
key = self.class.aqua_object_key_index( index )
key_rat = Aqua::Translator.pack_object( raw_key, path+"['#{self.class.aqua_key_register}'][#{index}]")
rat.hord( key_rat, [self.class.aqua_key_register, index] )
end
obj_rat = Aqua::Translator.pack_object( value, path+"['#{key}']" )
rat.hord( obj_rat, key )
end
rat
end
def self.aqua_key_register
"#{aqua_key_register_prefix}KEYS".freeze
end
def self.aqua_key_register_prefix
"/_OBJECT_"
end
def self.aqua_object_key_index( index )
"#{aqua_key_register_prefix}#{index}"
end
def aqua_next_object_index( hash )
hash[self.class.aqua_key_register] ||= []
hash[self.class.aqua_key_register].size
end
def self.aqua_init( init, opts=Aqua::Translator::Opts.new )
unpacked = {}
init.each do |key, value|
unless key == aqua_key_register
if key.match(/^#{aqua_key_register_prefix}(\d*)$/)
index = $1.to_i
key = Aqua::Translator.unpack_object( init[aqua_key_register][index], opts )
end
opts.path += "[#{key}]"
value = Aqua::Translator.unpack_object( value, opts )
unpacked[ key ] = value
end
end
self == Hash ? unpacked : new( unpacked )
end
end
class OpenStruct
transient_attr :table
def to_aqua_init( path='' )
instance_variable_get("@table").to_aqua_init( path )
end
def self.aqua_init( init, opts=Aqua::Translator::Opts.new )
init = Hash.aqua_init( init, opts )
new( init )
end
end
module Aqua
module FileInitializations
def to_aqua( opts=Aqua::Translator::Opts.new )
rat = Aqua::Translator::Rat.new(
{
'class' => to_aqua_class,
'init' => {
'id' => filename,
'methods' => {
'content_type' => content_type,
'content_length' => content_length
}
}
}, {}, [self]
)
ivar_rat = _pack_instance_vars( path )
rat.eat( ivar_rat ) if ivar_rat && ivar_rat.pack['ivars'] && !ivar_rat.pack['ivars'].empty?
rat
end
def content_length
if len = stat.size
rat = Aqua::Translator.pack_object( len )
rat.pack
else
''
end
end
def content_type
mime = MIME::Types.type_for( self.path )
mime && mime.first ? mime.first.to_s : ''
end
def to_aqua_class
'Aqua::FileStub'
end
def filename
path.match(/([^\/]*)\z/).to_s
end
end # FileInitializations
end # Aqua
class File
include Aqua::FileInitializations
end
class Tempfile
include Aqua::FileInitializations
transient_attr :clean_proc, :data, :tmpname, :tmpfile, :_dc_obj
def filename
path.match(/([^\/]*)\.\d*\.\d*\z/).captures.first
end
end | {
"content_hash": "31fa5d5fb523cab0505fa2d78baeedd4",
"timestamp": "",
"source": "github",
"line_count": 302,
"max_line_length": 159,
"avg_line_length": 23.456953642384107,
"alnum_prop": 0.5765104460756635,
"repo_name": "baccigalupi/aqua",
"id": "82ea18e88fad36fe4ca0486bb804fe7375026d5d",
"size": "7532",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/aqua/object/initializers.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "234004"
}
],
"symlink_target": ""
} |
#include <aws/managedblockchain/model/Network.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace ManagedBlockchain
{
namespace Model
{
Network::Network() :
m_idHasBeenSet(false),
m_nameHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_framework(Framework::NOT_SET),
m_frameworkHasBeenSet(false),
m_frameworkVersionHasBeenSet(false),
m_frameworkAttributesHasBeenSet(false),
m_vpcEndpointServiceNameHasBeenSet(false),
m_votingPolicyHasBeenSet(false),
m_status(NetworkStatus::NOT_SET),
m_statusHasBeenSet(false),
m_creationDateHasBeenSet(false),
m_tagsHasBeenSet(false),
m_arnHasBeenSet(false)
{
}
Network::Network(JsonView jsonValue) :
m_idHasBeenSet(false),
m_nameHasBeenSet(false),
m_descriptionHasBeenSet(false),
m_framework(Framework::NOT_SET),
m_frameworkHasBeenSet(false),
m_frameworkVersionHasBeenSet(false),
m_frameworkAttributesHasBeenSet(false),
m_vpcEndpointServiceNameHasBeenSet(false),
m_votingPolicyHasBeenSet(false),
m_status(NetworkStatus::NOT_SET),
m_statusHasBeenSet(false),
m_creationDateHasBeenSet(false),
m_tagsHasBeenSet(false),
m_arnHasBeenSet(false)
{
*this = jsonValue;
}
Network& Network::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Id"))
{
m_id = jsonValue.GetString("Id");
m_idHasBeenSet = true;
}
if(jsonValue.ValueExists("Name"))
{
m_name = jsonValue.GetString("Name");
m_nameHasBeenSet = true;
}
if(jsonValue.ValueExists("Description"))
{
m_description = jsonValue.GetString("Description");
m_descriptionHasBeenSet = true;
}
if(jsonValue.ValueExists("Framework"))
{
m_framework = FrameworkMapper::GetFrameworkForName(jsonValue.GetString("Framework"));
m_frameworkHasBeenSet = true;
}
if(jsonValue.ValueExists("FrameworkVersion"))
{
m_frameworkVersion = jsonValue.GetString("FrameworkVersion");
m_frameworkVersionHasBeenSet = true;
}
if(jsonValue.ValueExists("FrameworkAttributes"))
{
m_frameworkAttributes = jsonValue.GetObject("FrameworkAttributes");
m_frameworkAttributesHasBeenSet = true;
}
if(jsonValue.ValueExists("VpcEndpointServiceName"))
{
m_vpcEndpointServiceName = jsonValue.GetString("VpcEndpointServiceName");
m_vpcEndpointServiceNameHasBeenSet = true;
}
if(jsonValue.ValueExists("VotingPolicy"))
{
m_votingPolicy = jsonValue.GetObject("VotingPolicy");
m_votingPolicyHasBeenSet = true;
}
if(jsonValue.ValueExists("Status"))
{
m_status = NetworkStatusMapper::GetNetworkStatusForName(jsonValue.GetString("Status"));
m_statusHasBeenSet = true;
}
if(jsonValue.ValueExists("CreationDate"))
{
m_creationDate = jsonValue.GetString("CreationDate");
m_creationDateHasBeenSet = true;
}
if(jsonValue.ValueExists("Tags"))
{
Aws::Map<Aws::String, JsonView> tagsJsonMap = jsonValue.GetObject("Tags").GetAllObjects();
for(auto& tagsItem : tagsJsonMap)
{
m_tags[tagsItem.first] = tagsItem.second.AsString();
}
m_tagsHasBeenSet = true;
}
if(jsonValue.ValueExists("Arn"))
{
m_arn = jsonValue.GetString("Arn");
m_arnHasBeenSet = true;
}
return *this;
}
JsonValue Network::Jsonize() const
{
JsonValue payload;
if(m_idHasBeenSet)
{
payload.WithString("Id", m_id);
}
if(m_nameHasBeenSet)
{
payload.WithString("Name", m_name);
}
if(m_descriptionHasBeenSet)
{
payload.WithString("Description", m_description);
}
if(m_frameworkHasBeenSet)
{
payload.WithString("Framework", FrameworkMapper::GetNameForFramework(m_framework));
}
if(m_frameworkVersionHasBeenSet)
{
payload.WithString("FrameworkVersion", m_frameworkVersion);
}
if(m_frameworkAttributesHasBeenSet)
{
payload.WithObject("FrameworkAttributes", m_frameworkAttributes.Jsonize());
}
if(m_vpcEndpointServiceNameHasBeenSet)
{
payload.WithString("VpcEndpointServiceName", m_vpcEndpointServiceName);
}
if(m_votingPolicyHasBeenSet)
{
payload.WithObject("VotingPolicy", m_votingPolicy.Jsonize());
}
if(m_statusHasBeenSet)
{
payload.WithString("Status", NetworkStatusMapper::GetNameForNetworkStatus(m_status));
}
if(m_creationDateHasBeenSet)
{
payload.WithString("CreationDate", m_creationDate.ToGmtString(DateFormat::ISO_8601));
}
if(m_tagsHasBeenSet)
{
JsonValue tagsJsonMap;
for(auto& tagsItem : m_tags)
{
tagsJsonMap.WithString(tagsItem.first, tagsItem.second);
}
payload.WithObject("Tags", std::move(tagsJsonMap));
}
if(m_arnHasBeenSet)
{
payload.WithString("Arn", m_arn);
}
return payload;
}
} // namespace Model
} // namespace ManagedBlockchain
} // namespace Aws
| {
"content_hash": "f462a5db7bb0d4f706629f7c8a9cd2d0",
"timestamp": "",
"source": "github",
"line_count": 230,
"max_line_length": 94,
"avg_line_length": 21.091304347826085,
"alnum_prop": 0.7052154195011338,
"repo_name": "awslabs/aws-sdk-cpp",
"id": "0d09998587c38a5ca490679110c9e80f556b4c28",
"size": "4970",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-managedblockchain/source/model/Network.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "7596"
},
{
"name": "C++",
"bytes": "61740540"
},
{
"name": "CMake",
"bytes": "337520"
},
{
"name": "Java",
"bytes": "223122"
},
{
"name": "Python",
"bytes": "47357"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/app_icon"
android:layout_width="55dp"
android:layout_height="55dp"
android:minWidth="@android:dimen/app_icon_size"
android:minHeight="@android:dimen/app_icon_size"
android:layout_gravity="center_horizontal" />
<TextView
android:id="@+id/app_label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-condensed"
style="@style/AppItemGrid" />
<View
android:id="@+id/placeholder"
android:layout_width="match_parent"
android:layout_height="@dimen/filter_bar_height"
android:visibility="gone" />
</LinearLayout> | {
"content_hash": "1169a2e508bdb5552f81cded302a01f2",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 72,
"avg_line_length": 32.51851851851852,
"alnum_prop": 0.7072892938496583,
"repo_name": "casidiablo/app.color",
"id": "c6644d18b7c07e66f64c69483c0db535e1ff5e9d",
"size": "878",
"binary": false,
"copies": "1",
"ref": "refs/heads/github",
"path": "app/src/main/res/layout/app_item_grid.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "4195"
},
{
"name": "Java",
"bytes": "288063"
}
],
"symlink_target": ""
} |
var config = require('config')
var sendgrid = require('sendgrid')(config.email.sendgrid.username, config.email.sendgrid.password)
var validator = require('validator')
var logger = require('../../../lib/logger.js')()
exports.post = function (req, res) {
var subject = config.email.feedback_subject
var to = []
var from
var body
var message
var referer
var additionalInformation
to.push(config.email.feedback_recipient)
// Validate body text
try {
body = req.body
} catch (e) {
res.status(400).json({ msg: 'Could not parse body as JSON.' })
return
}
if (!body.hasOwnProperty('message') || (body.message.trim().length === 0)) {
res.status(400).json({ msg: 'Please specify a message.' })
return
}
message = body.message.trim()
// Log feedback
logger.info(body, 'Feedback received.')
// Append referring URL
referer = req.headers.referer || '(not specified)'
message += '\n\n--\nURL: ' + referer
// Validate and add from e-mail address
if (body.from) {
if (validator.isEmail(body.from)) {
from = body.from
to.push(body.from)
subject += ' from ' + from
} else {
message += '\nInvalid from email address specified: ' + body.from + '\n'
}
}
// Append other useful information to message
additionalInformation = body.additionalInformation || ''
message += '\n' + additionalInformation
sendgrid.send({
to: to,
from: from || config.email.feedback_sender_default,
subject: subject,
text: message
}, function (err, json) {
if (err) {
logger.error('Sendgrid: Error sending email. ', json)
res.status(500).json({ msg: 'Could not send feedback.' })
return
}
logger.info('Sendgrid: Feedback accepted. ', json)
res.status(202).json({ msg: 'Feedback accepted.' })
})
} // END function - exports.post
| {
"content_hash": "8298ce7ff144538013cef8017406a29a",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 98,
"avg_line_length": 26.52857142857143,
"alnum_prop": 0.6375875067312871,
"repo_name": "macGRID-SRN/streetmix",
"id": "34f19f1aab8d87201e9d455ae7e42e56eafb8b41",
"size": "1857",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/resources/v1/feedback.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "API Blueprint",
"bytes": "2516"
},
{
"name": "CSS",
"bytes": "56436"
},
{
"name": "HTML",
"bytes": "14150"
},
{
"name": "JavaScript",
"bytes": "422124"
},
{
"name": "Shell",
"bytes": "5140"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "a536d90bd5f0e73e7934b503642f2765",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 18,
"avg_line_length": 8.384615384615385,
"alnum_prop": 0.6788990825688074,
"repo_name": "mdoering/backbone",
"id": "4f37233ce00a6fba1a025487ab555223dbe784ee",
"size": "176",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Cladoniaceae/Cladonia/Cladonia squamosa/Cladonia squamosa asperella/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
<!--
This file is auto-generated from fbocolorbuffer_test_generator.py
DO NOT EDIT!
-->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebGL FBO Color Buffer Conformance Tests</title>
<link rel="stylesheet" href="../../../../resources/js-test-style.css"/>
<script src="../../../../js/js-test-pre.js"></script>
<script src="../../../../js/webgl-test-utils.js"></script>
<script src="../../../../closure-library/closure/goog/base.js"></script>
<script src="../../../deqp-deps.js"></script>
<script>goog.require('functional.gles3.es3fFboColorbufferTests');</script>
</head>
<body>
<div id="description"></div>
<div id="console"></div>
<canvas id="canvas" width="256" height="256"> </canvas>
<script>
var wtu = WebGLTestUtils;
var gl = wtu.create3DContext('canvas', null, 2);
var ext = gl.getExtension('EXT_color_buffer_float');
functional.gles3.es3fFboColorbufferTests.run(gl, [14, 15]);
</script>
</body>
</html>
| {
"content_hash": "b9d2ce2b93acd4caeef8a90403df35fb",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 74,
"avg_line_length": 29.9375,
"alnum_prop": 0.6722338204592901,
"repo_name": "endlessm/chromium-browser",
"id": "e01cee3b22fe8c4f6d4c5c81bc65ebad3552fcf2",
"size": "958",
"binary": false,
"copies": "17",
"ref": "refs/heads/master",
"path": "third_party/webgl/src/conformance-suites/2.0.0/deqp/functional/gles3/fbocolorbuffer/tex2darray_01.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "eb468f95bba374180aea318f429fa92b",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "687815c552dccb6f47f8e0f8d21d18b8b96826b8",
"size": "173",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Saxifragales/Grossulariaceae/Ribes/Ribes odoriferum/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
var CACHE_NAME = 'dependencies-cache';
self.addEventListener('install', function(event) {
// Perform the install step:
// * Load a JSON file from server
// * Parse as JSON
// * Add files to the cache list
// Message to simply show the lifecycle flow
console.log('[install] Kicking off service worker registration!');
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
// With the cache opened, load a JSON file containing an array of files to be cached
return fetch('files-to-cache.json').then(function(response) {
// Once the contents are loaded, convert the raw text to a JavaScript object
return response.json();
}).then(function(files) {
// Use cache.addAll just as you would a hardcoded array of items
console.log('[install] Adding files from JSON file: ', files);
return cache.addAll(files);
});
})
.then(function() {
// Message to simply show the lifecycle flow
console.log(
'[install] All required resources have been cached;',
'the Service Worker was successfully installed!'
);
// Force activation
return self.skipWaiting();
})
);
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return the response from the cached version
if (response) {
console.log(
'[fetch] Returning from Service Worker cache: ',
event.request.url
);
return response;
}
// Not in cache - return the result from the live server
// `fetch` is essentially a "fallback"
console.log('[fetch] Returning from server: ', event.request.url);
return fetch(event.request);
}
)
);
});
self.addEventListener('activate', function(event) {
// Message to simply show the lifecycle flow
console.log('[activate] Activating service worker!');
// Claim the service work for this client, forcing `controllerchange` event
console.log('[activate] Claiming this service worker!');
event.waitUntil(self.clients.claim());
});
| {
"content_hash": "ba6856da519d7e80605cd6ab479adfec",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 92,
"avg_line_length": 33.23880597014925,
"alnum_prop": 0.6281993713515941,
"repo_name": "mozilla/serviceworker-cookbook",
"id": "ced2cc3a4486c3ccc11d3532bc727112f56c9d6a",
"size": "2287",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "json-cache/service-worker.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "42550"
},
{
"name": "HTML",
"bytes": "44704"
},
{
"name": "JavaScript",
"bytes": "475534"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>UMEDITOR 提交示例</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link href="../themes/default/_css/umeditor.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="../third-party/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8" src="../umeditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="editor_api.js"></script>
<script type="text/javascript" src="../lang/zh-cn/zh-cn.js"></script>
<style type="text/css">
h1{
font-family: "微软雅黑";
font-weight: normal;
}
</style>
</head>
<body>
<h1>UMEDITOR 提交示例</h1>
<form id="form" method="post" target="_blank">
<script type="text/plain" id="myEditor" name="myEditor" style="width:800px;height:240px;">
<p>欢迎使用UMEDITOR!</p>
</script>
<input type="submit" value="通过input的submit提交">
</form>
<p>
<button onclick="document.getElementById('form').submit()">通过js调用submit提交</button>
</p>
<script type="text/javascript">
var um = UM.getEditor('myEditor');
//自动切换提交地址
var doc=document,
version=um.options.imageUrl||"php",
form=doc.getElementById("form");
if(version.match(/php/)){
form.action="./server/getContent.php";
}else if(version.match(/net/)){
form.action="./server/getContent.ashx";
}else if(version.match(/jsp/)){
form.action="./server/getContent.jsp";
}else if(version.match(/asp/)){
form.action="./server/getContent.asp";
}
</script>
</body>
</html> | {
"content_hash": "11a680aa4e5cf604ffe0d6cf35d88c62",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 94,
"avg_line_length": 32.96078431372549,
"alnum_prop": 0.6252230814991077,
"repo_name": "GaryGo/CodeIgniter-MiniBlog",
"id": "210ac3bd8ceb1216846f553c87a837ab985a76e6",
"size": "1753",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "static/editor/umeditor/_examples/submitFormDemo.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "114073"
},
{
"name": "ApacheConf",
"bytes": "240"
},
{
"name": "Batchfile",
"bytes": "210"
},
{
"name": "C#",
"bytes": "14616"
},
{
"name": "CSS",
"bytes": "344454"
},
{
"name": "HTML",
"bytes": "5918566"
},
{
"name": "Java",
"bytes": "27819"
},
{
"name": "JavaScript",
"bytes": "6402716"
},
{
"name": "PHP",
"bytes": "2741693"
},
{
"name": "Python",
"bytes": "40557"
},
{
"name": "Shell",
"bytes": "1425"
}
],
"symlink_target": ""
} |
using HTTPlease.Testability;
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace DD.CloudControl.Client.Tests
{
using Models.Directory;
/// <summary>
/// The base class for API client test suites.
/// </summary>
public abstract class ClientTestBase
{
/// <summary>
/// The organisation Id used in tests.
/// </summary>
protected static readonly Guid TestOrganizationId = new Guid("22edd5e3-a235-4d3c-b5b2-d2843aa77d41");
/// <summary>
/// The base address for client APIs.
/// </summary>
protected static readonly Uri ApiBaseAddress = new Uri("http://fake.api/");
/// <summary>
/// Create a new API client test suite.
/// </summary>
protected ClientTestBase()
{
}
/// <summary>
/// Get the default user account information used in tests.
/// </summary>
protected static UserAccount GetDefaultUserAccount() => new UserAccount
{
UserName = "test_user",
FirstName = "Test",
LastName = "User",
FullName = "Test User",
EmailAddress = "test.user@mycompany.com",
Department = "TestDepartment",
OrganizationId = TestOrganizationId
};
/// <summary>
/// Create a URI relative to the base addres for the CloudControl API.
/// </summary>
/// <param name="relativeUri">
/// The relative URI.
/// </param>
/// <returns>
/// The absolute URI.
/// </returns>
protected static Uri CreateApiUri(string relativeUri)
{
return CreateApiUri(
new Uri(relativeUri, UriKind.Relative)
);
}
/// <summary>
/// Create a URI relative to the base addres for the CloudControl API.
/// </summary>
/// <param name="relativeUri">
/// The relative URI.
/// </param>
/// <returns>
/// The absolute URI.
/// </returns>
protected static Uri CreateApiUri(Uri relativeUri)
{
if (relativeUri == null)
throw new ArgumentNullException(nameof(relativeUri));
return new Uri(ApiBaseAddress, relativeUri);
}
/// <summary>
/// Create a new CloudControl API client.
/// </summary>
/// <param name="httpClient">
/// The HTTP client used to communicate with the CloudControl API.
/// </param>
/// <returns>
/// The configured <see cref="CloudControlClient"/>.
/// </returns>
protected static CloudControlClient CreateCloudControlClient(Func<HttpRequestMessage, HttpResponseMessage> handler)
{
if (handler == null)
throw new ArgumentNullException(nameof(handler));
HttpClient httpClient = TestClients.RespondWith(handler);
httpClient.BaseAddress = ApiBaseAddress;
return new CloudControlClient(httpClient);
}
/// <summary>
/// Create a new CloudControl API client pre-populated with the default user account details.
/// </summary>
/// <param name="httpClient">
/// The HTTP client used to communicate with the CloudControl API.
/// </param>
/// <returns>
/// The configured <see cref="CloudControlClient"/>.
/// </returns>
protected static CloudControlClient CreateCloudControlClientWithUserAccount(Func<HttpRequestMessage, Task<HttpResponseMessage>> handler)
{
if (handler == null)
throw new ArgumentNullException(nameof(handler));
HttpClient httpClient = TestClients.AsyncRespondWith(handler);
httpClient.BaseAddress = ApiBaseAddress;
return new CloudControlClient(httpClient,
account: GetDefaultUserAccount()
);
}
/// <summary>
/// Create a new CloudControl API client pre-populated with the default user account details.
/// </summary>
/// <param name="httpClient">
/// The HTTP client used to communicate with the CloudControl API.
/// </param>
/// <returns>
/// The configured <see cref="CloudControlClient"/>.
/// </returns>
protected static CloudControlClient CreateCloudControlClientWithUserAccount(Func<HttpRequestMessage, HttpResponseMessage> handler)
{
if (handler == null)
throw new ArgumentNullException(nameof(handler));
HttpClient httpClient = TestClients.RespondWith(handler);
httpClient.BaseAddress = ApiBaseAddress;
return new CloudControlClient(httpClient,
account: GetDefaultUserAccount()
);
}
/// <summary>
/// Create a new CloudControl API client.
/// </summary>
/// <param name="httpClient">
/// The HTTP client used to communicate with the CloudControl API.
/// </param>
/// <returns>
/// The configured <see cref="CloudControlClient"/>.
/// </returns>
protected static CloudControlClient CreateCloudControlClient(HttpClient httpClient)
{
if (httpClient == null)
throw new ArgumentNullException(nameof(httpClient));
httpClient.BaseAddress = ApiBaseAddress;
return new CloudControlClient(httpClient);
}
}
} | {
"content_hash": "4ca8cd19ff25c4c1aefc394f3c02422a",
"timestamp": "",
"source": "github",
"line_count": 162,
"max_line_length": 138,
"avg_line_length": 28.734567901234566,
"alnum_prop": 0.6891514500537057,
"repo_name": "DimensionDataResearch/cloudcontrol-client-core",
"id": "fea91f5f27b8cdf36d36cfd9935aec2bf46f6ce5",
"size": "4655",
"binary": false,
"copies": "1",
"ref": "refs/heads/development/v1.0",
"path": "test/DD.CloudControl.Client.Tests/ClientTestBase.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "142361"
}
],
"symlink_target": ""
} |
@protocol NIMAdvancedTeamCardHeaderViewDelegate <NSObject>
- (void)onTouchAvatar:(id)sender;
@end
@interface NIMAdvancedTeamCardHeaderView : UIView
@property (nonatomic,strong) NIMAvatarImageView *avatar;
@property (nonatomic,strong) UILabel *titleLabel;
@property (nonatomic,strong) UILabel *numberLabel;
@property (nonatomic,strong) UILabel *createTimeLabel;
@property (nonatomic,strong) NIMTeam *team;
@property (nonatomic,weak) id<NIMAdvancedTeamCardHeaderViewDelegate> delegate;
- (void)refresh;
@end
@implementation NIMAdvancedTeamCardHeaderView
- (instancetype)initWithTeam:(NIMTeam*)team{
self = [super initWithFrame:CGRectZero];
if (self) {
_team = [[NIMSDK sharedSDK].teamManager teamById:team.teamId];
_avatar = [[NIMAvatarImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
[_avatar addTarget:self action:@selector(onTouchAvatar:) forControlEvents:UIControlEventTouchUpInside];
_titleLabel = [[UILabel alloc]initWithFrame:CGRectZero];
_titleLabel.backgroundColor = [UIColor clearColor];
_titleLabel.font = [UIFont systemFontOfSize:17.f];
_titleLabel.textColor = NIMKit_UIColorFromRGB(0x333333);
_numberLabel = [[UILabel alloc]initWithFrame:CGRectZero];
_numberLabel.backgroundColor = [UIColor clearColor];
_numberLabel.font = [UIFont systemFontOfSize:14.f];
_numberLabel.textColor = NIMKit_UIColorFromRGB(0x999999);
_createTimeLabel = [[UILabel alloc]initWithFrame:CGRectZero];
_createTimeLabel.backgroundColor = [UIColor clearColor];
_createTimeLabel.font = [UIFont systemFontOfSize:14.f];
_createTimeLabel.textColor = NIMKit_UIColorFromRGB(0x999999);
[self addSubview:_avatar];
[self addSubview:_titleLabel];
[self addSubview:_numberLabel];
[self addSubview:_createTimeLabel];
self.backgroundColor = NIMKit_UIColorFromRGB(0xecf1f5);
self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
[self refresh];
}
return self;
}
- (CGSize)sizeThatFits:(CGSize)size{
return CGSizeMake(size.width, CardHeaderHeight);
}
- (void)refresh
{
// team 缓存可能发生改变,需要重新从 SDK 里拿一遍
_team = [[NIMSDK sharedSDK].teamManager teamById:_team.teamId];
NSURL *avatarUrl = _team.thumbAvatarUrl.length? [NSURL URLWithString:_team.thumbAvatarUrl] : nil;
[_avatar nim_setImageWithURL:avatarUrl placeholderImage:[UIImage nim_imageInKit:@"avatar_team"]];
}
- (NSString*)formartCreateTime{
NSTimeInterval timestamp = self.team.createTime;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy/MM/dd"];
NSString *dateString = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSince1970:timestamp]];
if (!dateString.length) {
return @"未知时间创建";
}
return [NSString stringWithFormat:@"于%@创建",dateString];
}
- (void)onTouchAvatar:(id)sender
{
if ([self.delegate respondsToSelector:@selector(onTouchAvatar:)]) {
[self.delegate onTouchAvatar:sender];
}
}
#define AvatarLeft 20
#define AvatarTop 25
#define TitleAndAvatarSpacing 10
#define NumberAndTimeSpacing 10
#define MaxTitleLabelWidth 200
- (void)layoutSubviews{
[super layoutSubviews];
_titleLabel.text = self.team.teamName;
_numberLabel.text = self.team.teamId;
_createTimeLabel.text = [self formartCreateTime];
[_titleLabel sizeToFit];
[_createTimeLabel sizeToFit];
[_numberLabel sizeToFit];
self.titleLabel.nim_width = self.titleLabel.nim_width > MaxTitleLabelWidth ? MaxTitleLabelWidth : self.titleLabel.nim_width;
self.avatar.nim_left = AvatarLeft;
self.avatar.nim_top = AvatarTop;
self.titleLabel.nim_left = self.avatar.nim_right + TitleAndAvatarSpacing;
self.titleLabel.nim_top = self.avatar.nim_top;
self.numberLabel.nim_left = self.titleLabel.nim_left;
self.numberLabel.nim_bottom = self.avatar.nim_bottom;
self.createTimeLabel.nim_left = self.numberLabel.nim_right + NumberAndTimeSpacing;
self.createTimeLabel.nim_bottom = self.numberLabel.nim_bottom;
}
@end
#pragma mark - Card VC
#define TableCellReuseId @"tableCell"
#define TableButtonCellReuseId @"tableButtonCell"
#define TableMemberCellReuseId @"tableMemberCell"
#define TableSwitchReuseId @"tableSwitchCell"
@interface NIMAdvancedTeamCardViewController ()<NIMAdvancedTeamMemberCellActionDelegate,NIMContactSelectDelegate,NIMTeamSwitchProtocol,NIMAdvancedTeamCardHeaderViewDelegate,NIMTeamManagerDelegate,UIActionSheetDelegate,UITableViewDataSource,UITableViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
UIAlertView *_updateTeamNameAlertView;
UIAlertView *_updateTeamNickAlertView;
UIAlertView *_updateTeamIntroAlertView;
UIAlertView *_quitTeamAlertView;
UIAlertView *_dismissTeamAlertView;
UIActionSheet *_moreActionSheet;
UIActionSheet *_authActionSheet;
UIActionSheet *_inviteActionSheet;
UIActionSheet *_beInviteActionSheet;
UIActionSheet *_updateInfoActionSheet;
UIActionSheet *_avatarActionSheet;
}
@property (nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) NIMTeam *team;
@property(nonatomic,strong) NIMTeamMember *myTeamInfo;
@property(nonatomic,copy) NSArray *bodyData;
@property(nonatomic,copy) NSArray *memberData;
@end
@implementation NIMAdvancedTeamCardViewController
- (instancetype)initWithTeam:(NIMTeam *)team{
self = [super initWithNibName:nil bundle:nil];
if (self) {
_team = team;
}
return self;
}
- (void)dealloc
{
[[NIMSDK sharedSDK].teamManager removeDelegate:self];
}
- (void)viewDidLoad {
[super viewDidLoad];
NIMAdvancedTeamCardHeaderView *headerView = [[NIMAdvancedTeamCardHeaderView alloc] initWithTeam:self.team];
headerView.delegate = self;
headerView.nim_size = [headerView sizeThatFits:self.view.nim_size];
self.navigationItem.title = self.team.teamName;
self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
self.tableView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
[self.view addSubview:self.tableView];
self.tableView.tableHeaderView = headerView;
self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.tableView.backgroundColor = NIMKit_UIColorFromRGB(0xecf1f5);
self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
__weak typeof(self) wself = self;
[self requestData:^(NSError *error) {
if (!error) {
[wself reloadData];
}
}];
[[NIMSDK sharedSDK].teamManager addDelegate:self];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[self reloadData];
}
- (void)reloadData{
self.myTeamInfo = [[NIMSDK sharedSDK].teamManager teamMember:self.myTeamInfo.userId inTeam:self.myTeamInfo.teamId];
[self buildBodyData];
[self.tableView reloadData];
NIMAdvancedTeamCardHeaderView *headerView = (NIMAdvancedTeamCardHeaderView*)self.tableView.tableHeaderView;
headerView.titleLabel.text = self.team.teamName;;
self.navigationItem.title = self.team.teamName;
if (self.myTeamInfo.type == NIMTeamMemberTypeOwner) {
UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(onMore:)];
self.navigationItem.rightBarButtonItem = buttonItem;
}else{
self.navigationItem.rightBarButtonItem = nil;
}
}
- (void)requestData:(void(^)(NSError *error)) handler{
__weak typeof(self) wself = self;
[[NIMSDK sharedSDK].teamManager fetchTeamMembers:self.team.teamId completion:^(NSError *error, NSArray *members) {
if (!error) {
for (NIMTeamMember *member in members) {
if ([member.userId isEqualToString:[NIMSDK sharedSDK].loginManager.currentAccount]) {
wself.myTeamInfo = member;
break;
}
}
wself.memberData = members;
}else if(error.code == NIMRemoteErrorCodeTeamNotMember){
[wself.view makeToast:@"你已经不在群里" duration:2
position:CSToastPositionCenter];
}else{
[wself.view makeToast:[NSString stringWithFormat:@"拉好友失败 error: %zd",error.code] duration:2
position:CSToastPositionCenter];
}
handler(error);
}];
}
- (void)buildBodyData{
BOOL canEdit = [NIMKitUtil canEditTeamInfo:self.myTeamInfo];
BOOL isOwner = self.myTeamInfo.type == NIMTeamMemberTypeOwner;
BOOL isManager = self.myTeamInfo.type == NIMTeamMemberTypeManager;
NIMTeamCardRowItem *teamMember = [[NIMTeamCardRowItem alloc] init];
teamMember.title = @"群成员";
teamMember.rowHeight = 111.f;
teamMember.action = @selector(enterMemberCard);
teamMember.type = TeamCardRowItemTypeTeamMember;
NIMTeamCardRowItem *teamName = [[NIMTeamCardRowItem alloc] init];
teamName.title = @"群名称";
teamName.subTitle = self.team.teamName;
teamName.action = @selector(updateTeamName);
teamName.rowHeight = 50.f;
teamName.type = TeamCardRowItemTypeCommon;
teamName.actionDisabled = !canEdit;
NIMTeamCardRowItem *teamNick = [[NIMTeamCardRowItem alloc] init];
teamNick.title = @"群昵称";
teamNick.subTitle = self.myTeamInfo.nickname;
teamNick.action = @selector(updateTeamNick);
teamNick.rowHeight = 50.f;
teamNick.type = TeamCardRowItemTypeCommon;
NIMTeamCardRowItem *teamIntro = [[NIMTeamCardRowItem alloc] init];
teamIntro.title = @"群介绍";
teamIntro.subTitle = self.team.intro.length ? self.team.intro : (canEdit ? @"点击填写群介绍" : @"");
teamIntro.action = @selector(updateTeamIntro);
teamIntro.rowHeight = 50.f;
teamIntro.type = TeamCardRowItemTypeCommon;
teamIntro.actionDisabled = !canEdit;
NIMTeamCardRowItem *teamAnnouncement = [[NIMTeamCardRowItem alloc] init];
teamAnnouncement.title = @"群公告";
teamAnnouncement.subTitle = @"点击查看群公告";//self.team.announcement.length ? self.team.announcement : (isManager ? @"点击填写群公告" : @"");
teamAnnouncement.action = @selector(updateTeamAnnouncement);
teamAnnouncement.rowHeight = 50.f;
teamAnnouncement.type = TeamCardRowItemTypeCommon;
NIMTeamCardRowItem *teamNotify = [[NIMTeamCardRowItem alloc] init];
teamNotify.title = @"消息提醒";
teamNotify.switchOn = [self.team notifyForNewMsg];
teamNotify.rowHeight = 50.f;
teamNotify.type = TeamCardRowItemTypeSwitch;
NIMTeamCardRowItem *itemQuit = [[NIMTeamCardRowItem alloc] init];
itemQuit.title = @"退出高级群";
itemQuit.action = @selector(quitTeam);
itemQuit.rowHeight = 60.f;
itemQuit.type = TeamCardRowItemTypeRedButton;
NIMTeamCardRowItem *itemDismiss = [[NIMTeamCardRowItem alloc] init];
itemDismiss.title = @"解散群聊";
itemDismiss.action = @selector(dismissTeam);
itemDismiss.rowHeight = 60.f;
itemDismiss.type = TeamCardRowItemTypeRedButton;
NIMTeamCardRowItem *itemAuth = [[NIMTeamCardRowItem alloc] init];
itemAuth.title = @"身份验证";
itemAuth.subTitle = [self joinModeText:self.team.joinMode];
itemAuth.action = @selector(changeAuthMode);
itemAuth.actionDisabled = !canEdit;
itemAuth.rowHeight = 60.f;
itemAuth.type = TeamCardRowItemTypeCommon;
NIMTeamCardRowItem *itemInvite = [[NIMTeamCardRowItem alloc] init];
itemInvite.title = @"邀请他人权限";
itemInvite.subTitle = [self inviteModeText:self.team.inviteMode];
itemInvite.action = @selector(changeInviteMode);
itemInvite.actionDisabled = !canEdit;
itemInvite.rowHeight = 60.f;
itemInvite.type = TeamCardRowItemTypeCommon;
NIMTeamCardRowItem *itemUpdateInfo = [[NIMTeamCardRowItem alloc] init];
itemUpdateInfo.title = @"群资料修改权限";
itemUpdateInfo.subTitle = [self updateInfoModeText:self.team.updateInfoMode];
itemUpdateInfo.action = @selector(changeUpdateInfoMode);
itemUpdateInfo.actionDisabled = !canEdit;
itemUpdateInfo.rowHeight = 60.f;
itemUpdateInfo.type = TeamCardRowItemTypeCommon;
NIMTeamCardRowItem *itemBeInvite = [[NIMTeamCardRowItem alloc] init];
itemBeInvite.title = @"被邀请人身份验证";
itemBeInvite.subTitle = [self beInviteModeText:self.team.beInviteMode];
itemBeInvite.action = @selector(changeBeInviteMode);
itemBeInvite.actionDisabled = !canEdit;
itemBeInvite.rowHeight = 60.f;
itemBeInvite.type = TeamCardRowItemTypeCommon;
if (isOwner) {
self.bodyData = @[
@[teamMember],
@[teamName,teamNick,teamIntro,teamAnnouncement,teamNotify],
@[itemAuth],
@[itemInvite,itemUpdateInfo,itemBeInvite],
@[itemDismiss],
];
}else if(isManager){
self.bodyData = @[
@[teamMember],
@[teamName,teamNick,teamIntro,teamAnnouncement,teamNotify],
@[itemAuth],
@[itemInvite,itemUpdateInfo,itemBeInvite],
@[itemQuit],
];
}else{
self.bodyData = @[
@[teamMember],
@[teamName,teamNick,teamIntro,teamAnnouncement,teamNotify],
@[itemQuit],
];
}
}
- (id<NTESCardBodyData>)bodyDataAtIndexPath:(NSIndexPath*)indexpath{
NSArray *sectionData = self.bodyData[indexpath.section];
return sectionData[indexpath.row];
}
- (NSIndexPath *)cellIndexPathByTitle:(NSString *)title {
__block NSInteger section = 0;
__block NSInteger row = 0;
[self.bodyData enumerateObjectsUsingBlock:^(NSArray *rows, NSUInteger s, BOOL *stop) {
__block BOOL stopped = NO;
[rows enumerateObjectsUsingBlock:^(NIMTeamCardRowItem *item, NSUInteger r, BOOL *stop) {
if([item.title isEqualToString:title]) {
section = s;
row = r;
*stop = YES;
stopped = YES;
}
}];
*stop = stopped;
}];
return [NSIndexPath indexPathForRow:row inSection:section];
}
#pragma mark - NIMTeamManagerDelegate
- (void)onTeamMemberChanged:(NIMTeam *)team
{
__weak typeof(self) weakSelf = self;
[self requestData:^(NSError *error) {
[weakSelf reloadData];
}];
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[tableView deselectRowAtIndexPath:indexPath animated:NO];
id<NTESCardBodyData> bodyData = [self bodyDataAtIndexPath:indexPath];
if ([bodyData respondsToSelector:@selector(actionDisabled)] && bodyData.actionDisabled) {
return;
}
if ([bodyData respondsToSelector:@selector(action)]) {
if (bodyData.action) {
NIMKit_SuppressPerformSelectorLeakWarning([self performSelector:bodyData.action]);
}
}
}
#pragma mark - UITableViewDataSource
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
id<NTESCardBodyData> bodyData = [self bodyDataAtIndexPath:indexPath];
return bodyData.rowHeight;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return self.bodyData.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSArray *sectionData = self.bodyData[section];
return sectionData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
id<NTESCardBodyData> bodyData = [self bodyDataAtIndexPath:indexPath];
UITableViewCell * cell;
NIMKitTeamCardRowItemType type = bodyData.type;
switch (type) {
case TeamCardRowItemTypeCommon:
cell = [self builidCommonCell:bodyData];
break;
case TeamCardRowItemTypeRedButton:
cell = [self builidRedButtonCell:bodyData];
break;
case TeamCardRowItemTypeTeamMember:
cell = [self builidTeamMemberCell:bodyData];
break;
case TeamCardRowItemTypeSwitch:
cell = [self buildTeamSwitchCell:bodyData];
break;
default:
break;
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
if (section == 0) {
return 0.0f;
}
return 20.f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.backgroundColor = NIMKit_UIColorFromRGB(0xecf1f5);
return view;
}
- (UITableViewCell*)builidCommonCell:(id<NTESCardBodyData>) bodyData{
UITableViewCell * cell = [self.tableView dequeueReusableCellWithIdentifier:TableCellReuseId];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:TableCellReuseId];
CGFloat left = 15.f;
UIView *sep = [[UIView alloc] initWithFrame:CGRectMake(left, cell.nim_height-1, cell.nim_width, 1.f)];
sep.backgroundColor = NIMKit_UIColorFromRGB(0xebebeb);
[cell addSubview:sep];
sep.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
}
cell.textLabel.text = bodyData.title;
if ([bodyData respondsToSelector:@selector(subTitle)]) {
cell.detailTextLabel.text = bodyData.subTitle;
}
if ([bodyData respondsToSelector:@selector(actionDisabled)] && bodyData.actionDisabled) {
cell.accessoryType = UITableViewCellAccessoryNone;
}else{
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
return cell;
}
- (UITableViewCell*)builidRedButtonCell:(id<NTESCardBodyData>) bodyData{
NIMKitColorButtonCell * cell = [self.tableView dequeueReusableCellWithIdentifier:TableButtonCellReuseId];
if (!cell) {
cell = [[NIMKitColorButtonCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:TableButtonCellReuseId];
}
cell.button.style = NIMKitColorButtonCellStyleRed;
[cell.button setTitle:bodyData.title forState:UIControlStateNormal];
return cell;
}
- (UITableViewCell*)builidTeamMemberCell:(id<NTESCardBodyData>) bodyData{
NIMAdvancedTeamMemberCell * cell = [self.tableView dequeueReusableCellWithIdentifier:TableMemberCellReuseId];
if (!cell) {
cell = [[NIMAdvancedTeamMemberCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:TableMemberCellReuseId];
cell.delegate = self;
}
[cell rereshWithTeam:self.team members:self.memberData width:self.tableView.nim_width];
cell.textLabel.text = bodyData.title;
cell.detailTextLabel.text = bodyData.subTitle;
if ([bodyData respondsToSelector:@selector(actionDisabled)] && bodyData.actionDisabled) {
cell.accessoryType = UITableViewCellAccessoryNone;
}else{
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
return cell;
}
- (UITableViewCell *)buildTeamSwitchCell:(id<NTESCardBodyData>)bodyData
{
NIMTeamSwitchTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:TableSwitchReuseId];
if (!cell) {
cell = [[NIMTeamSwitchTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"NIMTeamSwitchTableViewCell"];
}
cell.textLabel.text = bodyData.title;
cell.switcher.on = bodyData.switchOn;
cell.switchDelegate = self;
return cell;
}
#pragma mark - Action
- (void)onMore:(id)sender{
_moreActionSheet = [[UIActionSheet alloc] initWithTitle:@"请操作" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"转让群",@"转让群并退出",nil];
[_moreActionSheet showInView:self.view];
}
- (void)onTouchAvatar:(id)sender{
if([NIMKitUtil canEditTeamInfo:self.myTeamInfo])
{
_avatarActionSheet = [[UIActionSheet alloc] initWithTitle:@"设置群头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册", nil];
[_avatarActionSheet showInView:self.view];
}
}
- (void)updateTeamName{
_updateTeamNameAlertView = [[UIAlertView alloc] initWithTitle:@"" message:@"修改群名称" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
_updateTeamNameAlertView.alertViewStyle = UIAlertViewStylePlainTextInput;
[_updateTeamNameAlertView show];
}
- (void)updateTeamNick{
_updateTeamNickAlertView = [[UIAlertView alloc] initWithTitle:@"" message:@"修改群昵称" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
_updateTeamNickAlertView.alertViewStyle = UIAlertViewStylePlainTextInput;
[_updateTeamNickAlertView show];
}
- (void)updateTeamIntro{
_updateTeamIntroAlertView = [[UIAlertView alloc] initWithTitle:@"" message:@"修改群介绍" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
_updateTeamIntroAlertView.alertViewStyle = UIAlertViewStylePlainTextInput;
[_updateTeamIntroAlertView show];
}
- (void)updateTeamAnnouncement{
NIMTeamAnnouncementListViewController *vc = [[NIMTeamAnnouncementListViewController alloc] initWithNibName:nil bundle:nil];
vc.team = self.team;
vc.canCreateAnnouncement = [NIMKitUtil canEditTeamInfo:self.myTeamInfo];
[self.navigationController pushViewController:vc animated:YES];
}
- (void)quitTeam{
_quitTeamAlertView = [[UIAlertView alloc] initWithTitle:@"" message:@"确认退出群聊?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
[_quitTeamAlertView show];
}
- (void)dismissTeam{
_dismissTeamAlertView = [[UIAlertView alloc] initWithTitle:@"" message:@"确认解散群聊?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
[_dismissTeamAlertView show];
}
- (void)changeAuthMode{
_authActionSheet = [[UIActionSheet alloc] initWithTitle:@"更改验证方式" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"允许任何人",@"需要验证",@"拒绝任何人", nil];
[_authActionSheet showInView:self.view];
}
- (void)changeInviteMode{
_inviteActionSheet = [[UIActionSheet alloc] initWithTitle:@"邀请他人入群" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"管理员邀请",@"所有人邀请", nil];
[_inviteActionSheet showInView:self.view];
}
- (void)changeUpdateInfoMode{
_updateInfoActionSheet = [[UIActionSheet alloc] initWithTitle:@"群资料修改权限" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"管理员修改",@"所有人修改", nil];
[_updateInfoActionSheet showInView:self.view];
}
- (void)changeBeInviteMode{
_beInviteActionSheet = [[UIActionSheet alloc] initWithTitle:@"被邀请人身份验证" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"需要验证",@"不需要验证", nil];
[_beInviteActionSheet showInView:self.view];
}
- (NSString*)joinModeText:(NIMTeamJoinMode)mode{
switch (mode) {
case NIMTeamJoinModeNoAuth:
return @"允许任何人";
case NIMTeamJoinModeNeedAuth:
return @"需要验证";
case NIMTeamJoinModeRejectAll:
return @"拒绝任何人";
default:
break;
}
}
- (NSString*)inviteModeText:(NIMTeamInviteMode)mode{
switch (mode) {
case NIMTeamInviteModeManager:
return @"管理员";
case NIMTeamInviteModeAll:
return @"所有人";
default:
return @"未知权限";
}
}
- (NSString*)updateInfoModeText:(NIMTeamUpdateInfoMode)mode{
switch (mode) {
case NIMTeamUpdateInfoModeManager:
return @"管理员";
case NIMTeamUpdateInfoModeAll:
return @"所有人";
default:
return @"未知权限";
}
}
- (NSString*)beInviteModeText:(NIMTeamBeInviteMode)mode{
switch (mode) {
case NIMTeamBeInviteModeNeedAuth:
return @"需要验证";
case NIMTeamBeInviteModeNoAuth:
return @"不需要验证";
default:
return @"未知";
}
}
- (void)enterMemberCard{
NIMTeamMemberListViewController *vc = [[NIMTeamMemberListViewController alloc] initTeam:self.team members:self.memberData];
[self.navigationController pushViewController:vc animated:YES];
}
- (void)onStateChanged:(BOOL)on
{
__weak typeof(self) weakSelf = self;
[[[NIMSDK sharedSDK] teamManager] updateNotifyState:on
inTeam:[self.team teamId]
completion:^(NSError *error) {
if (error) {
[weakSelf.view makeToast:[NSString stringWithFormat:@"修改失败 error:%zd",error.code]
duration:2
position:CSToastPositionCenter];
}
[weakSelf reloadData];
}];
}
#pragma mark - NIMAdvancedTeamMemberCellActionDelegate
- (void)didSelectAddOpeartor{
NSMutableArray *users = [[NSMutableArray alloc] init];
for (NIMTeamMember *member in self.memberData) {
[users addObject:member.userId];
}
NSString *currentUserID = [[[NIMSDK sharedSDK] loginManager] currentAccount];
[users addObject:currentUserID];
NIMContactFriendSelectConfig *config = [[NIMContactFriendSelectConfig alloc] init];
config.filterIds = users;
config.needMutiSelected = YES;
NIMContactSelectViewController *vc = [[NIMContactSelectViewController alloc] initWithConfig:config];
vc.delegate = self;
[vc show];
}
#pragma mark - ContactSelectDelegate
- (void)didFinishedSelect:(NSArray *)selectedContacts{
if (!selectedContacts.count) {
return;
}
NSString *postscript = @"邀请你加入群组";
[[NIMSDK sharedSDK].teamManager addUsers:selectedContacts toTeam:self.team.teamId postscript:postscript completion:^(NSError *error, NSArray *members) {
if (!error) {
[self.view makeToast:@"邀请成功"
duration:2
position:CSToastPositionCenter];
}else{
[self.view makeToast:[NSString stringWithFormat:@"邀请失败 code:%zd",error.code]
duration:2
position:CSToastPositionCenter];
}
}];
}
- (void)didCancelledSelect{
}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
if (alertView == _updateTeamNameAlertView) {
[self updateTeamNameAlert:buttonIndex];
}
else if (alertView == _updateTeamNickAlertView) {
[self updateTeamNickAlert:buttonIndex];
}
else if (alertView == _updateTeamIntroAlertView) {
[self updateTeamIntroAlert:buttonIndex];
}
else if (alertView == _quitTeamAlertView) {
[self quitTeamAlert:buttonIndex];
}
else if (alertView == _dismissTeamAlertView) {
[self dismissTeamAlert:buttonIndex];
}
}
- (void)updateTeamNameAlert:(NSInteger)index{
switch (index) {
case 0://取消
break;
case 1:{
NSString *name = [_updateTeamNameAlertView textFieldAtIndex:0].text;
if (name.length) {
[[NIMSDK sharedSDK].teamManager updateTeamName:name teamId:self.team.teamId completion:^(NSError *error) {
if (!error) {
self.team.teamName = name;
[self.view makeToast:@"修改成功" duration:2
position:CSToastPositionCenter];
[self reloadData];
}else{
[self.view makeToast:[NSString stringWithFormat:@"修改失败 code:%zd",error.code] duration:2
position:CSToastPositionCenter];
}
}];
}
break;
}
default:
break;
}
}
- (void)updateTeamNickAlert:(NSInteger)index{
switch (index) {
case 0://取消
break;
case 1:{
NSString *name = [_updateTeamNickAlertView textFieldAtIndex:0].text;
NSString *currentUserId = [NIMSDK sharedSDK].loginManager.currentAccount;
[[NIMSDK sharedSDK].teamManager updateUserNick:currentUserId newNick:name inTeam:self.team.teamId completion:^(NSError *error) {
if (!error) {
self.myTeamInfo.nickname = name;
[self.view makeToast:@"修改成功"];
[self reloadData];
}else{
[self.view makeToast:[NSString stringWithFormat:@"修改失败 code:%zd",error.code]];
}
}];
break;
}
default:
break;
}
}
- (void)updateTeamIntroAlert:(NSInteger)index{
switch (index) {
case 0://取消
break;
case 1:{
NSString *intro = [_updateTeamIntroAlertView textFieldAtIndex:0].text;
[[NIMSDK sharedSDK].teamManager updateTeamIntro:intro teamId:self.team.teamId completion:^(NSError *error) {
if (!error) {
self.team.intro = intro;
[self.view makeToast:@"修改成功"];
[self reloadData];
}else{
[self.view makeToast:[NSString stringWithFormat:@"修改失败 code:%zd",error.code]];
}
}];
break;
}
default:
break;
}
}
- (void)quitTeamAlert:(NSInteger)index{
switch (index) {
case 0://取消
break;
case 1:{
[[NIMSDK sharedSDK].teamManager quitTeam:self.team.teamId completion:^(NSError *error) {
if (!error) {
[self.navigationController popToRootViewControllerAnimated:YES];
}else{
[self.view makeToast:[NSString stringWithFormat:@"退出失败 code:%zd",error.code]];
}
}];
break;
}
default:
break;
}
}
- (void)dismissTeamAlert:(NSInteger)index{
switch (index) {
case 0://取消
break;
case 1:{
[[NIMSDK sharedSDK].teamManager dismissTeam:self.team.teamId completion:^(NSError *error) {
if (!error) {
[self.navigationController popToRootViewControllerAnimated:YES];
}else{
[self.view makeToast:[NSString stringWithFormat:@"解散失败 code:%zd",error.code]];
}
}];
break;
}
default:
break;
}
}
#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)index{
if (actionSheet == _moreActionSheet) {
[self ontransferActionSheet:actionSheet index:index];
}
else if (actionSheet == _authActionSheet) {
[self onAuthActionSheet:actionSheet index:index];
}
else if (actionSheet == _inviteActionSheet) {
[self onInviteActionSheet:actionSheet index:index];
}
else if (actionSheet == _updateInfoActionSheet) {
[self onUpdateInfoActionSheet:actionSheet index:index];
}
else if (actionSheet == _beInviteActionSheet)
{
[self onBeInviteActionSheet:actionSheet index:index];
}
else if (actionSheet == _avatarActionSheet)
{
[self onAvatarActionSheet:actionSheet index:index];
}
}
- (void)onAvatarActionSheet:(UIActionSheet *)actionSheet index:(NSInteger)index
{
switch (index) {
case 0:
[self showImagePicker:UIImagePickerControllerSourceTypeCamera];
break;
case 1:
[self showImagePicker:UIImagePickerControllerSourceTypePhotoLibrary];
break;
default:
break;
}
}
- (void)showImagePicker:(UIImagePickerControllerSourceType)type{
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
picker.delegate = self;
picker.sourceType = type;
picker.allowsEditing = YES;
[self presentViewController:picker animated:YES completion:nil];
}
- (void)ontransferActionSheet:(UIActionSheet *)actionSheet index:(NSInteger)index
{
BOOL isLeave = NO;
switch (index) {
case 0:{
isLeave = NO;
break;
case 1:
isLeave = YES;
break;
}
default:
return;
break;
}
__weak typeof(self) wself = self;
__block ContactSelectFinishBlock finishBlock = ^(NSArray * memeber){
[[NIMSDK sharedSDK].teamManager transferManagerWithTeam:wself.team.teamId newOwnerId:memeber.firstObject isLeave:isLeave completion:^(NSError *error) {
if (!error) {
[wself.view makeToast:@"转移成功!" duration:2.0 position:CSToastPositionCenter];
if (isLeave) {
[wself.navigationController popToRootViewControllerAnimated:YES];
}else{
[wself reloadData];
}
}else{
[wself.view makeToast:[NSString stringWithFormat:@"转移失败!code:%zd",error.code] duration:2.0 position:CSToastPositionCenter];
}
}];
};
NSString *currentUserID = [[[NIMSDK sharedSDK] loginManager] currentAccount];
NIMContactTeamMemberSelectConfig *config = [[NIMContactTeamMemberSelectConfig alloc] init];
config.teamId = self.team.teamId;
config.filterIds = @[currentUserID];
NIMContactSelectViewController *vc = [[NIMContactSelectViewController alloc] initWithConfig:config];
vc.finshBlock = finishBlock;
[vc show];
}
- (void)onAuthActionSheet:(UIActionSheet *)actionSheet index:(NSInteger)index
{
if (index == _authActionSheet.cancelButtonIndex) {
return;
}
[[NIMSDK sharedSDK].teamManager updateTeamJoinMode:index teamId:self.team.teamId completion:^(NSError *error) {
if (!error) {
self.team.joinMode = index;
[self.view makeToast:@"修改成功"];
[self reloadData];
}else{
[self.view makeToast:[NSString stringWithFormat:@"修改失败 code:%zd",error.code]];
}
}];
}
- (void)onInviteActionSheet:(UIActionSheet *)actionSheet index:(NSInteger)index
{
NIMTeamInviteMode mode;
switch (index) {
case 0:
mode = NIMTeamInviteModeManager;
break;
case 1:
mode = NIMTeamInviteModeAll;
break;
default:
return;
}
[[NIMSDK sharedSDK].teamManager updateTeamInviteMode:mode teamId:self.team.teamId completion:^(NSError *error) {
if (!error) {
self.team.inviteMode = mode;
[self.view makeToast:@"修改成功"];
[self reloadData];
}else{
[self.view makeToast:[NSString stringWithFormat:@"修改失败 code:%zd",error.code]];
}
}];
}
- (void)onUpdateInfoActionSheet:(UIActionSheet *)actionSheet index:(NSInteger)index
{
NIMTeamUpdateInfoMode mode;
switch (index) {
case 0:
mode = NIMTeamUpdateInfoModeManager;
break;
case 1:
mode = NIMTeamUpdateInfoModeAll;
break;
default:
return;
}
[[NIMSDK sharedSDK].teamManager updateTeamUpdateInfoMode:mode teamId:self.team.teamId completion:^(NSError *error) {
if (!error) {
self.team.updateInfoMode = mode;
[self.view makeToast:@"修改成功"];
[self reloadData];
}else{
[self.view makeToast:[NSString stringWithFormat:@"修改失败 code:%zd",error.code]];
}
}];
}
- (void)onBeInviteActionSheet:(UIActionSheet *)actionSheet index:(NSInteger)index
{
NIMTeamBeInviteMode mode;
switch (index) {
case 0:
mode = NIMTeamBeInviteModeNeedAuth;
break;
case 1:
mode = NIMTeamBeInviteModeNoAuth;
break;
default:
return;
}
[[NIMSDK sharedSDK].teamManager updateTeamBeInviteMode:mode teamId:self.team.teamId completion:^(NSError *error) {
if (!error) {
self.team.beInviteMode = mode;
[self.view makeToast:@"修改成功"];
[self reloadData];
}else{
[self.view makeToast:[NSString stringWithFormat:@"修改失败 code:%zd",error.code]];
}
}];
}
#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage *image = info[UIImagePickerControllerEditedImage];
[picker dismissViewControllerAnimated:YES completion:^{
[self uploadImage:image];
}];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - Private
- (void)uploadImage:(UIImage *)image{
UIImage *imageForAvatarUpload = [image nim_imageForAvatarUpload];
NSString *fileName = [[[[NSUUID UUID] UUIDString] lowercaseString] stringByAppendingPathExtension:@"jpg"];
NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:fileName];
NSData *data = UIImageJPEGRepresentation(imageForAvatarUpload, 1.0);
BOOL success = data && [data writeToFile:filePath atomically:YES];
__weak typeof(self) wself = self;
if (success) {
[SVProgressHUD show];
[[NIMSDK sharedSDK].resourceManager upload:filePath progress:nil completion:^(NSString *urlString, NSError *error) {
[SVProgressHUD dismiss];
if (!error && wself) {
[[NIMSDK sharedSDK].teamManager updateTeamAvatar:urlString teamId:wself.team.teamId completion:^(NSError *error) {
if (!error) {
wself.team.avatarUrl = urlString;
[[SDWebImageManager sharedManager] saveImageToCache:imageForAvatarUpload forURL:[NSURL URLWithString:urlString]];
NIMAdvancedTeamCardHeaderView *headerView = (NIMAdvancedTeamCardHeaderView *)wself.tableView.tableHeaderView;
[headerView refresh];
}else{
[wself.view makeToast:@"设置头像失败,请重试"
duration:2
position:CSToastPositionCenter];
}
}];
}else{
[wself.view makeToast:@"图片上传失败,请重试"
duration:2
position:CSToastPositionCenter];
}
}];
}else{
[self.view makeToast:@"图片保存失败,请重试"
duration:2
position:CSToastPositionCenter];
}
}
#pragma mark - 旋转处理 (iOS7)
- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
NSIndexPath *reloadIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView reloadRowsAtIndexPaths:@[reloadIndexPath] withRowAnimation:UITableViewRowAnimationNone];
}
#pragma mark - 旋转处理 (iOS8 or above)
- (void)viewWillTransitionToSize:(CGSize)size
withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator
{
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
[coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
NSIndexPath *reloadIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView reloadRowsAtIndexPaths:@[reloadIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
} completion:nil];
}
@end
| {
"content_hash": "416171cf4642463475a6cfa7bd8b6fe0",
"timestamp": "",
"source": "github",
"line_count": 1080,
"max_line_length": 324,
"avg_line_length": 37.26759259259259,
"alnum_prop": 0.6559169171904892,
"repo_name": "coderMONSTER/ioscelebrity",
"id": "763b560d714c460e93c0055192e2418c844ae2d7",
"size": "41921",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "YStar/YStar/Library/NIMKit/NIMKit/Classes/Sections/Team/NIMAdvancedTeamCardViewController.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "3314"
},
{
"name": "Objective-C",
"bytes": "768130"
},
{
"name": "Ruby",
"bytes": "1246"
},
{
"name": "Swift",
"bytes": "343265"
}
],
"symlink_target": ""
} |
<?php
/**
* Adminhtml sales create order product search grid product name column renderer
*
* @category Mage
* @package Mage_Adminhtml
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_Adminhtml_Block_Sales_Order_Create_Search_Grid_Renderer_Product extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Text
{
/**
* Render product name to add Configure link
*
* @param Varien_Object $row
* @return string
*/
public function render(Varien_Object $row)
{
$rendered = parent::render($row);
$isConfigurable = $row->canConfigure();
$style = $isConfigurable ? '' : 'style="color: #CCC;"';
$prodAttributes = $isConfigurable ? sprintf('list_type = "product_to_add" product_id = %s', $row->getId()) : 'disabled="disabled"';
return sprintf('<a href="javascript:void(0)" %s class="f-right" %s>%s</a>',
$style, $prodAttributes, Mage::helper('sales')->__('Configure')) . $rendered;
}
}
| {
"content_hash": "ecc91e2f0cd9bc33074ba1f95cb5d536",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 139,
"avg_line_length": 36.607142857142854,
"alnum_prop": 0.6204878048780488,
"repo_name": "5452/durex",
"id": "c285f2df9f720594d29be0dbee34747c6d0cd2d2",
"size": "1983",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "includes/src/Mage_Adminhtml_Block_Sales_Order_Create_Search_Grid_Renderer_Product.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ActionScript",
"bytes": "19946"
},
{
"name": "CSS",
"bytes": "2190550"
},
{
"name": "JavaScript",
"bytes": "1290492"
},
{
"name": "PHP",
"bytes": "102689019"
},
{
"name": "Shell",
"bytes": "642"
},
{
"name": "XSLT",
"bytes": "2066"
}
],
"symlink_target": ""
} |
using bytePassion.Lib.WpfLib.ViewModelBase;
namespace OQF.CommonUiElements.Info.Pages.PageViewModels.BotVsBotInfoPage
{
internal interface IBotVsBotInfoPageViewModel : IViewModel, IPage
{
}
} | {
"content_hash": "43ac2efed1879bda429776ccf198f691",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 73,
"avg_line_length": 22.11111111111111,
"alnum_prop": 0.8190954773869347,
"repo_name": "bytePassion/OpenQuoridorFramework",
"id": "0f5d57cfc6d472675dacbe1a67f8774f67d2488e",
"size": "201",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "OpenQuoridorFramework/OQF.CommonUiElements/Info/Pages/PageViewModels/BotVsBotInfoPage/IBotVsBotInfoPageViewModel.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C#",
"bytes": "569792"
}
],
"symlink_target": ""
} |
/* TODO: shared styles with deposit-workflow__banner -- extract common component? */
.issue-prepaid-card-workflow__banner {
padding-right: var(--boxel-sp);
}
.issue-prepaid-card-workflow__banner p {
margin: 0;
}
.issue-prepaid-card-workflow__banner small {
display: block;
color: var(--boxel-light-300);
font-size: var(--boxel-font-size-xs);
line-height: calc(18 / 11);
letter-spacing: var(--boxel-lsp-lg);
}
.issue-prepaid-card-workflow__banner strong {
font-weight: 700;
}
.issue-prepaid-card-workflow__banner p + p {
margin-top: var(--boxel-sp);
}
.issue-prepaid-card-workflow__banner p + p:last-of-type {
margin-top: var(--boxel-sp-lg);
}
| {
"content_hash": "521274a6044b92b4cac59c5ed62aad77",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 84,
"avg_line_length": 23.857142857142858,
"alnum_prop": 0.6796407185628742,
"repo_name": "cardstack/cardstack",
"id": "ca6cf7830aa27d1b18e6a4d34b6f16a971524fbf",
"size": "668",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "packages/web-client/app/components/card-pay/issue-prepaid-card-workflow/index.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "327952"
},
{
"name": "Dockerfile",
"bytes": "5072"
},
{
"name": "HCL",
"bytes": "53170"
},
{
"name": "HTML",
"bytes": "12660"
},
{
"name": "Handlebars",
"bytes": "309845"
},
{
"name": "JavaScript",
"bytes": "678790"
},
{
"name": "PLpgSQL",
"bytes": "57036"
},
{
"name": "Procfile",
"bytes": "48"
},
{
"name": "Python",
"bytes": "207635"
},
{
"name": "Ruby",
"bytes": "1753"
},
{
"name": "Shell",
"bytes": "5425"
},
{
"name": "TypeScript",
"bytes": "3614447"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "16c638fcd88912e27eb436195fabd467",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "88a04f551e142f6fb5bb05a116d7465ddfca73f6",
"size": "179",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Polemoniaceae/Phlox/Phlox prostrata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Azure.AI.FormRecognizer.Tests
{
/// <summary>
/// A static class that lumps together the filenames of all forms to be used for tests.
/// A single constant string must be added to this class for each new form added to the
/// test assets folder.
/// </summary>
public static class TestFile
{
/// <summary>A single-page blank form.</summary>
public const string Blank = "blank.pdf";
/// <summary>A driver's license.</summary>
public const string DriverLicenseJpg = "license.jpg";
/// <summary>One of the purchase orders used for model training.</summary>
public const string Form1 = "Form_1.jpg";
/// <summary>Form containing selection marks.</summary>
public const string FormSelectionMarks = "selectionMarkForm.pdf";
/// <summary>An itemized en-US receipt.</summary>
public const string ReceiptJpg = "contoso-receipt.jpg";
/// <summary>An itemized en-US receipt.</summary>
public const string ReceiptPng = "contoso-allinone.png";
/// <summary>A file with multiple receipts, one per page.</summary>
public const string ReceipMultipage = "multipleReceipt.pdf";
/// <summary>A three-page receipt file in which the second page is blank.</summary>
public const string ReceipMultipageWithBlankPage = "multipageReceiptBlankPage.pdf";
/// <summary>A business card file.</summary>
public const string BusinessCardJpg = "businessCard.jpg";
/// <summary>A business card file.</summary>
public const string BusinessCardtPng = "businessCard.png";
/// <summary>A business card file.</summary>
public const string BusinessCardtBmp = "businessCard.bmp";
/// <summary>A file with two business cards, one per page.</summary>
public const string BusinessMultipage = "multipleBusinessCards.pdf";
/// <summary>A complete invoice file.</summary>
public const string InvoiceJpg = "recommended_invoice.jpg";
/// <summary>A basic invoice file.</summary>
public const string InvoicePdf = "Invoice_1.pdf";
/// <summary>A basic invoice file.</summary>
public const string InvoiceLeTiff = "Invoice_1.tiff";
/// <summary>A two-page invoice file.</summary>
public const string InvoiceMultipage = "multi1.pdf";
/// <summary>A three-page invoice file in which the second page is blank.</summary>
public const string InvoiceMultipageBlank = "multipage_invoice1.pdf";
/// <summary>A form with a table that has dynamic rows and empty cells.</summary>
public const string FormTableDynamicRows = "label_table_dynamic_rows1.pdf";
/// <summary>A form with a table that has fixed rows and empty cells.</summary>
public const string FormTableFixedRows = "label_table_fixed_rows1.pdf";
}
}
| {
"content_hash": "dc4a87e2cb75f930b246c1be4626ad47",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 91,
"avg_line_length": 43,
"alnum_prop": 0.6674418604651163,
"repo_name": "AsrOneSdk/azure-sdk-for-net",
"id": "c8e360f99a31a90b7d31ea505ed90ee0a1c32137",
"size": "3012",
"binary": false,
"copies": "2",
"ref": "refs/heads/psSdkJson6Current",
"path": "sdk/formrecognizer/Azure.AI.FormRecognizer/tests/Infrastructure/TestFile.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "15473"
},
{
"name": "Bicep",
"bytes": "13438"
},
{
"name": "C#",
"bytes": "72203239"
},
{
"name": "CSS",
"bytes": "6089"
},
{
"name": "Dockerfile",
"bytes": "5652"
},
{
"name": "HTML",
"bytes": "6169271"
},
{
"name": "JavaScript",
"bytes": "16012"
},
{
"name": "PowerShell",
"bytes": "649218"
},
{
"name": "Shell",
"bytes": "31287"
},
{
"name": "Smarty",
"bytes": "11135"
}
],
"symlink_target": ""
} |
import usb.core
import usb.util
import sys, math
import json
# find our device
dev = usb.core.find(idVendor=0x04d8, idProduct=0x003f)
# was it found?
if dev is None:
raise ValueError('Device not found')
interface = 0
if dev.is_kernel_driver_active(interface) is True:
print "but we need to detach kernel driver"
dev.detach_kernel_driver(interface)
# set the active configuration. With no arguments, the first
# configuration will be the active one
dev.set_configuration()
# get an endpoint instance
cfg = dev.get_active_configuration()
#intf = cfg[(0,0)]
for cfg in dev:
sys.stdout.write("ConfigurationValue:" + str(cfg.bConfigurationValue) + '\n')
for intf in cfg:
#print vars(intf)
sys.stdout.write('\t' + \
"InterfaceNumber:" + str(intf.bInterfaceNumber) + \
',' + \
"AlternateSetting:" + str(intf.bAlternateSetting) + \
'\n')
for ep in intf:
#print vars(ep)
sys.stdout.write('\t\t' + \
"EndpointAddress:" + str(ep.bEndpointAddress) + \
'\n')
assert ep is not None
cmd = sys.argv[1]
scalingFactor = float(1) # the reading may need to be scaled. e.g. /3 if it is number of instruction cycles
if cmd == 'WP' :
# Write Pin
command = 0x11 # COMMAND_IO_WRITE_PIN
pinNum = 0xd4 # Naming convention like port+pin, e.g 0xd0=RD0, 0xa1= RA1 etc
carrierInterval = 26 # The carrier pulsing during high, e.g. for infrared remote etc
carrier_duty_cycle_on = 4; # part of carrierInterval in hi state
carrier_duty_cycle_off = 4; # part of carrierInterval in lo state. We can keep hi + lo < total to compensate for other code exec
durationsData = ""
# we can send data > 64 bytes, internally, it will be split into packets of 64 bytes
arr_durations = [2666,889,444,444,444,444,444,889,444,889,889,444,444,444,444,444,444,444,444,444,444,444,444,444,444,
444,444,444,444,444,444,444,444,444,444,444,444,444,889,889,444,444,444,444,444,444,444,444,444, 65000]
#for loop in range(1) :
# arr_durations.extend( (100, 200))
print arr_durations
print "sum(arr_durations):", sum(arr_durations) , "len:", len( arr_durations)
for duration in arr_durations :
durationsData = durationsData + chr( duration >>8) + chr( duration & 0xFF)
DURATION_START_INDEX = 7
# the extended flag tells the usb app that the command is not yet complete, more data is to follow.
flag_extended = 1 if len( arr_durations) * 2 > (64 - DURATION_START_INDEX) else 0 #1 : Extended( > 64 bytes < 128 bytes), 0 : <64 bytes
flag_repeat = 0 # 2 is ON, pattern is repeated num_repeats times.
num_repeats = 2 # a value of 0 means infinite
flag_is_millis = 0 # 4 : durations in milliseconds, 0 : in microseconds
flag_reset = 8 # 8 : reset to 0 after done
flags = flag_extended | flag_repeat | flag_is_millis | flag_reset
print "flags:" , flags
# send write pattern.
# interface, command, timeout
dev.write( 1, chr(command) + chr(pinNum) + chr(flags)
+ chr(carrierInterval) + chr(carrier_duty_cycle_on) + chr(carrier_duty_cycle_off)
+ chr(num_repeats)
+ durationsData
+ chr(0) + chr(0), # end of command data
10)
elif cmd == 'RP' or cmd == 'RPD' or cmd == 'RA':
allresults = []
# read the ADC. COMMAND_IO_READ_ADC
# send command on EP_OUT
if cmd == 'RA' :
command = 0x14
numSamples = 500
sampleInterval = 0 #uS
minStartingValue = 0 # value that should be reached before we start sampling. Useful for manual triggering like pressing a remote key
chnls = 0 # TODO : bitmap of ADC channels to use
flag_is_debug = 0 # 2 is ON, intervals are in ms
flags = flag_is_debug
numBytesInPacket = 64
numBytesInSample = 2
reservedBytesInPacket = 2
samplesPerPacket = (numBytesInPacket - reservedBytesInPacket)/numBytesInSample
packetsToRead = int( math.ceil( float(numSamples)/samplesPerPacket))
# Min time between samples taken by uC is 11*TAD+TACQ = 21us
# From comparing a wave of 100 ON/200 OFF, it seems around 8-10 uS is spent on code exec. This might be added as well
codeExecTime = 9 #uS
minSamplingTime = 21 #uS
effSamplingInterval = sampleInterval + minSamplingTime + codeExecTime
print "numSamples:%d, sampleInterval:%d, samplesPerPacket:%d, packetsToRead:%d" % (numSamples, sampleInterval, samplesPerPacket, packetsToRead)
dev.write( 1, chr(command) + chr(chnls) + chr(flags) + chr(numSamples >>8) + chr(numSamples & 0x00FF) + chr(sampleInterval >>8) + chr(sampleInterval & 0x00FF)
+ chr(minStartingValue >>8) + chr(minStartingValue & 0x00FF),
100)
elif cmd == 'RP' :
# Read PIN
command = 0x12
pinNum = 0xd2
flag_idleState = 1 # Hi/LO. We wait for state to change from this. Useful for manual input actions like pressing a remote.
flag_is_millis = 0 # 4 is ON, intervals are in ms
flag_is_debug = 2 # 2 is ON, intervals are in ms
flags = flag_idleState | flag_is_debug | flag_is_millis
numSamples = 1000
sampleInterval = 100 #uS
numBytesInPacket = 64
numBytesInSample = 1
reservedBytesInPacket = 2
samplesPerPacket = (numBytesInPacket - reservedBytesInPacket)/numBytesInSample
packetsToRead = int( math.ceil( float(numSamples)/samplesPerPacket))
# No ADC here, so no acquisition time
codeExecTime = 0 #uS
minSamplingTime = 0 #uS
effSamplingInterval = sampleInterval + minSamplingTime + codeExecTime
print "numSamples:%d, sampleInterval:%d, samplesPerPacket:%d, packetsToRead:%d" % ( numSamples, sampleInterval, samplesPerPacket, packetsToRead)
dev.write( 1, chr(command) + chr(pinNum) + chr(flags) + chr(numSamples >>8) + chr(numSamples & 0x00FF) + chr(sampleInterval >>8)
+ chr(sampleInterval & 0x00FF), 10)
elif cmd == 'RPD' :
# Read PIN DURATIONS
command = 0x13
pinNum = 0xd2
flag_idleState = 1 # Hi/LO. We wait for state to change from this. Useful for manual input actions like pressing a remote.
flag_is_millis = 0 # 4 is ON, intervals are in ms
flag_is_debug = 0 # 2 is ON, intervals are in ms
flags = flag_idleState | flag_is_debug | flag_is_millis
numSamples = 200
sampleInterval = 5 #uS
numBytesInPacket = 64
numBytesInSample = 2
reservedBytesInPacket = 2
samplesPerPacket = (numBytesInPacket - reservedBytesInPacket)/numBytesInSample
packetsToRead = int( math.ceil( float(numSamples)/samplesPerPacket))
# No ADC here, so no acquisition time
codeExecTime = 9 #uS
minSamplingTime = 1 #uS
effSamplingInterval = sampleInterval + minSamplingTime + codeExecTime
scalingFactor = float(sampleInterval + codeExecTime)/sampleInterval
print "numSamples:%d, sampleInterval:%d, samplesPerPacket:%d, packetsToRead:%d" % ( numSamples,sampleInterval, samplesPerPacket, packetsToRead)
dev.write( 1, chr(command) + chr(pinNum) + chr(flags) + chr(numSamples >>8) + chr(numSamples & 0x00FF) + chr(sampleInterval >>8)
+ chr(sampleInterval & 0x00FF), 10)
# read on EP_IN
# seems that the data-size we request should be in multiples of actual data size sent.
# e.g. requesting to read 100, when size is 64 can cause an overflow error.
# but 128 might work, in that case result of 2 requests will be clubbed together.
# Seems to be connected to timeout as well. 64 + 10ms works as expected
# Note that timeout is also directly related with sampling interval.
# Min time between samples taken by uC is 11*TAD+TACQ = 21us
try :
for loop in range( packetsToRead ) :
ret = dev.read( 129, 64, 10000) # ep, num-bytes, timeout
numValidBytes = int(ret[1])
print "Received cmd:%d, packetNum:%d, numValidBytes:%d, data[0]:%d, scalingFactor:%f" % (ret[0], loop, ret[1], (ret[2] << 8 | ret[3]), scalingFactor )
if numBytesInSample == 2 :
for i in xrange( reservedBytesInPacket, numValidBytes -1, 2):
allresults.append( int(round( (ret[i] << 8 | ret[i+1]) * scalingFactor )) )
elif numBytesInSample == 1 :
for i in xrange( reservedBytesInPacket, numValidBytes, 1):
allresults.append( int(round(ret[i] * scalingFactor)) )
allresults.append( -1) # End of packet indicator. There will be sampling discontinuity at this point, since time is spent in sending the packet.
# for binary file use : allresults.extend( ret[reservedBytesInPacket : numValidBytes-1] )
except Exception as error :
# trap error so that earlier results can be processed after a timeout. This may be useful in cases where we have kept numSamples
# on the higher side, and since we don't get those many in reality, a timeout may occur.
print "Error:" , error, sys.exc_info()
print "allresults:", allresults
# save to file
# for binary
# newFile = open ("results.bi", "wb")
# newFile.write( bytearray(allresults))
with open( "../hid_io_results_" + cmd + ".js", 'wb') as outfile:
outfile.write( "var sampleInterval = " + str(effSamplingInterval) + ";")
outfile.write( "var hid_io_data = ")
json.dump( allresults, outfile)
| {
"content_hash": "483bd432b257eaf2753f05419635c661",
"timestamp": "",
"source": "github",
"line_count": 195,
"max_line_length": 166,
"avg_line_length": 49.43589743589744,
"alnum_prop": 0.641597510373444,
"repo_name": "manojmo/pic_micro",
"id": "ad41cff041bab4c5aa4ec35ca267528d4b4193a7",
"size": "9640",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hid_io/hid_io_test.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "54988"
},
{
"name": "C++",
"bytes": "3477"
},
{
"name": "HTML",
"bytes": "2313"
},
{
"name": "Python",
"bytes": "9640"
}
],
"symlink_target": ""
} |
import React, { PropTypes } from 'react';
import styles from './App.css';
import './styles/globalStyles.css';
import Navbar from 'components/Navbar.js';
import Perf from 'react-addons-perf';
import Notification from 'components/Notification.js';
const devMode = process.env.NODE_ENV !== 'production';
if (devMode) {
window.Perf = Perf;
}
const propTypes = {
children: PropTypes.element,
};
export default function App(props) {
return (
<div className={ styles.Skeleton }>
<header className={ styles.Header }>
<div className={ styles.Title }>El Liger</div>
<Navbar />
</header>
<div className={ styles.Background }>
<div className={ styles.Content }>
{ props.children }
</div>
</div>
<Notification />
</div>
);
}
App.propTypes = propTypes;
| {
"content_hash": "39214fae3aabd10fbf479c70ca223e3e",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 54,
"avg_line_length": 24.441176470588236,
"alnum_prop": 0.6353790613718412,
"repo_name": "kinseyost/immutable-redux",
"id": "3e71f00318651232badeb2f6859d1e7f19bf0272",
"size": "831",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/App.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8889"
},
{
"name": "HTML",
"bytes": "9910"
},
{
"name": "JavaScript",
"bytes": "27124"
}
],
"symlink_target": ""
} |
## @file
# preprocess source file
#
# Copyright (c) 2007, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials
# are licensed and made available under the terms and conditions of the BSD License
# which accompanies this distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
#
##
# Import Modules
#
import re
import os
import sys
import antlr3
from CLexer import CLexer
from CParser import CParser
import FileProfile
from CodeFragment import Comment
from CodeFragment import PP_Directive
from ParserWarning import Warning
##define T_CHAR_SPACE ' '
##define T_CHAR_NULL '\0'
##define T_CHAR_CR '\r'
##define T_CHAR_TAB '\t'
##define T_CHAR_LF '\n'
##define T_CHAR_SLASH '/'
##define T_CHAR_BACKSLASH '\\'
##define T_CHAR_DOUBLE_QUOTE '\"'
##define T_CHAR_SINGLE_QUOTE '\''
##define T_CHAR_STAR '*'
##define T_CHAR_HASH '#'
(T_CHAR_SPACE, T_CHAR_NULL, T_CHAR_CR, T_CHAR_TAB, T_CHAR_LF, T_CHAR_SLASH, \
T_CHAR_BACKSLASH, T_CHAR_DOUBLE_QUOTE, T_CHAR_SINGLE_QUOTE, T_CHAR_STAR, T_CHAR_HASH) = \
(' ', '\0', '\r', '\t', '\n', '/', '\\', '\"', '\'', '*', '#')
SEPERATOR_TUPLE = ('=', '|', ',', '{', '}')
(T_COMMENT_TWO_SLASH, T_COMMENT_SLASH_STAR) = (0, 1)
(T_PP_INCLUDE, T_PP_DEFINE, T_PP_OTHERS) = (0, 1, 2)
## The collector for source code fragments.
#
# PreprocessFile method should be called prior to ParseFile
#
# GetNext*** procedures mean these procedures will get next token first, then make judgement.
# Get*** procedures mean these procedures will make judgement on current token only.
#
class CodeFragmentCollector:
## The constructor
#
# @param self The object pointer
# @param FileName The file that to be parsed
#
def __init__(self, FileName):
self.Profile = FileProfile.FileProfile(FileName)
self.Profile.FileLinesList.append(T_CHAR_LF)
self.FileName = FileName
self.CurrentLineNumber = 1
self.CurrentOffsetWithinLine = 0
self.__Token = ""
self.__SkippedChars = ""
## __IsWhiteSpace() method
#
# Whether char at current FileBufferPos is whitespace
#
# @param self The object pointer
# @param Char The char to test
# @retval True The char is a kind of white space
# @retval False The char is NOT a kind of white space
#
def __IsWhiteSpace(self, Char):
if Char in (T_CHAR_NULL, T_CHAR_CR, T_CHAR_SPACE, T_CHAR_TAB, T_CHAR_LF):
return True
else:
return False
## __SkipWhiteSpace() method
#
# Skip white spaces from current char, return number of chars skipped
#
# @param self The object pointer
# @retval Count The number of chars skipped
#
def __SkipWhiteSpace(self):
Count = 0
while not self.__EndOfFile():
Count += 1
if self.__CurrentChar() in (T_CHAR_NULL, T_CHAR_CR, T_CHAR_LF, T_CHAR_SPACE, T_CHAR_TAB):
self.__SkippedChars += str(self.__CurrentChar())
self.__GetOneChar()
else:
Count = Count - 1
return Count
## __EndOfFile() method
#
# Judge current buffer pos is at file end
#
# @param self The object pointer
# @retval True Current File buffer position is at file end
# @retval False Current File buffer position is NOT at file end
#
def __EndOfFile(self):
NumberOfLines = len(self.Profile.FileLinesList)
SizeOfLastLine = NumberOfLines
if NumberOfLines > 0:
SizeOfLastLine = len(self.Profile.FileLinesList[-1])
if self.CurrentLineNumber == NumberOfLines and self.CurrentOffsetWithinLine >= SizeOfLastLine - 1:
return True
elif self.CurrentLineNumber > NumberOfLines:
return True
else:
return False
## __EndOfLine() method
#
# Judge current buffer pos is at line end
#
# @param self The object pointer
# @retval True Current File buffer position is at line end
# @retval False Current File buffer position is NOT at line end
#
def __EndOfLine(self):
SizeOfCurrentLine = len(self.Profile.FileLinesList[self.CurrentLineNumber - 1])
if self.CurrentOffsetWithinLine >= SizeOfCurrentLine - 1:
return True
else:
return False
## Rewind() method
#
# Reset file data buffer to the initial state
#
# @param self The object pointer
#
def Rewind(self):
self.CurrentLineNumber = 1
self.CurrentOffsetWithinLine = 0
## __UndoOneChar() method
#
# Go back one char in the file buffer
#
# @param self The object pointer
# @retval True Successfully go back one char
# @retval False Not able to go back one char as file beginning reached
#
def __UndoOneChar(self):
if self.CurrentLineNumber == 1 and self.CurrentOffsetWithinLine == 0:
return False
elif self.CurrentOffsetWithinLine == 0:
self.CurrentLineNumber -= 1
self.CurrentOffsetWithinLine = len(self.__CurrentLine()) - 1
else:
self.CurrentOffsetWithinLine -= 1
return True
## __GetOneChar() method
#
# Move forward one char in the file buffer
#
# @param self The object pointer
#
def __GetOneChar(self):
if self.CurrentOffsetWithinLine == len(self.Profile.FileLinesList[self.CurrentLineNumber - 1]) - 1:
self.CurrentLineNumber += 1
self.CurrentOffsetWithinLine = 0
else:
self.CurrentOffsetWithinLine += 1
## __CurrentChar() method
#
# Get the char pointed to by the file buffer pointer
#
# @param self The object pointer
# @retval Char Current char
#
def __CurrentChar(self):
CurrentChar = self.Profile.FileLinesList[self.CurrentLineNumber - 1][self.CurrentOffsetWithinLine]
# if CurrentChar > 255:
# raise Warning("Non-Ascii char found At Line %d, offset %d" % (self.CurrentLineNumber, self.CurrentOffsetWithinLine), self.FileName, self.CurrentLineNumber)
return CurrentChar
## __NextChar() method
#
# Get the one char pass the char pointed to by the file buffer pointer
#
# @param self The object pointer
# @retval Char Next char
#
def __NextChar(self):
if self.CurrentOffsetWithinLine == len(self.Profile.FileLinesList[self.CurrentLineNumber - 1]) - 1:
return self.Profile.FileLinesList[self.CurrentLineNumber][0]
else:
return self.Profile.FileLinesList[self.CurrentLineNumber - 1][self.CurrentOffsetWithinLine + 1]
## __SetCurrentCharValue() method
#
# Modify the value of current char
#
# @param self The object pointer
# @param Value The new value of current char
#
def __SetCurrentCharValue(self, Value):
self.Profile.FileLinesList[self.CurrentLineNumber - 1][self.CurrentOffsetWithinLine] = Value
## __SetCharValue() method
#
# Modify the value of current char
#
# @param self The object pointer
# @param Value The new value of current char
#
def __SetCharValue(self, Line, Offset, Value):
self.Profile.FileLinesList[Line - 1][Offset] = Value
## __CurrentLine() method
#
# Get the list that contains current line contents
#
# @param self The object pointer
# @retval List current line contents
#
def __CurrentLine(self):
return self.Profile.FileLinesList[self.CurrentLineNumber - 1]
## __InsertComma() method
#
# Insert ',' to replace PP
#
# @param self The object pointer
# @retval List current line contents
#
def __InsertComma(self, Line):
if self.Profile.FileLinesList[Line - 1][0] != T_CHAR_HASH:
BeforeHashPart = str(self.Profile.FileLinesList[Line - 1]).split(T_CHAR_HASH)[0]
if BeforeHashPart.rstrip().endswith(T_CHAR_COMMA) or BeforeHashPart.rstrip().endswith(';'):
return
if Line - 2 >= 0 and str(self.Profile.FileLinesList[Line - 2]).rstrip().endswith(','):
return
if Line - 2 >= 0 and str(self.Profile.FileLinesList[Line - 2]).rstrip().endswith(';'):
return
if str(self.Profile.FileLinesList[Line]).lstrip().startswith(',') or str(self.Profile.FileLinesList[Line]).lstrip().startswith(';'):
return
self.Profile.FileLinesList[Line - 1].insert(self.CurrentOffsetWithinLine, ',')
## PreprocessFile() method
#
# Preprocess file contents, replace comments with spaces.
# In the end, rewind the file buffer pointer to the beginning
# BUGBUG: No !include statement processing contained in this procedure
# !include statement should be expanded at the same FileLinesList[CurrentLineNumber - 1]
#
# @param self The object pointer
#
def PreprocessFile(self):
self.Rewind()
InComment = False
DoubleSlashComment = False
HashComment = False
PPExtend = False
CommentObj = None
PPDirectiveObj = None
# HashComment in quoted string " " is ignored.
InString = False
InCharLiteral = False
self.Profile.FileLinesList = [list(s) for s in self.Profile.FileLinesListFromFile]
while not self.__EndOfFile():
if not InComment and self.__CurrentChar() == T_CHAR_DOUBLE_QUOTE:
InString = not InString
if not InComment and self.__CurrentChar() == T_CHAR_SINGLE_QUOTE:
InCharLiteral = not InCharLiteral
# meet new line, then no longer in a comment for // and '#'
if self.__CurrentChar() == T_CHAR_LF:
if HashComment and PPDirectiveObj != None:
if PPDirectiveObj.Content.rstrip(T_CHAR_CR).endswith(T_CHAR_BACKSLASH):
PPDirectiveObj.Content += T_CHAR_LF
PPExtend = True
else:
PPExtend = False
EndLinePos = (self.CurrentLineNumber, self.CurrentOffsetWithinLine)
if InComment and DoubleSlashComment:
InComment = False
DoubleSlashComment = False
CommentObj.Content += T_CHAR_LF
CommentObj.EndPos = EndLinePos
FileProfile.CommentList.append(CommentObj)
CommentObj = None
if InComment and HashComment and not PPExtend:
InComment = False
HashComment = False
PPDirectiveObj.Content += T_CHAR_LF
PPDirectiveObj.EndPos = EndLinePos
FileProfile.PPDirectiveList.append(PPDirectiveObj)
PPDirectiveObj = None
if InString or InCharLiteral:
CurrentLine = "".join(self.__CurrentLine())
if CurrentLine.rstrip(T_CHAR_LF).rstrip(T_CHAR_CR).endswith(T_CHAR_BACKSLASH):
SlashIndex = CurrentLine.rindex(T_CHAR_BACKSLASH)
self.__SetCharValue(self.CurrentLineNumber, SlashIndex, T_CHAR_SPACE)
if InComment and not DoubleSlashComment and not HashComment:
CommentObj.Content += T_CHAR_LF
self.CurrentLineNumber += 1
self.CurrentOffsetWithinLine = 0
# check for */ comment end
elif InComment and not DoubleSlashComment and not HashComment and self.__CurrentChar() == T_CHAR_STAR and self.__NextChar() == T_CHAR_SLASH:
CommentObj.Content += self.__CurrentChar()
# self.__SetCurrentCharValue(T_CHAR_SPACE)
self.__GetOneChar()
CommentObj.Content += self.__CurrentChar()
# self.__SetCurrentCharValue(T_CHAR_SPACE)
CommentObj.EndPos = (self.CurrentLineNumber, self.CurrentOffsetWithinLine)
FileProfile.CommentList.append(CommentObj)
CommentObj = None
self.__GetOneChar()
InComment = False
# set comments to spaces
elif InComment:
if HashComment:
# // follows hash PP directive
if self.__CurrentChar() == T_CHAR_SLASH and self.__NextChar() == T_CHAR_SLASH:
InComment = False
HashComment = False
PPDirectiveObj.EndPos = (self.CurrentLineNumber, self.CurrentOffsetWithinLine - 1)
FileProfile.PPDirectiveList.append(PPDirectiveObj)
PPDirectiveObj = None
continue
else:
PPDirectiveObj.Content += self.__CurrentChar()
if PPExtend:
self.__SetCurrentCharValue(T_CHAR_SPACE)
else:
CommentObj.Content += self.__CurrentChar()
# self.__SetCurrentCharValue(T_CHAR_SPACE)
self.__GetOneChar()
# check for // comment
elif self.__CurrentChar() == T_CHAR_SLASH and self.__NextChar() == T_CHAR_SLASH:
InComment = True
DoubleSlashComment = True
CommentObj = Comment('', (self.CurrentLineNumber, self.CurrentOffsetWithinLine), None, T_COMMENT_TWO_SLASH)
# check for '#' comment
elif self.__CurrentChar() == T_CHAR_HASH and not InString and not InCharLiteral:
InComment = True
HashComment = True
PPDirectiveObj = PP_Directive('', (self.CurrentLineNumber, self.CurrentOffsetWithinLine), None)
# check for /* comment start
elif self.__CurrentChar() == T_CHAR_SLASH and self.__NextChar() == T_CHAR_STAR:
CommentObj = Comment('', (self.CurrentLineNumber, self.CurrentOffsetWithinLine), None, T_COMMENT_SLASH_STAR)
CommentObj.Content += self.__CurrentChar()
# self.__SetCurrentCharValue( T_CHAR_SPACE)
self.__GetOneChar()
CommentObj.Content += self.__CurrentChar()
# self.__SetCurrentCharValue( T_CHAR_SPACE)
self.__GetOneChar()
InComment = True
else:
self.__GetOneChar()
EndLinePos = (self.CurrentLineNumber, self.CurrentOffsetWithinLine)
if InComment and DoubleSlashComment:
CommentObj.EndPos = EndLinePos
FileProfile.CommentList.append(CommentObj)
if InComment and HashComment and not PPExtend:
PPDirectiveObj.EndPos = EndLinePos
FileProfile.PPDirectiveList.append(PPDirectiveObj)
self.Rewind()
def PreprocessFileWithClear(self):
self.Rewind()
InComment = False
DoubleSlashComment = False
HashComment = False
PPExtend = False
CommentObj = None
PPDirectiveObj = None
# HashComment in quoted string " " is ignored.
InString = False
InCharLiteral = False
self.Profile.FileLinesList = [list(s) for s in self.Profile.FileLinesListFromFile]
while not self.__EndOfFile():
if not InComment and self.__CurrentChar() == T_CHAR_DOUBLE_QUOTE:
InString = not InString
if not InComment and self.__CurrentChar() == T_CHAR_SINGLE_QUOTE:
InCharLiteral = not InCharLiteral
# meet new line, then no longer in a comment for // and '#'
if self.__CurrentChar() == T_CHAR_LF:
if HashComment and PPDirectiveObj != None:
if PPDirectiveObj.Content.rstrip(T_CHAR_CR).endswith(T_CHAR_BACKSLASH):
PPDirectiveObj.Content += T_CHAR_LF
PPExtend = True
else:
PPExtend = False
EndLinePos = (self.CurrentLineNumber, self.CurrentOffsetWithinLine)
if InComment and DoubleSlashComment:
InComment = False
DoubleSlashComment = False
CommentObj.Content += T_CHAR_LF
CommentObj.EndPos = EndLinePos
FileProfile.CommentList.append(CommentObj)
CommentObj = None
if InComment and HashComment and not PPExtend:
InComment = False
HashComment = False
PPDirectiveObj.Content += T_CHAR_LF
PPDirectiveObj.EndPos = EndLinePos
FileProfile.PPDirectiveList.append(PPDirectiveObj)
PPDirectiveObj = None
if InString or InCharLiteral:
CurrentLine = "".join(self.__CurrentLine())
if CurrentLine.rstrip(T_CHAR_LF).rstrip(T_CHAR_CR).endswith(T_CHAR_BACKSLASH):
SlashIndex = CurrentLine.rindex(T_CHAR_BACKSLASH)
self.__SetCharValue(self.CurrentLineNumber, SlashIndex, T_CHAR_SPACE)
if InComment and not DoubleSlashComment and not HashComment:
CommentObj.Content += T_CHAR_LF
self.CurrentLineNumber += 1
self.CurrentOffsetWithinLine = 0
# check for */ comment end
elif InComment and not DoubleSlashComment and not HashComment and self.__CurrentChar() == T_CHAR_STAR and self.__NextChar() == T_CHAR_SLASH:
CommentObj.Content += self.__CurrentChar()
self.__SetCurrentCharValue(T_CHAR_SPACE)
self.__GetOneChar()
CommentObj.Content += self.__CurrentChar()
self.__SetCurrentCharValue(T_CHAR_SPACE)
CommentObj.EndPos = (self.CurrentLineNumber, self.CurrentOffsetWithinLine)
FileProfile.CommentList.append(CommentObj)
CommentObj = None
self.__GetOneChar()
InComment = False
# set comments to spaces
elif InComment:
if HashComment:
# // follows hash PP directive
if self.__CurrentChar() == T_CHAR_SLASH and self.__NextChar() == T_CHAR_SLASH:
InComment = False
HashComment = False
PPDirectiveObj.EndPos = (self.CurrentLineNumber, self.CurrentOffsetWithinLine - 1)
FileProfile.PPDirectiveList.append(PPDirectiveObj)
PPDirectiveObj = None
continue
else:
PPDirectiveObj.Content += self.__CurrentChar()
# if PPExtend:
# self.__SetCurrentCharValue(T_CHAR_SPACE)
else:
CommentObj.Content += self.__CurrentChar()
self.__SetCurrentCharValue(T_CHAR_SPACE)
self.__GetOneChar()
# check for // comment
elif self.__CurrentChar() == T_CHAR_SLASH and self.__NextChar() == T_CHAR_SLASH:
InComment = True
DoubleSlashComment = True
CommentObj = Comment('', (self.CurrentLineNumber, self.CurrentOffsetWithinLine), None, T_COMMENT_TWO_SLASH)
# check for '#' comment
elif self.__CurrentChar() == T_CHAR_HASH and not InString and not InCharLiteral:
InComment = True
HashComment = True
PPDirectiveObj = PP_Directive('', (self.CurrentLineNumber, self.CurrentOffsetWithinLine), None)
# check for /* comment start
elif self.__CurrentChar() == T_CHAR_SLASH and self.__NextChar() == T_CHAR_STAR:
CommentObj = Comment('', (self.CurrentLineNumber, self.CurrentOffsetWithinLine), None, T_COMMENT_SLASH_STAR)
CommentObj.Content += self.__CurrentChar()
self.__SetCurrentCharValue( T_CHAR_SPACE)
self.__GetOneChar()
CommentObj.Content += self.__CurrentChar()
self.__SetCurrentCharValue( T_CHAR_SPACE)
self.__GetOneChar()
InComment = True
else:
self.__GetOneChar()
EndLinePos = (self.CurrentLineNumber, self.CurrentOffsetWithinLine)
if InComment and DoubleSlashComment:
CommentObj.EndPos = EndLinePos
FileProfile.CommentList.append(CommentObj)
if InComment and HashComment and not PPExtend:
PPDirectiveObj.EndPos = EndLinePos
FileProfile.PPDirectiveList.append(PPDirectiveObj)
self.Rewind()
## ParseFile() method
#
# Parse the file profile buffer to extract fd, fv ... information
# Exception will be raised if syntax error found
#
# @param self The object pointer
#
def ParseFile(self):
self.PreprocessFile()
# restore from ListOfList to ListOfString
self.Profile.FileLinesList = ["".join(list) for list in self.Profile.FileLinesList]
FileStringContents = ''
for fileLine in self.Profile.FileLinesList:
FileStringContents += fileLine
cStream = antlr3.StringStream(FileStringContents)
lexer = CLexer(cStream)
tStream = antlr3.CommonTokenStream(lexer)
parser = CParser(tStream)
parser.translation_unit()
def ParseFileWithClearedPPDirective(self):
self.PreprocessFileWithClear()
# restore from ListOfList to ListOfString
self.Profile.FileLinesList = ["".join(list) for list in self.Profile.FileLinesList]
FileStringContents = ''
for fileLine in self.Profile.FileLinesList:
FileStringContents += fileLine
cStream = antlr3.StringStream(FileStringContents)
lexer = CLexer(cStream)
tStream = antlr3.CommonTokenStream(lexer)
parser = CParser(tStream)
parser.translation_unit()
def CleanFileProfileBuffer(self):
FileProfile.CommentList = []
FileProfile.PPDirectiveList = []
FileProfile.PredicateExpressionList = []
FileProfile.FunctionDefinitionList = []
FileProfile.VariableDeclarationList = []
FileProfile.EnumerationDefinitionList = []
FileProfile.StructUnionDefinitionList = []
FileProfile.TypedefDefinitionList = []
FileProfile.FunctionCallingList = []
def PrintFragments(self):
print '################# ' + self.FileName + '#####################'
print '/****************************************/'
print '/*************** COMMENTS ***************/'
print '/****************************************/'
for comment in FileProfile.CommentList:
print str(comment.StartPos) + comment.Content
print '/****************************************/'
print '/********* PREPROCESS DIRECTIVES ********/'
print '/****************************************/'
for pp in FileProfile.PPDirectiveList:
print str(pp.StartPos) + pp.Content
print '/****************************************/'
print '/********* VARIABLE DECLARATIONS ********/'
print '/****************************************/'
for var in FileProfile.VariableDeclarationList:
print str(var.StartPos) + var.Modifier + ' '+ var.Declarator
print '/****************************************/'
print '/********* FUNCTION DEFINITIONS *********/'
print '/****************************************/'
for func in FileProfile.FunctionDefinitionList:
print str(func.StartPos) + func.Modifier + ' '+ func.Declarator + ' ' + str(func.NamePos)
print '/****************************************/'
print '/************ ENUMERATIONS **************/'
print '/****************************************/'
for enum in FileProfile.EnumerationDefinitionList:
print str(enum.StartPos) + enum.Content
print '/****************************************/'
print '/*********** STRUCTS/UNIONS *************/'
print '/****************************************/'
for su in FileProfile.StructUnionDefinitionList:
print str(su.StartPos) + su.Content
print '/****************************************/'
print '/********* PREDICATE EXPRESSIONS ********/'
print '/****************************************/'
for predexp in FileProfile.PredicateExpressionList:
print str(predexp.StartPos) + predexp.Content
print '/****************************************/'
print '/************** TYPEDEFS ****************/'
print '/****************************************/'
for typedef in FileProfile.TypedefDefinitionList:
print str(typedef.StartPos) + typedef.ToType
if __name__ == "__main__":
collector = CodeFragmentCollector(sys.argv[1])
collector.PreprocessFile()
print "For Test."
| {
"content_hash": "0c070b86ef034f0644b9b20787eefdd3",
"timestamp": "",
"source": "github",
"line_count": 624,
"max_line_length": 168,
"avg_line_length": 42.291666666666664,
"alnum_prop": 0.549677908298598,
"repo_name": "egraba/vbox_openbsd",
"id": "09799a89b26a90bf05eb52c01d34d43b1faeaa12",
"size": "26390",
"binary": false,
"copies": "11",
"ref": "refs/heads/master",
"path": "VirtualBox-5.0.0/src/VBox/Devices/EFI/Firmware/BaseTools/Source/Python/Ecc/CodeFragmentCollector.py",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Ada",
"bytes": "88714"
},
{
"name": "Assembly",
"bytes": "4303680"
},
{
"name": "AutoIt",
"bytes": "2187"
},
{
"name": "Batchfile",
"bytes": "95534"
},
{
"name": "C",
"bytes": "192632221"
},
{
"name": "C#",
"bytes": "64255"
},
{
"name": "C++",
"bytes": "83842667"
},
{
"name": "CLIPS",
"bytes": "5291"
},
{
"name": "CMake",
"bytes": "6041"
},
{
"name": "CSS",
"bytes": "26756"
},
{
"name": "D",
"bytes": "41844"
},
{
"name": "DIGITAL Command Language",
"bytes": "56579"
},
{
"name": "DTrace",
"bytes": "1466646"
},
{
"name": "GAP",
"bytes": "350327"
},
{
"name": "Groff",
"bytes": "298540"
},
{
"name": "HTML",
"bytes": "467691"
},
{
"name": "IDL",
"bytes": "106734"
},
{
"name": "Java",
"bytes": "261605"
},
{
"name": "JavaScript",
"bytes": "80927"
},
{
"name": "Lex",
"bytes": "25122"
},
{
"name": "Logos",
"bytes": "4941"
},
{
"name": "Makefile",
"bytes": "426902"
},
{
"name": "Module Management System",
"bytes": "2707"
},
{
"name": "NSIS",
"bytes": "177212"
},
{
"name": "Objective-C",
"bytes": "5619792"
},
{
"name": "Objective-C++",
"bytes": "81554"
},
{
"name": "PHP",
"bytes": "58585"
},
{
"name": "Pascal",
"bytes": "69941"
},
{
"name": "Perl",
"bytes": "240063"
},
{
"name": "PowerShell",
"bytes": "10664"
},
{
"name": "Python",
"bytes": "9094160"
},
{
"name": "QMake",
"bytes": "3055"
},
{
"name": "R",
"bytes": "21094"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Shell",
"bytes": "1460572"
},
{
"name": "SourcePawn",
"bytes": "4139"
},
{
"name": "TypeScript",
"bytes": "142342"
},
{
"name": "Visual Basic",
"bytes": "7161"
},
{
"name": "XSLT",
"bytes": "1034475"
},
{
"name": "Yacc",
"bytes": "22312"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "b39c158e743f844f483a079c730f34f5",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "3f694b86e8f0888094d5c6a5619b1f75701de601",
"size": "184",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Trichocline/Trichocline crispa/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
//
// Created by Andrey on 12/11/14.
// Copyright (c) 2014 Andrey Gayvoronsky. All rights reserved.
//
#import "FXModelValidator.h"
/**
* FXModelRequiredValidator validates that the specified attribute is not empty or have required value.
*/
@interface FXModelRequiredValidator : FXModelValidator
/**
* The desired value that the attribute must have.
* If this is nil, the validator will validate that the specified attribute is not empty.
* If this is set as a value that is not nil, the validator will validate that
* the attribute has a value that is the same as this property value.
* Defaults to nil.
*/
@property(nonatomic, copy) id requiredValue;
@end | {
"content_hash": "a03684baa9601ded025e1a6791f709b0",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 102,
"avg_line_length": 31.476190476190474,
"alnum_prop": 0.7609682299546142,
"repo_name": "plandem/FXModelValidation",
"id": "12215499ea693eea260c678c0d0c68af10904faa",
"size": "661",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "FXModelValidation/validators/FXModelRequiredValidator.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "165286"
},
{
"name": "Ruby",
"bytes": "1658"
}
],
"symlink_target": ""
} |
<?php
class LineTest extends PHPUnit_Framework_TestCase
{
public function testOne()
{
$info = Embed\Embed::create('https://line.do/embed/8oq/vertical');
$this->assertEquals($info->title, 'PHP Evolution');
$this->assertEquals($info->type, 'rich');
$this->assertEquals($info->code, '<iframe src="https://line.do/embed/8oq/vertical" frameborder="0" allowTransparency="true" style="border:1px solid #e7e7e7;width:640px;height:640px;"></iframe>');
$this->assertEquals($info->width, 640);
$this->assertEquals($info->height, 640);
$this->assertEquals($info->providerName, 'Line.do');
$this->assertEquals($info->providerUrl, 'https://line.do');
}
}
| {
"content_hash": "3e4ee75c52f81354924fe8cb37ab0adc",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 203,
"avg_line_length": 44.875,
"alnum_prop": 0.6434540389972145,
"repo_name": "daveross/Embed",
"id": "f9bd7d893acbd8be986957da3c9c3198cb8876cd",
"size": "718",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/LineTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1629"
},
{
"name": "PHP",
"bytes": "222502"
}
],
"symlink_target": ""
} |
<?php
namespace app\models;
use Yii;
use yii\base\Model;
/**
* LoginForm is the model behind the login form.
*
* @property User|null $user This property is read-only.
*
*/
class LoginForm extends Model {
public $username;
public $password;
public $rememberMe = true;
private $_user = false;
/**
* @return array the validation rules.
*/
public function rules() {
return [
// username and password are both required
[['username', 'password'], 'required'],
// rememberMe must be a boolean value
['rememberMe', 'boolean'],
// password is validated by validatePassword()
['password', 'validatePassword'],
];
}
/**
* Validates the password.
* This method serves as the inline validation for password.
*
* @param string $attribute the attribute currently being validated
* @param array $params the additional name-value pairs given in the rule
*/
public function validatePassword($attribute, $params) {
if (!$this->hasErrors()) {
$user = $this->getUser();
//echo $this->password; die();
if (!$user || !$user->validatePassword($this->password)) {
$this->addError($attribute, 'Incorrect username or passwordd.');
}
}
}
/**
* Logs in a user using the provided username and password.
* @return boolean whether the user is logged in successfully
*/
public function login() {
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
}
return false;
}
/**
* Finds user by [[username]]
*
* @return User|null
*/
public function getUser() {
if ($this->_user === false) {
$this->_user = User::findByUsername($this->username);
}
return $this->_user;
}
}
| {
"content_hash": "99f4507cf5776ee22331e0bd7ec12368",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 100,
"avg_line_length": 26.466666666666665,
"alnum_prop": 0.5571788413098236,
"repo_name": "mateso/gac",
"id": "5a764c06a28946e8b83c8824b7f9ffe8db88e5e3",
"size": "1985",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "models/LoginForm.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "45551"
},
{
"name": "Batchfile",
"bytes": "1030"
},
{
"name": "C#",
"bytes": "175266"
},
{
"name": "CSS",
"bytes": "3664"
},
{
"name": "HTML",
"bytes": "11666"
},
{
"name": "JavaScript",
"bytes": "346443"
},
{
"name": "PHP",
"bytes": "397745"
},
{
"name": "Pascal",
"bytes": "5735"
},
{
"name": "PowerShell",
"bytes": "144833"
}
],
"symlink_target": ""
} |
FROM biocontainers/biocontainers:debian-stretch-backports
MAINTAINER biocontainers <biodocker@gmail.com>
LABEL software="melting" \
container="melting" \
about.summary="compute the melting temperature of nucleic acid duplex" \
about.home="http://www.ebi.ac.uk/compneur-srv/melting/" \
software.version="4.3.1dfsg-2b1-deb" \
version="1" \
about.license_file="/usr/share/doc/melting/copyright" \
extra.binaries="/usr/bin/melting" \
about.tags="field::biology, field::biology:molecular, implemented-in::c,:commandline, role::program, scope::utility, suite::gnu,:analysing, works-with-format::plaintext, works-with::TODO"
ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update && apt-get install -y melting && apt-get clean && apt-get purge && rm -rf /var/lib/apt/lists/* /tmp/*
USER biodocker
| {
"content_hash": "f5ff53cec0d26cfb2b42d9aaca6c2b71",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 192,
"avg_line_length": 55.6,
"alnum_prop": 0.7194244604316546,
"repo_name": "BioDocker/containers",
"id": "7f1c18996aaefa8934f8e5132f1d827458758cfc",
"size": "834",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "melting/4.3.1dfsg-2b1-deb/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "721349"
},
{
"name": "Python",
"bytes": "1353"
},
{
"name": "Shell",
"bytes": "1268"
}
],
"symlink_target": ""
} |
var keyMirror = require('react/lib/keyMirror');
module.exports = keyMirror({
LIST_CREATE: null,
LIST_DESTROY: null,
LIST_UPDATE_TITLE: null
}); | {
"content_hash": "7cd69af3f6c23c28a81a9d380ed6e043",
"timestamp": "",
"source": "github",
"line_count": 7,
"max_line_length": 47,
"avg_line_length": 21.428571428571427,
"alnum_prop": 0.7066666666666667,
"repo_name": "rafaelchiti/board",
"id": "5c9e6b92349a9ead894f2a12a60e530338b0720e",
"size": "150",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "webapp/client/src/board/constants/list_constants.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "97870"
},
{
"name": "JavaScript",
"bytes": "1457968"
}
],
"symlink_target": ""
} |
import urlconf_inner
class ChangeURLconfMiddleware(object):
def process_request(self, request):
request.urlconf = urlconf_inner.__name__
class NullChangeURLconfMiddleware(object):
def process_request(self, request):
request.urlconf = None
| {
"content_hash": "24d11822a6d2ca05c9003aa2da55e822",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 48,
"avg_line_length": 29.444444444444443,
"alnum_prop": 0.7320754716981132,
"repo_name": "disqus/django-old",
"id": "7bc42f8df4fc8296269f733553888d126ae85eb8",
"size": "265",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/regressiontests/urlpatterns_reverse/middleware.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "JavaScript",
"bytes": "85749"
},
{
"name": "Python",
"bytes": "7413553"
},
{
"name": "Shell",
"bytes": "9076"
}
],
"symlink_target": ""
} |
<?php
namespace AppBundle\Tests\Domain\ValueObject\Email;
use AppBundle\Domain\ValueObject\Email;
class ConstructorTest extends \PHPUnit_Framework_TestCase
{
public function testConstructor()
{
$word = 'test@example.com'; // 6 characters
$email = new Email($word);
$this->assertSame($word, $email->getEmail());
$this->assertSame($word, (string) $email);
}
/**
* @dataProvider providerOfInvalidEmails
* @param string $email
*/
public function testIllegalEmails($email)
{
$this->setExpectedException('AppBundle\Domain\Exception\ValidationException');
new Email($email);
}
public function providerOfInvalidEmails()
{
return [
[''],
[1],
[null],
['example'],
['example.com'],
['@example.com'],
['name@'],
['!@!.com']
];
}
}
| {
"content_hash": "58f2aaf45bee1e3bbf016865766a715c",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 86,
"avg_line_length": 23.5,
"alnum_prop": 0.55,
"repo_name": "djmarland/clrk-symfony",
"id": "425d4993307e69cd0b7aecae6d3ba0691c2742a3",
"size": "940",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/AppBundle/Tests/Domain/ValueObject/Email/ConstructorTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3297"
},
{
"name": "CSS",
"bytes": "305348"
},
{
"name": "HTML",
"bytes": "18646"
},
{
"name": "JavaScript",
"bytes": "113057"
},
{
"name": "PHP",
"bytes": "133733"
},
{
"name": "Shell",
"bytes": "343"
}
],
"symlink_target": ""
} |
<?php
class Consumer_Model_ConsumersUsers extends Zend_Db_Table_Abstract
{
protected $_name = 'consumers_users';
protected $_primary = 'consumer_id';
protected $_referenceMap = array(
'ConsumerUser' => array(
'columns' => array('consumer_id'),
'refTableClass'=>'Consumer_Model_Consumer',
'refColumns' => array('id')
),
'UserConsumer' => array(
'columns'=>array('user_id'),
'refTableClass'=>'Default_Model_User',
'refColumns' => array('id')
));
public function findByConsumerIdAndUserId($consumer_id, $user_id) {
$select = $this->select()->where("consumer_id = ?", $consumer_id)->where( 'user_id = ?', $user_id );
$result = $this->fetchRow($select);
if( empty($result)) {
return null;
}
$consumerModel = new Consumer_Model_Consumer;
return $consumerModel->findById($result->consumer_id);
}
public function assign($consumer_id, $user_id) {
$count = $this->count( $consumer_id, $user_id );
if( $count == 0 ){
$data = array('consumer_id'=>$consumer_id, 'user_id'=>$user_id);
return $this->insert($data);
}
return false;
}
public function remove($consumer_id, $user_id) {
$count = $this->count( $consumer_id, $user_id );
if( $count > 0 ){
return $this->delete(array('consumer_id = ?' => $consumer_id, 'user_id = ?' =>$user_id));
}
return false;
}
public function count($consumer_id, $user_id) {
$select = $this->select();
$select->from($this->_name, array("num"=>"COUNT(consumer_id)", "count_id"=>"consumer_id"));
$select->where("consumer_id = ?", $consumer_id)->where( 'user_id = ?', $user_id );
$result = $this->fetchRow($select);
//return the int count.
return (int)$result["num"];
}
public function getByUserId($user_id) {
$result_ids = $this->fetchAll($this->select()->where( 'user_id = ?', $user_id ))->toArray();
if( count($result_ids) == 0 ) {
return null;
}
$consumer_ids = array();
foreach( $result_ids as $val){
$consumer_ids[] = (int)$val['consumer_id'];
}
$consumerModel = new Consumer_Model_Consumer;
return $consumerModel->findByIds($consumer_ids);
}
}
| {
"content_hash": "7c59043cd9d604af7fece793cda9107b",
"timestamp": "",
"source": "github",
"line_count": 97,
"max_line_length": 108,
"avg_line_length": 29.443298969072163,
"alnum_prop": 0.4565826330532213,
"repo_name": "scottyadean/socialWorks",
"id": "68d7d87d1bf1b074c8323c0a60473965af8bdb7d",
"size": "2856",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "application/modules/consumer/models/ConsumersUsers.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "10632"
},
{
"name": "JavaScript",
"bytes": "50442"
},
{
"name": "PHP",
"bytes": "15379520"
},
{
"name": "Shell",
"bytes": "806"
}
],
"symlink_target": ""
} |
protobuf_mutator::protobuf::LogSilencer log_silencer;
namespace net_reporting_header_parser_fuzzer {
void FuzzReportingHeaderParser(const std::string& data_json,
const net::ReportingPolicy& policy) {
net::TestReportingContext context(base::DefaultClock::GetInstance(),
base::DefaultTickClock::GetInstance(),
policy);
// Emulate what ReportingService::OnHeader does before calling
// ReportingHeaderParser::ParseHeader.
std::unique_ptr<base::Value> data_value =
base::JSONReader::ReadDeprecated("[" + data_json + "]");
if (!data_value)
return;
// TODO: consider including proto definition for URL after moving that to
// testing/libfuzzer/proto and creating a separate converter.
net::ReportingHeaderParser::ParseHeader(&context, net::NetworkIsolationKey(),
GURL("https://origin/path"),
std::move(data_value));
if (context.cache()->GetEndpointCount() == 0) {
return;
}
}
void InitializeReportingPolicy(
net::ReportingPolicy& policy,
const net_reporting_policy_proto::ReportingPolicy& policy_data) {
policy.max_report_count = policy_data.max_report_count();
policy.max_endpoint_count = policy_data.max_endpoint_count();
policy.delivery_interval =
base::TimeDelta::FromMicroseconds(policy_data.delivery_interval_us());
policy.persistence_interval =
base::TimeDelta::FromMicroseconds(policy_data.persistence_interval_us());
policy.persist_reports_across_restarts =
policy_data.persist_reports_across_restarts();
policy.persist_clients_across_restarts =
policy_data.persist_clients_across_restarts();
policy.garbage_collection_interval = base::TimeDelta::FromMicroseconds(
policy_data.garbage_collection_interval_us());
policy.max_report_age =
base::TimeDelta::FromMicroseconds(policy_data.max_report_age_us());
policy.max_report_attempts = policy_data.max_report_attempts();
policy.persist_reports_across_network_changes =
policy_data.persist_reports_across_network_changes();
policy.persist_clients_across_network_changes =
policy_data.persist_clients_across_network_changes();
if (policy_data.has_max_endpoints_per_origin())
policy.max_endpoints_per_origin = policy_data.max_endpoints_per_origin();
if (policy_data.has_max_group_staleness_us()) {
policy.max_group_staleness =
base::TimeDelta::FromMicroseconds(policy_data.max_report_age_us());
}
}
DEFINE_BINARY_PROTO_FUZZER(
const net_reporting_policy_proto::ReportingHeaderParserFuzzInput& input) {
net::ReportingPolicy policy;
InitializeReportingPolicy(policy, input.policy());
json_proto::JsonProtoConverter converter;
auto data = converter.Convert(input.headers());
FuzzReportingHeaderParser(data, policy);
}
} // namespace net_reporting_header_parser_fuzzer
| {
"content_hash": "10d7d8e483ed3effcda58e36c9c1a12f",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 79,
"avg_line_length": 43.470588235294116,
"alnum_prop": 0.6982408660351827,
"repo_name": "endlessm/chromium-browser",
"id": "d52179fc790b4eadca43824b75fff8589df68df7",
"size": "3766",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "net/reporting/reporting_header_parser_fuzzer.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package com.hazelcast.query.impl;
import java.util.AbstractSet;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import static com.hazelcast.internal.util.SetUtil.createHashSet;
/**
* Or result set for Predicates.
*/
public class OrResultSet extends AbstractSet<QueryableEntry> {
private static final int ENTRY_MULTIPLE = 4;
private static final int ENTRY_MIN_SIZE = 8;
private final List<Set<QueryableEntry>> indexedResults;
private Set<QueryableEntry> entries;
public OrResultSet(List<Set<QueryableEntry>> indexedResults) {
this.indexedResults = indexedResults;
}
@Override
public boolean contains(Object o) {
for (Set<QueryableEntry> otherIndexedResult : indexedResults) {
if (otherIndexedResult.contains(o)) {
return true;
}
}
return false;
}
@Override
public Iterator<QueryableEntry> iterator() {
return getEntries().iterator();
}
@Override
public int size() {
return getEntries().size();
}
/**
* @return returns estimated size without allocating the full result set
*/
public int estimatedSize() {
if (entries == null) {
if (indexedResults.isEmpty()) {
return 0;
} else {
return indexedResults.get(0).size();
}
}
return entries.size();
}
private Set<QueryableEntry> getEntries() {
if (entries == null) {
if (indexedResults.isEmpty()) {
entries = Collections.emptySet();
} else {
if (indexedResults.size() == 1) {
entries = new HashSet<QueryableEntry>(indexedResults.get(0));
} else {
entries = createHashSet(Math.max(ENTRY_MIN_SIZE, indexedResults.size() * ENTRY_MULTIPLE));
for (Set<QueryableEntry> result : indexedResults) {
entries.addAll(result);
}
}
}
}
return entries;
}
}
| {
"content_hash": "fa0de9668f629efc4e94a2403e78e526",
"timestamp": "",
"source": "github",
"line_count": 81,
"max_line_length": 110,
"avg_line_length": 26.88888888888889,
"alnum_prop": 0.5771349862258953,
"repo_name": "emre-aydin/hazelcast",
"id": "00f06065bda652c32ec8bcde279a9459901d09ff",
"size": "2803",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "hazelcast/src/main/java/com/hazelcast/query/impl/OrResultSet.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1261"
},
{
"name": "C",
"bytes": "353"
},
{
"name": "Java",
"bytes": "39634758"
},
{
"name": "Shell",
"bytes": "29479"
}
],
"symlink_target": ""
} |
#import "FBTask.h"
#import "FBRunLoopSpinner.h"
#import "FBTaskConfiguration.h"
#import "FBControlCoreError.h"
#import "FBControlCoreLogger.h"
#import "FBFileDataConsumer.h"
#import "FBFileReader.h"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-retain-cycles"
NSString *const FBTaskErrorDomain = @"com.facebook.FBControlCore.task";
@interface FBTaskOutput : NSObject
- (NSString *)contents;
- (id)attachWithError:(NSError **)error;
- (void)teardownResources;
@end
@interface FBTaskOutput_File : FBTaskOutput
@property (nonatomic, copy, nullable, readonly) NSString *filePath;
@property (nonatomic, strong, nullable, readwrite) NSFileHandle *fileHandle;
@end
@interface FBTaskOutput_Consumer : FBTaskOutput
@property (nonatomic, strong, nullable, readwrite) NSPipe *pipe;
@property (nonatomic, strong, nullable, readwrite) FBFileReader *reader;
@property (nonatomic, strong, nullable, readwrite) FBAccumilatingFileDataConsumer *dataConsumer;
@property (nonatomic, strong, nullable, readwrite) id<FBFileDataConsumer> consumer;
@end
@interface FBTaskConfiguration (FBTaskOutput)
- (FBTaskOutput *)createTaskOutput;
@end
@implementation FBTaskOutput
- (NSString *)contents
{
NSAssert(NO, @"-[%@ %@] is abstract and should be overridden", NSStringFromClass(self.class), NSStringFromSelector(_cmd));
return nil;
}
- (id)attachWithError:(NSError **)error
{
NSAssert(NO, @"-[%@ %@] is abstract and should be overridden", NSStringFromClass(self.class), NSStringFromSelector(_cmd));
return nil;
}
- (void)teardownResources
{
NSAssert(NO, @"-[%@ %@] is abstract and should be overridden", NSStringFromClass(self.class), NSStringFromSelector(_cmd));
}
@end
@implementation FBTaskOutput_Consumer
- (instancetype)initWithConsumer:(id<FBFileDataConsumer>)consumer dataConsumer:(FBAccumilatingFileDataConsumer *)dataConsumer
{
self = [super init];
if (!self) {
return nil;
}
_consumer = consumer;
_dataConsumer = dataConsumer;
return self;
}
- (NSString *)contents
{
return [[[NSString alloc]
initWithData:self.dataConsumer.data encoding:NSUTF8StringEncoding]
stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet];
}
- (id)attachWithError:(NSError **)error
{
NSAssert(self.pipe == nil, @"Cannot attach when already attached to pipe %@", self.pipe);
self.pipe = [NSPipe pipe];
self.reader = [FBFileReader readerWithFileHandle:self.pipe.fileHandleForReading consumer:self.consumer];
if (![self.reader startReadingWithError:error]) {
self.reader = nil;
self.pipe = nil;
return nil;
}
return self.pipe;
}
- (void)teardownResources
{
self.pipe = nil;
[self.reader stopReadingWithError:nil];
self.reader = nil;
}
@end
@implementation FBTaskOutput_File
- (instancetype)initWithPath:(NSString *)filePath
{
self = [super init];
if (!self) {
return nil;
}
_filePath = filePath;
return self;
}
- (NSString *)contents
{
@synchronized(self) {
return [NSString stringWithContentsOfFile:self.filePath usedEncoding:nil error:nil];
}
}
- (id)attachWithError:(NSError **)error
{
NSAssert(self.fileHandle == nil, @"Cannot attach when already attached to file %@", self.fileHandle);
if (!self.filePath) {
self.fileHandle = NSFileHandle.fileHandleWithNullDevice;
return self.fileHandle;
}
if (![NSFileManager.defaultManager createFileAtPath:self.filePath contents:nil attributes:nil]) {
return [[FBControlCoreError
describeFormat:@"Could not create file for writing at %@", self.filePath]
fail:error];
}
self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:self.filePath];
return self.fileHandle;
}
- (void)teardownResources
{
[self.fileHandle closeFile];
self.fileHandle = nil;
}
@end
@interface FBTaskProcess : NSObject
@property (nonatomic, assign, readonly) int terminationStatus;
@property (nonatomic, assign, readonly) BOOL isRunning;
- (pid_t)launchWithError:(NSError **)error terminationHandler:(void(^)(FBTaskProcess *))terminationHandler;
- (void)mountStandardOut:(id)stdOut;
- (void)mountStandardErr:(id)stdOut;
- (void)terminate;
@end
@interface FBTaskProcess_NSTask : FBTaskProcess
@property (nonatomic, strong, readwrite) NSTask *task;
- (instancetype)initWithTask:(NSTask *)task;
@end
@implementation FBTaskProcess
+ (instancetype)fromConfiguration:(FBTaskConfiguration *)configuration
{
NSTask *task = [[NSTask alloc] init];
task.environment = configuration.environment;
task.launchPath = configuration.launchPath;
task.arguments = configuration.arguments;
return [[FBTaskProcess_NSTask alloc] initWithTask:task];
}
- (BOOL)isRunning
{
NSAssert(NO, @"-[%@ %@] is abstract and should be overridden", NSStringFromClass(self.class), NSStringFromSelector(_cmd));
return NO;
}
- (int)terminationStatus
{
NSAssert(NO, @"-[%@ %@] is abstract and should be overridden", NSStringFromClass(self.class), NSStringFromSelector(_cmd));
return 0;
}
- (void)mountStandardOut:(id)stdOut
{
NSAssert(NO, @"-[%@ %@] is abstract and should be overridden", NSStringFromClass(self.class), NSStringFromSelector(_cmd));
}
- (void)mountStandardErr:(id)stdOut
{
NSAssert(NO, @"-[%@ %@] is abstract and should be overridden", NSStringFromClass(self.class), NSStringFromSelector(_cmd));
}
- (void)terminate
{
NSAssert(NO, @"-[%@ %@] is abstract and should be overridden", NSStringFromClass(self.class), NSStringFromSelector(_cmd));
}
- (pid_t)launchWithError:(NSError **)error terminationHandler:(void(^)(FBTaskProcess *))terminationHandler
{
NSAssert(NO, @"-[%@ %@] is abstract and should be overridden", NSStringFromClass(self.class), NSStringFromSelector(_cmd));
return 0;
}
@end
@implementation FBTaskProcess_NSTask
- (instancetype)initWithTask:(NSTask *)task
{
self = [super init];
if (!self) {
return nil;
}
_task = task;
return self;
}
- (pid_t)processIdentifier
{
return self.task.processIdentifier;
}
- (int)terminationStatus
{
return self.task.terminationStatus;
}
- (BOOL)isRunning
{
return self.task.isRunning;
}
- (void)mountStandardOut:(id)stdOut
{
self.task.standardOutput = stdOut;
}
- (void)mountStandardErr:(id)stdErr
{
self.task.standardError = stdErr;
}
- (pid_t)launchWithError:(NSError **)error terminationHandler:(void(^)(FBTaskProcess *))terminationHandler
{
self.task.terminationHandler = ^(NSTask *_) {
[self terminate];
terminationHandler(self);
};
[self.task launch];
return self.task.processIdentifier;
}
- (void)terminate
{
[self.task terminate];
[self.task waitUntilExit];
self.task.terminationHandler = nil;
}
@end
@interface FBTask ()
@property (nonatomic, copy, readonly) NSSet<NSNumber *> *acceptableStatusCodes;
@property (nonatomic, strong, nullable, readwrite) FBTaskProcess *process;
@property (nonatomic, strong, nullable, readwrite) FBTaskOutput *stdOutSlot;
@property (nonatomic, strong, nullable, readwrite) FBTaskOutput *stdErrSlot;
@property (nonatomic, copy, nullable, readwrite) NSString *configurationDescription;
@property (atomic, assign, readwrite) pid_t processIdentifier;
@property (atomic, assign, readwrite) BOOL completedTeardown;
@property (atomic, copy, nullable, readwrite) NSString *emittedError;
@property (atomic, copy, nullable, readwrite) void (^terminationHandler)(FBTask *);
@end
@implementation FBTask
#pragma mark Initializers
+ (FBTaskOutput *)createTaskOutput:(id)output
{
if ([output isKindOfClass:NSString.class]) {
return [[FBTaskOutput_File alloc] initWithPath:output];
}
id<FBFileDataConsumer> consumer = nil;
NSMutableData *data = [NSMutableData data];
if ([output conformsToProtocol:@protocol(FBFileDataConsumer)]) {
consumer = output;
}
else if ([output conformsToProtocol:@protocol(FBControlCoreLogger)]) {
id<FBControlCoreLogger> logger = output;
consumer = [FBLineFileDataConsumer lineReaderWithConsumer:^(NSString *line) {
[logger log:line];
}];
}
else {
NSAssert([output isKindOfClass:NSMutableData.class], @"Unexpected output type %@", output);
data = output;
}
FBAccumilatingFileDataConsumer *dataConsumer = [[FBAccumilatingFileDataConsumer alloc] initWithMutableData:data];
consumer = consumer ? [FBCompositeFileDataConsumer consumerWithConsumers:@[consumer, dataConsumer]] : dataConsumer;
return [[FBTaskOutput_Consumer alloc] initWithConsumer:consumer dataConsumer:dataConsumer];
}
+ (instancetype)taskWithConfiguration:(FBTaskConfiguration *)configuration
{
FBTaskProcess *task = [FBTaskProcess fromConfiguration:configuration];
FBTaskOutput *stdOut = [self createTaskOutput:configuration.stdOut];
FBTaskOutput *stdErr = [self createTaskOutput:configuration.stdErr];
return [[self alloc] initWithProcess:task stdOut:stdOut stdErr:stdErr acceptableStatusCodes:configuration.acceptableStatusCodes configurationDescription:configuration.description];
}
- (instancetype)initWithProcess:(FBTaskProcess *)process stdOut:(FBTaskOutput *)stdOut stdErr:(FBTaskOutput *)stdErr acceptableStatusCodes:(NSSet<NSNumber *> *)acceptableStatusCodes configurationDescription:(NSString *)configurationDescription
{
self = [super init];
if (!self) {
return nil;
}
_process = process;
_acceptableStatusCodes = acceptableStatusCodes;
_stdOutSlot = stdOut;
_stdErrSlot = stdErr;
_configurationDescription = configurationDescription;
return self;
}
#pragma mark - FBTerminationHandle Protocol
- (void)terminate
{
[self terminateWithErrorMessage:nil];
}
#pragma mark - FBTask Protocl
#pragma mark Starting
- (instancetype)startAsynchronously
{
return [self launchWithTerminationHandler:nil];
}
- (instancetype)startAsynchronouslyWithTerminationHandler:(void (^)(FBTask *task))handler
{
return [self launchWithTerminationHandler:handler];
}
- (instancetype)startSynchronouslyWithTimeout:(NSTimeInterval)timeout
{
[self launchWithTerminationHandler:nil];
NSError *error = nil;
if (![self waitForCompletionWithTimeout:timeout error:&error]) {
return [self terminateWithErrorMessage:error.description];
}
return [self terminateWithErrorMessage:nil];
}
#pragma mark Awaiting Completion
- (BOOL)waitForCompletionWithTimeout:(NSTimeInterval)timeout error:(NSError **)error;
{
BOOL completed = [NSRunLoop.currentRunLoop spinRunLoopWithTimeout:timeout untilTrue:^ BOOL {
return !self.process.isRunning;
}];
if (!completed) {
return [[FBControlCoreError
describeFormat:@"Launched process '%@' took longer than %f seconds to terminate", self, timeout]
failBool:error];
}
[self terminateWithErrorMessage:nil];
return YES;
}
#pragma mark Accessors
- (NSString *)stdOut
{
return [self.stdOutSlot contents];
}
- (NSString *)stdErr
{
return [self.stdErrSlot contents];
}
- (nullable NSError *)error
{
if (!self.emittedError) {
return nil;
}
FBControlCoreError *error = [[[[FBControlCoreError
describe:self.emittedError]
inDomain:FBTaskErrorDomain]
extraInfo:@"stdout" value:self.stdOut]
extraInfo:@"stderr" value:self.stdErr];
if (!self.process.isRunning) {
[error extraInfo:@"exitcode" value:@(self.process.terminationStatus)];
}
return [error build];
}
- (BOOL)hasTerminated
{
return self.completedTeardown;
}
- (BOOL)wasSuccessful
{
@synchronized(self)
{
return self.hasTerminated && self.emittedError == nil;
}
}
#pragma mark Private
- (instancetype)launchWithTerminationHandler:(void (^)(FBTask *task))handler
{
// Since the FBTask may not be returned by anyone and is asynchronous, it needs to be retained.
// This Retain is matched by a release in -[FBTask completeTermination].
CFRetain((__bridge CFTypeRef)(self));
self.terminationHandler = handler;
NSError *error = nil;
id stdOut = [self.stdOutSlot attachWithError:&error];
if (!stdOut) {
return [self terminateWithErrorMessage:error.description];
}
[self.process mountStandardOut:stdOut];
id stdErr = [self.stdErrSlot attachWithError:&error];
if (!stdErr) {
return [self terminateWithErrorMessage:error.description];
}
[self.process mountStandardErr:stdErr];
pid_t pid = [self.process launchWithError:&error terminationHandler:^(FBTaskProcess *_) {
[self terminateWithErrorMessage:nil];
}];
if (pid < 1) {
return [self terminateWithErrorMessage:error.description];
}
self.processIdentifier = pid;
return self;
}
- (instancetype)terminateWithErrorMessage:(nullable NSString *)errorMessage
{
@synchronized(self) {
if (!self.emittedError) {
self.emittedError = errorMessage;
}
if (self.completedTeardown) {
return self;
}
[self teardownProcess];
[self teardownResources];
[self completeTermination];
self.completedTeardown = YES;
return self;
}
}
- (void)teardownProcess
{
if (self.process.isRunning) {
[self.process terminate];
}
}
- (void)teardownResources
{
[self.stdOutSlot teardownResources];
[self.stdErrSlot teardownResources];
}
- (void)completeTermination
{
NSAssert(self.process.isRunning == NO, @"Process should be terminated before calling completeTermination");
if (self.emittedError == nil && [self.acceptableStatusCodes containsObject:@(self.process.terminationStatus)] == NO) {
self.emittedError = [NSString stringWithFormat:@"Returned non-zero status code %d", self.process.terminationStatus];
}
// Matches the release in -[FBTask launchWithTerminationHandler:].
CFRelease((__bridge CFTypeRef)(self));
void (^terminationHandler)(FBTask *) = self.terminationHandler;
if (!terminationHandler) {
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
terminationHandler(self);
});
self.terminationHandler = nil;
}
- (NSString *)description
{
return [NSString
stringWithFormat:@"%@ | Has Terminated %d",
self.configurationDescription,
self.hasTerminated
];
}
@end
#pragma clang diagnostic pop
| {
"content_hash": "8b9c907118675618ad9950b6ad3f8e73",
"timestamp": "",
"source": "github",
"line_count": 537,
"max_line_length": 243,
"avg_line_length": 25.886405959031656,
"alnum_prop": 0.7373570246744838,
"repo_name": "ichu501/FBSimulatorControl",
"id": "74fd21b8b53f92bf1f051aa06243a87882b5ce15",
"size": "14209",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "FBControlCore/Tasks/FBTask.m",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Objective-C",
"bytes": "767441"
},
{
"name": "Ruby",
"bytes": "189"
}
],
"symlink_target": ""
} |
<?php
namespace DFZ\Dola\Database;
use Doctrine\DBAL\Schema\Column;
use Doctrine\DBAL\Schema\SchemaException;
use Doctrine\DBAL\Schema\TableDiff;
use DFZ\Dola\Database\Schema\SchemaManager;
use DFZ\Dola\Database\Schema\Table;
use DFZ\Dola\Database\Types\Type;
class DatabaseUpdater
{
protected $tableArr;
protected $table;
protected $originalTable;
public function __construct(array $tableArr)
{
Type::registerCustomPlatformTypes();
$this->table = Table::make($tableArr);
$this->tableArr = $tableArr;
$this->originalTable = SchemaManager::listTableDetails($tableArr['oldName']);
}
/**
* Update the table.
*
* @return void
*/
public static function update($table)
{
if (!is_array($table)) {
$table = json_decode($table, true);
}
if (!SchemaManager::tableExists($table['oldName'])) {
throw SchemaException::tableDoesNotExist($table['oldName']);
}
$updater = new self($table);
$updater->updateTable();
}
/**
* Updates the table.
*
* @return void
*/
public function updateTable()
{
// Get table new name
if (($newName = $this->table->getName()) != $this->originalTable->getName()) {
// Make sure the new name doesn't already exist
if (SchemaManager::tableExists($newName)) {
throw SchemaException::tableAlreadyExists($newName);
}
} else {
$newName = false;
}
// Rename columns
if ($renamedColumnsDiff = $this->getRenamedColumnsDiff()) {
SchemaManager::alterTable($renamedColumnsDiff);
// Refresh original table after renaming the columns
$this->originalTable = SchemaManager::listTableDetails($this->tableArr['oldName']);
}
$tableDiff = $this->originalTable->diff($this->table);
// Add new table name to tableDiff
if ($newName) {
if (!$tableDiff) {
$tableDiff = new TableDiff($this->tableArr['oldName']);
$tableDiff->fromTable = $this->originalTable;
}
$tableDiff->newName = $newName;
}
// Update the table
if ($tableDiff) {
SchemaManager::alterTable($tableDiff);
}
}
/**
* Get the table diff to rename columns.
*
* @return \Doctrine\DBAL\Schema\TableDiff
*/
protected function getRenamedColumnsDiff()
{
$renamedColumns = $this->getRenamedColumns();
if (empty($renamedColumns)) {
return false;
}
$renamedColumnsDiff = new TableDiff($this->tableArr['oldName']);
$renamedColumnsDiff->fromTable = $this->originalTable;
foreach ($renamedColumns as $oldName => $newName) {
$renamedColumnsDiff->renamedColumns[$oldName] = $this->table->getColumn($newName);
}
return $renamedColumnsDiff;
}
/**
* Get the table diff to rename columns and indexes.
*
* @return \Doctrine\DBAL\Schema\TableDiff
*/
protected function getRenamedDiff()
{
$renamedColumns = $this->getRenamedColumns();
$renamedIndexes = $this->getRenamedIndexes();
if (empty($renamedColumns) && empty($renamedIndexes)) {
return false;
}
$renamedDiff = new TableDiff($this->tableArr['oldName']);
$renamedDiff->fromTable = $this->originalTable;
foreach ($renamedColumns as $oldName => $newName) {
$renamedDiff->renamedColumns[$oldName] = $this->table->getColumn($newName);
}
foreach ($renamedIndexes as $oldName => $newName) {
$renamedDiff->renamedIndexes[$oldName] = $this->table->getIndex($newName);
}
return $renamedDiff;
}
/**
* Get columns that were renamed.
*
* @return array
*/
protected function getRenamedColumns()
{
$renamedColumns = [];
foreach ($this->tableArr['columns'] as $column) {
$oldName = $column['oldName'];
// make sure this is an existing column and not a new one
if ($this->originalTable->hasColumn($oldName)) {
$name = $column['name'];
if ($name != $oldName) {
$renamedColumns[$oldName] = $name;
}
}
}
return $renamedColumns;
}
/**
* Get indexes that were renamed.
*
* @return array
*/
protected function getRenamedIndexes()
{
$renamedIndexes = [];
foreach ($this->tableArr['indexes'] as $index) {
$oldName = $index['oldName'];
// make sure this is an existing index and not a new one
if ($this->originalTable->hasIndex($oldName)) {
$name = $index['name'];
if ($name != $oldName) {
$renamedIndexes[$oldName] = $name;
}
}
}
return $renamedIndexes;
}
}
| {
"content_hash": "8cc43464d92ad0f071af23b07475df94",
"timestamp": "",
"source": "github",
"line_count": 190,
"max_line_length": 95,
"avg_line_length": 26.852631578947367,
"alnum_prop": 0.5552724421795374,
"repo_name": "jaeder/Dola",
"id": "41f668bcc468e90baee277478c056cfd91396d76",
"size": "5102",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Database/DatabaseUpdater.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "491443"
},
{
"name": "HTML",
"bytes": "332253"
},
{
"name": "JavaScript",
"bytes": "576763"
},
{
"name": "PHP",
"bytes": "295833"
}
],
"symlink_target": ""
} |
CoconutKit is a library of high-quality iOS components written at [hortis le studio](http://www.hortis.ch/) and in my spare time. It includes several tools for dealing with view controllers, multi-threading, animations, as well as some new controls and various utility classes. These components are meant to make the life of an iOS programmer easier by reducing the boilerplate code written every day, improving code quality and enforcing solid application architecture.
Most of CoconutKit components are not sexy as is, but rather useful. Do not be freaked out! These components are meant to make you more productive, less focused on debugging, so that you can spend more time working on the design of your application (if you have a great designer at hand, of course). Give CoconutKit a try, your life as an iOS programmer will never be the same afterwards!
CoconutKit is distributed under a permissive [MIT license](http://www.opensource.org/licenses/mit-license.php), which means you can freely use it in your own projects (commercial or not).
### What can I find in CoconutKit?
CoconutKit provides your with several kinds of classes covering various aspects of iOS development:
* High-quality view controller containers. These containers are the result of two years of hard work, and exceed by far the capabilities of UIKit built-in containers. In particular, view controllers can be combined or stacked, using any kind of transition animation (even yours). Your applications will never look the same as before!
* View controller containment API (compatible with iOS 4), richer, easier to use and far more powerful than the iOS 5 UIKit containment API. Writing your own view controller containers correctly has never been easier!
* Easy way to change the language used by an application at runtime, without having to alter system preferences
* Localization of labels and buttons directly in nib files, without having to create and bind outlets anymore
* Classes for creating animations made of several UIView block-based or Core Animation-based sub-animations in a declarative way. Such animations can be paused, reversed, played instantaneously, cancelled, repeated, and even more! Animations have never been so fun and easy to create!
* Core Data model management and validation made easy. The usual boilerplate Core Data code has been completely eliminated. Interactions with managed contexts have been made simple by introducing context-free methods acting on a context stack. Core Data validation boilerplate code is never required anymore, and text field bindings make form creation painless
* View controllers for web browsing and easier table view search management
* Multi-threaded task management, including task grouping, cancelation, progress status, task dependencies and remaining time estimation
* New controls
* text field moving automatically with the keyboard
* cursor
* slideshow with several transition animations (cross fade, Ken Burns, etc.)
* label with vertical alignment
* expanding / collapsing search bar
* Classes for common UI tasks (keyboard management, interface locking)
* Classes for single-line table view cell and view instantiations
* Methods for skinning some built-in controls prior to iOS 5 appearance API
* Lightweight logger, assertions, float comparisons, etc.
* Various extensions to Cocoa and UIKit classes (calendrical calculations, collections, notifications, etc.)
* ... and more!
* ... and even more to come!
### Where can I download CoconutKit?
You can download CoconutKit from [the official github page](https://github.com/defagos/CoconutKit), both in binary and source forms. [A companion repository](https://github.com/defagos/CoconutKit-CocoaPods) exists for easy installation using CocoaPods, but you do not need to check it out directly.
You can also directly checkout the git repository. Note that there are submodules you must update using the `git submodules update --init` command.
### Supporting development
CoconutKit is and will stay free. However, if you enjoy using it, you can support the countless hours of work that are invested into its creation. Thank you in advance!
[](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=3V35ZXWYXGAYG&lc=CH¤cy_code=USD&bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHosted)
### Credits
If you enjoy the library, [hortis](http://www.hortis.ch/) and I would sincerely love being credited somewhere in your application, for example on some about page. Thanks for your support!
### How can I discover CoconutKit components?
Check out the CoconutKit source code repository by visiting [the official project github page](https://github.com/defagos/CoconutKit), open the workspace and either run the `CoconutKit-demo` or the `CoconutKit-dev` targets. The result of running those targets is the same, the only difference is that `CoconutKit-demo` compiles and builds the CoconutKit library source code before using the resulting binaries, whereas `CoconutKit-dev` includes and compiles all libary sources as part of the project itself.
### Why should I use CoconutKit?
When designing components, I strongly emphasize on clean and documented interfaces, as well as on code quality. My goal is to create components that are easy to use, reliable, and which do what they claim they do, without nasty surprises. You should never have to look at a component implementation to know how it works, this should be obvious just by looking at its interface. I also strive to avoid components that leak or crash. If those are qualities you love to find in libraries, then you should start using CoconutKit now!
### How should I add CoconutKit to my project?
You can add CoconutKit to your project in several different ways:
#### Adding binaries manually
You can grab the latest tagged binary package available from [the project download page](https://github.com/defagos/CoconutKit/downloads). Add the `.staticframework` directory to your project (the _Create groups for any added folders_ option must be checked) and link your project against the following system frameworks:
* `CoreData.framework`
* `MessageUI.framework`
* `QuartzCore.framework`
If your project targets iOS 4 as well as iOS 5 and above, you might encounter _symbol not found_ issues at runtime. When this happens:
* If the symbol belongs to UIKit, then weakly link your target with `UIKit.framework` (click on your target, select _Build Phases_, and under _Link Binary With Libraries_ set `UIKit.framework` as optional)
* If the symbol begins with `_objc`, then link your target with the ARC Lite libraries by adding the `-fobjc-arc` flag to your target `Other Linker Flags` settting
#### Adding source files using CocoaPods
Since CoconutKit 2.0, the easiest way to add CoconutKit to a project is using [CocoaPods](https://github.com/CocoaPods/CocoaPods). The CoconutKit specification file should be available from the official CocoaPods [specification repository](https://github.com/CocoaPods/Specs). If this is the case, simply edit your project `Podfile` file to add an entry for CoconutKit:
platform :ios
pod 'CoconutKit', '~> <version>'
If the specification file is not available from the official CocoaPods specification repository, use the specification file available in the `Tools/CocoaPods` directory. Either add it to your `~/.cocoapods` local specification repository (creating the dedicated folder structure), or edit your project `Podfile` to tell CocoaPods to use the file directly:
platform :ios
pod 'CoconutKit', :podspec => '/absolute/path/to/CoconutKit/Tools/CocoaPods/CoconutKit.podspec'
The specification file has successfully been tested with CocoaPods 0.15.2.
#### Enabling logging
CoconutKit uses a logger to provide valuable information about its internal status. This should help you easily discover any issue you might encounter when using CoconutKit. To enable internal CoconutKit logging:
* If you are using CoconutKit binaries:
* Link your project against the debug version of the CoconutKit `.staticframework` (edit your project debug configuration settings so that the debug binaries are used)
* Add an `HLSLoggerLevel` entry to your project `.plist` to set the desired logging level (`DEBUG`, `INFO`, `WARN`, `ERROR` or `FATAL`)
* If you are using CocoaPods:
* Edit the generated `Pods.xcodeproj` project settings, adding `-DHLS_LOGGER` to the _Other C Flags_ setting for the debug configuration. This setting is sadly lost every time your run `pod install` to generate the CocoaPods workspace
* Add an `HLSLoggerLevel` entry to your project `.plist` to set the desired logging level (`DEBUG`, `INFO`, `WARN`, `ERROR` or `FATAL`)
CoconutKit logger also supports [XcodeColors](https://github.com/robbiehanson/XcodeColors). Simply install the XcodeColors plugin and enable colors when debugging your project within Xcode by adding an environment variable called `XcodeColors` to your project schemes. Projects in the CoconutKit workspace all have this environment variable set. If you see strange `[fg` sequences in your Xcode debugging console, either install XcodeColors or disable the `XcodeColors` environment variable by editing the corresponding project schemes.
### How should I use CoconutKit?
After CoconutKit has been added to your project, simply import its global public header file in your project `.pch` file:
* If you are using CoconutKit binaries, use `#import <CoconutKit/CoconutKit.h>`
* If you are using CocoaPods, use `#import "CoconutKit.h"`
Some code snippets have been provided in the `Snippets` directory (and more will probably be added in the future), both for ARC and non-ARC projects. Add them to your favorite snippet manager to make working with CoconutKit classes even more easier!
### How can I learn using CoconutKit?
To discover what CoconutKit can do, read the [project wiki](https://github.com/defagos/CoconutKit/wiki) and, once you want to learn more, have a look at header documentation. I try to keep documentation close to the code, that is why header documentation is rather extensive. All you need to know should be written there since I avoid detailed external documentation which often gets outdated. After you have read the documentation of a class, have a look at the demos and unit tests to see how the component is used in a concrete case.
Good documentation is critical. If you think some documentation is missing, unclear or incorrect, please file a ticket.
### Versions and migration guide
I sadly have not enough time to develop new features and to refactor existing ones while keeping CoconutKit public APIs unchanged or backward compatible. Sometimes method prototypes or even class names must change, and I cannot afford marking methods or classes as deprecated while still maintaining them. Let's face the truth: CoconutKit is not yet widely enough used to justify the amount of work which would be required.
When updating the version of CoconutKit you use, your project might therefore not compile anymore. In general, you should keep in mind that:
* major versions might contain major changes to the public APIs
* minor versions should only contain minor changes
#### Migrating from 1.x to 2.x
Version 2.0 is a major improvement over 1.x, which means several classes have undergone major changes. As usual, please read the header documentation to find what has changed:
* View controller containers:
* Placeholder view controllers can now display several insets simultaneously, intead of just one. The `placeholderView` outlet has therefore been replaced with a `placeholderViews` outlet collection, and you need to update your code and nib files accordingly. Methods to set an inset view controller now require a new index parameter specifying which inset must be set. Moreover, transition animations are not specified anymore using an enum value, but rather using a class
* Stack controllers transition animations are not specified anymore using an enum value, but rather using a class. An `animated` parameter has also been added to push and pop methods
* The CoconutKit container `forwardingProperties` setting has been removed. If you relied on it, you will need to update your code accordingly
* HLSViewController autorotation is now managed using the new methods introduced with iOS 6, on iOS 4 and 5 as well. All your HLSViewController subclasses must be updated accordingly by removing any existing `-shouldAutorotateToInterfaceOrientation:` implementation, replacing it with `-shouldAutorotate` and `-supportedInterfaceOrientations` implementations
* The way your create an `HLSAnimation` has changed. `HLSAnimationStep` has now been split into `HLSViewAnimationStep` (for UIView block-based animation steps) and `HLSLayerAnimationStep` (for Core Animation layer-based animation steps). The old `HLSViewAnimationStep` has been replaced with `HLSViewAnimation` for UIView block-based animations, and a corresponding `HLSLayerAnimation` has been introduced. The animations you previously defined by setting transforms on `HLSViewAnimationStep` are now created by calling translation, rotation or scale methods on `HLSViewAnimation`, respectively `HLSLayerAnimation`
* Core Data: Explicit managed contexts have been eliminated. You now must create an `HLSModelManager` object and use the corresponding class methods to push it onto a stack for the current thread. Then use the `HLSModelManager` context-free methods to interact with the store
### The CoconutKit workspace
The workspace file contains everything to build CoconutKit binaries, demos and unit tests.
Several projects are available:
* `CoconutKit`: The project used to build the CoconutKit static library
* `CoconutKit-resources`: The project creating the `.bundle` containing all resources needed by CoconutKit
* `CoconutKit-dev`: The main project used when working on CoconutKit. This project is an almost empty shell referencing files from both the `CoconutKit` and `CoconutKit-demo` projects
* `CoconutKit-demo`: The project used to test CoconutKit binaries against linker issues. When building the demo project, the CoconutKit `.staticframework` is first built and saved into the `Binaries` directory
* `CoconutKit-test`: The project running unit tests. This project references files from the `CoconutKit` project
Several schemes are available:
* `CoconutKit`: Builds the CoconutKit static library
* `CoconutKit-staticframework`: Builds the CoconutKit `.staticframework` into the `Binaries` directory, both for the Release and Debug configurations
* `CoconutKit-resources`: Builds the CoconutKit resource bundle into the `CoconutKit` directory
* `CoconutKit-(dev|demo)`: The standard CoconutKit component demo
* `CoconutKit-(dev|demo)-RootStack`: A demo where CoconutKit stack controller is the root view controller of an application
* `CoconutKit-(dev|demo)-RootSplitView`: A demo where a UIKit split view controller is the root view controller of an application
* `CoconutKit-(dev|demo)-RootTabBar`: A demo where a UIKit tab bar controller is the root view controller of an application
* `CoconutKit-(dev|demo)-RootNavigation`: A demo where a UIKit navigation controller is the root view controller of an application
* `CoconutKit-(dev|demo)-RootStoryboard`: A demo where a storyboard defines the whole application view controller hierarchy (itself managed using CoconutKit view controller containers). Runs on iOS 5 and above
* `CoconutKit-test`: CoconutKit unit tests
Schemes ending with `ios4` are similar, but with features not available on iOS 4 removed.
### Frequently asked questions
#### With which versions of iOS is CoconutKit compatible?
CoconutKit is compatible with iOS 4 and later (this will change as old OS versions get deprecated), both for iPhone and iPad projects. Please file a bug if you discover this is not the case.
#### With which versions of Xcode and the iOS SDK is CoconutKit compatible?
CoconutKit can be used with Xcode 4.4.1 (iOS SDK 5.1) and above, but is best used with the latest versions of Xcode and of the iOS SDK. Binaries themselves have been compiled using LLVM so that only projects built with LLVM will be able to successfully link against it (linking a project built with LLVM GCC against a library built with LLVM may result in crashes at runtime).
#### Can I use CoconutKit with ARC projects?
Yes. As long as you use binaries or CocoaPods, no additional configuration is required.
#### Can I use CoconutKit for applications published on the AppStore?
CoconutKit does not use any private API and is therefore AppStore friendly. Several applications hortis developed use CoconutKit and have successfully been approved.
#### Why have you released CoconutKit?
My company, [hortis](http://www.hortis.ch/), has a long tradition of open source development. This is one of the major reasons why I started to work for its entity devoted to mobile development, hortis le studio.
When I started iOS development a few years ago, I immediately felt huge gaps needed to be filled in some areas, so that I could get more productive and write better applications. CoconutKit was born.
During the last years, I was able to develop some areas of expertise (most notably view controller management, animations and Core Data). I always try to push the envelope in those areas, and I humbly hope the iOS community will be able to benefit from my experience.
#### Does CoconutKit use ARC?
No, CoconutKit currently does not use ARC itself. This will maybe change in a not-so-near future as ARC is adopted.
#### What does the HLS class prefix mean?
HLS stands for hortis le studio.
### Contributing to CoconutKit
You can contribute, and you are strongly encouraged to. Use github pull requests to submit your improvements and bug fixes. You can submit everything you want, documentation and comment fixes included! Everything that tends to increase code quality is always warmly welcome.
#### Requirements
There are some requirements when contributing, though:
* Code style guidelines are not formalized anywhere, but try to stay as close as possible to the style I use. This saves me some work when merging pull requests. IMHO, having a consistent way of organizing and writing source code makes it easier to read, write and maintain
* Read my [article about the memory management techniques](http://subjective-objective-c.blogspot.com/2011/04/use-objective-c-properties-to-manage.html) I use, and apply the same rules
* Do not use ARC
* Use of private APIs is strictly forbidden (except if the private method calls never make it into released binaries. You can still call private APIs to implement helpful debugging features, for example)
* Development and demo projects should be updated. Both are almost the same, except that the demo project uses the library in its binary form. New components should be written using the development project, so that an example with good code coverage is automatically available when your new component is ready. The demo project should then be updated accordingly
* Unit tests require version 0.5.2 of the [GHUnit framework for iOS](https://github.com/gabriel/gh-unit) to be installed under `/Developer/Frameworks/GHUnitIOS/0.5.2/GHUnitIOS.framework`
#### Writing code
Use the `CoconutKit-dev` project to easily write and test your code. When you are done with the `CoconutKit-dev` project, update the `CoconutKit` and `CoconutKit-demo` projects to mirror the changes you made to the source tree. New resources must be added to the `CoconutKit-resources` project.
Any new public header file must be added to the `CoconutKit-(dev|test).pch` file, as well as to the `publicHeaders.txt` file located in the `CoconutKit-dev` directory. Source files with linker issues (source files containing categories only, or meant to be used in Interface Builder) must also be added to the `bootstrap.txt` file. Please refer to the `make-fmwk.sh` documentation for more information.
For non-interactive components, you should consider adding some test cases to the `CoconutKit-test` project as well. Update it to mirror the changes made to the source and resource files of the `CoconutKit` project.
#### Code repository
Branches are managed using [git-flow](https://github.com/nvie/gitflow/):
* `master` is the stable branch on which commits are only made when a new official release is created
* `develop` is the main development branch and should be stable enough for use in between official releases
* all new features are developed on `feature` branches. You should avoid such branches since they might not be stable all the time
If you plan to develop for CoconutKit, install `git-flow` and setup your local repository by running `git flow init`, using the default settings.
### Acknowledgements
I really would like to thank my company for having allowed me to publish this work, as well as all my colleagues which have contributed and given me invaluable advice. This work is yours as well!
#### Contributors
The following lists all people who contributed to CoconutKit:
* [Cédric Luthi (0xced)](http://0xced.blogspot.com/) wrote the clever dynamic localization functionality, as well as the HLSWebViewController class
* Joris Heuberger wrote the HLSLabel class
### Release notes
#### Version 2.0.2
* Fix an issue with non-running animations incorrectly started after the application wakes up from background
* Add HLSFileManager
* Fix default capacity for stacks used in storyboards
* Add bundle parameter to HLSModelManager creation methods
#### Version 2.0.1
* HLSCursor now fills the associated view frame and resizes properly, the spacing parameter has therefore been removed. The cursor behaviour has been improved. The animation duration can now be changed
* Fix a bug with responders
#### Version 2.0
* CoconutKit containers have been rewritten from scratch and are now more powerful than ever:
* Support for iOS 4, 5 and 6
* Correct implementation of all view controller methods introduced with iOS 4 and 5
* Placeholder view controllers can now display several child view controllers (previously only one)
* Full compatibility with UIKit built-in containers
* New transition animations, which can now be completely customized
* Segue support on iOS 5 and above
* Insertion and removal of view controllers at arbitrary locations in a stack of view controllers
* Support for container view resizing
* Complete API to implement your own correct view controller containers easily (HLSContainerStack). The old API (HLSContainerContent) is not available anymore
* Animations have been rewritten from scratch and are now more powerful than ever:
* Core Animation layer-based animations are now supported
* Core Animation layer-based and UIView block-based animations can be mixed
* Animations can be paused and resumed
* Animations can be played starting from an arbitrary start time, or delayed
* Animations can be repeated or played in a loop
* Animations are paused and resumed automatically when the application enters and exits background
* Slow motion has been implemented for Core Animation layer-based animations (iOS simulator only)
* HLSViewController: iOS 6 autorotation methods provide a single consistent formalism to define autorotation behavior, even on iOS 4 and 5
* An aurototation mode property has been added to CoconutKit and UIKit containers, with which containers can decide whether their children decide whether rotation can occur or not
* Core Data: HLSModelManager has been improved:
* Managed contexts are not visible anymore, all database operations are now made through context-free methods acting on a stack of model manager objects (on a per-thread basis)
* All kinds of persistent stores are now supported
* HLSLabel has been added. This label performs automatic font size adjustment and provides a vertical alignment property
* The CoconutKit Xcode workspace has been improved. The `.staticframework` can now built within Xcode, and demo projects build it first as well
* Full iOS 6 support (autorotation, view unloading deprecation)
* HLSReloadable has been removed as it was pretty useless
* Tools for the CocoaPods source code release have been added
* Optional web view preloading has been added when the application starts
* XcodeColors support has been added to HLSLogger
* A `-popoverController` method has been added to UIViewController so that parent popover controllers can easily be accessed
* And of course, many other minor fixes, additions and implementation improvements!
#### Version 1.1.4
* CocoaPods can and should now be used for easy setup
* Resources have been packaged into a bundle
* Added new fade-in animation
* Added zeroing weak references
* An HLSAnimation is now automatically canceled if it has a delegate which gets deallocated
* Animations can now be canceled (this inhibits remaining delegate events) or terminated (this does not inhibit them)
* HLSKenBurnsSlideshow is now a special case of the new HLSSlideshow class (several transition effects available). The HLSSlideshowDelegate protocol has been added
* Minor fixes and implementation improvements
#### Version 1.1.3
* Added scroll view synchronization. This makes parallax scrolling easy to implement
* Fixed bugs (tab bar controller in custom containers, simultaneous container add / removal operations, iOS 4 crashes) as well as link issues with HLSActionSheet
#### Version 1.1.2
* Container view controller bug fix for iOS 5: viewWillAppear: and viewDidAppear: are now forwarded correctly to child view controllers when the container is the root of an application or presented modally
#### Version 1.1.1
* CGAffineTransform replaced by CATransform3D for creating richer animations
* New transition styles for containers (Flipboard-like push, horizontal and vertical flips)
* Various bug fixes
#### Version 1.1
* Added easy Core Data validation
* Added UILabel and UIButton localization in nib files
* Added Ken Burns slideshow
* Added categories for UIToolbar, UINavigationBar and UIWebView skinning
* Various bug fixes
#### Version 1.0.1
* Added dynamic localization (thanks to Cédric Luthi)
* Added unit tests
* Added action sheet
* Added UIView category for conveying custom information and tagging a view using a string
* Added code snippets
* Renamed HLSXibView as HLSNibView, and the xibViewName method as nibName. Removed macros HLSTableViewCellGet and HLSXibViewGet (use class methods instead)
* Moved methods for calculating start and end dates to NSCalendar extension
* Flatter project layout
* Fixes for iOS 5
* Various bug fixes
#### Version 1.0
Initial release
### Contact
Feel free to contact me if you have any questions or suggestions:
* mail: defagos ((at)) gmail ((dot)) com
* Twitter: @defagos
Thanks for your feedback!
### Licence
Copyright (c) 2011-2012 hortis le studio, Samuel Défago
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
| {
"content_hash": "7457608e46f72684a43111f62a33b592",
"timestamp": "",
"source": "github",
"line_count": 360,
"max_line_length": 614,
"avg_line_length": 77.80833333333334,
"alnum_prop": 0.7956517082574702,
"repo_name": "bboyfeiyu/CoconutKit",
"id": "cd51fbf09c68da67ca255de043de379b083e9a1a",
"size": "28039",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.markdown",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
import cStringIO
import csv
import datetime
import functools
import hashlib
import itertools
import json
import logging
import time
from funcy import project
import xlsxwriter
from flask_login import AnonymousUserMixin, UserMixin
from flask_sqlalchemy import SQLAlchemy
from passlib.apps import custom_app_context as pwd_context
from redash import redis_connection, utils
from redash.destinations import (get_configuration_schema_for_destination_type,
get_destination)
from redash.metrics import database # noqa: F401
from redash.permissions import has_access, view_only
from redash.query_runner import (get_configuration_schema_for_query_runner_type,
get_query_runner)
from redash.utils import generate_token, json_dumps
from redash.utils.configuration import ConfigurationContainer
from sqlalchemy import or_
from sqlalchemy.dialects import postgresql
from sqlalchemy.event import listens_for
from sqlalchemy.ext.mutable import Mutable
from sqlalchemy.inspection import inspect
from sqlalchemy.orm import backref, joinedload, object_session, subqueryload
from sqlalchemy.orm.exc import NoResultFound # noqa: F401
from sqlalchemy.types import TypeDecorator
db = SQLAlchemy(session_options={
'expire_on_commit': False
})
Column = functools.partial(db.Column, nullable=False)
class ScheduledQueriesExecutions(object):
KEY_NAME = 'sq:executed_at'
def __init__(self):
self.executions = {}
def refresh(self):
self.executions = redis_connection.hgetall(self.KEY_NAME)
def update(self, query_id):
redis_connection.hmset(self.KEY_NAME, {
query_id: time.time()
})
def get(self, query_id):
timestamp = self.executions.get(str(query_id))
if timestamp:
timestamp = utils.dt_from_timestamp(timestamp)
return timestamp
scheduled_queries_executions = ScheduledQueriesExecutions()
# AccessPermission and Change use a 'generic foreign key' approach to refer to
# either queries or dashboards.
# TODO replace this with association tables.
_gfk_types = {}
class GFKBase(object):
"""
Compatibility with 'generic foreign key' approach Peewee used.
"""
# XXX Replace this with table-per-association.
object_type = Column(db.String(255))
object_id = Column(db.Integer)
_object = None
@property
def object(self):
session = object_session(self)
if self._object or not session:
return self._object
else:
object_class = _gfk_types[self.object_type]
self._object = session.query(object_class).filter(
object_class.id == self.object_id).first()
return self._object
@object.setter
def object(self, value):
self._object = value
self.object_type = value.__class__.__tablename__
self.object_id = value.id
# XXX replace PseudoJSON and MutableDict with real JSON field
class PseudoJSON(TypeDecorator):
impl = db.Text
def process_bind_param(self, value, dialect):
return json_dumps(value)
def process_result_value(self, value, dialect):
if not value:
return value
return json.loads(value)
class MutableDict(Mutable, dict):
@classmethod
def coerce(cls, key, value):
"Convert plain dictionaries to MutableDict."
if not isinstance(value, MutableDict):
if isinstance(value, dict):
return MutableDict(value)
# this call will raise ValueError
return Mutable.coerce(key, value)
else:
return value
def __setitem__(self, key, value):
"Detect dictionary set events and emit change events."
dict.__setitem__(self, key, value)
self.changed()
def __delitem__(self, key):
"Detect dictionary del events and emit change events."
dict.__delitem__(self, key)
self.changed()
class MutableList(Mutable, list):
def append(self, value):
list.append(self, value)
self.changed()
def remove(self, value):
list.remove(self, value)
self.changed()
@classmethod
def coerce(cls, key, value):
if not isinstance(value, MutableList):
if isinstance(value, list):
return MutableList(value)
return Mutable.coerce(key, value)
else:
return value
class TimestampMixin(object):
updated_at = Column(db.DateTime(True), default=db.func.now(),
onupdate=db.func.now(), nullable=False)
created_at = Column(db.DateTime(True), default=db.func.now(),
nullable=False)
class ChangeTrackingMixin(object):
skipped_fields = ('id', 'created_at', 'updated_at', 'version')
_clean_values = None
def __init__(self, *a, **kw):
super(ChangeTrackingMixin, self).__init__(*a, **kw)
self.record_changes(self.user)
def prep_cleanvalues(self):
self.__dict__['_clean_values'] = {}
for attr in inspect(self.__class__).column_attrs:
col, = attr.columns
# 'query' is col name but not attr name
self._clean_values[col.name] = None
def __setattr__(self, key, value):
if self._clean_values is None:
self.prep_cleanvalues()
for attr in inspect(self.__class__).column_attrs:
col, = attr.columns
previous = getattr(self, attr.key, None)
self._clean_values[col.name] = previous
super(ChangeTrackingMixin, self).__setattr__(key, value)
def record_changes(self, changed_by):
db.session.add(self)
db.session.flush()
changes = {}
for attr in inspect(self.__class__).column_attrs:
col, = attr.columns
if attr.key not in self.skipped_fields:
changes[col.name] = {'previous': self._clean_values[col.name],
'current': getattr(self, attr.key)}
db.session.add(Change(object=self,
object_version=self.version,
user=changed_by,
change=changes))
class BelongsToOrgMixin(object):
@classmethod
def get_by_id_and_org(cls, object_id, org):
return db.session.query(cls).filter(cls.id == object_id, cls.org == org).one()
class PermissionsCheckMixin(object):
def has_permission(self, permission):
return self.has_permissions((permission,))
def has_permissions(self, permissions):
has_permissions = reduce(lambda a, b: a and b,
map(lambda permission: permission in self.permissions,
permissions),
True)
return has_permissions
class AnonymousUser(AnonymousUserMixin, PermissionsCheckMixin):
@property
def permissions(self):
return []
def is_api_user(self):
return False
class ApiUser(UserMixin, PermissionsCheckMixin):
def __init__(self, api_key, org, groups, name=None):
self.object = None
if isinstance(api_key, basestring):
self.id = api_key
self.name = name
else:
self.id = api_key.api_key
self.name = "ApiKey: {}".format(api_key.id)
self.object = api_key.object
self.group_ids = groups
self.org = org
def __repr__(self):
return u"<{}>".format(self.name)
def is_api_user(self):
return True
@property
def permissions(self):
return ['view_query']
def has_access(self, obj, access_type):
return False
class Organization(TimestampMixin, db.Model):
SETTING_GOOGLE_APPS_DOMAINS = 'google_apps_domains'
SETTING_IS_PUBLIC = "is_public"
id = Column(db.Integer, primary_key=True)
name = Column(db.String(255))
slug = Column(db.String(255), unique=True)
settings = Column(MutableDict.as_mutable(PseudoJSON))
groups = db.relationship("Group", lazy="dynamic")
__tablename__ = 'organizations'
def __repr__(self):
return u"<Organization: {}, {}>".format(self.id, self.name)
def __unicode__(self):
return u'%s (%s)' % (self.name, self.id)
@classmethod
def get_by_slug(cls, slug):
return cls.query.filter(cls.slug == slug).first()
@property
def default_group(self):
return self.groups.filter(Group.name == 'default', Group.type == Group.BUILTIN_GROUP).first()
@property
def google_apps_domains(self):
return self.settings.get(self.SETTING_GOOGLE_APPS_DOMAINS, [])
@property
def is_public(self):
return self.settings.get(self.SETTING_IS_PUBLIC, False)
@property
def admin_group(self):
return self.groups.filter(Group.name == 'admin', Group.type == Group.BUILTIN_GROUP).first()
def has_user(self, email):
return self.users.filter(User.email == email).count() == 1
class Group(db.Model, BelongsToOrgMixin):
DEFAULT_PERMISSIONS = ['create_dashboard', 'create_query', 'edit_dashboard', 'edit_query',
'view_query', 'view_source', 'execute_query', 'list_users', 'schedule_query',
'list_dashboards', 'list_alerts', 'list_data_sources']
BUILTIN_GROUP = 'builtin'
REGULAR_GROUP = 'regular'
id = Column(db.Integer, primary_key=True)
data_sources = db.relationship("DataSourceGroup", back_populates="group",
cascade="all")
org_id = Column(db.Integer, db.ForeignKey('organizations.id'))
org = db.relationship(Organization, back_populates="groups")
type = Column(db.String(255), default=REGULAR_GROUP)
name = Column(db.String(100))
permissions = Column(postgresql.ARRAY(db.String(255)),
default=DEFAULT_PERMISSIONS)
created_at = Column(db.DateTime(True), default=db.func.now())
__tablename__ = 'groups'
def to_dict(self):
return {
'id': self.id,
'name': self.name,
'permissions': self.permissions,
'type': self.type,
'created_at': self.created_at
}
@classmethod
def all(cls, org):
return cls.query.filter(cls.org == org)
@classmethod
def members(cls, group_id):
return User.query.filter(User.group_ids.any(group_id))
@classmethod
def find_by_name(cls, org, group_names):
result = cls.query.filter(cls.org == org, cls.name.in_(group_names))
return list(result)
def __unicode__(self):
return unicode(self.id)
class User(TimestampMixin, db.Model, BelongsToOrgMixin, UserMixin, PermissionsCheckMixin):
id = Column(db.Integer, primary_key=True)
org_id = Column(db.Integer, db.ForeignKey('organizations.id'))
org = db.relationship(Organization, backref=db.backref("users", lazy="dynamic"))
name = Column(db.String(320))
email = Column(db.String(320))
password_hash = Column(db.String(128), nullable=True)
# XXX replace with association table
group_ids = Column('groups', MutableList.as_mutable(postgresql.ARRAY(db.Integer)), nullable=True)
api_key = Column(db.String(40),
default=lambda: generate_token(40),
unique=True)
__tablename__ = 'users'
__table_args__ = (db.Index('users_org_id_email', 'org_id', 'email', unique=True),)
def __init__(self, *args, **kwargs):
super(User, self).__init__(*args, **kwargs)
def to_dict(self, with_api_key=False):
d = {
'id': self.id,
'name': self.name,
'email': self.email,
'gravatar_url': self.gravatar_url,
'groups': self.group_ids,
'updated_at': self.updated_at,
'created_at': self.created_at
}
if self.password_hash is None:
d['auth_type'] = 'external'
else:
d['auth_type'] = 'password'
if with_api_key:
d['api_key'] = self.api_key
return d
def is_api_user(self):
return False
@property
def gravatar_url(self):
email_md5 = hashlib.md5(self.email.lower()).hexdigest()
return "https://www.gravatar.com/avatar/%s?s=40" % email_md5
@property
def permissions(self):
# TODO: this should be cached.
return list(itertools.chain(*[g.permissions for g in
Group.query.filter(Group.id.in_(self.group_ids))]))
@classmethod
def get_by_email_and_org(cls, email, org):
return cls.query.filter(cls.email == email, cls.org == org).one()
@classmethod
def get_by_api_key_and_org(cls, api_key, org):
return cls.query.filter(cls.api_key == api_key, cls.org == org).one()
@classmethod
def all(cls, org):
return cls.query.filter(cls.org == org)
@classmethod
def find_by_email(cls, email):
return cls.query.filter(cls.email == email)
def __unicode__(self):
return u'%s (%s)' % (self.name, self.email)
def hash_password(self, password):
self.password_hash = pwd_context.encrypt(password)
def verify_password(self, password):
return self.password_hash and pwd_context.verify(password, self.password_hash)
def update_group_assignments(self, group_names):
groups = Group.find_by_name(self.org, group_names)
groups.append(self.org.default_group)
self.group_ids = [g.id for g in groups]
db.session.add(self)
def has_access(self, obj, access_type):
return AccessPermission.exists(obj, access_type, grantee=self)
class Configuration(TypeDecorator):
impl = db.Text
def process_bind_param(self, value, dialect):
return value.to_json()
def process_result_value(self, value, dialect):
return ConfigurationContainer.from_json(value)
class DataSource(BelongsToOrgMixin, db.Model):
id = Column(db.Integer, primary_key=True)
org_id = Column(db.Integer, db.ForeignKey('organizations.id'))
org = db.relationship(Organization, backref="data_sources")
name = Column(db.String(255))
type = Column(db.String(255))
options = Column(ConfigurationContainer.as_mutable(Configuration))
queue_name = Column(db.String(255), default="queries")
scheduled_queue_name = Column(db.String(255), default="scheduled_queries")
created_at = Column(db.DateTime(True), default=db.func.now())
data_source_groups = db.relationship("DataSourceGroup", back_populates="data_source",
cascade="all")
__tablename__ = 'data_sources'
__table_args__ = (db.Index('data_sources_org_id_name', 'org_id', 'name'),)
def __eq__(self, other):
return self.id == other.id
def to_dict(self, all=False, with_permissions_for=None):
d = {
'id': self.id,
'name': self.name,
'type': self.type,
'syntax': self.query_runner.syntax,
'paused': self.paused,
'pause_reason': self.pause_reason
}
if all:
schema = get_configuration_schema_for_query_runner_type(self.type)
self.options.set_schema(schema)
d['options'] = self.options.to_dict(mask_secrets=True)
d['queue_name'] = self.queue_name
d['scheduled_queue_name'] = self.scheduled_queue_name
d['groups'] = self.groups
if with_permissions_for is not None:
d['view_only'] = db.session.query(DataSourceGroup.view_only).filter(
DataSourceGroup.group == with_permissions_for,
DataSourceGroup.data_source == self).one()[0]
return d
def __unicode__(self):
return self.name
@classmethod
def create_with_group(cls, *args, **kwargs):
data_source = cls(*args, **kwargs)
data_source_group = DataSourceGroup(
data_source=data_source,
group=data_source.org.default_group)
db.session.add_all([data_source, data_source_group])
return data_source
@classmethod
def all(cls, org, group_ids=None):
data_sources = cls.query.filter(cls.org == org).order_by(cls.id.asc())
if group_ids:
data_sources = data_sources.join(DataSourceGroup).filter(
DataSourceGroup.group_id.in_(group_ids))
return data_sources
@classmethod
def get_by_id(cls, _id):
return cls.query.filter(cls.id == _id).one()
def delete(self):
Query.query.filter(Query.data_source == self).update(dict(data_source_id=None, latest_query_data_id=None))
QueryResult.query.filter(QueryResult.data_source == self).delete()
res = db.session.delete(self)
db.session.commit()
return res
def get_schema(self, refresh=False):
key = "data_source:schema:{}".format(self.id)
cache = None
if not refresh:
cache = redis_connection.get(key)
if cache is None:
query_runner = self.query_runner
schema = sorted(query_runner.get_schema(get_stats=refresh), key=lambda t: t['name'])
redis_connection.set(key, json.dumps(schema))
else:
schema = json.loads(cache)
return schema
def _pause_key(self):
return 'ds:{}:pause'.format(self.id)
@property
def paused(self):
return redis_connection.exists(self._pause_key())
@property
def pause_reason(self):
return redis_connection.get(self._pause_key())
def pause(self, reason=None):
redis_connection.set(self._pause_key(), reason)
def resume(self):
redis_connection.delete(self._pause_key())
def add_group(self, group, view_only=False):
dsg = DataSourceGroup(group=group, data_source=self, view_only=view_only)
db.session.add(dsg)
return dsg
def remove_group(self, group):
db.session.query(DataSourceGroup).filter(
DataSourceGroup.group == group,
DataSourceGroup.data_source == self).delete()
db.session.commit()
def update_group_permission(self, group, view_only):
dsg = DataSourceGroup.query.filter(
DataSourceGroup.group == group,
DataSourceGroup.data_source == self).one()
dsg.view_only = view_only
db.session.add(dsg)
return dsg
@property
def query_runner(self):
return get_query_runner(self.type, self.options)
@classmethod
def get_by_name(cls, name):
return cls.query.filter(cls.name == name).one()
# XXX examine call sites to see if a regular SQLA collection would work better
@property
def groups(self):
groups = db.session.query(DataSourceGroup).filter(
DataSourceGroup.data_source == self)
return dict(map(lambda g: (g.group_id, g.view_only), groups))
class DataSourceGroup(db.Model):
# XXX drop id, use datasource/group as PK
id = Column(db.Integer, primary_key=True)
data_source_id = Column(db.Integer, db.ForeignKey("data_sources.id"))
data_source = db.relationship(DataSource, back_populates="data_source_groups")
group_id = Column(db.Integer, db.ForeignKey("groups.id"))
group = db.relationship(Group, back_populates="data_sources")
view_only = Column(db.Boolean, default=False)
__tablename__ = "data_source_groups"
class QueryResult(db.Model, BelongsToOrgMixin):
id = Column(db.Integer, primary_key=True)
org_id = Column(db.Integer, db.ForeignKey('organizations.id'))
org = db.relationship(Organization)
data_source_id = Column(db.Integer, db.ForeignKey("data_sources.id"))
data_source = db.relationship(DataSource, backref=backref('query_results'))
query_hash = Column(db.String(32), index=True)
query_text = Column('query', db.Text)
data = Column(db.Text)
runtime = Column(postgresql.DOUBLE_PRECISION)
retrieved_at = Column(db.DateTime(True))
__tablename__ = 'query_results'
def to_dict(self):
return {
'id': self.id,
'query_hash': self.query_hash,
'query': self.query_text,
'data': json.loads(self.data),
'data_source_id': self.data_source_id,
'runtime': self.runtime,
'retrieved_at': self.retrieved_at
}
@classmethod
def unused(cls, days=7):
age_threshold = datetime.datetime.now() - datetime.timedelta(days=days)
unused_results = (db.session.query(QueryResult.id).filter(
Query.id == None, QueryResult.retrieved_at < age_threshold)
.outerjoin(Query))
return unused_results
@classmethod
def get_latest(cls, data_source, query, max_age=0):
query_hash = utils.gen_query_hash(query)
if max_age == -1:
q = db.session.query(QueryResult).filter(
cls.query_hash == query_hash,
cls.data_source == data_source).order_by(
QueryResult.retrieved_at.desc())
else:
q = db.session.query(QueryResult).filter(
QueryResult.query_hash == query_hash,
QueryResult.data_source == data_source,
db.func.timezone('utc', QueryResult.retrieved_at) +
datetime.timedelta(seconds=max_age) >=
db.func.timezone('utc', db.func.now())
).order_by(QueryResult.retrieved_at.desc())
return q.first()
@classmethod
def store_result(cls, org, data_source, query_hash, query, data, run_time, retrieved_at):
query_result = cls(org=org,
query_hash=query_hash,
query_text=query,
runtime=run_time,
data_source=data_source,
retrieved_at=retrieved_at,
data=data)
db.session.add(query_result)
logging.info("Inserted query (%s) data; id=%s", query_hash, query_result.id)
# TODO: Investigate how big an impact this select-before-update makes.
queries = db.session.query(Query).filter(
Query.query_hash == query_hash,
Query.data_source == data_source)
for q in queries:
q.latest_query_data = query_result
db.session.add(q)
query_ids = [q.id for q in queries]
logging.info("Updated %s queries with result (%s).", len(query_ids), query_hash)
return query_result, query_ids
def __unicode__(self):
return u"%d | %s | %s" % (self.id, self.query_hash, self.retrieved_at)
@property
def groups(self):
return self.data_source.groups
def make_csv_content(self):
s = cStringIO.StringIO()
query_data = json.loads(self.data)
writer = csv.DictWriter(s, extrasaction="ignore", fieldnames=[col['name'] for col in query_data['columns']])
writer.writer = utils.UnicodeWriter(s)
writer.writeheader()
for row in query_data['rows']:
writer.writerow(row)
return s.getvalue()
def make_excel_content(self):
s = cStringIO.StringIO()
query_data = json.loads(self.data)
book = xlsxwriter.Workbook(s)
sheet = book.add_worksheet("result")
column_names = []
for (c, col) in enumerate(query_data['columns']):
sheet.write(0, c, col['name'])
column_names.append(col['name'])
for (r, row) in enumerate(query_data['rows']):
for (c, name) in enumerate(column_names):
sheet.write(r + 1, c, row.get(name))
book.close()
return s.getvalue()
def should_schedule_next(previous_iteration, now, schedule, failures):
if schedule.isdigit():
ttl = int(schedule)
next_iteration = previous_iteration + datetime.timedelta(seconds=ttl)
else:
hour, minute = schedule.split(':')
hour, minute = int(hour), int(minute)
# The following logic is needed for cases like the following:
# - The query scheduled to run at 23:59.
# - The scheduler wakes up at 00:01.
# - Using naive implementation of comparing timestamps, it will skip the execution.
normalized_previous_iteration = previous_iteration.replace(hour=hour, minute=minute)
if normalized_previous_iteration > previous_iteration:
previous_iteration = normalized_previous_iteration - datetime.timedelta(days=1)
next_iteration = (previous_iteration + datetime.timedelta(days=1)).replace(hour=hour, minute=minute)
if failures:
next_iteration += datetime.timedelta(minutes=2**failures)
return now > next_iteration
class Query(ChangeTrackingMixin, TimestampMixin, BelongsToOrgMixin, db.Model):
id = Column(db.Integer, primary_key=True)
version = Column(db.Integer, default=1)
org_id = Column(db.Integer, db.ForeignKey('organizations.id'))
org = db.relationship(Organization, backref="queries")
data_source_id = Column(db.Integer, db.ForeignKey("data_sources.id"), nullable=True)
data_source = db.relationship(DataSource, backref='queries')
latest_query_data_id = Column(db.Integer, db.ForeignKey("query_results.id"), nullable=True)
latest_query_data = db.relationship(QueryResult)
name = Column(db.String(255))
description = Column(db.String(4096), nullable=True)
query_text = Column("query", db.Text)
query_hash = Column(db.String(32))
api_key = Column(db.String(40), default=lambda: generate_token(40))
user_id = Column(db.Integer, db.ForeignKey("users.id"))
user = db.relationship(User, foreign_keys=[user_id])
last_modified_by_id = Column(db.Integer, db.ForeignKey('users.id'), nullable=True)
last_modified_by = db.relationship(User, backref="modified_queries",
foreign_keys=[last_modified_by_id])
is_archived = Column(db.Boolean, default=False, index=True)
is_draft = Column(db.Boolean, default=True, index=True)
schedule = Column(db.String(10), nullable=True)
schedule_failures = Column(db.Integer, default=0)
visualizations = db.relationship("Visualization", cascade="all, delete-orphan")
options = Column(MutableDict.as_mutable(PseudoJSON), default={})
__tablename__ = 'queries'
__mapper_args__ = {
"version_id_col": version,
'version_id_generator': False
}
def to_dict(self, with_stats=False, with_visualizations=False, with_user=True, with_last_modified_by=True):
d = {
'id': self.id,
'latest_query_data_id': self.latest_query_data_id,
'name': self.name,
'description': self.description,
'query': self.query_text,
'query_hash': self.query_hash,
'schedule': self.schedule,
'api_key': self.api_key,
'is_archived': self.is_archived,
'is_draft': self.is_draft,
'updated_at': self.updated_at,
'created_at': self.created_at,
'data_source_id': self.data_source_id,
'options': self.options,
'version': self.version
}
if with_user:
d['user'] = self.user.to_dict()
else:
d['user_id'] = self.user_id
if with_last_modified_by:
d['last_modified_by'] = self.last_modified_by.to_dict() if self.last_modified_by is not None else None
else:
d['last_modified_by_id'] = self.last_modified_by_id
if with_stats:
if self.latest_query_data is not None:
d['retrieved_at'] = self.retrieved_at
d['runtime'] = self.runtime
else:
d['retrieved_at'] = None
d['runtime'] = None
if with_visualizations:
d['visualizations'] = [vis.to_dict(with_query=False)
for vis in self.visualizations]
return d
def archive(self, user=None):
db.session.add(self)
self.is_archived = True
self.schedule = None
for vis in self.visualizations:
for w in vis.widgets:
db.session.delete(w)
for a in self.alerts:
db.session.delete(a)
if user:
self.record_changes(user)
@classmethod
def create(cls, **kwargs):
query = cls(**kwargs)
db.session.add(Visualization(query_rel=query,
name="Table",
description='',
type="TABLE",
options="{}"))
return query
@classmethod
def all_queries(cls, group_ids, user_id=None, drafts=False):
q = (cls.query
.options(joinedload(Query.user),
joinedload(Query.latest_query_data).load_only('runtime', 'retrieved_at'))
.join(DataSourceGroup, Query.data_source_id == DataSourceGroup.data_source_id)
.filter(Query.is_archived == False)
.filter(DataSourceGroup.group_id.in_(group_ids))
.order_by(Query.created_at.desc()))
if not drafts:
q = q.filter(or_(Query.is_draft == False, Query.user_id == user_id))
return q
@classmethod
def by_user(cls, user):
return cls.all_queries(user.group_ids, user.id).filter(Query.user == user)
@classmethod
def outdated_queries(cls):
queries = (db.session.query(Query)
.options(joinedload(Query.latest_query_data).load_only('retrieved_at'))
.filter(Query.schedule != None)
.order_by(Query.id))
now = utils.utcnow()
outdated_queries = {}
scheduled_queries_executions.refresh()
for query in queries:
if query.latest_query_data:
retrieved_at = query.latest_query_data.retrieved_at
else:
retrieved_at = now
retrieved_at = scheduled_queries_executions.get(query.id) or retrieved_at
if should_schedule_next(retrieved_at, now, query.schedule, query.schedule_failures):
key = "{}:{}".format(query.query_hash, query.data_source_id)
outdated_queries[key] = query
return outdated_queries.values()
@classmethod
def search(cls, term, group_ids, include_drafts=False):
# TODO: This is very naive implementation of search, to be replaced with PostgreSQL full-text-search solution.
where = (Query.name.ilike(u"%{}%".format(term)) |
Query.description.ilike(u"%{}%".format(term)))
if term.isdigit():
where |= Query.id == term
where &= Query.is_archived == False
if not include_drafts:
where &= Query.is_draft == False
where &= DataSourceGroup.group_id.in_(group_ids)
query_ids = (
db.session.query(Query.id).join(
DataSourceGroup,
Query.data_source_id == DataSourceGroup.data_source_id)
.filter(where)).distinct()
return Query.query.options(joinedload(Query.user)).filter(Query.id.in_(query_ids))
@classmethod
def recent(cls, group_ids, user_id=None, limit=20):
query = (cls.query.options(subqueryload(Query.user))
.filter(Event.created_at > (db.func.current_date() - 7))
.join(Event, Query.id == Event.object_id.cast(db.Integer))
.join(DataSourceGroup, Query.data_source_id == DataSourceGroup.data_source_id)
.filter(
Event.action.in_(['edit', 'execute', 'edit_name',
'edit_description', 'view_source']),
Event.object_id != None,
Event.object_type == 'query',
DataSourceGroup.group_id.in_(group_ids),
or_(Query.is_draft == False, Query.user_id == user_id),
Query.is_archived == False)
.group_by(Event.object_id, Query.id)
.order_by(db.desc(db.func.count(0))))
if user_id:
query = query.filter(Event.user_id == user_id)
query = query.limit(limit)
return query
@classmethod
def get_by_id(cls, _id):
return cls.query.filter(cls.id == _id).one()
def fork(self, user):
forked_list = ['org', 'data_source', 'latest_query_data', 'description',
'query_text', 'query_hash']
kwargs = {a: getattr(self, a) for a in forked_list}
forked_query = Query.create(name=u'Copy of (#{}) {}'.format(self.id, self.name),
user=user, **kwargs)
for v in self.visualizations:
if v.type == 'TABLE':
continue
forked_v = v.to_dict()
forked_v['options'] = v.options
forked_v['query_rel'] = forked_query
forked_v.pop('id')
forked_query.visualizations.append(Visualization(**forked_v))
db.session.add(forked_query)
return forked_query
@property
def runtime(self):
return self.latest_query_data.runtime
@property
def retrieved_at(self):
return self.latest_query_data.retrieved_at
@property
def groups(self):
if self.data_source is None:
return {}
return self.data_source.groups
def __unicode__(self):
return unicode(self.id)
@listens_for(Query.query_text, 'set')
def gen_query_hash(target, val, oldval, initiator):
target.query_hash = utils.gen_query_hash(val)
target.schedule_failures = 0
@listens_for(Query.user_id, 'set')
def query_last_modified_by(target, val, oldval, initiator):
target.last_modified_by_id = val
class AccessPermission(GFKBase, db.Model):
id = Column(db.Integer, primary_key=True)
# 'object' defined in GFKBase
access_type = Column(db.String(255))
grantor_id = Column(db.Integer, db.ForeignKey("users.id"))
grantor = db.relationship(User, backref='grantor', foreign_keys=[grantor_id])
grantee_id = Column(db.Integer, db.ForeignKey("users.id"))
grantee = db.relationship(User, backref='grantee', foreign_keys=[grantee_id])
__tablename__ = 'access_permissions'
@classmethod
def grant(cls, obj, access_type, grantee, grantor):
grant = cls.query.filter(cls.object_type == obj.__tablename__,
cls.object_id == obj.id,
cls.access_type == access_type,
cls.grantee == grantee,
cls.grantor == grantor).one_or_none()
if not grant:
grant = cls(object_type=obj.__tablename__,
object_id=obj.id,
access_type=access_type,
grantee=grantee,
grantor=grantor)
db.session.add(grant)
return grant
@classmethod
def revoke(cls, obj, grantee, access_type=None):
permissions = cls._query(obj, access_type, grantee)
return permissions.delete()
@classmethod
def find(cls, obj, access_type=None, grantee=None, grantor=None):
return cls._query(obj, access_type, grantee, grantor)
@classmethod
def exists(cls, obj, access_type, grantee):
return cls.find(obj, access_type, grantee).count() > 0
@classmethod
def _query(cls, obj, access_type=None, grantee=None, grantor=None):
q = cls.query.filter(cls.object_id == obj.id,
cls.object_type == obj.__tablename__)
if access_type:
q.filter(AccessPermission.access_type == access_type)
if grantee:
q.filter(AccessPermission.grantee == grantee)
if grantor:
q.filter(AccessPermission.grantor == grantor)
return q
def to_dict(self):
d = {
'id': self.id,
'object_id': self.object_id,
'object_type': self.object_type,
'access_type': self.access_type,
'grantor': self.grantor_id,
'grantee': self.grantee_id
}
return d
class Change(GFKBase, db.Model):
id = Column(db.Integer, primary_key=True)
# 'object' defined in GFKBase
object_version = Column(db.Integer, default=0)
user_id = Column(db.Integer, db.ForeignKey("users.id"))
user = db.relationship(User, backref='changes')
change = Column(PseudoJSON)
created_at = Column(db.DateTime(True), default=db.func.now())
__tablename__ = 'changes'
def to_dict(self, full=True):
d = {
'id': self.id,
'object_id': self.object_id,
'object_type': self.object_type,
'change_type': self.change_type,
'object_version': self.object_version,
'change': self.change,
'created_at': self.created_at
}
if full:
d['user'] = self.user.to_dict()
else:
d['user_id'] = self.user_id
return d
@classmethod
def last_change(cls, obj):
return db.session.query(cls).filter(
cls.object_id == obj.id,
cls.object_type == obj.__class__.__tablename__).order_by(
cls.object_version.desc()).first()
class Alert(TimestampMixin, db.Model):
UNKNOWN_STATE = 'unknown'
OK_STATE = 'ok'
TRIGGERED_STATE = 'triggered'
id = Column(db.Integer, primary_key=True)
name = Column(db.String(255))
query_id = Column(db.Integer, db.ForeignKey("queries.id"))
query_rel = db.relationship(Query, backref=backref('alerts', cascade="all"))
user_id = Column(db.Integer, db.ForeignKey("users.id"))
user = db.relationship(User, backref='alerts')
options = Column(MutableDict.as_mutable(PseudoJSON))
state = Column(db.String(255), default=UNKNOWN_STATE)
subscriptions = db.relationship("AlertSubscription", cascade="all, delete-orphan")
last_triggered_at = Column(db.DateTime(True), nullable=True)
rearm = Column(db.Integer, nullable=True)
__tablename__ = 'alerts'
@classmethod
def all(cls, group_ids):
return db.session.query(Alert)\
.options(joinedload(Alert.user), joinedload(Alert.query_rel))\
.join(Query)\
.join(DataSourceGroup, DataSourceGroup.data_source_id == Query.data_source_id)\
.filter(DataSourceGroup.group_id.in_(group_ids))
@classmethod
def get_by_id_and_org(cls, id, org):
return db.session.query(Alert).join(Query).filter(Alert.id == id, Query.org == org).one()
def to_dict(self, full=True):
d = {
'id': self.id,
'name': self.name,
'options': self.options,
'state': self.state,
'last_triggered_at': self.last_triggered_at,
'updated_at': self.updated_at,
'created_at': self.created_at,
'rearm': self.rearm
}
if full:
d['query'] = self.query_rel.to_dict()
d['user'] = self.user.to_dict()
else:
d['query_id'] = self.query_id
d['user_id'] = self.user_id
return d
def evaluate(self):
data = json.loads(self.query_rel.latest_query_data.data)
# todo: safe guard for empty
value = data['rows'][0][self.options['column']]
op = self.options['op']
if op == 'greater than' and value > self.options['value']:
new_state = self.TRIGGERED_STATE
elif op == 'less than' and value < self.options['value']:
new_state = self.TRIGGERED_STATE
elif op == 'equals' and value == self.options['value']:
new_state = self.TRIGGERED_STATE
else:
new_state = self.OK_STATE
return new_state
def subscribers(self):
return User.query.join(AlertSubscription).filter(AlertSubscription.alert == self)
@property
def groups(self):
return self.query_rel.groups
def generate_slug(ctx):
slug = utils.slugify(ctx.current_parameters['name'])
tries = 1
while Dashboard.query.filter(Dashboard.slug == slug).first() is not None:
slug = utils.slugify(ctx.current_parameters['name']) + "_" + str(tries)
tries += 1
return slug
class Dashboard(ChangeTrackingMixin, TimestampMixin, BelongsToOrgMixin, db.Model):
id = Column(db.Integer, primary_key=True)
version = Column(db.Integer)
org_id = Column(db.Integer, db.ForeignKey("organizations.id"))
org = db.relationship(Organization, backref="dashboards")
slug = Column(db.String(140), index=True, default=generate_slug)
name = Column(db.String(100))
user_id = Column(db.Integer, db.ForeignKey("users.id"))
user = db.relationship(User)
# TODO: The layout should dynamically be built from position and size information on each widget.
# Will require update in the frontend code to support this.
layout = Column(db.Text)
dashboard_filters_enabled = Column(db.Boolean, default=False)
is_archived = Column(db.Boolean, default=False, index=True)
is_draft = Column(db.Boolean, default=True, index=True)
widgets = db.relationship('Widget', backref='dashboard', lazy='dynamic')
__tablename__ = 'dashboards'
__mapper_args__ = {
"version_id_col": version
}
def to_dict(self, with_widgets=False, user=None):
layout = json.loads(self.layout)
if with_widgets:
widget_list = Widget.query.filter(Widget.dashboard == self)
widgets = {}
for w in widget_list:
if w.visualization_id is None:
widgets[w.id] = w.to_dict()
elif user and has_access(w.visualization.query_rel.groups, user, view_only):
widgets[w.id] = w.to_dict()
else:
widgets[w.id] = project(w.to_dict(),
('id', 'width', 'dashboard_id', 'options', 'created_at', 'updated_at'))
widgets[w.id]['restricted'] = True
# The following is a workaround for cases when the widget object gets deleted without the dashboard layout
# updated. This happens for users with old databases that didn't have a foreign key relationship between
# visualizations and widgets.
# It's temporary until better solution is implemented (we probably should move the position information
# to the widget).
widgets_layout = []
for row in layout:
if not row:
continue
new_row = []
for widget_id in row:
widget = widgets.get(widget_id, None)
if widget:
new_row.append(widget)
widgets_layout.append(new_row)
else:
widgets_layout = None
return {
'id': self.id,
'slug': self.slug,
'name': self.name,
'user_id': self.user_id,
'layout': layout,
'dashboard_filters_enabled': self.dashboard_filters_enabled,
'widgets': widgets_layout,
'is_archived': self.is_archived,
'is_draft': self.is_draft,
'updated_at': self.updated_at,
'created_at': self.created_at,
'version': self.version
}
@classmethod
def all(cls, org, group_ids, user_id):
query = (
Dashboard.query
.outerjoin(Widget)
.outerjoin(Visualization)
.outerjoin(Query)
.outerjoin(DataSourceGroup, Query.data_source_id == DataSourceGroup.data_source_id)
.filter(
Dashboard.is_archived == False,
(DataSourceGroup.group_id.in_(group_ids) |
(Dashboard.user_id == user_id) |
((Widget.dashboard != None) & (Widget.visualization == None))),
Dashboard.org == org)
.group_by(Dashboard.id))
query = query.filter(or_(Dashboard.user_id == user_id, Dashboard.is_draft == False))
return query
@classmethod
def recent(cls, org, group_ids, user_id, for_user=False, limit=20):
query = (Dashboard.query
.outerjoin(Event, Dashboard.id == Event.object_id.cast(db.Integer))
.outerjoin(Widget)
.outerjoin(Visualization)
.outerjoin(Query)
.outerjoin(DataSourceGroup, Query.data_source_id == DataSourceGroup.data_source_id)
.filter(
Event.created_at > (db.func.current_date() - 7),
Event.action.in_(['edit', 'view']),
Event.object_id != None,
Event.object_type == 'dashboard',
Dashboard.org == org,
Dashboard.is_archived == False,
or_(Dashboard.is_draft == False, Dashboard.user_id == user_id),
DataSourceGroup.group_id.in_(group_ids) |
(Dashboard.user_id == user_id) |
((Widget.dashboard != None) & (Widget.visualization == None)))
.group_by(Event.object_id, Dashboard.id)
.order_by(db.desc(db.func.count(0))))
if for_user:
query = query.filter(Event.user_id == user_id)
query = query.limit(limit)
return query
@classmethod
def get_by_slug_and_org(cls, slug, org):
return cls.query.filter(cls.slug == slug, cls.org == org).one()
def __unicode__(self):
return u"%s=%s" % (self.id, self.name)
class Visualization(TimestampMixin, db.Model):
id = Column(db.Integer, primary_key=True)
type = Column(db.String(100))
query_id = Column(db.Integer, db.ForeignKey("queries.id"))
# query_rel and not query, because db.Model already has query defined.
query_rel = db.relationship(Query, back_populates='visualizations')
name = Column(db.String(255))
description = Column(db.String(4096), nullable=True)
options = Column(db.Text)
__tablename__ = 'visualizations'
def to_dict(self, with_query=True):
d = {
'id': self.id,
'type': self.type,
'name': self.name,
'description': self.description,
'options': json.loads(self.options),
'updated_at': self.updated_at,
'created_at': self.created_at
}
if with_query:
d['query'] = self.query_rel.to_dict()
return d
@classmethod
def get_by_id_and_org(cls, visualization_id, org):
return db.session.query(Visualization).join(Query).filter(
cls.id == visualization_id,
Query.org == org).one()
def __unicode__(self):
return u"%s %s" % (self.id, self.type)
class Widget(TimestampMixin, db.Model):
id = Column(db.Integer, primary_key=True)
visualization_id = Column(db.Integer, db.ForeignKey('visualizations.id'), nullable=True)
visualization = db.relationship(Visualization, backref='widgets')
text = Column(db.Text, nullable=True)
width = Column(db.Integer)
options = Column(db.Text)
dashboard_id = Column(db.Integer, db.ForeignKey("dashboards.id"), index=True)
# unused; kept for backward compatability:
type = Column(db.String(100), nullable=True)
query_id = Column(db.Integer, nullable=True)
__tablename__ = 'widgets'
def to_dict(self):
d = {
'id': self.id,
'width': self.width,
'options': json.loads(self.options),
'dashboard_id': self.dashboard_id,
'text': self.text,
'updated_at': self.updated_at,
'created_at': self.created_at
}
if self.visualization and self.visualization.id:
d['visualization'] = self.visualization.to_dict()
return d
def delete(self):
layout = json.loads(self.dashboard.layout)
layout = map(lambda row: filter(lambda w: w != self.id, row), layout)
layout = filter(lambda row: len(row) > 0, layout)
self.dashboard.layout = json.dumps(layout)
db.session.add(self.dashboard)
db.session.delete(self)
def __unicode__(self):
return u"%s" % self.id
@classmethod
def get_by_id_and_org(cls, widget_id, org):
return db.session.query(cls).join(Dashboard).filter(cls.id == widget_id, Dashboard.org == org).one()
class Event(db.Model):
id = Column(db.Integer, primary_key=True)
org_id = Column(db.Integer, db.ForeignKey("organizations.id"))
org = db.relationship(Organization, backref="events")
user_id = Column(db.Integer, db.ForeignKey("users.id"), nullable=True)
user = db.relationship(User, backref="events")
action = Column(db.String(255))
object_type = Column(db.String(255))
object_id = Column(db.String(255), nullable=True)
additional_properties = Column(MutableDict.as_mutable(PseudoJSON), nullable=True, default={})
created_at = Column(db.DateTime(True), default=db.func.now())
__tablename__ = 'events'
def __unicode__(self):
return u"%s,%s,%s,%s" % (self.user_id, self.action, self.object_type, self.object_id)
def to_dict(self):
return {
'org_id': self.org_id,
'user_id': self.user_id,
'action': self.action,
'object_type': self.object_type,
'object_id': self.object_id,
'additional_properties': self.additional_properties,
'created_at': self.created_at.isoformat()
}
@classmethod
def record(cls, event):
org_id = event.pop('org_id')
user_id = event.pop('user_id', None)
action = event.pop('action')
object_type = event.pop('object_type')
object_id = event.pop('object_id', None)
created_at = datetime.datetime.utcfromtimestamp(event.pop('timestamp'))
event = cls(org_id=org_id, user_id=user_id, action=action,
object_type=object_type, object_id=object_id,
additional_properties=event,
created_at=created_at)
db.session.add(event)
return event
class ApiKey(TimestampMixin, GFKBase, db.Model):
id = Column(db.Integer, primary_key=True)
org_id = Column(db.Integer, db.ForeignKey("organizations.id"))
org = db.relationship(Organization)
api_key = Column(db.String(255), index=True, default=lambda: generate_token(40))
active = Column(db.Boolean, default=True)
# 'object' provided by GFKBase
created_by_id = Column(db.Integer, db.ForeignKey("users.id"), nullable=True)
created_by = db.relationship(User)
__tablename__ = 'api_keys'
__table_args__ = (db.Index('api_keys_object_type_object_id', 'object_type', 'object_id'),)
@classmethod
def get_by_api_key(cls, api_key):
return cls.query.filter(cls.api_key == api_key, cls.active == True).one()
@classmethod
def get_by_object(cls, object):
return cls.query.filter(cls.object_type == object.__class__.__tablename__, cls.object_id == object.id, cls.active == True).first()
@classmethod
def create_for_object(cls, object, user):
k = cls(org=user.org, object=object, created_by=user)
db.session.add(k)
return k
class NotificationDestination(BelongsToOrgMixin, db.Model):
id = Column(db.Integer, primary_key=True)
org_id = Column(db.Integer, db.ForeignKey("organizations.id"))
org = db.relationship(Organization, backref="notification_destinations")
user_id = Column(db.Integer, db.ForeignKey("users.id"))
user = db.relationship(User, backref="notification_destinations")
name = Column(db.String(255))
type = Column(db.String(255))
options = Column(Configuration)
created_at = Column(db.DateTime(True), default=db.func.now())
__tablename__ = 'notification_destinations'
__table_args__ = (db.Index('notification_destinations_org_id_name', 'org_id',
'name', unique=True),)
def to_dict(self, all=False):
d = {
'id': self.id,
'name': self.name,
'type': self.type,
'icon': self.destination.icon()
}
if all:
schema = get_configuration_schema_for_destination_type(self.type)
self.options.set_schema(schema)
d['options'] = self.options.to_dict(mask_secrets=True)
return d
def __unicode__(self):
return self.name
@property
def destination(self):
return get_destination(self.type, self.options)
@classmethod
def all(cls, org):
notification_destinations = cls.query.filter(cls.org == org).order_by(cls.id.asc())
return notification_destinations
def notify(self, alert, query, user, new_state, app, host):
schema = get_configuration_schema_for_destination_type(self.type)
self.options.set_schema(schema)
return self.destination.notify(alert, query, user, new_state,
app, host, self.options)
class AlertSubscription(TimestampMixin, db.Model):
id = Column(db.Integer, primary_key=True)
user_id = Column(db.Integer, db.ForeignKey("users.id"))
user = db.relationship(User)
destination_id = Column(db.Integer,
db.ForeignKey("notification_destinations.id"),
nullable=True)
destination = db.relationship(NotificationDestination)
alert_id = Column(db.Integer, db.ForeignKey("alerts.id"))
alert = db.relationship(Alert, back_populates="subscriptions")
__tablename__ = 'alert_subscriptions'
__table_args__ = (db.Index('alert_subscriptions_destination_id_alert_id',
'destination_id', 'alert_id', unique=True),)
def to_dict(self):
d = {
'id': self.id,
'user': self.user.to_dict(),
'alert_id': self.alert_id
}
if self.destination:
d['destination'] = self.destination.to_dict()
return d
@classmethod
def all(cls, alert_id):
return AlertSubscription.query.join(User).filter(AlertSubscription.alert_id == alert_id)
def notify(self, alert, query, user, new_state, app, host):
if self.destination:
return self.destination.notify(alert, query, user, new_state,
app, host)
else:
# User email subscription, so create an email destination object
config = {'addresses': self.user.email}
schema = get_configuration_schema_for_destination_type('email')
options = ConfigurationContainer(config, schema)
destination = get_destination('email', options)
return destination.notify(alert, query, user, new_state, app, host, options)
class QuerySnippet(TimestampMixin, db.Model, BelongsToOrgMixin):
id = Column(db.Integer, primary_key=True)
org_id = Column(db.Integer, db.ForeignKey("organizations.id"))
org = db.relationship(Organization, backref="query_snippets")
trigger = Column(db.String(255), unique=True)
description = Column(db.Text)
user_id = Column(db.Integer, db.ForeignKey("users.id"))
user = db.relationship(User, backref="query_snippets")
snippet = Column(db.Text)
__tablename__ = 'query_snippets'
@classmethod
def all(cls, org):
return cls.query.filter(cls.org == org)
def to_dict(self):
d = {
'id': self.id,
'trigger': self.trigger,
'description': self.description,
'snippet': self.snippet,
'user': self.user.to_dict(),
'updated_at': self.updated_at,
'created_at': self.created_at
}
return d
_gfk_types = {'queries': Query, 'dashboards': Dashboard}
def init_db():
default_org = Organization(name="Default", slug='default', settings={})
admin_group = Group(name='admin', permissions=['admin', 'super_admin'], org=default_org, type=Group.BUILTIN_GROUP)
default_group = Group(name='default', permissions=Group.DEFAULT_PERMISSIONS, org=default_org, type=Group.BUILTIN_GROUP)
db.session.add_all([default_org, admin_group, default_group])
# XXX remove after fixing User.group_ids
db.session.commit()
return default_org, admin_group, default_group
| {
"content_hash": "cd0b32497492e47bf74e161964e6142c",
"timestamp": "",
"source": "github",
"line_count": 1608,
"max_line_length": 138,
"avg_line_length": 35.32960199004975,
"alnum_prop": 0.594367188875198,
"repo_name": "useabode/redash",
"id": "d298267dd8d69bbc82af2bfb624487ab39983754",
"size": "56810",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "redash/models.py",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "226049"
},
{
"name": "HTML",
"bytes": "138642"
},
{
"name": "JavaScript",
"bytes": "309528"
},
{
"name": "Jupyter Notebook",
"bytes": "52302"
},
{
"name": "Makefile",
"bytes": "825"
},
{
"name": "Mako",
"bytes": "494"
},
{
"name": "Python",
"bytes": "676986"
},
{
"name": "Shell",
"bytes": "25888"
}
],
"symlink_target": ""
} |
#ifndef SkJpegInfo_DEFINED
#define SkJpegInfo_DEFINED
#include "SkSize.h"
class SkData;
struct SkJFIFInfo {
SkISize fSize;
enum Type {
kGrayscale,
kYCbCr,
} fType;
};
/** Returns true iff the data seems to be a valid JFIF JPEG image.
If so and if info is not nullptr, populate info.
JPEG/JFIF References:
http://www.w3.org/Graphics/JPEG/itu-t81.pdf
http://www.w3.org/Graphics/JPEG/jfif3.pdf
*/
bool SkIsJFIF(const SkData* skdata, SkJFIFInfo* info);
#endif // SkJpegInfo_DEFINED
| {
"content_hash": "fc948d288dc4a8f5147c45b8a8a57476",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 66,
"avg_line_length": 20.692307692307693,
"alnum_prop": 0.6728624535315985,
"repo_name": "tmpvar/skia.cc",
"id": "39de99455af110bed49ac9089f5fc48818456360",
"size": "681",
"binary": false,
"copies": "9",
"ref": "refs/heads/no-webp",
"path": "src/pdf/SkJpegInfo.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1133"
},
{
"name": "C",
"bytes": "900542"
},
{
"name": "C++",
"bytes": "19621631"
},
{
"name": "Go",
"bytes": "7147"
},
{
"name": "HTML",
"bytes": "477"
},
{
"name": "Java",
"bytes": "27980"
},
{
"name": "JavaScript",
"bytes": "7593"
},
{
"name": "Lua",
"bytes": "25531"
},
{
"name": "Makefile",
"bytes": "8868"
},
{
"name": "Objective-C",
"bytes": "22088"
},
{
"name": "Objective-C++",
"bytes": "97189"
},
{
"name": "PHP",
"bytes": "116206"
},
{
"name": "Python",
"bytes": "371459"
},
{
"name": "Shell",
"bytes": "52874"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_27) on Wed Nov 21 16:03:56 EST 2012 -->
<TITLE>
Uses of Class org.pentaho.di.ui.trans.steps.fuzzymatch.FuzzyMatchDialog
</TITLE>
<META NAME="date" CONTENT="2012-11-21">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.pentaho.di.ui.trans.steps.fuzzymatch.FuzzyMatchDialog";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../org/pentaho/di/ui/trans/steps/fuzzymatch/FuzzyMatchDialog.html" title="class in org.pentaho.di.ui.trans.steps.fuzzymatch"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../../index.html?org/pentaho/di/ui/trans/steps/fuzzymatch//class-useFuzzyMatchDialog.html" target="_top"><B>FRAMES</B></A>
<A HREF="FuzzyMatchDialog.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.pentaho.di.ui.trans.steps.fuzzymatch.FuzzyMatchDialog</B></H2>
</CENTER>
No usage of org.pentaho.di.ui.trans.steps.fuzzymatch.FuzzyMatchDialog
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../org/pentaho/di/ui/trans/steps/fuzzymatch/FuzzyMatchDialog.html" title="class in org.pentaho.di.ui.trans.steps.fuzzymatch"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../../../index.html?org/pentaho/di/ui/trans/steps/fuzzymatch//class-useFuzzyMatchDialog.html" target="_top"><B>FRAMES</B></A>
<A HREF="FuzzyMatchDialog.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
</BODY>
</HTML>
| {
"content_hash": "1e0bf2183a1bc48ad4993d6435e003af",
"timestamp": "",
"source": "github",
"line_count": 144,
"max_line_length": 263,
"avg_line_length": 43.520833333333336,
"alnum_prop": 0.6068294239668103,
"repo_name": "ColFusion/PentahoKettle",
"id": "3969b9605852f5c18bfe75ad8b30debf7efd0040",
"size": "6267",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kettle-data-integration/docs/api/org/pentaho/di/ui/trans/steps/fuzzymatch/class-use/FuzzyMatchDialog.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ActionScript",
"bytes": "21071"
},
{
"name": "Batchfile",
"bytes": "21366"
},
{
"name": "C",
"bytes": "7006"
},
{
"name": "CSS",
"bytes": "1952277"
},
{
"name": "Groff",
"bytes": "684"
},
{
"name": "Groovy",
"bytes": "33843"
},
{
"name": "HTML",
"bytes": "197173221"
},
{
"name": "Java",
"bytes": "3685348"
},
{
"name": "JavaScript",
"bytes": "31972698"
},
{
"name": "PHP",
"bytes": "224688"
},
{
"name": "Perl",
"bytes": "6881"
},
{
"name": "PigLatin",
"bytes": "7496"
},
{
"name": "Python",
"bytes": "109487"
},
{
"name": "Shell",
"bytes": "43881"
},
{
"name": "Smarty",
"bytes": "2952"
},
{
"name": "XQuery",
"bytes": "798"
},
{
"name": "XSLT",
"bytes": "562453"
}
],
"symlink_target": ""
} |
package cmd
import (
"testing"
"github.com/drud/ddev/pkg/exec"
"github.com/stretchr/testify/assert"
)
// TestDevRestart runs `drud legacy restart` on the test apps
func TestDevRemove(t *testing.T) {
assert := assert.New(t)
// Make sure we have running sites.
addSites()
for _, site := range DevTestSites {
cleanup := site.Chdir()
out, err := exec.RunCommand(DdevBin, []string{"remove"})
assert.NoError(err, "ddev remove should succeed but failed, err: %v, output: %s", err, out)
assert.Contains(out, "Successfully removed")
cleanup()
}
// Now put the sites back together so other tests can use them.
addSites()
}
| {
"content_hash": "098fdb7fbcd453a4c4c697e4c1d284d0",
"timestamp": "",
"source": "github",
"line_count": 28,
"max_line_length": 93,
"avg_line_length": 22.857142857142858,
"alnum_prop": 0.69375,
"repo_name": "cyberswat/ddev",
"id": "db5c17dbed53df8256dfd07115bdc8b0d53f031b",
"size": "640",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "cmd/ddev/cmd/remove_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "214"
},
{
"name": "Go",
"bytes": "226744"
},
{
"name": "Makefile",
"bytes": "16145"
},
{
"name": "Shell",
"bytes": "14315"
}
],
"symlink_target": ""
} |
'use strict'
var DashboardPage = require('./dashboard-view');
var DeployedProcessesListPage = require('./deployed-processes-list');
var DeployedProcessesPreviewsPage = require('./deployed-processes-previews');
var DeployedDecisionsListPage = require('./deployed-decisions-list');
var AuthenticationPage = require('../../../commons/pages/authentication');
module.exports = new DashboardPage();
module.exports.deployedProcessesList = new DeployedProcessesListPage();
module.exports.deployedProcessesPreviews = new DeployedProcessesPreviewsPage();
module.exports.deployedDecisionsList = new DeployedDecisionsListPage();
module.exports.authentication = new AuthenticationPage();
| {
"content_hash": "1d6ab4d4fa659eb6b1759260eac8eb2e",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 79,
"avg_line_length": 42.5,
"alnum_prop": 0.8029411764705883,
"repo_name": "nagyistoce/camunda-bpm-webapp",
"id": "9c2891126666f8437e60972cc8bd0f6c06e776df",
"size": "680",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "webapp/src/test/js/e2e/cockpit/pages/dashboard/index.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "95812"
},
{
"name": "Java",
"bytes": "567205"
},
{
"name": "JavaScript",
"bytes": "563426"
}
],
"symlink_target": ""
} |
<!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">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>VO808X: Documentation</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtreedata.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
$(window).load(resizeHeight);
</script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">VO808X
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li class="current"><a href="pages.html"><span>Related Pages</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
</div><!-- top -->
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
<div id="nav-sync" class="sync"></div>
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){initNavTree('md__home_bhargavi_Documents_SDR_Copy_Exam_808X_vendor_googletest_googletest_docs_Documentation.html','');});
</script>
<div id="doc-content">
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div class="header">
<div class="headertitle">
<div class="title">Documentation </div> </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p>This page lists all documentation wiki pages for Google Test **(the SVN trunk version)** – <b>if you use a released version of Google Test, please read the documentation for that specific version instead.</b></p>
<ul>
<li><a class="el" href="_primer_8md.html">Primer</a> – start here if you are new to Google Test.</li>
<li><a class="el" href="_samples_8md.html">Samples</a> – learn from examples.</li>
<li><a class="el" href="_advanced_guide_8md.html">AdvancedGuide</a> – learn more about Google Test.</li>
<li><a class="el" href="_xcode_guide_8md.html">XcodeGuide</a> – how to use Google Test in Xcode on Mac.</li>
<li><a class="el" href="_f_a_q_8md.html">Frequently-Asked Questions</a> – check here before asking a question on the mailing list.</li>
</ul>
<p>To contribute code to Google Test, read:</p>
<ul>
<li><a class="el" href="googletest_2docs_2_dev_guide_8md.html">DevGuide</a> – read this <em>before</em> writing your first patch.</li>
<li><a class="el" href="_pump_manual_8md.html">PumpManual</a> – how we generate some of Google Test's source files. </li>
</ul>
</div></div><!-- contents -->
</div><!-- doc-content -->
<!-- start footer part -->
<div id="nav-path" class="navpath"><!-- id is needed for treeview function! -->
<ul>
<li class="footer">Generated by
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.11 </li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "c9b252eb684ea8c2c750e260d0a12afd",
"timestamp": "",
"source": "github",
"line_count": 129,
"max_line_length": 244,
"avg_line_length": 43.64341085271318,
"alnum_prop": 0.6587921847246891,
"repo_name": "bhargavipatel/808X_VO",
"id": "abc5b8c1b2400866ffd1451c301dd8f662133eff",
"size": "5630",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/html/md__home_bhargavi_Documents_SDR_Copy_Exam_808X_vendor_googletest_googletest_docs_Documentation.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C++",
"bytes": "18150"
},
{
"name": "CMake",
"bytes": "9404"
},
{
"name": "Matlab",
"bytes": "10128"
},
{
"name": "Python",
"bytes": "5095"
}
],
"symlink_target": ""
} |
package palindrome
import (
"errors"
"strconv"
)
// Define Product type here.
type Product struct {
palindrome int
Factorizations [][2]int
}
func Products(fmin, fmax int) (min Product, max Product, e error) {
if fmin > fmax {
// This error message doesn't conform to go-staticcheck but this problem expects this exact error string
return min, max, errors.New("fmin > fmax...")
}
products := getProducts(fmin, fmax)
if len(products) == 0 {
// This error message doesn't conform to go-staticcheck but this problem expects this exact error string
return min, max, errors.New("no palindromes...")
}
return getMin(products), getMax(products), nil
}
func getProducts(min int, max int) (products []Product) {
palindromeToFactors := getPalindromeToFactors(min, max)
for palindrome, factors := range palindromeToFactors {
product := Product{
palindrome: palindrome,
Factorizations: factors,
}
products = append(products, product)
}
return products
}
func getPalindromeToFactors(min int, max int) (palindromeToFactors map[int][][2]int) {
palindromeToFactors = make(map[int][][2]int)
for i := min; i <= max; i++ {
for j := i; j <= max; j++ {
candidate := i * j
factor := [2]int{i, j}
if isPalindrome(candidate) {
if factors, ok := palindromeToFactors[candidate]; ok {
factors = append(factors, factor)
palindromeToFactors[candidate] = factors
} else {
palindromeToFactors[candidate] = [][2]int{factor}
}
}
}
}
return palindromeToFactors
}
func getMin(products []Product) (min Product) {
min = products[0]
for _, product := range products {
if product.palindrome < min.palindrome {
min = product
}
}
return min
}
func getMax(products []Product) (max Product) {
max = products[0]
for _, product := range products {
if product.palindrome > max.palindrome {
max = product
}
}
return max
}
func isPalindrome(x int) bool {
str := strconv.Itoa(x)
return str == reverse(str)
}
func reverse(original string) (reversed string) {
for _, v := range original {
reversed = string(v) + reversed
}
return reversed
}
| {
"content_hash": "bb12a189f6d9ca4836851ad34da00fdf",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 106,
"avg_line_length": 24.045454545454547,
"alnum_prop": 0.6786389413988658,
"repo_name": "rootulp/exercism",
"id": "8311102b3df657254d85d293f1b3e326a5f8ae82",
"size": "2116",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "go/palindrome-products/palindrome_products.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "18900"
},
{
"name": "CoffeeScript",
"bytes": "15342"
},
{
"name": "Elm",
"bytes": "48222"
},
{
"name": "Go",
"bytes": "594636"
},
{
"name": "HTML",
"bytes": "81617"
},
{
"name": "Java",
"bytes": "231244"
},
{
"name": "JavaScript",
"bytes": "126832"
},
{
"name": "Python",
"bytes": "242540"
},
{
"name": "Ruby",
"bytes": "192051"
},
{
"name": "Rust",
"bytes": "77292"
},
{
"name": "TypeScript",
"bytes": "78185"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_45) on Fri Feb 07 15:41:29 IST 2014 -->
<title>player Class Hierarchy</title>
<meta name="date" content="2014-02-07">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="player Class Hierarchy";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../main/package-tree.html">Prev</a></li>
<li><a href="../util/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?player/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package player</h1>
<span class="strong">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Class Hierarchy">Class Hierarchy</h2>
<ul>
<li type="circle">java.lang.Object
<ul>
<li type="circle">player.<a href="../player/AbstractPlayerFactory.html" title="class in player"><span class="strong">AbstractPlayerFactory</span></a></li>
<li type="circle">player.<a href="../player/AbstractView.html" title="class in player"><span class="strong">AbstractView</span></a> (implements java.util.Observer, player.<a href="../player/View.html" title="interface in player">View</a>)
<ul>
<li type="circle">player.<a href="../player/ConsoleView.html" title="class in player"><span class="strong">ConsoleView</span></a></li>
<li type="circle">player.<a href="../player/LastMoveView.html" title="class in player"><span class="strong">LastMoveView</span></a></li>
</ul>
</li>
<li type="circle">player.<a href="../player/Player.html" title="class in player"><span class="strong">Player</span></a> (implements player.<a href="../player/IPlayer.html" title="interface in player">IPlayer</a>)</li>
<li type="circle">player.<a href="../player/RandomPlayerFactory.html" title="class in player"><span class="strong">RandomPlayerFactory</span></a> (implements player.<a href="../player/PlayerFactory.html" title="interface in player">PlayerFactory</a>)</li>
<li type="circle">player.<a href="../player/RandomStrategy.html" title="class in player"><span class="strong">RandomStrategy</span></a> (implements player.<a href="../player/IPlayerStrategy.html" title="interface in player">IPlayerStrategy</a>)</li>
<li type="circle">player.<a href="../player/ViewDecorator.html" title="class in player"><span class="strong">ViewDecorator</span></a> (implements java.util.Observer, player.<a href="../player/View.html" title="interface in player">View</a>)
<ul>
<li type="circle">player.<a href="../player/PlayersViewDecorator.html" title="class in player"><span class="strong">PlayersViewDecorator</span></a></li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 title="Interface Hierarchy">Interface Hierarchy</h2>
<ul>
<li type="circle">player.<a href="../player/IPlayer.html" title="interface in player"><span class="strong">IPlayer</span></a></li>
<li type="circle">player.<a href="../player/IPlayerStrategy.html" title="interface in player"><span class="strong">IPlayerStrategy</span></a></li>
<li type="circle">java.util.Observer
<ul>
<li type="circle">player.<a href="../player/View.html" title="interface in player"><span class="strong">View</span></a></li>
</ul>
</li>
<li type="circle">player.<a href="../player/PlayerFactory.html" title="interface in player"><span class="strong">PlayerFactory</span></a></li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li>Use</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../deprecated-list.html">Deprecated</a></li>
<li><a href="../index-files/index-1.html">Index</a></li>
<li><a href="../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../main/package-tree.html">Prev</a></li>
<li><a href="../util/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../index.html?player/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "25edbcf0047e0e3e0c2fa4f77db4362a",
"timestamp": "",
"source": "github",
"line_count": 153,
"max_line_length": 255,
"avg_line_length": 41.42483660130719,
"alnum_prop": 0.6599873777216788,
"repo_name": "soupi/FourRow",
"id": "75eeed019be0c6fe8b9b6581c80df35dd5512979",
"size": "6338",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "four/doc/player/package-tree.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AspectJ",
"bytes": "3782"
},
{
"name": "CSS",
"bytes": "11139"
},
{
"name": "Java",
"bytes": "22705"
}
],
"symlink_target": ""
} |
package org.apache.pulsar.io;
import static org.apache.pulsar.broker.auth.MockedPulsarServiceBaseTest.retryStrategically;
import static org.apache.pulsar.functions.worker.PulsarFunctionLocalRunTest.getPulsarIODataGeneratorNar;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import java.util.Map;
import java.util.Set;
import org.apache.pulsar.client.admin.PulsarAdminException;
import org.apache.pulsar.common.functions.FunctionConfig;
import org.apache.pulsar.common.functions.Utils;
import org.apache.pulsar.common.io.SourceConfig;
import org.apache.pulsar.common.policies.data.TopicStats;
import org.apache.pulsar.functions.utils.FunctionCommon;
import org.apache.pulsar.functions.worker.PulsarFunctionTestUtils;
import org.testng.annotations.Test;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
/**
* Test Pulsar Source
*/
@Test(groups = "broker-io")
public class PulsarSourceE2ETest extends AbstractPulsarE2ETest {
private void testPulsarSourceStats(String jarFilePathUrl) throws Exception {
final String namespacePortion = "io";
final String replNamespace = tenant + "/" + namespacePortion;
final String sinkTopic = "persistent://" + replNamespace + "/output";
final String sourceName = "PulsarSource-test";
admin.namespaces().createNamespace(replNamespace);
Set<String> clusters = Sets.newHashSet(Lists.newArrayList("use"));
admin.namespaces().setNamespaceReplicationClusters(replNamespace, clusters);
SourceConfig sourceConfig = createSourceConfig(tenant, namespacePortion, sourceName, sinkTopic);
if (jarFilePathUrl.startsWith(Utils.BUILTIN)) {
sourceConfig.setArchive(jarFilePathUrl);
admin.sources().createSource(sourceConfig, null);
} else {
admin.sources().createSourceWithUrl(sourceConfig, jarFilePathUrl);
}
retryStrategically((test) -> {
try {
return (admin.topics().getStats(sinkTopic).getPublishers().size() == 1);
} catch (PulsarAdminException e) {
return false;
}
}, 10, 150);
final String sinkTopic2 = "persistent://" + replNamespace + "/output2";
sourceConfig.setTopicName(sinkTopic2);
if (jarFilePathUrl.startsWith(Utils.BUILTIN)) {
admin.sources().updateSource(sourceConfig, null);
} else {
admin.sources().updateSourceWithUrl(sourceConfig, jarFilePathUrl);
}
retryStrategically((test) -> {
try {
TopicStats sourceStats = admin.topics().getStats(sinkTopic2);
return sourceStats.getPublishers().size() == 1
&& sourceStats.getPublishers().get(0).getMetadata() != null
&& sourceStats.getPublishers().get(0).getMetadata().containsKey("id")
&& sourceStats.getPublishers().get(0).getMetadata().get("id").equals(String.format("%s/%s/%s", tenant, namespacePortion, sourceName));
} catch (PulsarAdminException e) {
return false;
}
}, 50, 150);
TopicStats sourceStats = admin.topics().getStats(sinkTopic2);
assertEquals(sourceStats.getPublishers().size(), 1);
assertNotNull(sourceStats.getPublishers().get(0).getMetadata());
assertTrue(sourceStats.getPublishers().get(0).getMetadata().containsKey("id"));
assertEquals(sourceStats.getPublishers().get(0).getMetadata().get("id"), String.format("%s/%s/%s", tenant, namespacePortion, sourceName));
retryStrategically((test) -> {
try {
return (admin.topics().getStats(sinkTopic2).getPublishers().size() == 1) && (admin.topics().getInternalStats(sinkTopic2, false).numberOfEntries > 4);
} catch (PulsarAdminException e) {
return false;
}
}, 50, 150);
assertEquals(admin.topics().getStats(sinkTopic2).getPublishers().size(), 1);
String prometheusMetrics = PulsarFunctionTestUtils.getPrometheusMetrics(pulsar.getListenPortHTTP().get());
log.info("prometheusMetrics: {}", prometheusMetrics);
Map<String, PulsarFunctionTestUtils.Metric> metrics = PulsarFunctionTestUtils.parseMetrics(prometheusMetrics);
PulsarFunctionTestUtils.Metric m = metrics.get("pulsar_source_received_total");
assertEquals(m.tags.get("cluster"), config.getClusterName());
assertEquals(m.tags.get("instance_id"), "0");
assertEquals(m.tags.get("name"), sourceName);
assertEquals(m.tags.get("namespace"), String.format("%s/%s", tenant, namespacePortion));
assertEquals(m.tags.get("fqfn"), FunctionCommon.getFullyQualifiedName(tenant, namespacePortion, sourceName));
assertTrue(m.value > 0.0);
m = metrics.get("pulsar_source_received_1min_total");
assertEquals(m.tags.get("cluster"), config.getClusterName());
assertEquals(m.tags.get("instance_id"), "0");
assertEquals(m.tags.get("name"), sourceName);
assertEquals(m.tags.get("namespace"), String.format("%s/%s", tenant, namespacePortion));
assertEquals(m.tags.get("fqfn"), FunctionCommon.getFullyQualifiedName(tenant, namespacePortion, sourceName));
assertTrue(m.value > 0.0);
m = metrics.get("pulsar_source_written_total");
assertEquals(m.tags.get("cluster"), config.getClusterName());
assertEquals(m.tags.get("instance_id"), "0");
assertEquals(m.tags.get("name"), sourceName);
assertEquals(m.tags.get("namespace"), String.format("%s/%s", tenant, namespacePortion));
assertEquals(m.tags.get("fqfn"), FunctionCommon.getFullyQualifiedName(tenant, namespacePortion, sourceName));
assertTrue(m.value > 0.0);
m = metrics.get("pulsar_source_written_1min_total");
assertEquals(m.tags.get("cluster"), config.getClusterName());
assertEquals(m.tags.get("instance_id"), "0");
assertEquals(m.tags.get("name"), sourceName);
assertEquals(m.tags.get("namespace"), String.format("%s/%s", tenant, namespacePortion));
assertEquals(m.tags.get("fqfn"), FunctionCommon.getFullyQualifiedName(tenant, namespacePortion, sourceName));
assertTrue(m.value > 0.0);
m = metrics.get("pulsar_source_source_exceptions_total");
assertEquals(m.tags.get("cluster"), config.getClusterName());
assertEquals(m.tags.get("instance_id"), "0");
assertEquals(m.tags.get("name"), sourceName);
assertEquals(m.tags.get("namespace"), String.format("%s/%s", tenant, namespacePortion));
assertEquals(m.tags.get("fqfn"), FunctionCommon.getFullyQualifiedName(tenant, namespacePortion, sourceName));
assertEquals(m.value, 0.0);
m = metrics.get("pulsar_source_source_exceptions_1min_total");
assertEquals(m.tags.get("cluster"), config.getClusterName());
assertEquals(m.tags.get("instance_id"), "0");
assertEquals(m.tags.get("name"), sourceName);
assertEquals(m.tags.get("namespace"), String.format("%s/%s", tenant, namespacePortion));
assertEquals(m.tags.get("fqfn"), FunctionCommon.getFullyQualifiedName(tenant, namespacePortion, sourceName));
assertEquals(m.value, 0.0);
m = metrics.get("pulsar_source_system_exceptions_total");
assertEquals(m.tags.get("cluster"), config.getClusterName());
assertEquals(m.tags.get("instance_id"), "0");
assertEquals(m.tags.get("name"), sourceName);
assertEquals(m.tags.get("namespace"), String.format("%s/%s", tenant, namespacePortion));
assertEquals(m.tags.get("fqfn"), FunctionCommon.getFullyQualifiedName(tenant, namespacePortion, sourceName));
assertEquals(m.value, 0.0);
m = metrics.get("pulsar_source_system_exceptions_1min_total");
assertEquals(m.tags.get("cluster"), config.getClusterName());
assertEquals(m.tags.get("instance_id"), "0");
assertEquals(m.tags.get("name"), sourceName);
assertEquals(m.tags.get("namespace"), String.format("%s/%s", tenant, namespacePortion));
assertEquals(m.tags.get("fqfn"), FunctionCommon.getFullyQualifiedName(tenant, namespacePortion, sourceName));
assertEquals(m.value, 0.0);
m = metrics.get("pulsar_source_last_invocation");
assertEquals(m.tags.get("cluster"), config.getClusterName());
assertEquals(m.tags.get("instance_id"), "0");
assertEquals(m.tags.get("name"), sourceName);
assertEquals(m.tags.get("namespace"), String.format("%s/%s", tenant, namespacePortion));
assertEquals(m.tags.get("fqfn"), FunctionCommon.getFullyQualifiedName(tenant, namespacePortion, sourceName));
assertTrue(m.value > 0.0);
tempDirectory.assertThatFunctionDownloadTempFilesHaveBeenDeleted();
admin.sources().deleteSource(tenant, namespacePortion, sourceName);
}
@Test(timeOut = 20000, groups = "builtin")
public void testPulsarSourceStatsBuiltin() throws Exception {
String jarFilePathUrl = String.format("%s://data-generator", Utils.BUILTIN);
testPulsarSourceStats(jarFilePathUrl);
}
@Test(timeOut = 20000, groups = "builtin", expectedExceptions = {PulsarAdminException.class}, expectedExceptionsMessageRegExp = "Built-in source is not available")
public void testPulsarSourceStatsBuiltinDoesNotExist() throws Exception {
String jarFilePathUrl = String.format("%s://foo", Utils.BUILTIN);
testPulsarSourceStats(jarFilePathUrl);
}
@Test(timeOut = 20000)
public void testPulsarSourceStatsWithFile() throws Exception {
String jarFilePathUrl = getPulsarIODataGeneratorNar().toURI().toString();
testPulsarSourceStats(jarFilePathUrl);
}
@Test(timeOut = 40000)
public void testPulsarSourceStatsWithUrl() throws Exception {
testPulsarSourceStats(fileServer.getUrl("/pulsar-io-data-generator.nar"));
}
private static SourceConfig createSourceConfig(String tenant, String namespace, String functionName, String sinkTopic) {
SourceConfig sourceConfig = new SourceConfig();
sourceConfig.setTenant(tenant);
sourceConfig.setNamespace(namespace);
sourceConfig.setName(functionName);
sourceConfig.setParallelism(1);
sourceConfig.setProcessingGuarantees(FunctionConfig.ProcessingGuarantees.ATLEAST_ONCE);
sourceConfig.setTopicName(sinkTopic);
return sourceConfig;
}
}
| {
"content_hash": "cc5bc7b2c54b4d5cf566d0daee0f8271",
"timestamp": "",
"source": "github",
"line_count": 198,
"max_line_length": 167,
"avg_line_length": 53.46969696969697,
"alnum_prop": 0.6827240955889298,
"repo_name": "yahoo/pulsar",
"id": "2dea2fb020eddd5c32e4d82f4c5733c5caa177ca",
"size": "11395",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "pulsar-broker/src/test/java/org/apache/pulsar/io/PulsarSourceE2ETest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "77960"
},
{
"name": "C++",
"bytes": "736937"
},
{
"name": "CMake",
"bytes": "9092"
},
{
"name": "HTML",
"bytes": "29382"
},
{
"name": "Java",
"bytes": "5371040"
},
{
"name": "Protocol Buffer",
"bytes": "15090"
},
{
"name": "Python",
"bytes": "91802"
},
{
"name": "Shell",
"bytes": "47717"
}
],
"symlink_target": ""
} |
package greycat.utility.distance;
public class Distances {
public static final int EUCLIDEAN = 0;
public static final int GEODISTANCE = 1;
public static final int COSINE = 2;
public static final int PEARSON = 3;
public static final int GAUSSIAN = 4;
public static final int DEFAULT = EUCLIDEAN;
public static Distance getDistance(int distance, double[] distancearg) {
switch (distance) {
case EUCLIDEAN:
return EuclideanDistance.instance();
case GEODISTANCE:
return GeoDistance.instance();
case COSINE:
return CosineDistance.instance();
case PEARSON:
return PearsonDistance.instance();
case GAUSSIAN:
return new GaussianDistance(distancearg);
}
return getDistance(DEFAULT,null);
}
}
| {
"content_hash": "371aa44ce863b1ed7a705ac869cc434f",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 76,
"avg_line_length": 28.580645161290324,
"alnum_prop": 0.6117381489841986,
"repo_name": "Neoskai/greycat",
"id": "e4504a1266e0ffc240e4be904e45b363b2ec3c3d",
"size": "1520",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "greycat/src/main/java/greycat/utility/distance/Distances.java",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "2633"
},
{
"name": "C",
"bytes": "2737"
},
{
"name": "CSS",
"bytes": "298300"
},
{
"name": "HTML",
"bytes": "18265"
},
{
"name": "Java",
"bytes": "4125943"
},
{
"name": "JavaScript",
"bytes": "2081822"
},
{
"name": "Shell",
"bytes": "9894"
},
{
"name": "TypeScript",
"bytes": "53327"
}
],
"symlink_target": ""
} |
package org.dync.giftlibrary.util;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by KathLine on 2017/4/27.
*/
public class RecyclerViewUtil {
private RecyclerView mRecyclerView = null;
private GestureDetector mGestureDetector = null;
private RecyclerView.SimpleOnItemTouchListener mSimpleOnItemTouchListener;
private OnItemClickListener mOnItemClickListener = null;
private OnItemLongClickListener mOnItemLongClickListener = null;
private Context context;
public RecyclerViewUtil(Context context, RecyclerView recyclerView) {
this.context = context;
this.mRecyclerView = recyclerView;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
//长按事件
@Override
public void onLongPress(MotionEvent e) {
super.onLongPress(e);
if (mOnItemLongClickListener != null) {
View childView = mRecyclerView.findChildViewUnder(e.getX(), e.getY());
if (childView != null) {
int position = mRecyclerView.getChildLayoutPosition(childView);
mOnItemLongClickListener.onItemLongClick(position, childView);
}
}
}
//单击事件
@Override
public boolean onSingleTapUp(MotionEvent e) {
if (mOnItemClickListener != null) {
View childView = mRecyclerView.findChildViewUnder(e.getX(), e.getY());
if (childView != null) {
int position = mRecyclerView.getChildLayoutPosition(childView);
mOnItemClickListener.onItemClick(position, childView);
return true;
}
}
return super.onSingleTapUp(e);
}
});
mSimpleOnItemTouchListener = new RecyclerView.SimpleOnItemTouchListener() {
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
if (mGestureDetector.onTouchEvent(e)) {
return true;
}
return false;
}
};
mRecyclerView.addOnItemTouchListener(mSimpleOnItemTouchListener);
}
public void setOnItemClickListener(OnItemClickListener l) {
mOnItemClickListener = l;
}
public void setOnItemLongClickListener(OnItemLongClickListener l) {
mOnItemLongClickListener = l;
}
//长按事件接口
public interface OnItemLongClickListener {
void onItemLongClick(int position, View view);
}
//单击事件接口
public interface OnItemClickListener {
void onItemClick(int position, View view);
}
}
| {
"content_hash": "0c99273220a0c040c5ea16ac1e8306e9",
"timestamp": "",
"source": "github",
"line_count": 85,
"max_line_length": 103,
"avg_line_length": 34.529411764705884,
"alnum_prop": 0.6173764906303236,
"repo_name": "DyncKathline/LiveGiftLayout",
"id": "ced8b15d9aa0b47ca467498805490cee580d3e97",
"size": "2975",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "giftlibrary/src/main/java/org/dync/giftlibrary/util/RecyclerViewUtil.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "144902"
}
],
"symlink_target": ""
} |
package org.dyn4j.geometry.hull;
import org.dyn4j.geometry.Geometry;
import org.dyn4j.geometry.Vector2;
/**
* Represents an algorithm used to create a convex hull of a given point set.
* @author William Bittle
* @version 3.0.1
* @since 2.2.0
*/
public interface HullGenerator {
/**
* Returns the points of the convex hull generated from the given point set.
* <p>
* The resulting point set may not have the correct winding. Use the {@link Geometry#getWinding(Vector2...)}
* and {@link Geometry#reverseWinding(Vector2...)} methods to get and set the winding direction.
* @param points the point set
* @return {@link Vector2}[] the convex hull vertices
* @throws NullPointerException if points is null or contains null points
*/
public abstract Vector2[] generate(Vector2... points);
}
| {
"content_hash": "e736771d91f68dd90e02b203b4b0f3b3",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 110,
"avg_line_length": 34.791666666666664,
"alnum_prop": 0.7053892215568862,
"repo_name": "yuripourre/etyllica-physics",
"id": "720efa06b8c184121c63ddd3855ffb6b9f1d95a6",
"size": "2455",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/org/dyn4j/geometry/hull/HullGenerator.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "1598120"
}
],
"symlink_target": ""
} |
const char *CDABlockToPerformKey = "CDABlockToPerform";
const char *CDABlocksToPerformKey = "CDABlocksToPerform";
const char *CDAAuditingMultipleBlocksKey = "CDAAuditingMultipleBlocks";
@implementation NSManagedObjectContext (Leech)
- (void)Leech_PerformBlock:(core_data_perform_t)block {
NSNumber *multipleAuditFlag = objc_getAssociatedObject([NSManagedObjectContext class], CDAAuditingMultipleBlocksKey);
if (multipleAuditFlag.boolValue) {
NSMutableArray *blocks = [(NSArray*)objc_getAssociatedObject([NSManagedObjectContext class], CDABlocksToPerformKey) mutableCopy];
if (!blocks) {
blocks = [NSMutableArray new];
}
[blocks addObject:block];
objc_setAssociatedObject([NSManagedObjectContext class], CDABlocksToPerformKey, [NSArray arrayWithArray:blocks], OBJC_ASSOCIATION_RETAIN);
}
else {
objc_setAssociatedObject([NSManagedObjectContext class], CDABlockToPerformKey, block, OBJC_ASSOCIATION_RETAIN);
}
}
//- (void)Leech_PerformBlockAndWait:(core_data_perform_t)block {
// NSNumber *multipleAuditFlag = objc_getAssociatedObject([NSManagedObjectContext class], CDAAuditingMultipleBlocksKey);
// if (multipleAuditFlag.boolValue) {
// NSMutableArray *blocks = [(NSArray*)objc_getAssociatedObject([NSManagedObjectContext class], CDABlocksToPerformKey) mutableCopy];
// if (!blocks) {
// blocks = [NSMutableArray new];
// }
// [blocks addObject:block];
// objc_setAssociatedObject([NSManagedObjectContext class], CDABlocksToPerformKey, [NSArray arrayWithArray:blocks], OBJC_ASSOCIATION_RETAIN);
// }
// else {
// objc_setAssociatedObject([NSManagedObjectContext class], CDABlockToPerformKey, block, OBJC_ASSOCIATION_RETAIN);
// }
//}
@end
////////////////////////////////////////////////////////////////////////////////
// Category on NSManagedObject
////////////////////////////////////////////////////////////////////////////////
const char *CDADidCallWillAccessValueForKey = "CDADidCallWillAccessValueForKey";
const char *CDAKeyForWillAccessValueForKey = "CDAKeyForWillAccessValueForKey";
const char *CDADidCallDidAccessValueForKey = "CDADidCallDidAccessValueForKey";
const char *CDAKeyForDidAccessValueForKey = "CDAKeyForDidAccessValueForKey";
const char *CDADidCallWillChangeValueForKey = "CDADidCallWillChangeValueForKey";
const char *CDAKeyForWillChangeValueForKey = "CDAKeyForWillChangeValueForKey";
const char *CDADidCallDidChangeValueForKey = "CDADidCallDidChangeValueForKey";
const char *CDAKeyForDidChangeValueForKey = "CDAKeyForDidChangeValueForKey";
@implementation NSManagedObject (Leech)
- (void)Leech_WillAccessValueForKey:(NSString *)key {
NSLog(@"In will access swizzled");
objc_setAssociatedObject(self, CDADidCallWillAccessValueForKey, @(YES), OBJC_ASSOCIATION_RETAIN);
objc_setAssociatedObject(self, CDAKeyForWillAccessValueForKey, key, OBJC_ASSOCIATION_RETAIN);
}
- (void)Leech_DidAccessValueForKey:(NSString *)key {
}
- (void)Leech_WillChangeValueForKey:(NSString *)key {
}
- (void)Leech_DidChangeValueForKey:(NSString *)key {
}
@end
////////////////////////////////////////////////////////////////////////////////
// Implementation of Core Data auditor
////////////////////////////////////////////////////////////////////////////////
@implementation LTTCoreDataAuditor
#pragma mark - Perform block methods
+ (core_data_perform_t)blockToPerform {
return objc_getAssociatedObject([NSManagedObjectContext class], CDABlockToPerformKey);
}
+ (NSArray *)blocksToPerform {
return objc_getAssociatedObject([NSManagedObjectContext class], CDABlocksToPerformKey);
}
#pragma mark -performBlock:
+ (void)auditPerformBlock {
[LTTMethodSwizzler swapInstanceMethodsForClass:[NSManagedObjectContext class] selectorOne:@selector(performBlock:) selectorTwo:@selector(Leech_PerformBlock:)];
}
+ (void)stopAuditingPerformBlock {
objc_setAssociatedObject([NSManagedObjectContext class], CDABlockToPerformKey, nil, OBJC_ASSOCIATION_ASSIGN);
[LTTMethodSwizzler swapInstanceMethodsForClass:[NSManagedObjectContext class] selectorOne:@selector(performBlock:) selectorTwo:@selector(Leech_PerformBlock:)];
}
+ (void)auditPerformMultipleBlocks {
objc_setAssociatedObject([NSManagedObjectContext class], CDAAuditingMultipleBlocksKey, @(YES), OBJC_ASSOCIATION_RETAIN);
[LTTMethodSwizzler swapInstanceMethodsForClass:[NSManagedObjectContext class] selectorOne:@selector(performBlock:) selectorTwo:@selector(Leech_PerformBlock:)];
}
+ (void)stopAuditingPerformMultipleBlocks {
objc_setAssociatedObject([NSManagedObjectContext class], CDAAuditingMultipleBlocksKey, nil, OBJC_ASSOCIATION_ASSIGN);
objc_setAssociatedObject([NSManagedObjectContext class], CDABlocksToPerformKey, nil, OBJC_ASSOCIATION_ASSIGN);
[LTTMethodSwizzler swapInstanceMethodsForClass:[NSManagedObjectContext class] selectorOne:@selector(performBlock:) selectorTwo:@selector(Leech_PerformBlock:)];
}
#pragma mark -performBlockAndWait:
+ (void)auditPerformBlockAndWait {
[LTTMethodSwizzler swapInstanceMethodsForClass:[NSManagedObjectContext class] selectorOne:@selector(performBlockAndWait:) selectorTwo:@selector(Leech_PerformBlock:)];
}
+ (void)stopAuditingPerformBlockAndWait {
objc_setAssociatedObject([NSManagedObjectContext class], CDABlockToPerformKey, nil, OBJC_ASSOCIATION_ASSIGN);
[LTTMethodSwizzler swapInstanceMethodsForClass:[NSManagedObjectContext class] selectorOne:@selector(performBlockAndWait:) selectorTwo:@selector(Leech_PerformBlock:)];
}
+ (void)auditPerformMultipleBlocksAndWait {
objc_setAssociatedObject([NSManagedObjectContext class], CDAAuditingMultipleBlocksKey, @(YES), OBJC_ASSOCIATION_RETAIN);
[LTTMethodSwizzler swapInstanceMethodsForClass:[NSManagedObjectContext class] selectorOne:@selector(performBlockAndWait:) selectorTwo:@selector(Leech_PerformBlock:)];
}
+ (void)stopAuditingPerformMultipleBlocksAndWait {
objc_setAssociatedObject([NSManagedObjectContext class], CDAAuditingMultipleBlocksKey, nil, OBJC_ASSOCIATION_ASSIGN);
objc_setAssociatedObject([NSManagedObjectContext class], CDABlocksToPerformKey, nil, OBJC_ASSOCIATION_ASSIGN);
[LTTMethodSwizzler swapInstanceMethodsForClass:[NSManagedObjectContext class] selectorOne:@selector(performBlockAndWait:) selectorTwo:@selector(Leech_PerformBlock:)];
}
#pragma mark - Managed object access/mutation
#pragma mark Attribute access
+ (void)auditAccessNotificationsForManagedObject:(NSManagedObject *)managedObject onAttribute:(NSString *)attributeName {
[LTTMethodSwizzler swapInstanceMethodsForClass:[managedObject class] selectorOne:@selector(willAccessValueForKey:) selectorTwo:@selector(Leech_WillAccessValueForKey:)];
[LTTMethodSwizzler swapInstanceMethodsForClass:[managedObject class] selectorOne:@selector(didAccessValueForKey:) selectorTwo:@selector(Leech_DidAccessValueForKey:)];
}
+ (void)stopAuditingAccessNotificationsForManagedObject:(NSManagedObject *)managedObject {
objc_setAssociatedObject(self, CDADidCallWillAccessValueForKey, nil, OBJC_ASSOCIATION_ASSIGN);
objc_setAssociatedObject(self, CDAKeyForWillAccessValueForKey, nil, OBJC_ASSOCIATION_ASSIGN);
[LTTMethodSwizzler swapInstanceMethodsForClass:[NSManagedObject class] selectorOne:@selector(willAccessValueForKey:) selectorTwo:@selector(Leech_WillAccessValueForKey:)];
[LTTMethodSwizzler swapInstanceMethodsForClass:[NSManagedObject class] selectorOne:@selector(didAccessValueForKey:) selectorTwo:@selector(Leech_DidAccessValueForKey:)];
}
+ (BOOL)didCallWillAccessValueForKeyOnObject:(NSManagedObject *)object {
NSNumber *didCall = objc_getAssociatedObject(object, CDADidCallWillAccessValueForKey);
return didCall.boolValue;
}
+ (BOOL)didCallDidAccessValueForKeyOnObject:(NSManagedObject *)object {
return NO;
}
+ (NSString *)keyForWillAccessValueOnObject:(NSManagedObject *)object {
return nil;
}
+ (NSString *)keyForDidAccessValueOnObject:(NSManagedObject *)object {
return nil;
}
#pragma mark Attribute mutation
+ (void)auditChangeNotificationsForManagedObject:(NSManagedObject *)managedObject onAttribute:(NSString *)attributeName {
[LTTMethodSwizzler swapInstanceMethodsForClass:[NSManagedObject class] selectorOne:@selector(willChangeValueForKey:) selectorTwo:@selector(Leech_WillChangeValueForKey:)];
[LTTMethodSwizzler swapInstanceMethodsForClass:[NSManagedObject class] selectorOne:@selector(didChangeValueForKey:) selectorTwo:@selector(Leech_DidChangeValueForKey:)];
}
+ (void)stopAuditingChangeNotificationsForManagedObject:(NSManagedObject *)mangedObject {
[LTTMethodSwizzler swapInstanceMethodsForClass:[NSManagedObject class] selectorOne:@selector(willChangeValueForKey:) selectorTwo:@selector(Leech_WillChangeValueForKey:)];
[LTTMethodSwizzler swapInstanceMethodsForClass:[NSManagedObject class] selectorOne:@selector(didChangeValueForKey:) selectorTwo:@selector(Leech_DidChangeValueForKey:)];
}
+ (BOOL)didCallWillChangeValueForKeyOnObject:(NSManagedObject *)object {
return NO;
}
+ (BOOL)didCallDidChangeValueForKeyOnObject:(NSManagedObject *)object {
return NO;
}
+ (NSString *)keyForWillChangeValueOnObject:(NSManagedObject *)object {
return nil;
}
+ (NSString *)keyForDidChangeValueOnObject:(NSManagedObject *)object {
return nil;
}
@end
| {
"content_hash": "ce2ddcd2bdca15f3025a02b61bd4661a",
"timestamp": "",
"source": "github",
"line_count": 202,
"max_line_length": 174,
"avg_line_length": 46.31683168316832,
"alnum_prop": 0.7727661393758016,
"repo_name": "samodom/Leech",
"id": "ad36b958f805666566f573c0149559bfc8916ece",
"size": "9759",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Leech/LTTCoreDataAuditor.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "348754"
},
{
"name": "Ruby",
"bytes": "920"
}
],
"symlink_target": ""
} |
package org.pentaho.di.ui.job.entries.sqoop;
import org.apache.commons.vfs.FileObject;
import org.pentaho.di.core.exception.KettleFileException;
import org.pentaho.di.core.hadoop.HadoopSpoonPlugin;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entries.sqoop.AbstractSqoopJobEntry;
import org.pentaho.di.job.entries.sqoop.SqoopExportConfig;
import org.pentaho.di.job.entries.sqoop.SqoopExportJobEntry;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.binding.Binding;
import org.pentaho.ui.xul.binding.BindingFactory;
import org.pentaho.vfs.ui.VfsFileChooserDialog;
import java.util.Collection;
import java.util.List;
import static org.pentaho.di.job.entries.sqoop.SqoopExportConfig.EXPORT_DIR;
/**
* Controller for the Sqoop Export Dialog.
*/
public class SqoopExportJobEntryController extends AbstractSqoopJobEntryController<SqoopExportConfig, SqoopExportJobEntry> {
public SqoopExportJobEntryController(JobMeta jobMeta, XulDomContainer container, SqoopExportJobEntry sqoopJobEntry, BindingFactory bindingFactory) {
super(jobMeta, container, sqoopJobEntry, bindingFactory);
}
@Override
public String getDialogElementId() {
return "sqoop-export";
}
@Override
protected void createBindings(SqoopExportConfig config, XulDomContainer container, BindingFactory bindingFactory, Collection<Binding> bindings) {
super.createBindings(config, container, bindingFactory, bindings);
bindings.add(bindingFactory.createBinding(config, EXPORT_DIR, EXPORT_DIR, "value"));
}
public void browseForExportDirectory() {
FileObject path = null;
try {
// TODO Build proper URL for path
// path = resolveFile(getConfig().getExportDir());
} catch (Exception e) {
// Ignore, use null (default VFS browse path)
}
try {
FileObject exportDir = browseVfs(null, path, VfsFileChooserDialog.VFS_DIALOG_OPEN_DIRECTORY, HadoopSpoonPlugin.HDFS_SCHEME, HadoopSpoonPlugin.HDFS_SCHEME, false);
if (exportDir != null) {
getConfig().setExportDir(exportDir.getName().getPath());
}
} catch (KettleFileException e) {
getJobEntry().logError(BaseMessages.getString(AbstractSqoopJobEntry.class, "ErrorBrowsingDirectory"), e);
}
}
@Override
public void accept() {
// Set the database meta based on the current database
jobEntry.setDatabaseMeta(jobMeta.findDatabase(config.getDatabase()));
super.accept();
}
}
| {
"content_hash": "0e3f5950fee68ee385812014542edae7",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 168,
"avg_line_length": 36.51470588235294,
"alnum_prop": 0.7652033830044301,
"repo_name": "mtseu/big-data-plugin",
"id": "183de3073667edbe841864bec8a36558b4b2ddf9",
"size": "3357",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/org/pentaho/di/ui/job/entries/sqoop/SqoopExportJobEntryController.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "1922602"
}
],
"symlink_target": ""
} |
#include <shogun/features/DotFeatures.h>
#include <shogun/mathematics/linalg/LinalgNamespace.h>
#include <shogun/structure/HierarchicalMultilabelModel.h>
#include <shogun/structure/MultilabelSOLabels.h>
#include <shogun/lib/DynamicArray.h>
using namespace shogun;
CHierarchicalMultilabelModel::CHierarchicalMultilabelModel()
: CStructuredModel()
{
init(SGVector<int32_t>(0), false);
}
CHierarchicalMultilabelModel::CHierarchicalMultilabelModel(CFeatures * features,
CStructuredLabels * labels, SGVector<int32_t> taxonomy,
bool leaf_nodes_mandatory)
: CStructuredModel(features, labels)
{
init(taxonomy, leaf_nodes_mandatory);
}
CStructuredLabels * CHierarchicalMultilabelModel::structured_labels_factory(
int32_t num_labels)
{
return new CMultilabelSOLabels(num_labels, m_num_classes);
}
CHierarchicalMultilabelModel::~CHierarchicalMultilabelModel()
{
SG_FREE(m_children);
}
void CHierarchicalMultilabelModel::init(SGVector<int32_t> taxonomy,
bool leaf_nodes_mandatory)
{
SG_ADD(&m_num_classes, "num_classes", "Number of (binary) class assignment per label");
SG_ADD(&m_taxonomy, "taxonomy", "Taxonomy of the hierarchy of the labels");
SG_ADD(&m_leaf_nodes_mandatory, "leaf_nodes_mandatory", "Whether internal nodes belong"
"to output class or not");
SG_ADD(&m_root, "root", "Node-id of the ROOT element");
m_leaf_nodes_mandatory = leaf_nodes_mandatory;
m_num_classes = 0;
int32_t num_classes = 0;
if (m_labels)
{
num_classes = ((CMultilabelSOLabels *)m_labels)->get_num_classes();
}
REQUIRE(num_classes == taxonomy.vlen, "Number of classes must be equal to taxonomy vector = %d\n",
taxonomy.vlen);
m_taxonomy = SGVector<int32_t>(num_classes);
m_root = -1;
int32_t root_node_count = 0;
for (index_t i = 0; i < num_classes; i++)
{
REQUIRE(taxonomy[i] < num_classes && taxonomy[i] >= -1, "parent-id of node-id:%d is taxonomy[%d] = %d,"
" but must be within [-1; %d-1] (-1 for root node)\n", i, i,
taxonomy[i], num_classes);
m_taxonomy[i] = taxonomy[i];
if (m_taxonomy[i] == -1)
{
m_root = i;
root_node_count++;
}
}
if (num_classes)
{
REQUIRE(m_root != -1 && root_node_count == 1, "Single ROOT element must be defined "
"with parent-id = -1\n");
}
// storing all the children of all the nodes in form of array of vectors
m_children = SG_MALLOC(SGVector<int32_t>, num_classes);
for (int32_t i = 0; i < num_classes; i++)
{
SGVector<int32_t> child_id = m_taxonomy.find(i);
m_children[i] = child_id;
}
}
int32_t CHierarchicalMultilabelModel::get_dim() const
{
int32_t num_classes = ((CMultilabelSOLabels *)m_labels)->get_num_classes();
int32_t feats_dim = ((CDotFeatures *)m_features)->get_dim_feature_space();
return num_classes * feats_dim;
}
SGVector<int32_t> CHierarchicalMultilabelModel::get_label_vector(
SGVector<int32_t> sparse_label)
{
int32_t num_classes = ((CMultilabelSOLabels *)m_labels)->get_num_classes();
SGVector<int32_t> label_vector(num_classes);
label_vector.zero();
for (index_t i = 0; i < sparse_label.vlen; i++)
{
int32_t node_id = sparse_label[i];
label_vector[node_id] = 1;
for (int32_t parent_id = m_taxonomy[node_id]; parent_id != -1;
parent_id = m_taxonomy[parent_id])
{
label_vector[parent_id] = 1;
}
}
return label_vector;
}
SGVector<float64_t> CHierarchicalMultilabelModel::get_joint_feature_vector(
int32_t feat_idx, CStructuredData * y)
{
CSparseMultilabel * slabel = y->as<CSparseMultilabel>();
SGVector<int32_t> slabel_data = slabel->get_data();
SGVector<int32_t> label_vector = get_label_vector(slabel_data);
SGVector<float64_t> psi(get_dim());
psi.zero();
CDotFeatures * dot_feats = (CDotFeatures *)m_features;
SGVector<float64_t> x = dot_feats->get_computed_dot_feature_vector(feat_idx);
int32_t feats_dim = dot_feats->get_dim_feature_space();
for (index_t i = 0; i < label_vector.vlen; i++)
{
int32_t label = label_vector[i];
if (label)
{
int32_t offset = i * feats_dim;
for (index_t j = 0; j < feats_dim; j++)
{
psi[offset + j] = x[j];
}
}
}
return psi;
}
float64_t CHierarchicalMultilabelModel::delta_loss(CStructuredData * y1,
CStructuredData * y2)
{
CSparseMultilabel * y1_slabel = y1->as<CSparseMultilabel>();
CSparseMultilabel * y2_slabel = y2->as<CSparseMultilabel>();
ASSERT(y1_slabel != NULL);
ASSERT(y2_slabel != NULL);
return delta_loss(get_label_vector(y1_slabel->get_data()),
get_label_vector(y2_slabel->get_data()));
}
float64_t CHierarchicalMultilabelModel::delta_loss(SGVector<int32_t> y1,
SGVector<int32_t> y2)
{
REQUIRE(y1.vlen == y2.vlen, "Size of both the vectors should be same\n");
float64_t loss = 0;
for (index_t i = 0; i < y1.vlen; i++)
{
loss += delta_loss(y1[i], y2[i]);
}
return loss;
}
float64_t CHierarchicalMultilabelModel::delta_loss(int32_t y1, int32_t y2)
{
return y1 != y2 ? 1 : 0;
}
void CHierarchicalMultilabelModel::init_primal_opt(
float64_t regularization,
SGMatrix<float64_t> &A,
SGVector<float64_t> a,
SGMatrix<float64_t> B,
SGVector<float64_t> &b,
SGVector<float64_t> &lb,
SGVector<float64_t> &ub,
SGMatrix<float64_t> &C)
{
C = SGMatrix<float64_t>::create_identity_matrix(get_dim(), regularization);
}
CResultSet * CHierarchicalMultilabelModel::argmax(SGVector<float64_t> w,
int32_t feat_idx, bool const training)
{
CDotFeatures * dot_feats = (CDotFeatures *)m_features;
int32_t feats_dim = dot_feats->get_dim_feature_space();
CMultilabelSOLabels * multi_labs = (CMultilabelSOLabels *)m_labels;
if (training)
{
m_num_classes = multi_labs->get_num_classes();
}
REQUIRE(m_num_classes > 0, "The model needs to be trained before using "
"if for prediction\n");
int32_t dim = get_dim();
ASSERT(dim == w.vlen);
// nodes_to_traverse is a dynamic list which keep tracks of which nodes to
// traverse
CDynamicArray<int32_t> * nodes_to_traverse = new CDynamicArray<int32_t>();
SG_REF(nodes_to_traverse);
// start traversing with the root node
// insertion of node at the back end
nodes_to_traverse->push_back(m_root);
SGVector<int32_t> y_pred_sparse(m_num_classes);
int32_t count = 0;
while (nodes_to_traverse->get_num_elements())
{
// extraction of the node at the front end
int32_t node = nodes_to_traverse->get_element(0);
nodes_to_traverse->delete_element(0);
float64_t score = dot_feats->dense_dot(feat_idx, w.vector + node * feats_dim,
feats_dim);
// if the score is greater than zero, then all the children nodes are
// to be traversed next
if (score > 0)
{
SGVector<int32_t> child_id = m_children[node];
// inserting the children nodes at the back end
for (index_t i = 0; i < child_id.vlen; i++)
{
nodes_to_traverse->push_back(child_id[i]);
}
if (m_leaf_nodes_mandatory)
{
// terminal nodes don't have any children
if (child_id.vlen == 0)
{
y_pred_sparse[count++] = node;
}
}
else
{
y_pred_sparse[count++] = node;
}
}
}
y_pred_sparse.resize_vector(count);
CResultSet * ret = new CResultSet();
SG_REF(ret);
ret->psi_computed = true;
CSparseMultilabel * y_pred = new CSparseMultilabel(y_pred_sparse);
SG_REF(y_pred);
ret->psi_pred = get_joint_feature_vector(feat_idx, y_pred);
ret->score = linalg::dot(w, ret->psi_pred);
ret->argmax = y_pred;
if (training)
{
ret->delta = CStructuredModel::delta_loss(feat_idx, y_pred);
ret->psi_truth = CStructuredModel::get_joint_feature_vector(feat_idx,
feat_idx);
ret->score += (ret->delta - linalg::dot(w, ret->psi_truth));
}
SG_UNREF(nodes_to_traverse);
return ret;
}
| {
"content_hash": "1e8345fe77369729b5f1993cef5128ff",
"timestamp": "",
"source": "github",
"line_count": 296,
"max_line_length": 105,
"avg_line_length": 26.54054054054054,
"alnum_prop": 0.6563136456211812,
"repo_name": "sorig/shogun",
"id": "d111db157a3478cbe2eac9afb2cd7bab220a3be5",
"size": "8047",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src/shogun/structure/HierarchicalMultilabelModel.cpp",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "568"
},
{
"name": "C",
"bytes": "11644"
},
{
"name": "C++",
"bytes": "10500045"
},
{
"name": "CMake",
"bytes": "196913"
},
{
"name": "Dockerfile",
"bytes": "2423"
},
{
"name": "GDB",
"bytes": "89"
},
{
"name": "HTML",
"bytes": "3829"
},
{
"name": "MATLAB",
"bytes": "8755"
},
{
"name": "Makefile",
"bytes": "244"
},
{
"name": "Python",
"bytes": "284970"
},
{
"name": "Shell",
"bytes": "11995"
}
],
"symlink_target": ""
} |
package org.springframework.security.oauth2.provider.token.store;
import static org.junit.Assert.*;
import java.security.KeyPair;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.DefaultOAuth2RefreshToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.OAuth2Request;
import org.springframework.security.oauth2.provider.token.AccessTokenConverter;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;
/**
* @author Dave Syer
* @author Luke Taylor
*/
public class JwtAccessTokenConverterTests {
private JwtAccessTokenConverter tokenEnhancer;
private Authentication userAuthentication;
@Before
public void setUp() throws Exception {
tokenEnhancer = new JwtAccessTokenConverter();
userAuthentication = new TestAuthentication("test2", true);
}
@Test
public void testEnhanceAccessToken() {
OAuth2Authentication authentication = new OAuth2Authentication(createOAuth2Request("foo", null),
userAuthentication);
OAuth2AccessToken token = tokenEnhancer.enhance(new DefaultOAuth2AccessToken("FOO"), authentication);
assertNotNull(token.getValue());
assertEquals("FOO", token.getAdditionalInformation().get(AccessTokenConverter.JTI));
String claims = JwtHelper.decode(token.getValue()).getClaims();
assertTrue("Wrong claims: " + claims, claims.contains("\"" + AccessTokenConverter.JTI + "\""));
assertTrue("Wrong claims: " + claims, claims.contains("\"" + UserAuthenticationConverter.USERNAME + "\""));
}
@Test
public void testScopePreserved() {
OAuth2Authentication authentication = new OAuth2Authentication(createOAuth2Request("foo",
Collections.singleton("read")), userAuthentication);
DefaultOAuth2AccessToken original = new DefaultOAuth2AccessToken("FOO");
original.setScope(authentication.getOAuth2Request().getScope());
OAuth2AccessToken token = tokenEnhancer.enhance(original, authentication);
assertNotNull(token.getValue());
assertEquals(Collections.singleton("read"), token.getScope());
}
@Test
public void testRefreshTokenAdded() throws Exception {
OAuth2Authentication authentication = new OAuth2Authentication(createOAuth2Request("foo",
Collections.singleton("read")), userAuthentication);
DefaultOAuth2AccessToken original = new DefaultOAuth2AccessToken("FOO");
original.setScope(authentication.getOAuth2Request().getScope());
original.setRefreshToken(new DefaultOAuth2RefreshToken("BAR"));
OAuth2AccessToken token = tokenEnhancer.enhance(original, authentication);
assertNotNull(token.getValue());
assertNotNull(token.getRefreshToken());
String claims = JwtHelper.decode(token.getRefreshToken().getValue()).getClaims();
assertTrue("Wrong claims: " + claims, claims.contains("\"" + AccessTokenConverter.SCOPE + "\""));
tokenEnhancer.afterPropertiesSet();
assertTrue(tokenEnhancer.isRefreshToken(tokenEnhancer.extractAccessToken(token.getRefreshToken().getValue(),
tokenEnhancer.decode(token.getRefreshToken().getValue()))));
}
@Test
public void rsaKeyCreatesValidRsaSignedTokens() throws Exception {
String rsaKey = "-----BEGIN RSA PRIVATE KEY----- \n"
+ "MIIBywIBAAJhAOTeb4AZ+NwOtPh+ynIgGqa6UWNVe6JyJi+loPmPZdpHtzoqubnC \n"
+ "wEs6JSiSZ3rButEAw8ymgLV6iBY02hdjsl3h5Z0NWaxx8dzMZfXe4EpfB04ISoqq\n"
+ "hZCxchvuSDP4eQIDAQABAmEAqUuYsuuDWFRQrZgsbGsvC7G6zn3HLIy/jnM4NiJK\n"
+ "t0JhWNeN9skGsR7bqb1Sak2uWqW8ZqnqgAC32gxFRYHTavJEk6LTaHWovwDEhPqc\n"
+ "Zs+vXd6tZojJQ35chR/slUEBAjEA/sAd1oFLWb6PHkaz7r2NllwUBTvXL4VcMWTS\n"
+ "pN+5cU41i9fsZcHw6yZEl+ZCicDxAjEA5f3R+Bj42htNI7eylebew1+sUnFv1xT8\n"
+ "jlzxSzwVkoZo+vef7OD6OcFLeInAHzAJAjEAs6izolK+3ETa1CRSwz0lPHQlnmdM\n"
+ "Y/QuR5tuPt6U/saEVuJpkn4LNRtg5qt6I4JRAjAgFRYTG7irBB/wmZFp47izXEc3\n"
+ "gOdvA1hvq3tlWU5REDrYt24xpviA0fvrJpwMPbECMAKDKdiDi6Q4/iBkkzNMefA8\n"
+ "7HX27b9LR33don/1u/yvzMUo+lrRdKAFJ+9GPE9XFA== \n" + "-----END RSA PRIVATE KEY----- ";
tokenEnhancer.setSigningKey(rsaKey);
OAuth2Authentication authentication = new OAuth2Authentication(createOAuth2Request("foo", null),
userAuthentication);
OAuth2AccessToken token = tokenEnhancer.enhance(new DefaultOAuth2AccessToken("FOO"), authentication);
System.err.println(token.getValue());
JwtHelper.decodeAndVerify(token.getValue(), new RsaVerifier(rsaKey));
}
@Test
public void publicKeyStringIsReturnedFromTokenKeyEndpoint() throws Exception {
tokenEnhancer.setVerifierKey("-----BEGIN RSA PUBLIC KEY-----\n"
+ "MGgCYQDk3m+AGfjcDrT4fspyIBqmulFjVXuiciYvpaD5j2XaR7c6Krm5wsBLOiUo\n"
+ "kmd6wbrRAMPMpoC1eogWNNoXY7Jd4eWdDVmscfHczGX13uBKXwdOCEqKqoWQsXIb\n" + "7kgz+HkCAwEAAQ==\n"
+ "-----END RSA PUBLIC KEY-----");
tokenEnhancer.afterPropertiesSet();
Map<String, String> key = tokenEnhancer.getKey();
assertTrue("Wrong key: " + key, key.get("value").contains("-----BEGIN"));
}
@Test
public void publicKeyStringIsReturnedFromTokenKeyEndpointWithNullPrincipal() throws Exception {
tokenEnhancer.setVerifierKey("-----BEGIN RSA PUBLIC KEY-----\n"
+ "MGgCYQDk3m+AGfjcDrT4fspyIBqmulFjVXuiciYvpaD5j2XaR7c6Krm5wsBLOiUo\n"
+ "kmd6wbrRAMPMpoC1eogWNNoXY7Jd4eWdDVmscfHczGX13uBKXwdOCEqKqoWQsXIb\n" + "7kgz+HkCAwEAAQ==\n"
+ "-----END RSA PUBLIC KEY-----");
Map<String, String> key = tokenEnhancer.getKey();
assertTrue("Wrong key: " + key, key.get("value").contains("-----BEGIN"));
}
@Test
public void sharedSecretIsReturnedFromTokenKeyEndpoint() throws Exception {
tokenEnhancer.setVerifierKey("someKey");
assertEquals("{alg=HMACSHA256, value=someKey}", tokenEnhancer.getKey().toString());
}
@Test(expected = IllegalStateException.class)
public void keysNotMatchingWithMacSigner() throws Exception {
tokenEnhancer.setSigningKey("aKey");
tokenEnhancer.setVerifierKey("someKey");
tokenEnhancer.afterPropertiesSet();
}
@Test
public void rsaKeyPair() throws Exception {
KeyStoreKeyFactory factory = new KeyStoreKeyFactory(new ClassPathResource("keystore.jks"),
"foobar".toCharArray());
KeyPair keys = factory.getKeyPair("test");
tokenEnhancer.setKeyPair(keys);
tokenEnhancer.afterPropertiesSet();
assertTrue(tokenEnhancer.getKey().get("value").contains("BEGIN PUBLIC"));
}
@Test
public void publicKeyOnlyAllowedForVerification() throws Exception {
tokenEnhancer.setVerifierKey("-----BEGIN RSA PUBLIC KEY-----\n"
+ "MGgCYQDk3m+AGfjcDrT4fspyIBqmulFjVXuiciYvpaD5j2XaR7c6Krm5wsBLOiUo\n"
+ "kmd6wbrRAMPMpoC1eogWNNoXY7Jd4eWdDVmscfHczGX13uBKXwdOCEqKqoWQsXIb\n" + "7kgz+HkCAwEAAQ==\n"
+ "-----END RSA PUBLIC KEY-----");
tokenEnhancer.afterPropertiesSet();
tokenEnhancer
.decode("eyJhbGciOiJSUzI1NiJ9.eyJ1c2VyX25hbWUiOiJ0ZXN0MiIsImp0aSI6IkZPTyIsImNsaWVudF9pZCI6ImZvbyJ9.b43ob1ALSIwr_J2oEnfMhsXvYkr1qVBNhigNH2zlaE1OQLhLfT-DMlFtHcyUlyap0C2n0q61SPaGE_z715TV0uTAv2YKDN4fKZz2bMR7eHLsvaaCuvs7KCOi_aSROaUG");
Map<String, String> key = tokenEnhancer.getKey();
assertTrue("Wrong key: " + key, key.get("value").contains("-----BEGIN"));
}
private OAuth2Request createOAuth2Request(String clientId, Set<String> scope) {
return new OAuth2Request(Collections.<String, String> emptyMap(), clientId, null, true, scope, null, null,
null, null);
}
protected static class TestAuthentication extends AbstractAuthenticationToken {
private static final long serialVersionUID = 1L;
private String principal;
public TestAuthentication(String name, boolean authenticated) {
super(null);
setAuthenticated(authenticated);
this.principal = name;
}
public Object getCredentials() {
return null;
}
public Object getPrincipal() {
return this.principal;
}
}
}
| {
"content_hash": "7f68bfd63b309a3fcc62903228e7d880",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 234,
"avg_line_length": 44.043010752688176,
"alnum_prop": 0.783203125,
"repo_name": "ahmadOwais/spring-security-oauth",
"id": "137e102072fcce9e084a45b4d60be31a2e8cf97e",
"size": "8698",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spring-security-oauth2/src/test/java/org/springframework/security/oauth2/provider/token/store/JwtAccessTokenConverterTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2052406"
}
],
"symlink_target": ""
} |
package main_test
import (
"cmd/go/internal/script"
"cmd/go/internal/script/scripttest"
"cmd/go/internal/work"
"errors"
"fmt"
"os"
"os/exec"
"strings"
"time"
)
func scriptCommands(interrupt os.Signal, waitDelay time.Duration) map[string]script.Cmd {
cmds := scripttest.DefaultCmds()
// Customize the "exec" interrupt signal and grace period.
var cancel func(cmd *exec.Cmd) error
if interrupt != nil {
cancel = func(cmd *exec.Cmd) error {
return cmd.Process.Signal(interrupt)
}
}
cmdExec := script.Exec(cancel, waitDelay)
cmds["exec"] = cmdExec
add := func(name string, cmd script.Cmd) {
if _, ok := cmds[name]; ok {
panic(fmt.Sprintf("command %q is already registered", name))
}
cmds[name] = cmd
}
add("cc", scriptCC(cmdExec))
cmdGo := scriptGo(cancel, waitDelay)
add("go", cmdGo)
add("stale", scriptStale(cmdGo))
return cmds
}
// scriptCC runs the C compiler along with platform specific options.
func scriptCC(cmdExec script.Cmd) script.Cmd {
return script.Command(
script.CmdUsage{
Summary: "run the platform C compiler",
Args: "args...",
},
func(s *script.State, args ...string) (script.WaitFunc, error) {
b := work.NewBuilder(s.Getwd())
wait, err := cmdExec.Run(s, append(b.GccCmd(".", ""), args...)...)
if err != nil {
return wait, err
}
waitAndClean := func(s *script.State) (stdout, stderr string, err error) {
stdout, stderr, err = wait(s)
if closeErr := b.Close(); err == nil {
err = closeErr
}
return stdout, stderr, err
}
return waitAndClean, nil
})
}
// scriptGo runs the go command.
func scriptGo(cancel func(*exec.Cmd) error, waitDelay time.Duration) script.Cmd {
return script.Program(testGo, cancel, waitDelay)
}
// scriptStale checks that the named build targets are stale.
func scriptStale(cmdGo script.Cmd) script.Cmd {
return script.Command(
script.CmdUsage{
Summary: "check that build targets are stale",
Args: "target...",
},
func(s *script.State, args ...string) (script.WaitFunc, error) {
if len(args) == 0 {
return nil, script.ErrUsage
}
tmpl := "{{if .Error}}{{.ImportPath}}: {{.Error.Err}}" +
"{{else}}{{if not .Stale}}{{.ImportPath}} ({{.Target}}) is not stale{{end}}" +
"{{end}}"
wait, err := cmdGo.Run(s, append([]string{"list", "-e", "-f=" + tmpl}, args...)...)
if err != nil {
return nil, err
}
stdout, stderr, err := wait(s)
if len(stderr) != 0 {
s.Logf("%s", stderr)
}
if err != nil {
return nil, err
}
if out := strings.TrimSpace(stdout); out != "" {
return nil, errors.New(out)
}
return nil, nil
})
}
| {
"content_hash": "5a5ab5ff61a92112d2c9d4ac7d85f78f",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 89,
"avg_line_length": 25.16190476190476,
"alnum_prop": 0.6305828917486752,
"repo_name": "golang/go",
"id": "db5e6cafdafe51d5a94f97e0841f1c3e9fa62a27",
"size": "2802",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/cmd/go/scriptcmds_test.go",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Assembly",
"bytes": "2705689"
},
{
"name": "Awk",
"bytes": "450"
},
{
"name": "Batchfile",
"bytes": "8497"
},
{
"name": "C",
"bytes": "127970"
},
{
"name": "C++",
"bytes": "917"
},
{
"name": "Dockerfile",
"bytes": "2789"
},
{
"name": "Fortran",
"bytes": "100"
},
{
"name": "Go",
"bytes": "41103717"
},
{
"name": "HTML",
"bytes": "2621340"
},
{
"name": "JavaScript",
"bytes": "20492"
},
{
"name": "Makefile",
"bytes": "748"
},
{
"name": "Perl",
"bytes": "31365"
},
{
"name": "Python",
"bytes": "15738"
},
{
"name": "Shell",
"bytes": "62900"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="10dp"
android:focusable="true"
android:focusableInTouchMode="true"
android:gravity="center_vertical"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="检测人:"
android:textSize="@dimen/size_little"
android:textStyle="bold"/>
<EditText
android:id="@+id/testperson"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="50dp"
android:layout_weight="1"
android:background="@drawable/btntestmsgesamplename_selector"
android:padding="10dp"
android:textColor="@color/maincolor"
android:textSize="@dimen/size_little"/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="检测单位:"
android:textSize="@dimen/size_little"
android:textStyle="bold"/>
<EditText
android:id="@+id/testunit"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="50dp"
android:layout_weight="1"
android:background="@drawable/btntestmsgesamplename_selector"
android:padding="10dp"
android:textColor="@color/maincolor"
android:textSize="@dimen/size_little"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="检测日期:"
android:textColor="@android:color/darker_gray"
android:textSize="@dimen/size_little"/>
<TextView
android:id="@+id/testtime"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_weight="1"
android:padding="10dp"
android:textColor="@android:color/darker_gray"
android:textSize="@dimen/size_little"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="15dp"
android:layout_weight="1"
android:background="@drawable/btntestmsgesamplename_selector"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/img_itemunchoosed"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="0.5"
android:text="@string/num"
android:textSize="@dimen/size_little"
android:textStyle="bold"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="@string/testitem"
android:textSize="@dimen/size_little"
android:textStyle="bold"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="@string/sample_type"
android:textSize="@dimen/size_little"
android:textStyle="bold"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="@string/sample_name"
android:textSize="@dimen/size_little"
android:textStyle="bold"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="@string/test_result"
android:textSize="@dimen/size_little"
android:textStyle="bold"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="@string/limit_standard"
android:textSize="@dimen/size_little"
android:textStyle="bold"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="@string/unit"
android:textSize="@dimen/size_little"
android:textStyle="bold"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="@string/judge_result"
android:textSize="@dimen/size_little"
android:textStyle="bold"/>
</LinearLayout>
<ListView
android:id="@+id/resultlist"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginLeft="10dp"
android:layout_weight="1"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:gravity="center_vertical"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="@+id/save"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:background="@drawable/btn_bg_selector"
android:clickable="true"
android:gravity="center"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:text="@string/save"
android:textColor="@android:color/white"
android:textSize="@dimen/size_little"/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="@+id/newtest"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:background="@drawable/btn_bg_selector"
android:clickable="true"
android:gravity="center"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:text="@string/newtest"
android:textColor="@android:color/white"
android:textSize="@dimen/size_little"/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="@+id/print"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:background="@drawable/btn_bg_selector"
android:clickable="true"
android:gravity="center"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:text="@string/print"
android:textColor="@android:color/white"
android:textSize="@dimen/size_little"/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="@+id/updata"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:background="@drawable/btn_bg_selector"
android:clickable="true"
android:gravity="center"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:text="@string/updata"
android:textColor="@android:color/white"
android:textSize="@dimen/size_little"/>
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:orientation="horizontal"
android:visibility="gone">
<TextView
android:id="@+id/checkforms"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:background="@drawable/btn_bg_selector"
android:clickable="true"
android:gravity="center"
android:paddingBottom="5dp"
android:paddingTop="5dp"
android:text="@string/check_forms"
android:textColor="@android:color/white"
android:textSize="@dimen/size_little"/>
</LinearLayout>
</LinearLayout>
</LinearLayout> | {
"content_hash": "7955fc72fd8206eabd2a36599e8ef07d",
"timestamp": "",
"source": "github",
"line_count": 312,
"max_line_length": 77,
"avg_line_length": 38.1025641025641,
"alnum_prop": 0.5397880215343204,
"repo_name": "kydiwen/GeneralFoodSafe",
"id": "a8397f01db4adf41ff322064a1b9e9fcaa06e825",
"size": "11910",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/main/res/layout/controller_specshowresult.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "8314"
},
{
"name": "Batchfile",
"bytes": "8390"
},
{
"name": "C",
"bytes": "3551111"
},
{
"name": "C++",
"bytes": "689595"
},
{
"name": "CMake",
"bytes": "3758"
},
{
"name": "CSS",
"bytes": "6320"
},
{
"name": "HTML",
"bytes": "5561"
},
{
"name": "Java",
"bytes": "2683192"
},
{
"name": "M4",
"bytes": "21511"
},
{
"name": "Makefile",
"bytes": "484906"
},
{
"name": "Module Management System",
"bytes": "13679"
},
{
"name": "Roff",
"bytes": "35409"
},
{
"name": "SAS",
"bytes": "14183"
},
{
"name": "Shell",
"bytes": "345756"
},
{
"name": "Smalltalk",
"bytes": "5908"
},
{
"name": "WebAssembly",
"bytes": "13987"
}
],
"symlink_target": ""
} |
/* $Id: getopt.cpp $ */
/** @file
* IPRT - Command Line Parsing
*/
/*
* Copyright (C) 2007-2015 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* you can redistribute it and/or modify it under the terms of the GNU
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*
* The contents of this file may alternatively be used under the terms
* of the Common Development and Distribution License Version 1.0
* (CDDL) only, as it comes in the "COPYING.CDDL" file of the
* VirtualBox OSE distribution, in which case the provisions of the
* CDDL are applicable instead of those of the GPL.
*
* You may elect to license modified versions of this file under the
* terms and conditions of either the GPL or the CDDL or both.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#include <iprt/cidr.h>
#include <iprt/net.h> /* must come before getopt.h */
#include <iprt/getopt.h>
#include "internal/iprt.h"
#include <iprt/assert.h>
#include <iprt/ctype.h>
#include <iprt/err.h>
#include <iprt/message.h>
#include <iprt/string.h>
#include <iprt/uuid.h>
/*******************************************************************************
* Global Variables *
*******************************************************************************/
/**
* Standard options that gets included unless RTGETOPTINIT_FLAGS_NO_STD_OPTS is
* set.
*/
static RTGETOPTDEF const g_aStdOptions[] =
{
{ "--help", 'h', RTGETOPT_REQ_NOTHING },
{ "-help", 'h', RTGETOPT_REQ_NOTHING },
{ "--version", 'V', RTGETOPT_REQ_NOTHING },
{ "-version", 'V', RTGETOPT_REQ_NOTHING },
};
/** The index of --help in g_aStdOptions. Used for some trickery. */
#define RTGETOPT_STD_OPTIONS_HELP_IDX 0
RTDECL(int) RTGetOptInit(PRTGETOPTSTATE pState, int argc, char **argv,
PCRTGETOPTDEF paOptions, size_t cOptions,
int iFirst, uint32_t fFlags)
{
AssertReturn(!(fFlags & ~(RTGETOPTINIT_FLAGS_OPTS_FIRST | RTGETOPTINIT_FLAGS_NO_STD_OPTS)), VERR_INVALID_PARAMETER);
pState->argv = argv;
pState->argc = argc;
pState->paOptions = paOptions;
pState->cOptions = cOptions;
pState->iNext = iFirst;
pState->pszNextShort = NULL;
pState->pDef = NULL;
pState->uIndex = UINT32_MAX;
pState->fFlags = fFlags;
pState->cNonOptions = 0;
/* validate the options. */
for (size_t i = 0; i < cOptions; i++)
{
Assert(!(paOptions[i].fFlags & ~RTGETOPT_VALID_MASK));
Assert(paOptions[i].iShort > 0);
Assert(paOptions[i].iShort != VINF_GETOPT_NOT_OPTION);
Assert(paOptions[i].iShort != '-');
}
return VINF_SUCCESS;
}
RT_EXPORT_SYMBOL(RTGetOptInit);
/**
* Converts an stringified IPv4 address into the RTNETADDRIPV4 representation.
*
* @returns VINF_SUCCESS on success, VERR_GETOPT_INVALID_ARGUMENT_FORMAT on
* failure.
*
* @param pszValue The value to convert.
* @param pAddr Where to store the result.
*/
static int rtgetoptConvertIPv4Addr(const char *pszValue, PRTNETADDRIPV4 pAddr)
{
if (RT_FAILURE(RTNetStrToIPv4Addr(pszValue, pAddr)))
return VERR_GETOPT_INVALID_ARGUMENT_FORMAT;
return VINF_SUCCESS;
}
/**
* Converts an stringified Ethernet MAC address into the RTMAC representation.
*
* @returns VINF_SUCCESS on success, VERR_GETOPT_INVALID_ARGUMENT_FORMAT on
* failure.
*
* @param pszValue The value to convert.
* @param pAddr Where to store the result.
*/
static int rtgetoptConvertMacAddr(const char *pszValue, PRTMAC pAddr)
{
int rc = RTNetStrToMacAddr(pszValue, pAddr);
if (RT_FAILURE(rc))
return VERR_GETOPT_INVALID_ARGUMENT_FORMAT;
return VINF_SUCCESS;
}
/**
* Searches for a long option.
*
* @returns Pointer to a matching option.
* @param pszOption The alleged long option.
* @param paOptions Option array.
* @param cOptions Number of items in the array.
* @param fFlags Init flags.
*/
static PCRTGETOPTDEF rtGetOptSearchLong(const char *pszOption, PCRTGETOPTDEF paOptions, size_t cOptions, uint32_t fFlags)
{
PCRTGETOPTDEF pOpt = paOptions;
while (cOptions-- > 0)
{
if (pOpt->pszLong)
{
if ((pOpt->fFlags & RTGETOPT_REQ_MASK) != RTGETOPT_REQ_NOTHING)
{
/*
* A value is required with the argument. We're trying to be
* understanding here and will permit any of the following:
* --long12:value, --long12=value, --long12 value,
* --long:value, --long=value, --long value,
*
* If the option is index, then all trailing chars must be
* digits. For error reporting reasons we also match where
* there is no index.
*/
size_t cchLong = strlen(pOpt->pszLong);
if ( !strncmp(pszOption, pOpt->pszLong, cchLong)
|| ( pOpt->fFlags & RTGETOPT_FLAG_ICASE
&& !RTStrNICmp(pszOption, pOpt->pszLong, cchLong)))
{
if (pOpt->fFlags & RTGETOPT_FLAG_INDEX)
while (RT_C_IS_DIGIT(pszOption[cchLong]))
cchLong++;
if ( pszOption[cchLong] == '\0'
|| pszOption[cchLong] == ':'
|| pszOption[cchLong] == '=')
return pOpt;
}
}
else if (pOpt->fFlags & RTGETOPT_FLAG_INDEX)
{
/*
* The option takes an index but no value.
* As above, we also match where there is no index.
*/
size_t cchLong = strlen(pOpt->pszLong);
if ( !strncmp(pszOption, pOpt->pszLong, cchLong)
|| ( pOpt->fFlags & RTGETOPT_FLAG_ICASE
&& !RTStrNICmp(pszOption, pOpt->pszLong, cchLong)))
{
while (RT_C_IS_DIGIT(pszOption[cchLong]))
cchLong++;
if (pszOption[cchLong] == '\0')
return pOpt;
}
}
else if ( !strcmp(pszOption, pOpt->pszLong)
|| ( pOpt->fFlags & RTGETOPT_FLAG_ICASE
&& !RTStrICmp(pszOption, pOpt->pszLong)))
return pOpt;
}
pOpt++;
}
if (!(fFlags & RTGETOPTINIT_FLAGS_NO_STD_OPTS))
for (uint32_t i = 0; i < RT_ELEMENTS(g_aStdOptions); i++)
if ( !strcmp(pszOption, g_aStdOptions[i].pszLong)
|| ( g_aStdOptions[i].fFlags & RTGETOPT_FLAG_ICASE
&& !RTStrICmp(pszOption, g_aStdOptions[i].pszLong)))
return &g_aStdOptions[i];
return NULL;
}
/**
* Searches for a matching short option.
*
* @returns Pointer to a matching option.
* @param chOption The option char.
* @param paOptions Option array.
* @param cOptions Number of items in the array.
* @param fFlags Init flags.
*/
static PCRTGETOPTDEF rtGetOptSearchShort(int chOption, PCRTGETOPTDEF paOptions, size_t cOptions, uint32_t fFlags)
{
PCRTGETOPTDEF pOpt = paOptions;
while (cOptions-- > 0)
{
if (pOpt->iShort == chOption)
return pOpt;
pOpt++;
}
if (!(fFlags & RTGETOPTINIT_FLAGS_NO_STD_OPTS))
{
for (uint32_t i = 0; i < RT_ELEMENTS(g_aStdOptions); i++)
if (g_aStdOptions[i].iShort == chOption)
return &g_aStdOptions[i];
if (chOption == '?')
return &g_aStdOptions[RTGETOPT_STD_OPTIONS_HELP_IDX];
}
return NULL;
}
/**
* Value string -> Value union.
*
* @returns IPRT status code.
* @param fFlags The value flags.
* @param pszValue The value string.
* @param pValueUnion Where to return the processed value.
*/
static int rtGetOptProcessValue(uint32_t fFlags, const char *pszValue, PRTGETOPTUNION pValueUnion)
{
/*
* Transform into a option value as requested.
* If decimal conversion fails, we'll check for "0x<xdigit>" and
* try a 16 based conversion. We will not interpret any of the
* generic ints as octals.
*/
switch (fFlags & ( RTGETOPT_REQ_MASK
| RTGETOPT_FLAG_HEX
| RTGETOPT_FLAG_DEC
| RTGETOPT_FLAG_OCT))
{
case RTGETOPT_REQ_STRING:
pValueUnion->psz = pszValue;
break;
case RTGETOPT_REQ_BOOL:
if ( !RTStrICmp(pszValue, "true")
|| !RTStrICmp(pszValue, "t")
|| !RTStrICmp(pszValue, "yes")
|| !RTStrICmp(pszValue, "y")
|| !RTStrICmp(pszValue, "enabled")
|| !RTStrICmp(pszValue, "enable")
|| !RTStrICmp(pszValue, "en")
|| !RTStrICmp(pszValue, "e")
|| !RTStrICmp(pszValue, "on")
|| !RTStrCmp(pszValue, "1")
)
pValueUnion->f = true;
else if ( !RTStrICmp(pszValue, "false")
|| !RTStrICmp(pszValue, "f")
|| !RTStrICmp(pszValue, "no")
|| !RTStrICmp(pszValue, "n")
|| !RTStrICmp(pszValue, "disabled")
|| !RTStrICmp(pszValue, "disable")
|| !RTStrICmp(pszValue, "dis")
|| !RTStrICmp(pszValue, "d")
|| !RTStrICmp(pszValue, "off")
|| !RTStrCmp(pszValue, "0")
)
pValueUnion->f = false;
else
{
pValueUnion->psz = pszValue;
return VERR_GETOPT_UNKNOWN_OPTION;
}
break;
case RTGETOPT_REQ_BOOL_ONOFF:
if (!RTStrICmp(pszValue, "on"))
pValueUnion->f = true;
else if (!RTStrICmp(pszValue, "off"))
pValueUnion->f = false;
else
{
pValueUnion->psz = pszValue;
return VERR_GETOPT_UNKNOWN_OPTION;
}
break;
#define MY_INT_CASE(req, type, memb, convfn) \
case req: \
{ \
type Value; \
if ( convfn(pszValue, 10, &Value) != VINF_SUCCESS \
&& ( pszValue[0] != '0' \
|| (pszValue[1] != 'x' && pszValue[1] != 'X') \
|| !RT_C_IS_XDIGIT(pszValue[2]) \
|| convfn(pszValue, 16, &Value) != VINF_SUCCESS ) ) \
return VERR_GETOPT_INVALID_ARGUMENT_FORMAT; \
pValueUnion->memb = Value; \
break; \
}
#define MY_BASE_INT_CASE(req, type, memb, convfn, base) \
case req: \
{ \
type Value; \
if (convfn(pszValue, base, &Value) != VINF_SUCCESS) \
return VERR_GETOPT_INVALID_ARGUMENT_FORMAT; \
pValueUnion->memb = Value; \
break; \
}
MY_INT_CASE(RTGETOPT_REQ_INT8, int8_t, i8, RTStrToInt8Full)
MY_INT_CASE(RTGETOPT_REQ_INT16, int16_t, i16, RTStrToInt16Full)
MY_INT_CASE(RTGETOPT_REQ_INT32, int32_t, i32, RTStrToInt32Full)
MY_INT_CASE(RTGETOPT_REQ_INT64, int64_t, i64, RTStrToInt64Full)
MY_INT_CASE(RTGETOPT_REQ_UINT8, uint8_t, u8, RTStrToUInt8Full)
MY_INT_CASE(RTGETOPT_REQ_UINT16, uint16_t, u16, RTStrToUInt16Full)
MY_INT_CASE(RTGETOPT_REQ_UINT32, uint32_t, u32, RTStrToUInt32Full)
MY_INT_CASE(RTGETOPT_REQ_UINT64, uint64_t, u64, RTStrToUInt64Full)
MY_BASE_INT_CASE(RTGETOPT_REQ_INT8 | RTGETOPT_FLAG_HEX, int8_t, i8, RTStrToInt8Full, 16)
MY_BASE_INT_CASE(RTGETOPT_REQ_INT16 | RTGETOPT_FLAG_HEX, int16_t, i16, RTStrToInt16Full, 16)
MY_BASE_INT_CASE(RTGETOPT_REQ_INT32 | RTGETOPT_FLAG_HEX, int32_t, i32, RTStrToInt32Full, 16)
MY_BASE_INT_CASE(RTGETOPT_REQ_INT64 | RTGETOPT_FLAG_HEX, int64_t, i64, RTStrToInt64Full, 16)
MY_BASE_INT_CASE(RTGETOPT_REQ_UINT8 | RTGETOPT_FLAG_HEX, uint8_t, u8, RTStrToUInt8Full, 16)
MY_BASE_INT_CASE(RTGETOPT_REQ_UINT16 | RTGETOPT_FLAG_HEX, uint16_t, u16, RTStrToUInt16Full, 16)
MY_BASE_INT_CASE(RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_HEX, uint32_t, u32, RTStrToUInt32Full, 16)
MY_BASE_INT_CASE(RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_HEX, uint64_t, u64, RTStrToUInt64Full, 16)
MY_BASE_INT_CASE(RTGETOPT_REQ_INT8 | RTGETOPT_FLAG_DEC, int8_t, i8, RTStrToInt8Full, 10)
MY_BASE_INT_CASE(RTGETOPT_REQ_INT16 | RTGETOPT_FLAG_DEC, int16_t, i16, RTStrToInt16Full, 10)
MY_BASE_INT_CASE(RTGETOPT_REQ_INT32 | RTGETOPT_FLAG_DEC, int32_t, i32, RTStrToInt32Full, 10)
MY_BASE_INT_CASE(RTGETOPT_REQ_INT64 | RTGETOPT_FLAG_DEC, int64_t, i64, RTStrToInt64Full, 10)
MY_BASE_INT_CASE(RTGETOPT_REQ_UINT8 | RTGETOPT_FLAG_DEC, uint8_t, u8, RTStrToUInt8Full, 10)
MY_BASE_INT_CASE(RTGETOPT_REQ_UINT16 | RTGETOPT_FLAG_DEC, uint16_t, u16, RTStrToUInt16Full, 10)
MY_BASE_INT_CASE(RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_DEC, uint32_t, u32, RTStrToUInt32Full, 10)
MY_BASE_INT_CASE(RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_DEC, uint64_t, u64, RTStrToUInt64Full, 10)
MY_BASE_INT_CASE(RTGETOPT_REQ_INT8 | RTGETOPT_FLAG_OCT, int8_t, i8, RTStrToInt8Full, 8)
MY_BASE_INT_CASE(RTGETOPT_REQ_INT16 | RTGETOPT_FLAG_OCT, int16_t, i16, RTStrToInt16Full, 8)
MY_BASE_INT_CASE(RTGETOPT_REQ_INT32 | RTGETOPT_FLAG_OCT, int32_t, i32, RTStrToInt32Full, 8)
MY_BASE_INT_CASE(RTGETOPT_REQ_INT64 | RTGETOPT_FLAG_OCT, int64_t, i64, RTStrToInt64Full, 8)
MY_BASE_INT_CASE(RTGETOPT_REQ_UINT8 | RTGETOPT_FLAG_OCT, uint8_t, u8, RTStrToUInt8Full, 8)
MY_BASE_INT_CASE(RTGETOPT_REQ_UINT16 | RTGETOPT_FLAG_OCT, uint16_t, u16, RTStrToUInt16Full, 8)
MY_BASE_INT_CASE(RTGETOPT_REQ_UINT32 | RTGETOPT_FLAG_OCT, uint32_t, u32, RTStrToUInt32Full, 8)
MY_BASE_INT_CASE(RTGETOPT_REQ_UINT64 | RTGETOPT_FLAG_OCT, uint64_t, u64, RTStrToUInt64Full, 8)
#undef MY_INT_CASE
#undef MY_BASE_INT_CASE
case RTGETOPT_REQ_IPV4ADDR:
{
RTNETADDRIPV4 Addr;
if (rtgetoptConvertIPv4Addr(pszValue, &Addr) != VINF_SUCCESS)
return VERR_GETOPT_INVALID_ARGUMENT_FORMAT;
pValueUnion->IPv4Addr = Addr;
break;
}
case RTGETOPT_REQ_IPV4CIDR:
{
RTNETADDRIPV4 network;
RTNETADDRIPV4 netmask;
if (RT_FAILURE(RTCidrStrToIPv4(pszValue, &network, &netmask)))
return VERR_GETOPT_INVALID_ARGUMENT_FORMAT;
pValueUnion->CidrIPv4.IPv4Network.u = network.u;
pValueUnion->CidrIPv4.IPv4Netmask.u = netmask.u;
break;
}
case RTGETOPT_REQ_MACADDR:
{
RTMAC Addr;
if (rtgetoptConvertMacAddr(pszValue, &Addr) != VINF_SUCCESS)
return VERR_GETOPT_INVALID_ARGUMENT_FORMAT;
pValueUnion->MacAddr = Addr;
break;
}
case RTGETOPT_REQ_UUID:
{
RTUUID Uuid;
if (RTUuidFromStr(&Uuid, pszValue) != VINF_SUCCESS)
return VERR_GETOPT_INVALID_ARGUMENT_FORMAT;
pValueUnion->Uuid = Uuid;
break;
}
default:
AssertMsgFailed(("f=%#x\n", fFlags));
return VERR_INTERNAL_ERROR;
}
return VINF_SUCCESS;
}
/**
* Moves one argv option entries.
*
* @param papszTo Destination.
* @param papszFrom Source.
*/
static void rtGetOptMoveArgvEntries(char **papszTo, char **papszFrom)
{
if (papszTo != papszFrom)
{
Assert((uintptr_t)papszTo < (uintptr_t)papszFrom);
char * const pszMoved = papszFrom[0];
memmove(&papszTo[1], &papszTo[0], (uintptr_t)papszFrom - (uintptr_t)papszTo);
papszTo[0] = pszMoved;
}
}
RTDECL(int) RTGetOpt(PRTGETOPTSTATE pState, PRTGETOPTUNION pValueUnion)
{
/*
* Reset the variables kept in state.
*/
pState->pDef = NULL;
pState->uIndex = UINT32_MAX;
/*
* Make sure the union is completely cleared out, whatever happens below.
*/
pValueUnion->u64 = 0;
pValueUnion->pDef = NULL;
/*
* The next option.
*/
bool fShort;
int iThis;
const char *pszArgThis;
PCRTGETOPTDEF pOpt;
if (pState->pszNextShort)
{
/*
* We've got short options left over from the previous call.
*/
pOpt = rtGetOptSearchShort(*pState->pszNextShort, pState->paOptions, pState->cOptions, pState->fFlags);
if (!pOpt)
{
pValueUnion->psz = pState->pszNextShort;
return VERR_GETOPT_UNKNOWN_OPTION;
}
pState->pszNextShort++;
pszArgThis = pState->pszNextShort - 2;
iThis = pState->iNext;
fShort = true;
}
else
{
/*
* Pop off the next argument. Sorting options and dealing with the
* dash-dash makes this a little extra complicated.
*/
for (;;)
{
if (pState->iNext >= pState->argc)
return 0;
if (pState->cNonOptions)
{
if (pState->cNonOptions == INT32_MAX)
{
pValueUnion->psz = pState->argv[pState->iNext++];
return VINF_GETOPT_NOT_OPTION;
}
if (pState->iNext + pState->cNonOptions >= pState->argc)
{
pState->cNonOptions = INT32_MAX;
continue;
}
}
iThis = pState->iNext++;
pszArgThis = pState->argv[iThis + pState->cNonOptions];
/*
* Do a long option search first and then a short option one.
* This way we can make sure single dash long options doesn't
* get mixed up with short ones.
*/
pOpt = rtGetOptSearchLong(pszArgThis, pState->paOptions, pState->cOptions, pState->fFlags);
if ( !pOpt
&& pszArgThis[0] == '-'
&& pszArgThis[1] != '-'
&& pszArgThis[1] != '\0')
{
pOpt = rtGetOptSearchShort(pszArgThis[1], pState->paOptions, pState->cOptions, pState->fFlags);
fShort = pOpt != NULL;
}
else
fShort = false;
/* Look for dash-dash. */
if (!pOpt && !strcmp(pszArgThis, "--"))
{
rtGetOptMoveArgvEntries(&pState->argv[iThis], &pState->argv[iThis + pState->cNonOptions]);
pState->cNonOptions = INT32_MAX;
continue;
}
/* Options first hacks. */
if (pState->fFlags & RTGETOPTINIT_FLAGS_OPTS_FIRST)
{
if (pOpt)
rtGetOptMoveArgvEntries(&pState->argv[iThis], &pState->argv[iThis + pState->cNonOptions]);
else if (*pszArgThis == '-')
{
pValueUnion->psz = pszArgThis;
return VERR_GETOPT_UNKNOWN_OPTION;
}
else
{
/* not an option, add it to the non-options and try again. */
pState->iNext--;
pState->cNonOptions++;
/* Switch to returning non-options if we've reached the end. */
if (pState->iNext + pState->cNonOptions >= pState->argc)
pState->cNonOptions = INT32_MAX;
continue;
}
}
/* done */
break;
}
}
if (pOpt)
{
pValueUnion->pDef = pOpt; /* in case of no value or error. */
if ((pOpt->fFlags & RTGETOPT_REQ_MASK) != RTGETOPT_REQ_NOTHING)
{
/*
* Find the argument value.
*
* A value is required with the argument. We're trying to be
* understanding here and will permit any of the following:
* -svalue, -s value, -s:value and -s=value
* (Ditto for long options.)
*/
const char *pszValue;
if (fShort)
{
if (pszArgThis[2] == '\0')
{
if (iThis + 1 >= pState->argc)
return VERR_GETOPT_REQUIRED_ARGUMENT_MISSING;
pszValue = pState->argv[iThis + pState->cNonOptions + 1];
rtGetOptMoveArgvEntries(&pState->argv[iThis + 1], &pState->argv[iThis + pState->cNonOptions + 1]);
pState->iNext++;
}
else /* same argument. */
pszValue = &pszArgThis[2 + (pszArgThis[2] == ':' || pszArgThis[2] == '=')];
if (pState->pszNextShort)
{
pState->pszNextShort = NULL;
pState->iNext++;
}
}
else
{
size_t cchLong = strlen(pOpt->pszLong);
if (pOpt->fFlags & RTGETOPT_FLAG_INDEX)
{
if (pszArgThis[cchLong] == '\0')
return VERR_GETOPT_INDEX_MISSING;
uint32_t uIndex;
char *pszRet = NULL;
int rc = RTStrToUInt32Ex(&pszArgThis[cchLong], &pszRet, 10, &uIndex);
if (rc == VWRN_TRAILING_CHARS)
{
if ( pszRet[0] != ':'
&& pszRet[0] != '=')
return VERR_GETOPT_INVALID_ARGUMENT_FORMAT;
pState->uIndex = uIndex;
pszValue = pszRet + 1;
}
else if (rc == VINF_SUCCESS)
{
if (iThis + 1 >= pState->argc)
return VERR_GETOPT_REQUIRED_ARGUMENT_MISSING;
pState->uIndex = uIndex;
pszValue = pState->argv[iThis + pState->cNonOptions + 1];
rtGetOptMoveArgvEntries(&pState->argv[iThis + 1], &pState->argv[iThis + pState->cNonOptions + 1]);
pState->iNext++;
}
else
AssertMsgFailedReturn(("%s\n", pszArgThis), VERR_GETOPT_INVALID_ARGUMENT_FORMAT); /* search bug */
}
else
{
if (pszArgThis[cchLong] == '\0')
{
if (iThis + 1 >= pState->argc)
return VERR_GETOPT_REQUIRED_ARGUMENT_MISSING;
pszValue = pState->argv[iThis + pState->cNonOptions + 1];
rtGetOptMoveArgvEntries(&pState->argv[iThis + 1], &pState->argv[iThis + pState->cNonOptions + 1]);
pState->iNext++;
}
else /* same argument. */
pszValue = &pszArgThis[cchLong + 1];
}
}
/*
* Set up the ValueUnion.
*/
int rc = rtGetOptProcessValue(pOpt->fFlags, pszValue, pValueUnion);
if (RT_FAILURE(rc))
return rc;
}
else if (fShort)
{
/*
* Deal with "compressed" short option lists, correcting the next
* state variables for the start and end cases.
*/
if (pszArgThis[2])
{
if (!pState->pszNextShort)
{
/* start */
pState->pszNextShort = &pszArgThis[2];
pState->iNext--;
}
}
else if (pState->pszNextShort)
{
/* end */
pState->pszNextShort = NULL;
pState->iNext++;
}
}
else if (pOpt->fFlags & RTGETOPT_FLAG_INDEX)
{
size_t cchLong = strlen(pOpt->pszLong);
if (pszArgThis[cchLong] == '\0')
return VERR_GETOPT_INDEX_MISSING;
uint32_t uIndex;
if (RTStrToUInt32Full(&pszArgThis[cchLong], 10, &uIndex) == VINF_SUCCESS)
pState->uIndex = uIndex;
else
AssertMsgFailedReturn(("%s\n", pszArgThis), VERR_GETOPT_INVALID_ARGUMENT_FORMAT); /* search bug */
}
pState->pDef = pOpt;
return pOpt->iShort;
}
/*
* Not a known option argument. If it starts with a switch char (-) we'll
* fail with unknown option, and if it doesn't we'll return it as a non-option.
*/
if (*pszArgThis == '-')
{
pValueUnion->psz = pszArgThis;
return VERR_GETOPT_UNKNOWN_OPTION;
}
pValueUnion->psz = pszArgThis;
return VINF_GETOPT_NOT_OPTION;
}
RT_EXPORT_SYMBOL(RTGetOpt);
RTDECL(int) RTGetOptFetchValue(PRTGETOPTSTATE pState, PRTGETOPTUNION pValueUnion, uint32_t fFlags)
{
/*
* Validate input.
*/
PCRTGETOPTDEF pOpt = pState->pDef;
AssertReturn(!(fFlags & ~RTGETOPT_VALID_MASK), VERR_INVALID_PARAMETER);
AssertReturn((fFlags & RTGETOPT_REQ_MASK) != RTGETOPT_REQ_NOTHING, VERR_INVALID_PARAMETER);
/*
* Make sure the union is completely cleared out, whatever happens below.
*/
pValueUnion->u64 = 0;
pValueUnion->pDef = NULL;
/*
* Pop off the next argument and convert it into a value union.
*/
if (pState->iNext >= pState->argc)
return VERR_GETOPT_REQUIRED_ARGUMENT_MISSING;
int iThis = pState->iNext++;
const char *pszValue = pState->argv[iThis + (pState->cNonOptions != INT32_MAX ? pState->cNonOptions : 0)];
pValueUnion->pDef = pOpt; /* in case of no value or error. */
if (pState->cNonOptions && pState->cNonOptions != INT32_MAX)
rtGetOptMoveArgvEntries(&pState->argv[iThis], &pState->argv[iThis + pState->cNonOptions]);
return rtGetOptProcessValue(fFlags, pszValue, pValueUnion);
}
RT_EXPORT_SYMBOL(RTGetOptFetchValue);
RTDECL(RTEXITCODE) RTGetOptPrintError(int ch, PCRTGETOPTUNION pValueUnion)
{
if (ch == VINF_GETOPT_NOT_OPTION)
RTMsgError("Invalid parameter: %s", pValueUnion->psz);
else if (ch > 0)
{
if (RT_C_IS_GRAPH(ch))
RTMsgError("Unhandled option: -%c", ch);
else
RTMsgError("Unhandled option: %i (%#x)", ch, ch);
}
else if (ch == VERR_GETOPT_UNKNOWN_OPTION)
RTMsgError("Unknown option: '%s'", pValueUnion->psz);
else if (pValueUnion->pDef && ch == VERR_GETOPT_INVALID_ARGUMENT_FORMAT)
/** @todo r=klaus not really ideal, as the value isn't available */
RTMsgError("The value given '%s' has an invalid format.", pValueUnion->pDef->pszLong);
else if (pValueUnion->pDef)
RTMsgError("%s: %Rrs\n", pValueUnion->pDef->pszLong, ch);
else
RTMsgError("%Rrs\n", ch);
return RTEXITCODE_SYNTAX;
}
RT_EXPORT_SYMBOL(RTGetOptPrintError);
| {
"content_hash": "9316fa74cd032c0fc3a123eb620a1d5e",
"timestamp": "",
"source": "github",
"line_count": 753,
"max_line_length": 122,
"avg_line_length": 37.419654714475435,
"alnum_prop": 0.5245058026049615,
"repo_name": "egraba/vbox_openbsd",
"id": "ac582095606741da06da0ff5b5926f5e2b1fb40c",
"size": "28177",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "VirtualBox-5.0.0/src/VBox/Runtime/common/misc/getopt.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ada",
"bytes": "88714"
},
{
"name": "Assembly",
"bytes": "4303680"
},
{
"name": "AutoIt",
"bytes": "2187"
},
{
"name": "Batchfile",
"bytes": "95534"
},
{
"name": "C",
"bytes": "192632221"
},
{
"name": "C#",
"bytes": "64255"
},
{
"name": "C++",
"bytes": "83842667"
},
{
"name": "CLIPS",
"bytes": "5291"
},
{
"name": "CMake",
"bytes": "6041"
},
{
"name": "CSS",
"bytes": "26756"
},
{
"name": "D",
"bytes": "41844"
},
{
"name": "DIGITAL Command Language",
"bytes": "56579"
},
{
"name": "DTrace",
"bytes": "1466646"
},
{
"name": "GAP",
"bytes": "350327"
},
{
"name": "Groff",
"bytes": "298540"
},
{
"name": "HTML",
"bytes": "467691"
},
{
"name": "IDL",
"bytes": "106734"
},
{
"name": "Java",
"bytes": "261605"
},
{
"name": "JavaScript",
"bytes": "80927"
},
{
"name": "Lex",
"bytes": "25122"
},
{
"name": "Logos",
"bytes": "4941"
},
{
"name": "Makefile",
"bytes": "426902"
},
{
"name": "Module Management System",
"bytes": "2707"
},
{
"name": "NSIS",
"bytes": "177212"
},
{
"name": "Objective-C",
"bytes": "5619792"
},
{
"name": "Objective-C++",
"bytes": "81554"
},
{
"name": "PHP",
"bytes": "58585"
},
{
"name": "Pascal",
"bytes": "69941"
},
{
"name": "Perl",
"bytes": "240063"
},
{
"name": "PowerShell",
"bytes": "10664"
},
{
"name": "Python",
"bytes": "9094160"
},
{
"name": "QMake",
"bytes": "3055"
},
{
"name": "R",
"bytes": "21094"
},
{
"name": "SAS",
"bytes": "1847"
},
{
"name": "Shell",
"bytes": "1460572"
},
{
"name": "SourcePawn",
"bytes": "4139"
},
{
"name": "TypeScript",
"bytes": "142342"
},
{
"name": "Visual Basic",
"bytes": "7161"
},
{
"name": "XSLT",
"bytes": "1034475"
},
{
"name": "Yacc",
"bytes": "22312"
}
],
"symlink_target": ""
} |
import { Component, Input, OnInit,OnDestroy } from '@angular/core';
import { FORM_DIRECTIVES, ControlGroup } from '@angular/common';
import {Subject, Observable, BehaviorSubject} from 'rxjs';
import { CHECKLIST_FORM_DIRECTIVES } from './directives/index';
import { QuestionBase } from './models/base-question.model';
import { ChecklistBase } from './models/base-checklist.model';
import { ChecklistService } from './services/checklist.service';
import { ChecklistControlService } from './services/checklist-control.service';
import { ChecklistFormQuestionComponent } from './checklist-form-question.component';
@Component({
selector:'checklist-edit-form',
inputs: ["questions","checklist","checklistForm"],
template: require('./templates/checklist-edit-form.component.html'),
directives: [FORM_DIRECTIVES, CHECKLIST_FORM_DIRECTIVES, ChecklistFormQuestionComponent],
providers: []
})
export class ChecklistEditFormComponent implements OnInit,OnDestroy{
checklist: ChecklistBase = new ChecklistBase();
questions: QuestionBase<any>[] = [];
messages: Array<any>;
checklistForm:ControlGroup;
constructor(private service: ChecklistService, private controlService: ChecklistControlService) {
this.messages = [];
console.debug("ChecklistEditFormComponent.constructor()");
}
ngOnInit(){
this.questions = this.checklist.questions;
this.checklistForm = this.controlService.toControlGroup(this.checklist);
console.debug("ChecklistEditFormComponent.init()",this);
}
ngOnDestroy() {
console.debug("ChecklistEditFormComponent.onDestroy()");
}
onSubmit() {
//this.payLoad = JSON.stringify(this.checklistForm.value);
}
} | {
"content_hash": "81680ac23c69d2cf5f817e4754f9d052",
"timestamp": "",
"source": "github",
"line_count": 44,
"max_line_length": 101,
"avg_line_length": 43.31818181818182,
"alnum_prop": 0.657922350472193,
"repo_name": "crimsonskyfalling/ocean-seed",
"id": "36615f640cd4955df86fae811d429a84ef8da0b4",
"size": "1906",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/app/checklists/checklist-edit-form.component.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "6509"
},
{
"name": "HTML",
"bytes": "23493"
},
{
"name": "JavaScript",
"bytes": "21791"
},
{
"name": "TypeScript",
"bytes": "90932"
}
],
"symlink_target": ""
} |
import gettext as gettext_module
import importlib
import json
import os
from django import http
from django.apps import apps
from django.conf import settings
from django.template import Context, Engine
from django.urls import translate_url
from django.utils import six
from django.utils._os import upath
from django.utils.encoding import smart_text
from django.utils.formats import get_format, get_format_modules
from django.utils.http import is_safe_url
from django.utils.translation import (
LANGUAGE_SESSION_KEY, check_for_language, get_language, to_locale,
)
DEFAULT_PACKAGES = ['django.conf']
LANGUAGE_QUERY_PARAMETER = 'language'
def set_language(request):
"""
Redirect to a given url while setting the chosen language in the
session or cookie. The url and the language code need to be
specified in the request parameters.
Since this view changes how the user will see the rest of the site, it must
only be accessed as a POST request. If called as a GET request, it will
redirect to the page in the request (the 'next' parameter) without changing
any state.
"""
next = request.POST.get('next', request.GET.get('next'))
if not is_safe_url(url=next, host=request.get_host()):
next = request.META.get('HTTP_REFERER')
if not is_safe_url(url=next, host=request.get_host()):
next = '/'
response = http.HttpResponseRedirect(next)
if request.method == 'POST':
lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER)
if lang_code and check_for_language(lang_code):
next_trans = translate_url(next, lang_code)
if next_trans != next:
response = http.HttpResponseRedirect(next_trans)
if hasattr(request, 'session'):
request.session[LANGUAGE_SESSION_KEY] = lang_code
else:
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code,
max_age=settings.LANGUAGE_COOKIE_AGE,
path=settings.LANGUAGE_COOKIE_PATH,
domain=settings.LANGUAGE_COOKIE_DOMAIN)
return response
def get_formats():
"""
Returns all formats strings required for i18n to work
"""
FORMAT_SETTINGS = (
'DATE_FORMAT', 'DATETIME_FORMAT', 'TIME_FORMAT',
'YEAR_MONTH_FORMAT', 'MONTH_DAY_FORMAT', 'SHORT_DATE_FORMAT',
'SHORT_DATETIME_FORMAT', 'FIRST_DAY_OF_WEEK', 'DECIMAL_SEPARATOR',
'THOUSAND_SEPARATOR', 'NUMBER_GROUPING',
'DATE_INPUT_FORMATS', 'TIME_INPUT_FORMATS', 'DATETIME_INPUT_FORMATS'
)
result = {}
for module in [settings] + get_format_modules(reverse=True):
for attr in FORMAT_SETTINGS:
result[attr] = get_format(attr)
formats = {}
for k, v in result.items():
if isinstance(v, (six.string_types, int)):
formats[k] = smart_text(v)
elif isinstance(v, (tuple, list)):
formats[k] = [smart_text(value) for value in v]
return formats
js_catalog_template = r"""
{% autoescape off %}
(function(globals) {
var django = globals.django || (globals.django = {});
{% if plural %}
django.pluralidx = function(n) {
var v={{ plural }};
if (typeof(v) == 'boolean') {
return v ? 1 : 0;
} else {
return v;
}
};
{% else %}
django.pluralidx = function(count) { return (count == 1) ? 0 : 1; };
{% endif %}
/* gettext library */
django.catalog = django.catalog || {};
{% if catalog_str %}
var newcatalog = {{ catalog_str }};
for (var key in newcatalog) {
django.catalog[key] = newcatalog[key];
}
{% endif %}
if (!django.jsi18n_initialized) {
django.gettext = function(msgid) {
var value = django.catalog[msgid];
if (typeof(value) == 'undefined') {
return msgid;
} else {
return (typeof(value) == 'string') ? value : value[0];
}
};
django.ngettext = function(singular, plural, count) {
var value = django.catalog[singular];
if (typeof(value) == 'undefined') {
return (count == 1) ? singular : plural;
} else {
return value[django.pluralidx(count)];
}
};
django.gettext_noop = function(msgid) { return msgid; };
django.pgettext = function(context, msgid) {
var value = django.gettext(context + '\x04' + msgid);
if (value.indexOf('\x04') != -1) {
value = msgid;
}
return value;
};
django.npgettext = function(context, singular, plural, count) {
var value = django.ngettext(context + '\x04' + singular, context + '\x04' + plural, count);
if (value.indexOf('\x04') != -1) {
value = django.ngettext(singular, plural, count);
}
return value;
};
django.interpolate = function(fmt, obj, named) {
if (named) {
return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])});
} else {
return fmt.replace(/%s/g, function(match){return String(obj.shift())});
}
};
/* formatting library */
django.formats = {{ formats_str }};
django.get_format = function(format_type) {
var value = django.formats[format_type];
if (typeof(value) == 'undefined') {
return format_type;
} else {
return value;
}
};
/* add to global namespace */
globals.pluralidx = django.pluralidx;
globals.gettext = django.gettext;
globals.ngettext = django.ngettext;
globals.gettext_noop = django.gettext_noop;
globals.pgettext = django.pgettext;
globals.npgettext = django.npgettext;
globals.interpolate = django.interpolate;
globals.get_format = django.get_format;
django.jsi18n_initialized = true;
}
}(this));
{% endautoescape %}
"""
def render_javascript_catalog(catalog=None, plural=None):
template = Engine().from_string(js_catalog_template)
indent = lambda s: s.replace('\n', '\n ')
context = Context({
'catalog_str': indent(json.dumps(
catalog, sort_keys=True, indent=2)) if catalog else None,
'formats_str': indent(json.dumps(
get_formats(), sort_keys=True, indent=2)),
'plural': plural,
})
return http.HttpResponse(template.render(context), 'text/javascript')
def get_javascript_catalog(locale, domain, packages):
default_locale = to_locale(settings.LANGUAGE_CODE)
app_configs = apps.get_app_configs()
allowable_packages = set(app_config.name for app_config in app_configs)
allowable_packages.update(DEFAULT_PACKAGES)
packages = [p for p in packages if p in allowable_packages]
t = {}
paths = []
en_selected = locale.startswith('en')
en_catalog_missing = True
# paths of requested packages
for package in packages:
p = importlib.import_module(package)
path = os.path.join(os.path.dirname(upath(p.__file__)), 'locale')
paths.append(path)
# add the filesystem paths listed in the LOCALE_PATHS setting
paths.extend(reversed(settings.LOCALE_PATHS))
# first load all english languages files for defaults
for path in paths:
try:
catalog = gettext_module.translation(domain, path, ['en'])
t.update(catalog._catalog)
except IOError:
pass
else:
# 'en' is the selected language and at least one of the packages
# listed in `packages` has an 'en' catalog
if en_selected:
en_catalog_missing = False
# next load the settings.LANGUAGE_CODE translations if it isn't english
if default_locale != 'en':
for path in paths:
try:
catalog = gettext_module.translation(domain, path, [default_locale])
except IOError:
catalog = None
if catalog is not None:
t.update(catalog._catalog)
# last load the currently selected language, if it isn't identical to the default.
if locale != default_locale:
# If the currently selected language is English but it doesn't have a
# translation catalog (presumably due to being the language translated
# from) then a wrong language catalog might have been loaded in the
# previous step. It needs to be discarded.
if en_selected and en_catalog_missing:
t = {}
else:
locale_t = {}
for path in paths:
try:
catalog = gettext_module.translation(domain, path, [locale])
except IOError:
catalog = None
if catalog is not None:
locale_t.update(catalog._catalog)
if locale_t:
t = locale_t
plural = None
if '' in t:
for l in t[''].split('\n'):
if l.startswith('Plural-Forms:'):
plural = l.split(':', 1)[1].strip()
if plural is not None:
# this should actually be a compiled function of a typical plural-form:
# Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 :
# n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=', 1)[1]
pdict = {}
maxcnts = {}
catalog = {}
for k, v in t.items():
if k == '':
continue
if isinstance(k, six.string_types):
catalog[k] = v
elif isinstance(k, tuple):
msgid = k[0]
cnt = k[1]
maxcnts[msgid] = max(cnt, maxcnts.get(msgid, 0))
pdict.setdefault(msgid, {})[cnt] = v
else:
raise TypeError(k)
for k, v in pdict.items():
catalog[k] = [v.get(i, '') for i in range(maxcnts[msgid] + 1)]
return catalog, plural
def _get_locale(request):
language = request.GET.get(LANGUAGE_QUERY_PARAMETER)
if not (language and check_for_language(language)):
language = get_language()
return to_locale(language)
def _parse_packages(packages):
if packages is None:
packages = list(DEFAULT_PACKAGES)
elif isinstance(packages, six.string_types):
packages = packages.split('+')
return packages
def null_javascript_catalog(request, domain=None, packages=None):
"""
Returns "identity" versions of the JavaScript i18n functions -- i.e.,
versions that don't actually do anything.
"""
return render_javascript_catalog()
def javascript_catalog(request, domain='djangojs', packages=None):
"""
Returns the selected language catalog as a javascript library.
Receives the list of packages to check for translations in the
packages parameter either from an infodict or as a +-delimited
string from the request. Default is 'django.conf'.
Additionally you can override the gettext domain for this view,
but usually you don't want to do that, as JavaScript messages
go to the djangojs domain. But this might be needed if you
deliver your JavaScript source from Django templates.
"""
locale = _get_locale(request)
packages = _parse_packages(packages)
catalog, plural = get_javascript_catalog(locale, domain, packages)
return render_javascript_catalog(catalog, plural)
def json_catalog(request, domain='djangojs', packages=None):
"""
Return the selected language catalog as a JSON object.
Receives the same parameters as javascript_catalog(), but returns
a response with a JSON object of the following format:
{
"catalog": {
# Translations catalog
},
"formats": {
# Language formats for date, time, etc.
},
"plural": '...' # Expression for plural forms, or null.
}
"""
locale = _get_locale(request)
packages = _parse_packages(packages)
catalog, plural = get_javascript_catalog(locale, domain, packages)
data = {
'catalog': catalog,
'formats': get_formats(),
'plural': plural,
}
return http.JsonResponse(data)
| {
"content_hash": "e70fcf9a6b2b581fcbf50a77821b4e12",
"timestamp": "",
"source": "github",
"line_count": 357,
"max_line_length": 113,
"avg_line_length": 34.0140056022409,
"alnum_prop": 0.6084987235444289,
"repo_name": "mrbox/django",
"id": "37d38d9e740cded08815722fedeef36abd336be2",
"size": "12143",
"binary": false,
"copies": "7",
"ref": "refs/heads/master",
"path": "django/views/i18n.py",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "52334"
},
{
"name": "HTML",
"bytes": "170436"
},
{
"name": "JavaScript",
"bytes": "255321"
},
{
"name": "Makefile",
"bytes": "125"
},
{
"name": "Python",
"bytes": "11425411"
},
{
"name": "Shell",
"bytes": "809"
},
{
"name": "Smarty",
"bytes": "130"
}
],
"symlink_target": ""
} |
namespace Rocks.Expectations;
public sealed class ExplicitPropertyGetterExpectations<T, TContainingType>
: ExplicitPropertyExpectations<T, TContainingType>
where T : class, TContainingType
{
public ExplicitPropertyGetterExpectations(ExplicitPropertyExpectations<T, TContainingType> expectations)
: base(expectations ?? throw new ArgumentNullException(nameof(expectations))) { }
} | {
"content_hash": "07e13a7a59a654bff64fe8bc8fb7ca52",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 105,
"avg_line_length": 42.888888888888886,
"alnum_prop": 0.8341968911917098,
"repo_name": "JasonBock/Rocks",
"id": "d632b15f42749cfeead47e5588bcc9eb4231a2ef",
"size": "388",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/Rocks/Expectations/ExplicitPropertyGetterExpectations.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1386390"
},
{
"name": "Smalltalk",
"bytes": "3"
}
],
"symlink_target": ""
} |
<?php
class Keywords {
public static function SelectListFor($TypeId) {
$sql = "SELECT id, Name FROM 2014Spring_Keywords WHERE Parent_id = $TypeId ";
return fetch_all($sql);
}
} | {
"content_hash": "04b58ff9fdf7d806b392fe324e4d7290",
"timestamp": "",
"source": "github",
"line_count": 9,
"max_line_length": 80,
"avg_line_length": 21.11111111111111,
"alnum_prop": 0.6736842105263158,
"repo_name": "mukkur/webdev2014",
"id": "2e1ee3dded98313ec35a5c5acbdff11fb32fc387",
"size": "190",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Final/Models/Keywords.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "PHP",
"bytes": "195404"
}
],
"symlink_target": ""
} |
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, sex characteristics, gender identity and expression,
level of experience, education, socio-economic status, nationality, personal
appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team. All complaints will be reviewed and
investigated and will result in a response that is deemed necessary and
appropriate to the circumstances. The project team is obligated to maintain
confidentiality with regard to the reporter of an incident. Further details
of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see
https://www.contributor-covenant.org/faq
| {
"content_hash": "d3162e8934d5d21d853197f579bbebc5",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 87,
"avg_line_length": 45.458333333333336,
"alnum_prop": 0.822792545065689,
"repo_name": "CenturyLinkLabs/watchtower",
"id": "6a76fea4b55df61282c1e2b7185ec10d6515f352",
"size": "3328",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CODE_OF_CONDUCT.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "27776"
}
],
"symlink_target": ""
} |
export const version = '###_VERSION_###';
| {
"content_hash": "fb1668d76142a531dd7eddddfc43316c",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 41,
"avg_line_length": 14.666666666666666,
"alnum_prop": 0.5681818181818182,
"repo_name": "implydata/plywood",
"id": "b0e19a103e0d1e45ba7ce51bb8297b2bf219b857",
"size": "648",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/version.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "868326"
},
{
"name": "PEG.js",
"bytes": "7398"
},
{
"name": "Shell",
"bytes": "7939"
},
{
"name": "TypeScript",
"bytes": "425084"
}
],
"symlink_target": ""
} |
@extends('layouts.layout')
@section('content')
<?php $articles = Factura::find($factura->id)->articles ?>
@if (count($articles) > 0)
<div class="page-header">
<h4>Hi ha material vinculat a la factura. No puc esborrar!</h4>
</div>
@else
<div class="page-header">
<h1>Elimina factura {{ $factura->idfactura }} <small>Estàs segur?</small></h1>
</div>
<form action="{{ action('FacturesController@handleDelete') }}" method="post" role="form">
<input type="hidden" name="factura" value="{{ $factura->id }}" />
<input type="submit" class="btn btn-danger" value="Si" />
<a href="{{ action('FacturesController@index') }}" class="btn btn-default">No!</a>
</form>
@endif
@stop | {
"content_hash": "4ad80447252dda6b5dd7687ca8ac6dc5",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 93,
"avg_line_length": 38.78947368421053,
"alnum_prop": 0.6065128900949797,
"repo_name": "escanton/invoices-providers",
"id": "0af2e66c5aa576f5a209cdb825955ed18e384b87",
"size": "738",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/views/factures/delete.blade.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "415"
},
{
"name": "PHP",
"bytes": "78488"
},
{
"name": "Perl",
"bytes": "2424"
},
{
"name": "Shell",
"bytes": "195"
}
],
"symlink_target": ""
} |
[Class] Event
@version 1.1, 2015-07-05
@author TheOddByte
--]]
local Event = {
events = {};
keys = {
isRepeat = true;
}
}
for k, v in pairs( keys ) do
Event.keys[k] = false
end
---------------------------------------------
-------------[ Local Functions ]-------------
---------------------------------------------
-- Ignore these functions, as they're only --
-- used for other functions and I don't --
-- believe you need them --
---------------------------------------------
local function isReleased( self, event )
for k, v in pairs( self.events[event]["keys"] ) do
if v == true then
return false
end
end
return true
end
local function isValid( self, event )
for k, v in pairs( self.events[event]["keys"] ) do
if v == false then
return false
end
end
return true
end
--[[
Registers a custom event that will be pulled
when certain keys are down, you can change it
so that it repeats the event until the keys
are released
@param self, table, "Self-explainatory"
@param name, string, "The event name"
@param _keys, table, "The keys that needs to be pressed"
@param ..., ..., "The parameters that will be returned"
@return nil
--]]
function Event.register( self, name, _keys, ... )
assert( type( self ) == "table", "table expected, got " .. type( self ), 2 )
assert( type( name ) == "string", "string expected, got " .. type( name ), 2 )
assert( type( _keys ) == "table", "table expected, got " .. type( _keys ), 2 )
self.events[name] = {
["keys"] = {};
enabled = false;
parameters = {...};
isRepeat = isRepeat or false;
}
for i, v in ipairs( _keys ) do
if type( v ) == "string" then
if #v == 1 then
v = v:lower()
for _name, value in pairs( keys ) do
if v == _name then
self.events[name]["keys"][_name] = false;
break
end
end
end
elseif type( v ) == "number" then
for key, value in pairs( keys ) do
if v == value then
self.events[name]["keys"][keys.getName( v )] = false;
break
end
end
end
end
end
--[[
Handles custom events and repeating keys
@param self, table, "Self-explainatory"
@param ..., "The parameters from the os.pullEvent call"
--]]
function Event.handle( self, ... )
local e = {...}
local key = keys.getName( e[2] )
if e[1] == "key" then
--# Handle custom events
for k, v in pairs( self.events ) do
if self.events[k]["keys"][key] ~= nil then
self.events[k]["keys"][key] = true
break
end
end
--# Handle repeat, prevent it from being repeated all the time( if isRepeat is false )
if not self.keys.isRepeat then
for k, v in pairs( self.keys ) do
for key, value in pairs( keys ) do
if k == key then
if v then
return nil
else
self.keys[k] = true
end
end
end
end
end
elseif e[1] == "key_up" then
--# Handle custom events
for k, v in pairs( self.events ) do
if self.events[k]["keys"][key] ~= nil then
self.events[k]["keys"][key] = false
break
end
end
--# Handle repeat
if not self.keys.isRepeat then
for k, v in pairs( self.keys ) do
for key, value in pairs( keys ) do
if k == key then
self.keys[k] = false
end
end
end
end
end
for k, v in pairs( self.events ) do
if v.enabled then
if v.isRepeat then
if isValid( self, k ) then
return k, unpack( v.parameters )
end
else
if not v.eventSent then
self.events[k].eventSent = true
self.events[k].enabled = false
return k, unpack( v.parameters )
end
end
else
if not v.eventSent then
if isValid( self, k ) then
self.events[k].enabled = true
end
else
if isReleased( self, k ) then
self.events[k].eventSent = false
end
end
end
end
return unpack( e )
end
--[[
Sets if keys should be repeated or not
@param self, table, "Self-explainatory"
@param bool, boolean, "Sets whether or not the keys should be repeated"
@return nil
--]]
function Event.setKeyRepeat( self, bool )
assert( type( bool ) == "boolean", "boolean expected, got " .. type( bool ), 2 )
self.keys.isRepeat = bool
end
--[[
Quits the running program
--]]
function Event.quit()
CLove.Graphics.clear( "black" )
error()
end
--[[
Queues multiple events
@param, ..., string(s), "The events you want to send"
@return nil
--]]
function Event.send( ... )
local e = { ... }
for i, v in ipairs( e ) do
os.queueEvent( unpack( v ) )
end
end
--[[
Waits for a specific event, then sends
the parameters to the function specified
@param event, string, "The event you want to wait for"
@param func, string, "The function you want to call"
@return ..., "Returns what the function returns"
--]]
function Event.waitFor( event, func )
local e
repeat
e = { os.pullEvent() }
until e[1] == event
return func( unpack( e ) )
end
--[[
Queues multiple keys to be pulled
@param ..., string(s)/number(s), "The keys you want to send"
@return nil
--]]
function Event.sendKeys( ... )
local e = { ... }
for i, v in ipairs( e ) do
if type( v ) ~= "number" and type( v ) ~= "string" then
return false, "expected number/string, got " .. type( v )
end
os.queueEvent( type( v ) == "number" and "key" or "char", v )
end
return true
end
--[[
Queues a mouse click to be pulled
@param x, number, "The x coordinate"
@param y, number, "The y coordinate"
@param button, number, "The mouse button"
--]]
function Event.sendMouseClick( x, y, button )
os.queueEvent( "mouse_click", button, x, y )
end
--[[
Queues a mouse scroll to be pulled
@param x, number, "The x coordinate"
@param y, number, "The y coordinate"
@param button, number, "The mouse button"
--]]
function Event.sendMouseScroll( x, y, button )
os.queueEvent( "mouse_scroll", button, x, y )
end
return Event
| {
"content_hash": "5a06667b2d007ec764e63fb1ec3883ff",
"timestamp": "",
"source": "github",
"line_count": 298,
"max_line_length": 94,
"avg_line_length": 24.40268456375839,
"alnum_prop": 0.4808855885588559,
"repo_name": "TheOddByte/CLove",
"id": "988a424fc89042ec3ff4b128cda9799c50bbcc14",
"size": "7277",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "classes/Event.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Lua",
"bytes": "63338"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>pype32.directories.ImageDebugDirectory</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="pype32-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="http://code.google.com/p/pype32">pype32 - Programming Reference</a></th>
</tr></table></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
<a href="pype32-module.html">Package pype32</a> ::
<a href="pype32.directories-module.html" onclick="show_private();">Module directories</a> ::
Class ImageDebugDirectory
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="pype32.directories.ImageDebugDirectory-class.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<!-- ==================== CLASS DESCRIPTION ==================== -->
<h1 class="epydoc">Class ImageDebugDirectory</h1><p class="nomargin-top"><span class="codelink"><a href="pype32.directories-pysrc.html#ImageDebugDirectory">source code</a></span></p>
<pre class="base-tree">
object --+
|
<a href="pype32.baseclasses.BaseStructClass-class.html">baseclasses.BaseStructClass</a> --+
|
<strong class="uidshort">ImageDebugDirectory</strong>
</pre>
<hr />
<p>ImageDebugDirectory object.</p>
<!-- ==================== INSTANCE METHODS ==================== -->
<a name="section-InstanceMethods"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Instance Methods</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-InstanceMethods"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pype32.directories.ImageDebugDirectory-class.html#__init__" class="summary-sig-name">__init__</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">shouldPack</span>=<span class="summary-sig-default">True</span>)</span><br />
Class representation of a <code>IMAGE_DEBUG_DIRECTORY</code>
structure.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pype32.directories-pysrc.html#ImageDebugDirectory.__init__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pype32.directories.ImageDebugDirectory-class.html#getType" class="summary-sig-name">getType</a>(<span class="summary-sig-arg">self</span>)</span><br />
Returns <a href="pype32.consts-module.html#IMAGE_DEBUG_DIRECTORY"
class="link">consts.IMAGE_DEBUG_DIRECTORY</a>.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pype32.directories-pysrc.html#ImageDebugDirectory.getType">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__delattr__</code>,
<code>__format__</code>,
<code>__getattribute__</code>,
<code>__hash__</code>,
<code>__new__</code>,
<code>__reduce__</code>,
<code>__reduce_ex__</code>,
<code>__repr__</code>,
<code>__setattr__</code>,
<code>__sizeof__</code>,
<code>__subclasshook__</code>
</p>
</td>
</tr>
<tr bgcolor="#e8f0f8" >
<th colspan="2" class="group-header"
> Inherited from <a href="pype32.baseclasses.BaseStructClass-class.html">baseclasses.BaseStructClass</a></th></tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__len__"></a><span class="summary-sig-name">__len__</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="pype32.baseclasses-pysrc.html#BaseStructClass.__len__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pype32.baseclasses.BaseStructClass-class.html#__str__" class="summary-sig-name">__str__</a>(<span class="summary-sig-arg">self</span>)</span><br />
str(x)</td>
<td align="right" valign="top">
<span class="codelink"><a href="pype32.baseclasses-pysrc.html#BaseStructClass.__str__">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type">dict</span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pype32.baseclasses.BaseStructClass-class.html#getFields" class="summary-sig-name">getFields</a>(<span class="summary-sig-arg">self</span>)</span><br />
Returns all the class attributues.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pype32.baseclasses-pysrc.html#BaseStructClass.getFields">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="sizeof"></a><span class="summary-sig-name">sizeof</span>(<span class="summary-sig-arg">self</span>)</span></td>
<td align="right" valign="top">
<span class="codelink"><a href="pype32.baseclasses-pysrc.html#BaseStructClass.sizeof">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
</table>
<!-- ==================== STATIC METHODS ==================== -->
<a name="section-StaticMethods"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Static Methods</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-StaticMethods"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"><a href="pype32.directories.ImageDebugDirectory-class.html"
class="link">ImageDebugDirectory</a></span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="pype32.directories.ImageDebugDirectory-class.html#parse" class="summary-sig-name">parse</a>(<span class="summary-sig-arg">readDataInstance</span>)</span><br />
Returns a new <a
href="pype32.directories.ImageDebugDirectory-class.html"
class="link">ImageDebugDirectory</a> object.</td>
<td align="right" valign="top">
<span class="codelink"><a href="pype32.directories-pysrc.html#ImageDebugDirectory.parse">source code</a></span>
</td>
</tr>
</table>
</td>
</tr>
</table>
<!-- ==================== INSTANCE VARIABLES ==================== -->
<a name="section-InstanceVariables"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Instance Variables</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-InstanceVariables"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="characteristics"></a><span class="summary-name">characteristics</span><br />
<a href="pype32.datatypes.DWORD-class.html" class="link">DWORD</a>
characteristics.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="timeDateStamp"></a><span class="summary-name">timeDateStamp</span><br />
<a href="pype32.datatypes.DWORD-class.html" class="link">DWORD</a>
timeDateStamp.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="majorVersion"></a><span class="summary-name">majorVersion</span><br />
<a href="pype32.datatypes.WORD-class.html" class="link">WORD</a>
majorVersion.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="minorVersion"></a><span class="summary-name">minorVersion</span><br />
<a href="pype32.datatypes.WORD-class.html" class="link">WORD</a>
minorVersion.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="type"></a><span class="summary-name">type</span><br />
<a href="pype32.datatypes.DWORD-class.html" class="link">DWORD</a>
type.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="sizeOfData"></a><span class="summary-name">sizeOfData</span><br />
<a href="pype32.datatypes.DWORD-class.html" class="link">DWORD</a>
sizeOfData.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="addressOfData"></a><span class="summary-name">addressOfData</span><br />
<a href="pype32.datatypes.DWORD-class.html" class="link">DWORD</a>
addressOfData.
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<a name="pointerToRawData"></a><span class="summary-name">pointerToRawData</span><br />
<a href="pype32.datatypes.DWORD-class.html" class="link">DWORD</a>
pointerToRawData.
</td>
</tr>
</table>
<!-- ==================== PROPERTIES ==================== -->
<a name="section-Properties"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Properties</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-Properties"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>:
<code>__class__</code>
</p>
</td>
</tr>
</table>
<!-- ==================== METHOD DETAILS ==================== -->
<a name="section-MethodDetails"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Method Details</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-MethodDetails"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="__init__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__init__</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">shouldPack</span>=<span class="sig-default">True</span>)</span>
<br /><em class="fname">(Constructor)</em>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="pype32.directories-pysrc.html#ImageDebugDirectory.__init__">source code</a></span>
</td>
</tr></table>
<p>Class representation of a <code>IMAGE_DEBUG_DIRECTORY</code>
structure.</p>
<dl class="fields">
<dt>Parameters:</dt>
<dd><ul class="nomargin-top">
<li><strong class="pname"><code>shouldPack</code></strong> (bool) - (Optional) If set to c{True}, the object will be packed. If set
to <code>False</code>, the object won't be packed.</li>
</ul></dd>
<dt>Overrides:
object.__init__
</dt>
</dl>
<div class="fields"> <p><strong>See Also:</strong>
<a
href="http://msdn.microsoft.com/es-es/library/windows/desktop/ms680307%28v=vs.85%29.aspx"
target="_top">http://msdn.microsoft.com/es-es/library/windows/desktop/ms680307%28v=vs.85%29.aspx</a>
</p>
</div></td></tr></table>
</div>
<a name="getType"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">getType</span>(<span class="sig-arg">self</span>)</span>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="pype32.directories-pysrc.html#ImageDebugDirectory.getType">source code</a></span>
</td>
</tr></table>
<p>Returns <a href="pype32.consts-module.html#IMAGE_DEBUG_DIRECTORY"
class="link">consts.IMAGE_DEBUG_DIRECTORY</a>.</p>
<dl class="fields">
<dt>Raises:</dt>
<dd><ul class="nomargin-top">
<li><code><strong class='fraise'>NotImplementedError</strong></code> - The method wasn't implemented in the inherited class.</li>
</ul></dd>
<dt>Overrides:
<a href="pype32.baseclasses.BaseStructClass-class.html#getType">baseclasses.BaseStructClass.getType</a>
</dt>
</dl>
</td></tr></table>
</div>
<a name="parse"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">parse</span>(<span class="sig-arg">readDataInstance</span>)</span>
<br /><em class="fname">Static Method</em>
</h3>
</td><td align="right" valign="top"
><span class="codelink"><a href="pype32.directories-pysrc.html#ImageDebugDirectory.parse">source code</a></span>
</td>
</tr></table>
<p>Returns a new <a
href="pype32.directories.ImageDebugDirectory-class.html"
class="link">ImageDebugDirectory</a> object.</p>
<dl class="fields">
<dt>Parameters:</dt>
<dd><ul class="nomargin-top">
<li><strong class="pname"><code>readDataInstance</code></strong> (<a href="pype32.utils.ReadData-class.html"
class="link">ReadData</a>) - A new <a href="pype32.utils.ReadData-class.html"
class="link">ReadData</a> object with data to be parsed as a <a
href="pype32.directories.ImageDebugDirectory-class.html"
class="link">ImageDebugDirectory</a> object.</li>
</ul></dd>
<dt>Returns: <a href="pype32.directories.ImageDebugDirectory-class.html"
class="link">ImageDebugDirectory</a></dt>
<dd>A new <a href="pype32.directories.ImageDebugDirectory-class.html"
class="link">ImageDebugDirectory</a> object.</dd>
</dl>
</td></tr></table>
</div>
<br />
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Home link -->
<th> <a
href="pype32-module.html">Home</a> </th>
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
><a class="navbar" target="_top" href="http://code.google.com/p/pype32">pype32 - Programming Reference</a></th>
</tr></table></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Fri Jul 12 18:53:46 2013
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
| {
"content_hash": "3d0c71fe583a065d94ca11a1502e6960",
"timestamp": "",
"source": "github",
"line_count": 536,
"max_line_length": 208,
"avg_line_length": 39.93283582089552,
"alnum_prop": 0.5874602877966735,
"repo_name": "snemes/pype32",
"id": "510f3c6b120477db5c2bdfa8caec0d3325427c0b",
"size": "21404",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "doc/pype32.directories.ImageDebugDirectory-class.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Python",
"bytes": "244797"
}
],
"symlink_target": ""
} |
<?php
include "header.php";
include "subheader.php";
$transaction = new transaction;
$user = new user;
$user_data = $user->getbyid($user->getloggedid());
$balance = $transaction->balance();
if($user_data['type']=="seeker" || $user_data['type']=="provider")
{
?>
<div style="height:20px; clear:both;"></div>
<strong>List of All Services You have Posted</strong>
<?php
$objservice=new service;
$servicelist=$objservice->get_all_services_by_userid($_SESSION['foongigs_userid']);
$objmaincat=new maincategory;
$objcommon=new common;
if(is_array($servicelist))
{
?>
<div id="account_open_projects" style="clear:both; width:100%;">
<table width="100%" >
<tr class="heading"><td>Service Title</td><td>Posted On</td><td>Status</td><td>Edit</td><td>Option</td></tr>
<?php
foreach($servicelist as $data)
{
echo '<tr>';
echo '<td><a href="service_view.php?id='.$data['id'].'">'.$data['title'].'</a></td>';
echo '<td>'.$data['posted_time'].'</td>';
echo '<td>'.$objservice->getstatus($data['id']).'</td>';
echo "<td><a href='edit_service.php?sid=".$data['id']."'>Edit</a></td>";
echo "<td>".$objservice->getoption($data['id'])."</td>";
echo '</tr>';
}
?>
</table>
</div>
<?php }
else
echo '<h3 class="subheading" style="clear:both;">No Services found...</h3>';
?>
<?php
}
include "subfooter.php";
include "footer.php";
?>
| {
"content_hash": "a98ca85a6d475e68b3f7273ca068578d",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 116,
"avg_line_length": 31,
"alnum_prop": 0.5338393421884883,
"repo_name": "sknlim/classified-2",
"id": "fccb84c4f5be06f5dfc0cc653ea1293f711162de",
"size": "1581",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "viewallservices.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "57659"
},
{
"name": "CSS",
"bytes": "62164"
},
{
"name": "ColdFusion",
"bytes": "47523"
},
{
"name": "HTML",
"bytes": "536599"
},
{
"name": "JavaScript",
"bytes": "1525992"
},
{
"name": "Lasso",
"bytes": "35556"
},
{
"name": "PHP",
"bytes": "847275"
},
{
"name": "Perl",
"bytes": "58984"
},
{
"name": "Python",
"bytes": "30250"
}
],
"symlink_target": ""
} |
package org.openksavi.sponge.grpcapi.server;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import io.grpc.Server;
import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.shaded.io.grpc.netty.NettyServerBuilder;
import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder;
import io.grpc.protobuf.services.ProtoReflectionService;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.openksavi.sponge.config.Configuration;
import org.openksavi.sponge.core.util.SpongeUtils;
import org.openksavi.sponge.core.util.SslConfiguration;
import org.openksavi.sponge.grpcapi.server.core.kb.GrpcApiSubscribeCorrelator;
import org.openksavi.sponge.grpcapi.server.support.kb.GrpcApiManageSubscription;
import org.openksavi.sponge.grpcapi.server.util.GrpcApiServerUtils;
import org.openksavi.sponge.java.JPlugin;
import org.openksavi.sponge.kb.KnowledgeBaseEngineOperations;
import org.openksavi.sponge.remoteapi.RemoteApiConstants;
import org.openksavi.sponge.remoteapi.server.RemoteApiServerPlugin;
/**
* Sponge gRPC API server plugin.
*/
public class GrpcApiServerPlugin extends JPlugin {
private static final Logger logger = LoggerFactory.getLogger(GrpcApiServerPlugin.class);
public static final String NAME = "grpcApiServer";
public static final String KB_CORE_PACKAGE_TO_SCAN = GrpcApiSubscribeCorrelator.class.getPackage().getName();
public static final String KB_SUPPORT_PACKAGE_TO_SCAN = GrpcApiManageSubscription.class.getPackage().getName();
private RemoteApiServerPlugin remoteApiServerPlugin;
private DefaultGrpcApiService service;
private boolean autoStart = GrpcApiServerConstants.DEFAULT_AUTO_START;
private Integer port;
private Server server;
private Consumer<NettyServerBuilder> serverConfigurator;
private final Lock lock = new ReentrantLock(true);
public GrpcApiServerPlugin() {
setName(NAME);
}
public GrpcApiServerPlugin(String name) {
super(name);
}
@Override
public void onConfigure(Configuration configuration) {
autoStart = configuration.getBoolean(GrpcApiServerConstants.TAG_AUTO_START, autoStart);
port = configuration.getInteger(GrpcApiServerConstants.TAG_PORT, port);
}
@Override
public void onStartup() {
if (isAutoStart()) {
start();
}
}
@Override
public void onShutdown() {
stop();
}
public void start() {
if (remoteApiServerPlugin == null) {
// The Remote API server plugin is required by the Sponge gRPC API.
setRemoteApiServerPlugin(getEngine().getOperations().getPlugin(RemoteApiServerPlugin.class));
}
Validate.notNull(remoteApiServerPlugin, "The Remote API server plugin is required for the gRPC API server plugin");
startServer();
remoteApiServerPlugin.getService().setFeature(RemoteApiConstants.REMOTE_API_FEATURE_GRPC_ENABLED, true);
getSponge().enableJavaByScan(KB_CORE_PACKAGE_TO_SCAN);
}
protected int resolveServerPort() {
String portProperty = getEngine().getConfigurationManager().getProperty(GrpcApiServerConstants.PROPERTY_GRPC_PORT);
if (portProperty != null) {
return Integer.parseInt(portProperty.trim());
}
if (port != null) {
return port;
}
// Default port convention.
return GrpcApiServerUtils.calculateDefaultPortByRemoteApi(remoteApiServerPlugin.getSettings().getPort());
}
/**
* Starts the gRPC server.
*/
protected void startServer() {
lock.lock();
try {
if (server != null) {
return;
}
if (service == null) {
// Use the default service.
service = new DefaultGrpcApiService();
}
service.setEngine(getEngine());
service.setRemoteApiService(remoteApiServerPlugin.getService());
service.setSubscriptionManager(new ServerSubscriptionManager(getEngine(), remoteApiServerPlugin.getService()));
int port = resolveServerPort();
NettyServerBuilder builder = NettyServerBuilder.forPort(port).addService(service);
// Turn on the gRPC Server Reflection
// [https://github.com/grpc/grpc-java/blob/master/documentation/server-reflection-tutorial.md].
builder.addService(ProtoReflectionService.newInstance());
SslConfiguration sslConfiguration = remoteApiServerPlugin.getService().getSettings().getSslConfiguration();
if (sslConfiguration != null) {
// Use the TLS configuration from the Remote API server.
builder.sslContext(GrpcSslContexts
.configure(SslContextBuilder.forServer(SpongeUtils.createKeyManagerFactory(sslConfiguration))).build());
}
if (serverConfigurator != null) {
serverConfigurator.accept(builder);
}
server = builder.build();
logger.info("Starting the {} gRPC server on port {}", sslConfiguration != null ? "secure" : "insecure", port);
server.start();
} catch (IOException e) {
throw SpongeUtils.wrapException(e);
} finally {
lock.unlock();
}
}
public void stop() {
if (remoteApiServerPlugin != null) {
remoteApiServerPlugin.getService().setFeature(RemoteApiConstants.REMOTE_API_FEATURE_GRPC_ENABLED, false);
}
getSponge().disableJavaByScan(KB_CORE_PACKAGE_TO_SCAN);
stopServer();
}
protected void stopServer() {
lock.lock();
try {
if (server == null) {
return;
}
logger.info("Stopping the gRPC server");
server.shutdownNow().awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw SpongeUtils.wrapException(e);
} finally {
server = null;
lock.unlock();
}
}
public boolean isServerRunning() {
return server != null && !server.isShutdown() && !server.isTerminated();
}
/**
* Enables support processors (e.g. subscription actions) in the knowledge base.
*
* @param engineOperations the engine operations assosiated with the knowledge base.
*/
public void enableSupport(KnowledgeBaseEngineOperations engineOperations) {
engineOperations.enableJavaByScan(KB_SUPPORT_PACKAGE_TO_SCAN);
}
public void pushEvent(org.openksavi.sponge.event.Event event) {
service.pushEvent(event);
}
public RemoteApiServerPlugin getRemoteApiServerPlugin() {
return remoteApiServerPlugin;
}
public void setRemoteApiServerPlugin(RemoteApiServerPlugin remoteApiServerPlugin) {
this.remoteApiServerPlugin = remoteApiServerPlugin;
}
public DefaultGrpcApiService getService() {
return service;
}
public void setService(DefaultGrpcApiService service) {
this.service = service;
}
public boolean isAutoStart() {
return autoStart;
}
public void setAutoStart(boolean autoStart) {
this.autoStart = autoStart;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public Consumer<NettyServerBuilder> getServerConfigurator() {
return serverConfigurator;
}
public void setServerConfigurator(Consumer<NettyServerBuilder> serverConfigurator) {
this.serverConfigurator = serverConfigurator;
}
}
| {
"content_hash": "21568c3bbd0cb141b0739abbf02fbe21",
"timestamp": "",
"source": "github",
"line_count": 245,
"max_line_length": 128,
"avg_line_length": 32.159183673469386,
"alnum_prop": 0.6744510724711258,
"repo_name": "softelnet/sponge",
"id": "66571b220475dbef23631a0d71de73a71f3bddf4",
"size": "8487",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "sponge-grpc-api-server/src/main/java/org/openksavi/sponge/grpcapi/server/GrpcApiServerPlugin.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "482"
},
{
"name": "Dockerfile",
"bytes": "2389"
},
{
"name": "Groovy",
"bytes": "70914"
},
{
"name": "HTML",
"bytes": "6759"
},
{
"name": "Java",
"bytes": "3300560"
},
{
"name": "JavaScript",
"bytes": "70716"
},
{
"name": "Kotlin",
"bytes": "113542"
},
{
"name": "Mustache",
"bytes": "38"
},
{
"name": "Python",
"bytes": "426240"
},
{
"name": "Ruby",
"bytes": "65491"
},
{
"name": "SCSS",
"bytes": "6217"
},
{
"name": "Shell",
"bytes": "1388"
}
],
"symlink_target": ""
} |
.class public Lcom/payu/android/sdk/payment/model/PaymentMethodViewModel;
.super Ljava/lang/Object;
# instance fields
.field private a:Ljava/lang/String;
.field private b:Ljava/lang/String;
.field private c:Ljava/lang/String;
.field private d:I
# direct methods
.method public constructor <init>(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V
.locals 0
.line 10
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
.line 11
iput-object p1, p0, Lcom/payu/android/sdk/payment/model/PaymentMethodViewModel;->a:Ljava/lang/String;
.line 12
iput-object p2, p0, Lcom/payu/android/sdk/payment/model/PaymentMethodViewModel;->b:Ljava/lang/String;
.line 13
iput-object p3, p0, Lcom/payu/android/sdk/payment/model/PaymentMethodViewModel;->c:Ljava/lang/String;
.line 14
iput p4, p0, Lcom/payu/android/sdk/payment/model/PaymentMethodViewModel;->d:I
.line 15
return-void
.end method
# virtual methods
.method public getDescription()Ljava/lang/String;
.locals 1
.line 22
iget-object v0, p0, Lcom/payu/android/sdk/payment/model/PaymentMethodViewModel;->b:Ljava/lang/String;
return-object v0
.end method
.method public getLogoUrl()Ljava/lang/String;
.locals 1
.line 26
iget-object v0, p0, Lcom/payu/android/sdk/payment/model/PaymentMethodViewModel;->c:Ljava/lang/String;
return-object v0
.end method
.method public getTitle()Ljava/lang/String;
.locals 1
.line 18
iget-object v0, p0, Lcom/payu/android/sdk/payment/model/PaymentMethodViewModel;->a:Ljava/lang/String;
return-object v0
.end method
.method public getTitleMaxLineNumbers()I
.locals 1
.line 30
iget v0, p0, Lcom/payu/android/sdk/payment/model/PaymentMethodViewModel;->d:I
return v0
.end method
| {
"content_hash": "fcab5d98aee50d8586b71de1cea65f6f",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 105,
"avg_line_length": 24.135135135135137,
"alnum_prop": 0.7245240761478163,
"repo_name": "gelldur/jak_oni_to_robia_prezentacja",
"id": "bad350e77c70aa9b55f728a6ad64c3c12846752e",
"size": "1786",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Starbucks/output/smali/com/payu/android/sdk/payment/model/PaymentMethodViewModel.smali",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "8427"
},
{
"name": "Shell",
"bytes": "2303"
},
{
"name": "Smali",
"bytes": "57557982"
}
],
"symlink_target": ""
} |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/about_ui.h"
#include <stddef.h>
#include <stdint.h>
#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/format_macros.h"
#include "base/i18n/number_formatting.h"
#include "base/json/json_writer.h"
#include "base/macros.h"
#include "base/memory/singleton.h"
#include "base/metrics/statistics_recorder.h"
#include "base/process/process_metrics.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/system/sys_info.h"
#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "base/threading/scoped_blocking_call.h"
#include "base/threading/thread.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/about_flags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/defaults.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/browser_resources.h"
#include "chrome/grit/chromium_strings.h"
#include "chrome/grit/generated_resources.h"
#include "components/about_ui/credit_utils.h"
#include "components/grit/components_resources.h"
#include "components/strings/grit/components_locale_settings.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/url_data_source.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_client.h"
#include "content/public/common/process_type.h"
#include "google_apis/gaia/google_service_auth_error.h"
#include "net/base/escape.h"
#include "net/base/filename_util.h"
#include "net/base/load_flags.h"
#include "net/http/http_response_headers.h"
#include "third_party/brotli/include/brotli/decode.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/base/webui/jstemplate_builder.h"
#include "ui/base/webui/web_ui_util.h"
#include "url/gurl.h"
#if !defined(OS_ANDROID)
#include "chrome/browser/ui/webui/theme_source.h"
#endif
#if defined(OS_CHROMEOS)
#include <map>
#include "base/base64.h"
#include "base/stl_util.h"
#include "base/strings/strcat.h"
#include "chrome/browser/browser_process_platform_part_chromeos.h"
#include "chrome/browser/chromeos/customization/customization_document.h"
#include "chrome/browser/chromeos/login/demo_mode/demo_setup_controller.h"
#include "chrome/browser/chromeos/login/wizard_controller.h"
#include "chrome/browser/component_updater/cros_component_manager.h"
#include "chromeos/system/statistics_provider.h"
#include "components/language/core/common/locale_util.h"
#include "third_party/cros_system_api/dbus/service_constants.h"
#endif
using content::BrowserThread;
namespace {
constexpr char kCreditsJsPath[] = "credits.js";
constexpr char kStatsJsPath[] = "stats.js";
constexpr char kStringsJsPath[] = "strings.js";
#if defined(OS_CHROMEOS)
constexpr char kKeyboardUtilsPath[] = "keyboard_utils.js";
constexpr char kTerminaCreditsPath[] = "about_os_credits.html";
// APAC region name.
constexpr char kApac[] = "apac";
// EMEA region name.
constexpr char kEmea[] = "emea";
// EU region name.
constexpr char kEu[] = "eu";
// List of countries that belong to APAC.
const char* const kApacCountries[] = {"au", "bd", "cn", "hk", "id", "in", "jp",
"kh", "la", "lk", "mm", "mn", "my", "nz",
"np", "ph", "sg", "th", "tw", "vn"};
// List of countries that belong to EMEA.
const char* const kEmeaCountries[] = {"na", "za", "am", "az", "ch", "eg", "ge",
"il", "is", "ke", "kg", "li", "mk", "no",
"rs", "ru", "tr", "tz", "ua", "ug", "za"};
// List of countries that belong to EU.
const char* const kEuCountries[] = {
"at", "be", "bg", "cz", "dk", "es", "fi", "fr", "gb", "gr", "hr", "hu",
"ie", "it", "lt", "lu", "lv", "nl", "pl", "pt", "ro", "se", "si", "sk"};
// Maps country to one of 3 regions: APAC, EMEA, EU.
typedef std::map<std::string, std::string> CountryRegionMap;
// Returns country to region map with EU, EMEA and APAC countries.
CountryRegionMap CreateCountryRegionMap() {
CountryRegionMap region_map;
for (size_t i = 0; i < base::size(kApacCountries); ++i) {
region_map.emplace(kApacCountries[i], kApac);
}
for (size_t i = 0; i < base::size(kEmeaCountries); ++i) {
region_map.emplace(kEmeaCountries[i], kEmea);
}
for (size_t i = 0; i < base::size(kEuCountries); ++i) {
region_map.emplace(kEuCountries[i], kEu);
}
return region_map;
}
// Reads device region from VPD. Returns "us" in case of read or parsing errors.
std::string ReadDeviceRegionFromVpd() {
std::string region = "us";
chromeos::system::StatisticsProvider* provider =
chromeos::system::StatisticsProvider::GetInstance();
bool region_found =
provider->GetMachineStatistic(chromeos::system::kRegionKey, ®ion);
if (region_found) {
// We only need the first part of the complex region codes like ca.ansi.
std::vector<std::string> region_pieces = base::SplitString(
region, ".", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);
if (!region_pieces.empty())
region = region_pieces[0];
} else {
LOG(WARNING) << "Device region for Play Store ToS not found in VPD - "
"defaulting to US.";
}
return base::ToLowerASCII(region);
}
// Returns an absolute path under the preinstalled demo resources directory.
base::FilePath CreateDemoResourcesTermsPath(const base::FilePath& file_path) {
// Offline ARC TOS are only available during demo mode setup.
auto* wizard_controller = chromeos::WizardController::default_controller();
if (!wizard_controller || !wizard_controller->demo_setup_controller())
return base::FilePath();
return wizard_controller->demo_setup_controller()
->GetPreinstalledDemoResourcesPath(file_path);
}
// Loads bundled terms of service contents (Eula, OEM Eula, Play Store Terms).
// The online version of terms is fetched in OOBE screen javascript. This is
// intentional because chrome://terms runs in a privileged webui context and
// should never load from untrusted places.
class ChromeOSTermsHandler
: public base::RefCountedThreadSafe<ChromeOSTermsHandler> {
public:
static void Start(const std::string& path,
content::URLDataSource::GotDataCallback callback) {
scoped_refptr<ChromeOSTermsHandler> handler(
new ChromeOSTermsHandler(path, std::move(callback)));
handler->StartOnUIThread();
}
private:
friend class base::RefCountedThreadSafe<ChromeOSTermsHandler>;
ChromeOSTermsHandler(const std::string& path,
content::URLDataSource::GotDataCallback callback)
: path_(path),
callback_(std::move(callback)),
// Previously we were using "initial locale" http://crbug.com/145142
locale_(g_browser_process->GetApplicationLocale()) {}
virtual ~ChromeOSTermsHandler() {}
void StartOnUIThread() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (path_ == chrome::kOemEulaURLPath) {
// Load local OEM EULA from the disk.
base::ThreadPool::PostTaskAndReply(
FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE},
base::BindOnce(&ChromeOSTermsHandler::LoadOemEulaFileAsync, this),
base::BindOnce(&ChromeOSTermsHandler::ResponseOnUIThread, this));
} else if (path_ == chrome::kArcTermsURLPath) {
// Load ARC++ terms from the file.
base::ThreadPool::PostTaskAndReply(
FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE},
base::BindOnce(&ChromeOSTermsHandler::LoadArcTermsFileAsync, this),
base::BindOnce(&ChromeOSTermsHandler::ResponseOnUIThread, this));
} else if (path_ == chrome::kArcPrivacyPolicyURLPath) {
// Load ARC++ privacy policy from the file.
base::ThreadPool::PostTaskAndReply(
FROM_HERE, {base::MayBlock(), base::TaskPriority::USER_VISIBLE},
base::BindOnce(&ChromeOSTermsHandler::LoadArcPrivacyPolicyFileAsync,
this),
base::BindOnce(&ChromeOSTermsHandler::ResponseOnUIThread, this));
} else {
NOTREACHED();
ResponseOnUIThread();
}
}
void LoadOemEulaFileAsync() {
base::ScopedBlockingCall scoped_blocking_call(
FROM_HERE, base::BlockingType::MAY_BLOCK);
const chromeos::StartupCustomizationDocument* customization =
chromeos::StartupCustomizationDocument::GetInstance();
if (!customization->IsReady())
return;
base::FilePath oem_eula_file_path;
if (net::FileURLToFilePath(GURL(customization->GetEULAPage(locale_)),
&oem_eula_file_path)) {
if (!base::ReadFileToString(oem_eula_file_path, &contents_)) {
contents_.clear();
}
}
}
void LoadArcPrivacyPolicyFileAsync() {
base::ScopedBlockingCall scoped_blocking_call(
FROM_HERE, base::BlockingType::MAY_BLOCK);
for (const auto& locale : CreateArcLocaleLookupArray()) {
// Offline ARC privacy policis are only available during demo mode setup.
auto path =
CreateDemoResourcesTermsPath(base::FilePath(base::StringPrintf(
chrome::kArcPrivacyPolicyPathFormat, locale.c_str())));
std::string contents;
if (base::ReadFileToString(path, &contents)) {
base::Base64Encode(contents, &contents_);
VLOG(1) << "Read offline Play Store privacy policy for: " << locale;
return;
}
LOG(WARNING) << "Could not find offline Play Store privacy policy for: "
<< locale;
}
LOG(ERROR) << "Failed to load offline Play Store privacy policy";
contents_.clear();
}
void LoadArcTermsFileAsync() {
base::ScopedBlockingCall scoped_blocking_call(
FROM_HERE, base::BlockingType::MAY_BLOCK);
for (const auto& locale : CreateArcLocaleLookupArray()) {
// Offline ARC TOS are only available during demo mode setup.
auto path = CreateDemoResourcesTermsPath(base::FilePath(
base::StringPrintf(chrome::kArcTermsPathFormat, locale.c_str())));
std::string contents;
if (base::ReadFileToString(path, &contents_)) {
VLOG(1) << "Read offline Play Store terms for: " << locale;
return;
}
LOG(WARNING) << "Could not find offline Play Store terms for: " << locale;
}
LOG(ERROR) << "Failed to load offline Play Store ToS";
contents_.clear();
}
std::vector<std::string> CreateArcLocaleLookupArray() {
// To get Play Store asset we look for the first locale match in the
// following order:
// * language and device region combination
// * default region (APAC, EMEA, EU)
// * en-US
// Note: AMERICAS region defaults to en-US and to simplify it is not
// included in the country region map.
std::vector<std::string> locale_lookup_array;
const std::string device_region = ReadDeviceRegionFromVpd();
locale_lookup_array.push_back(base::StrCat(
{base::ToLowerASCII(language::ExtractBaseLanguage(locale_)), "-",
device_region}));
const CountryRegionMap country_region_map = CreateCountryRegionMap();
const auto region = country_region_map.find(device_region);
if (region != country_region_map.end()) {
locale_lookup_array.push_back(region->second.c_str());
}
locale_lookup_array.push_back("en-us");
return locale_lookup_array;
}
void ResponseOnUIThread() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// If we fail to load Chrome OS EULA from disk, load it from resources.
// Do nothing if OEM EULA or Play Store ToS load failed.
if (contents_.empty() && path_.empty()) {
contents_ =
ui::ResourceBundle::GetSharedInstance().LoadLocalizedResourceString(
IDS_TERMS_HTML);
}
std::move(callback_).Run(base::RefCountedString::TakeString(&contents_));
}
// Path in the URL.
const std::string path_;
// Callback to run with the response.
content::URLDataSource::GotDataCallback callback_;
// Locale of the EULA.
const std::string locale_;
// EULA contents that was loaded from file.
std::string contents_;
DISALLOW_COPY_AND_ASSIGN(ChromeOSTermsHandler);
};
class ChromeOSCreditsHandler
: public base::RefCountedThreadSafe<ChromeOSCreditsHandler> {
public:
static void Start(const std::string& path,
content::URLDataSource::GotDataCallback callback) {
scoped_refptr<ChromeOSCreditsHandler> handler(
new ChromeOSCreditsHandler(path, std::move(callback)));
handler->StartOnUIThread();
}
private:
friend class base::RefCountedThreadSafe<ChromeOSCreditsHandler>;
ChromeOSCreditsHandler(const std::string& path,
content::URLDataSource::GotDataCallback callback)
: path_(path), callback_(std::move(callback)) {}
virtual ~ChromeOSCreditsHandler() {}
void StartOnUIThread() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (path_ == kKeyboardUtilsPath) {
contents_ =
ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(
IDR_KEYBOARD_UTILS_JS);
ResponseOnUIThread();
return;
}
// Load local Chrome OS credits from the disk.
base::ThreadPool::PostTaskAndReply(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
base::BindOnce(&ChromeOSCreditsHandler::LoadCreditsFileAsync, this),
base::BindOnce(&ChromeOSCreditsHandler::ResponseOnUIThread, this));
}
void LoadCreditsFileAsync() {
base::FilePath credits_file_path(chrome::kChromeOSCreditsPath);
if (!base::ReadFileToString(credits_file_path, &contents_)) {
// File with credits not found, ResponseOnUIThread will load credits
// from resources if contents_ is empty.
contents_.clear();
}
}
void ResponseOnUIThread() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// If we fail to load Chrome OS credits from disk, load it from resources.
if (contents_.empty() && path_ != kKeyboardUtilsPath) {
contents_ =
ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(
IDR_OS_CREDITS_HTML);
}
std::move(callback_).Run(base::RefCountedString::TakeString(&contents_));
}
// Path in the URL.
const std::string path_;
// Callback to run with the response.
content::URLDataSource::GotDataCallback callback_;
// Chrome OS credits contents that was loaded from file.
std::string contents_;
DISALLOW_COPY_AND_ASSIGN(ChromeOSCreditsHandler);
};
class CrostiniCreditsHandler
: public base::RefCountedThreadSafe<CrostiniCreditsHandler> {
public:
static void Start(const std::string& path,
content::URLDataSource::GotDataCallback callback) {
scoped_refptr<CrostiniCreditsHandler> handler(
new CrostiniCreditsHandler(path, std::move(callback)));
handler->StartOnUIThread();
}
private:
friend class base::RefCountedThreadSafe<CrostiniCreditsHandler>;
CrostiniCreditsHandler(const std::string& path,
content::URLDataSource::GotDataCallback callback)
: path_(path), callback_(std::move(callback)) {}
virtual ~CrostiniCreditsHandler() {}
void StartOnUIThread() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (path_ == kKeyboardUtilsPath) {
contents_ =
ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(
IDR_KEYBOARD_UTILS_JS);
ResponseOnUIThread();
return;
}
auto component_manager =
g_browser_process->platform_part()->cros_component_manager();
if (!component_manager) {
LoadCredits(base::FilePath(chrome::kLinuxCreditsPath));
return;
}
component_manager->Load(
imageloader::kTerminaComponentName,
component_updater::CrOSComponentManager::MountPolicy::kMount,
component_updater::CrOSComponentManager::UpdatePolicy::kSkip,
base::BindOnce(&CrostiniCreditsHandler::OnTerminaLoaded, this));
}
void LoadCredits(base::FilePath path) {
// Load crostini credits from the disk.
base::ThreadPool::PostTaskAndReply(
FROM_HERE, {base::MayBlock(), base::TaskPriority::BEST_EFFORT},
base::BindOnce(&CrostiniCreditsHandler::LoadCrostiniCreditsFileAsync,
this, std::move(path)),
base::BindOnce(&CrostiniCreditsHandler::ResponseOnUIThread, this));
}
void LoadCrostiniCreditsFileAsync(base::FilePath credits_file_path) {
if (!base::ReadFileToString(credits_file_path, &contents_)) {
// File with credits not found, ResponseOnUIThread will load credits
// from resources if contents_ is empty.
contents_.clear();
}
}
void OnTerminaLoaded(component_updater::CrOSComponentManager::Error error,
const base::FilePath& path) {
if (error == component_updater::CrOSComponentManager::Error::NONE) {
LoadCredits(path.Append(kTerminaCreditsPath));
return;
}
LoadCredits(base::FilePath(chrome::kLinuxCreditsPath));
}
void ResponseOnUIThread() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// If we fail to load Linux credits from disk, load the placeholder from
// resources.
// TODO(rjwright): Add a linux-specific placeholder in resources.
if (contents_.empty() && path_ != kKeyboardUtilsPath) {
contents_ =
ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(
IDR_OS_CREDITS_HTML);
}
std::move(callback_).Run(base::RefCountedString::TakeString(&contents_));
}
// Path in the URL.
const std::string path_;
// Callback to run with the response.
content::URLDataSource::GotDataCallback callback_;
// Linux credits contents that was loaded from file.
std::string contents_;
DISALLOW_COPY_AND_ASSIGN(CrostiniCreditsHandler);
};
#endif
} // namespace
// Individual about handlers ---------------------------------------------------
namespace about_ui {
void AppendHeader(std::string* output, int refresh,
const std::string& unescaped_title) {
output->append("<!DOCTYPE HTML>\n<html>\n<head>\n");
if (!unescaped_title.empty()) {
output->append("<title>");
output->append(net::EscapeForHTML(unescaped_title));
output->append("</title>\n");
}
output->append("<meta charset='utf-8'>\n");
if (refresh > 0) {
output->append("<meta http-equiv='refresh' content='");
output->append(base::NumberToString(refresh));
output->append("'/>\n");
}
}
void AppendBody(std::string *output) {
output->append("</head>\n<body>\n");
}
void AppendFooter(std::string *output) {
output->append("</body>\n</html>\n");
}
} // namespace about_ui
using about_ui::AppendHeader;
using about_ui::AppendBody;
using about_ui::AppendFooter;
namespace {
std::string ChromeURLs() {
std::string html;
AppendHeader(&html, 0, "Chrome URLs");
AppendBody(&html);
html += "<h2>List of Chrome URLs</h2>\n<ul>\n";
std::vector<std::string> hosts(
chrome::kChromeHostURLs,
chrome::kChromeHostURLs + chrome::kNumberOfChromeHostURLs);
std::sort(hosts.begin(), hosts.end());
for (std::vector<std::string>::const_iterator i = hosts.begin();
i != hosts.end(); ++i)
html += "<li><a href='chrome://" + *i + "/'>chrome://" + *i + "</a></li>\n";
html += "</ul>\n<h2>For Debug</h2>\n"
"<p>The following pages are for debugging purposes only. Because they "
"crash or hang the renderer, they're not linked directly; you can type "
"them into the address bar if you need them.</p>\n<ul>";
for (size_t i = 0; i < chrome::kNumberOfChromeDebugURLs; i++)
html += "<li>" + std::string(chrome::kChromeDebugURLs[i]) + "</li>\n";
html += "</ul>\n";
AppendFooter(&html);
return html;
}
#if defined(OS_LINUX) || defined(OS_OPENBSD)
std::string AboutLinuxProxyConfig() {
std::string data;
AppendHeader(&data, 0,
l10n_util::GetStringUTF8(IDS_ABOUT_LINUX_PROXY_CONFIG_TITLE));
data.append("<style>body { max-width: 70ex; padding: 2ex 5ex; }</style>");
AppendBody(&data);
base::FilePath binary = base::CommandLine::ForCurrentProcess()->GetProgram();
data.append(
l10n_util::GetStringFUTF8(IDS_ABOUT_LINUX_PROXY_CONFIG_BODY,
l10n_util::GetStringUTF16(IDS_PRODUCT_NAME),
base::ASCIIToUTF16(binary.BaseName().value())));
AppendFooter(&data);
return data;
}
#endif
} // namespace
// AboutUIHTMLSource ----------------------------------------------------------
AboutUIHTMLSource::AboutUIHTMLSource(const std::string& source_name,
Profile* profile)
: source_name_(source_name),
profile_(profile) {}
AboutUIHTMLSource::~AboutUIHTMLSource() {}
std::string AboutUIHTMLSource::GetSource() {
return source_name_;
}
void AboutUIHTMLSource::StartDataRequest(
const GURL& url,
const content::WebContents::Getter& wc_getter,
content::URLDataSource::GotDataCallback callback) {
// TODO(crbug/1009127): Simplify usages of |path| since |url| is available.
const std::string path = content::URLDataSource::URLToRequestPath(url);
std::string response;
// Add your data source here, in alphabetical order.
if (source_name_ == chrome::kChromeUIChromeURLsHost) {
response = ChromeURLs();
} else if (source_name_ == chrome::kChromeUICreditsHost) {
int idr = IDR_ABOUT_UI_CREDITS_HTML;
if (path == kCreditsJsPath)
idr = IDR_ABOUT_UI_CREDITS_JS;
#if defined(OS_CHROMEOS)
else if (path == kKeyboardUtilsPath)
idr = IDR_KEYBOARD_UTILS_JS;
#endif
if (idr == IDR_ABOUT_UI_CREDITS_HTML) {
response = about_ui::GetCredits(true /*include_scripts*/);
} else {
response =
ui::ResourceBundle::GetSharedInstance().LoadDataResourceString(idr);
}
#if defined(OS_LINUX) || defined(OS_OPENBSD)
} else if (source_name_ == chrome::kChromeUILinuxProxyConfigHost) {
response = AboutLinuxProxyConfig();
#endif
#if defined(OS_CHROMEOS)
} else if (source_name_ == chrome::kChromeUIOSCreditsHost) {
ChromeOSCreditsHandler::Start(path, std::move(callback));
return;
} else if (source_name_ == chrome::kChromeUICrostiniCreditsHost) {
CrostiniCreditsHandler::Start(path, std::move(callback));
return;
#endif
#if !defined(OS_ANDROID)
} else if (source_name_ == chrome::kChromeUITermsHost) {
#if defined(OS_CHROMEOS)
if (!path.empty()) {
ChromeOSTermsHandler::Start(path, std::move(callback));
return;
}
#endif
response =
ui::ResourceBundle::GetSharedInstance().LoadLocalizedResourceString(
IDS_TERMS_HTML);
#endif
}
FinishDataRequest(response, std::move(callback));
}
void AboutUIHTMLSource::FinishDataRequest(
const std::string& html,
content::URLDataSource::GotDataCallback callback) {
std::string html_copy(html);
std::move(callback).Run(base::RefCountedString::TakeString(&html_copy));
}
std::string AboutUIHTMLSource::GetMimeType(const std::string& path) {
if (path == kCreditsJsPath ||
#if defined(OS_CHROMEOS)
path == kKeyboardUtilsPath ||
#endif
path == kStatsJsPath ||
path == kStringsJsPath) {
return "application/javascript";
}
return "text/html";
}
bool AboutUIHTMLSource::ShouldAddContentSecurityPolicy() {
#if defined(OS_CHROMEOS)
if (source_name_ == chrome::kChromeUIOSCreditsHost ||
source_name_ == chrome::kChromeUICrostiniCreditsHost) {
return false;
}
#endif
return content::URLDataSource::ShouldAddContentSecurityPolicy();
}
std::string AboutUIHTMLSource::GetAccessControlAllowOriginForOrigin(
const std::string& origin) {
#if defined(OS_CHROMEOS)
// Allow chrome://oobe to load chrome://terms via XHR.
if (source_name_ == chrome::kChromeUITermsHost &&
base::StartsWith(chrome::kChromeUIOobeURL, origin,
base::CompareCase::SENSITIVE)) {
return origin;
}
#endif
return content::URLDataSource::GetAccessControlAllowOriginForOrigin(origin);
}
AboutUI::AboutUI(content::WebUI* web_ui, const std::string& name)
: WebUIController(web_ui) {
Profile* profile = Profile::FromWebUI(web_ui);
#if !defined(OS_ANDROID)
// Set up the chrome://theme/ source.
content::URLDataSource::Add(profile, std::make_unique<ThemeSource>(profile));
#endif
content::URLDataSource::Add(
profile, std::make_unique<AboutUIHTMLSource>(name, profile));
}
| {
"content_hash": "5bdf598c6f26dab6322fa262fbbb5df3",
"timestamp": "",
"source": "github",
"line_count": 704,
"max_line_length": 80,
"avg_line_length": 35.98295454545455,
"alnum_prop": 0.6761408495183957,
"repo_name": "endlessm/chromium-browser",
"id": "2bda9c07e29ad13984cfcaa554a1e038eb427a7e",
"size": "25332",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "chrome/browser/ui/webui/about_ui.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [],
"symlink_target": ""
} |
package net.techcable.techapi;
import com.google.common.base.Charsets;
import com.google.common.base.Throwables;
import com.google.common.io.*;
import com.google.common.net.HttpHeaders;
import com.google.common.net.MediaType;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.SettableFuture;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import net.techcable.techapi.uuid.ProfileUtils;
import net.techcable.techapi.uuid.ProfileUtils.PlayerProfile;
import be.maximvdw.spigotsite.api.SpigotSite;
import be.maximvdw.spigotsite.api.SpigotSiteAPI;
import spark.Request;
import spark.Response;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static spark.Spark.*;
public class TechAPI {
public static void main(String[] args) throws IOException {
setPort(12345);
CharSource in = Files.asCharSource(configFile, Charsets.UTF_8);
config = new APIConfig((Map<String, String>) yaml.load(in.openBufferedStream()));
get("/minecraft/uuid/:name", (Request request, Response response) -> {
response.header(HttpHeaders.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.toString());
PlayerProfile profile = ProfileUtils.lookup(request.params(":name"));
if (profile == null) {
return "none" + "||" + request.params(":name");
} else {
return profile.getId() + "||" + profile.getName();
}
});
get("/minecraft/name/:uuid", (Request request, Response response) -> {
response.header(HttpHeaders.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.toString());
PlayerProfile profile = ProfileUtils.lookup(UUID.fromString(request.params(":name")));
if (profile == null) {
return "none" + "||" + request.params(":uuid");
}
return profile.getId() + "||" + profile.getName();
});
get("/minecraft/rawskin/:uuid", (Request request, Response response) -> {
response.header(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString());
PlayerProfile profile = ProfileUtils.lookupProperties(UUID.fromString(request.params(":uuid")));
if (profile == null) {
return "";
}
JsonArray properties = profile.getProperties();
for (JsonElement property : properties) {
JsonObject object = property.getAsJsonObject();
if (object.get("name").equals("textures")) {
return object.toString();
}
}
return "";
});
}
}
| {
"content_hash": "da5fe481d5b6cd0e2597128e951ff4da",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 108,
"avg_line_length": 38.888888888888886,
"alnum_prop": 0.6407142857142857,
"repo_name": "Techcable/TechAPI",
"id": "d235be0c7438c34022ef4f7bdc7e69b60083fc08",
"size": "3933",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/net/techcable/techapi/TechAPI.java",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "15404"
}
],
"symlink_target": ""
} |
package retrofit.http;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Named key/value pairs for a form-encoded request.
* <p>
* Field values may be {@code null} which will omit them from the request body.
* <p>
* Simple Example:
* <pre>
* @FormUrlEncoded
* @POST("/things")
* void things(@FieldMap Map<String, String> fields);
* }
* </pre>
* Calling with {@code foo.things(ImmutableMap.of("foo", "bar", "kit", "kat")} yields a request
* body of {@code foo=bar&kit=kat}.
*
* @see FormUrlEncoded
* @see Field
*/
@Documented
@Target(PARAMETER)
@Retention(RUNTIME)
public @interface FieldMap {
}
| {
"content_hash": "c5cae33088b8be3e42e66cfdbb50aee7",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 95,
"avg_line_length": 24.636363636363637,
"alnum_prop": 0.7134071340713407,
"repo_name": "TomkeyZhang/retrofit",
"id": "8bbfda2c2b20e65d2fbf4a8c7ec2cfaa8510143d",
"size": "1413",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "retrofit/src/main/java/retrofit/http/FieldMap.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3692"
},
{
"name": "Java",
"bytes": "386427"
},
{
"name": "Shell",
"bytes": "986"
}
],
"symlink_target": ""
} |
<?php
/**
* @author Alexey Samoylov <alexey.samoylov@gmail.com>
*/
namespace mirocow\eav\handlers;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
/**
* Class MultipleOptionsValueHandler
*
* @package mirocow\eav
*/
class MultipleOptionsValueHandler extends ValueHandler
{
/** @var AttributeHandler */
public $attributeHandler;
public function load()
{
$EavModel = $this->attributeHandler->owner;
/** @var ActiveRecord $valueClass */
$valueClass = $EavModel->valueClass;
$models = $valueClass::findAll(
[
'entityId' => $EavModel->entityModel->getPrimaryKey(),
'attributeId' => $this->attributeHandler->attributeModel->getPrimaryKey(),
]
);
$values = ArrayHelper::getColumn(
$models,
function ($element) {
return $element->optionId;
}
);
return $values;
}
/**
* @inheritdoc
*/
public function defaultValue()
{
$defaultOptions = [];
foreach ($this->attributeHandler->attributeModel->eavOptions as $option) {
if ($option->defaultOptionId === 1) {
$defaultOptions[] = $option->id;
}
}
return $defaultOptions;
}
public function save()
{
$EavModel = $this->attributeHandler->owner;
$attribute = $this->attributeHandler->getAttributeName();
/** @var ActiveRecord $valueClass */
$valueClass = $EavModel->valueClass;
$baseQuery = $valueClass::find()->where(
[
'entityId' => $EavModel->entityModel->getPrimaryKey(),
'attributeId' => $this->attributeHandler->attributeModel->getPrimaryKey(),
]
);
$allOptions = ArrayHelper::getColumn(
$this->attributeHandler->attributeModel->eavOptions,
function ($element) {
return $element->getPrimaryKey();
}
);
$query = clone $baseQuery;
$query->andWhere(['NOT IN', 'optionId', $allOptions]);
$valueClass::deleteAll($query->where);
// then we delete unselected options
$selectedOptions = ArrayHelper::getValue($EavModel->attributes, $attribute);
if (!is_array($selectedOptions)) {
$selectedOptions = [];
}
$deleteOptions = array_diff($allOptions, $selectedOptions);
$query = clone $baseQuery;
$query->andWhere(['IN', 'optionId', $deleteOptions]);
$valueClass::deleteAll($query->where);
// third we insert missing options
foreach ($selectedOptions as $id) {
$query = clone $baseQuery;
$query->andWhere(['optionId' => $id]);
$valueModel = $query->one();
if (!$valueModel instanceof ActiveRecord) {
/** @var ActiveRecord $valueModel */
$valueModel = new $valueClass;
$valueModel->entityId = $EavModel->entityModel->getPrimaryKey();
$valueModel->attributeId = $this->attributeHandler->attributeModel->getPrimaryKey();
$valueModel->optionId = $id;
if (!$valueModel->save()) {
throw new \Exception("Can't save value model");
}
}
}
}
public function getTextValue()
{
$EavModel = $this->attributeHandler->owner;
/** @var ActiveRecord $valueClass */
$valueClass = $EavModel->valueClass;
$models = $valueClass::findAll(
[
'entityId' => $EavModel->entityModel->getPrimaryKey(),
'attributeId' => $this->attributeHandler->attributeModel->getPrimaryKey(),
]
);
$values = [];
foreach ($models as $model) {
$values[] = $model->option->value;
}
return implode(', ', $values);
}
public function addRules()
{
$model = &$this->attributeHandler->owner;
$attribute = &$this->attributeHandler->attributeModel;
$attribute_name = $this->attributeHandler->getAttributeName();
}
} | {
"content_hash": "5f0f4a37edd24fe803db6724a1ab1fe0",
"timestamp": "",
"source": "github",
"line_count": 146,
"max_line_length": 100,
"avg_line_length": 28.73972602739726,
"alnum_prop": 0.547902764537655,
"repo_name": "Mirocow/yii2-eav",
"id": "ebdad905f60a66be94186b075a4687f05dbd00fb",
"size": "4196",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/handlers/MultipleOptionsValueHandler.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "28861"
},
{
"name": "JavaScript",
"bytes": "372679"
},
{
"name": "PHP",
"bytes": "91915"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace MetroRadiance.UI.Controls
{
public class LinkButton : Button
{
static LinkButton()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(LinkButton), new FrameworkPropertyMetadata(typeof(LinkButton)));
}
#region Text 依存関係プロパティ
public string Text
{
get { return (string)this.GetValue(TextProperty); }
set { this.SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(LinkButton), new UIPropertyMetadata(""));
#endregion
#region TextTrimming 依存関係プロパティ
public TextTrimming TextTrimming
{
get { return (TextTrimming)this.GetValue(TextTrimmingProperty); }
set { this.SetValue(TextTrimmingProperty, value); }
}
public static readonly DependencyProperty TextTrimmingProperty =
DependencyProperty.Register("TextTrimming", typeof(TextTrimming), typeof(LinkButton), new UIPropertyMetadata(TextTrimming.CharacterEllipsis));
#endregion
#region TextWrapping 依存関係プロパティ
public TextWrapping TextWrapping
{
get { return (TextWrapping)this.GetValue(TextWrappingProperty); }
set { this.SetValue(TextWrappingProperty, value); }
}
public static readonly DependencyProperty TextWrappingProperty =
DependencyProperty.Register("TextWrapping", typeof(TextWrapping), typeof(LinkButton), new UIPropertyMetadata(TextWrapping.NoWrap));
#endregion
}
}
| {
"content_hash": "204f6c8b6aef949a75a8e746800df7f1",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 145,
"avg_line_length": 29.90740740740741,
"alnum_prop": 0.7486068111455109,
"repo_name": "FreyYa/MetroRadiance",
"id": "cd5611efc431b6b138eb7b88f01e82e85b2bc0ad",
"size": "1671",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "source/MetroRadiance/UI/Controls/LinkButton.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "280"
},
{
"name": "C#",
"bytes": "401311"
}
],
"symlink_target": ""
} |
FROM balenalib/odroid-c1-ubuntu:cosmic-run
ENV NODE_VERSION 14.15.4
ENV YARN_VERSION 1.22.4
RUN buildDeps='curl libatomic1' \
&& set -x \
&& for key in \
6A010C5166006599AA17F08146C2130DFD2497F5 \
; do \
gpg --keyserver pgp.mit.edu --recv-keys "$key" || \
gpg --keyserver keyserver.pgp.com --recv-keys "$key" || \
gpg --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
done \
&& apt-get update && apt-get install -y $buildDeps --no-install-recommends \
&& rm -rf /var/lib/apt/lists/* \
&& curl -SLO "http://nodejs.org/dist/v$NODE_VERSION/node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& echo "ffce90b07675434491361dfc74eee230f9ffc65c6c08efb88a18781bcb931871 node-v$NODE_VERSION-linux-armv7l.tar.gz" | sha256sum -c - \
&& tar -xzf "node-v$NODE_VERSION-linux-armv7l.tar.gz" -C /usr/local --strip-components=1 \
&& rm "node-v$NODE_VERSION-linux-armv7l.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz" \
&& curl -fSLO --compressed "https://yarnpkg.com/downloads/$YARN_VERSION/yarn-v$YARN_VERSION.tar.gz.asc" \
&& gpg --batch --verify yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& mkdir -p /opt/yarn \
&& tar -xzf yarn-v$YARN_VERSION.tar.gz -C /opt/yarn --strip-components=1 \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarn \
&& ln -s /opt/yarn/bin/yarn /usr/local/bin/yarnpkg \
&& rm yarn-v$YARN_VERSION.tar.gz.asc yarn-v$YARN_VERSION.tar.gz \
&& npm config set unsafe-perm true -g --unsafe-perm \
&& rm -rf /tmp/*
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@node.sh" \
&& echo "Running test-stack@node" \
&& chmod +x test-stack@node.sh \
&& bash test-stack@node.sh \
&& rm -rf test-stack@node.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu cosmic \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nNode.js v14.15.4, Yarn v1.22.4 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {
"content_hash": "3ce2c2a3ca6bbb0760fb67b1618e9413",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 692,
"avg_line_length": 64.35555555555555,
"alnum_prop": 0.7047651933701657,
"repo_name": "nghiant2710/base-images",
"id": "29571d05849c9f12b8cdb1b39a9d0e803fc6c012",
"size": "2917",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/node/odroid-c1/ubuntu/cosmic/14.15.4/run/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "144558581"
},
{
"name": "JavaScript",
"bytes": "16316"
},
{
"name": "Shell",
"bytes": "368690"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en-us">
<head>
<link href="http://gmpg.org/xfn/11" rel="profile">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta property="og:title" content="linux">
<meta property="og:type" content="website">
<meta property="og:description" content="">
<meta property="og:url" content="https://satoshun.github.io/tags/linux/">
<meta property="og:site_name" content="stsnブログ">
<meta property="twitter:title" content="linux">
<meta property="twitter:description" content="Android, Python, Reactive, DB(RDS), etc">
<meta property="twitter:image" content="https://bit.ly/2S8StSM">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">
<title> linux - stsnブログ </title>
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel="stylesheet" href="https://satoshun.github.io/css/main.css">
<link rel="stylesheet" href="https://satoshun.github.io/css/poole.css">
<link rel="stylesheet" href="https://satoshun.github.io/css/syntax.css">
<link rel="stylesheet" href="https://satoshun.github.io/css/hyde.css">
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=PT+Sans:400,400italic,700|Abril+Fatface">
<link rel="shortcut icon" href="/favicon.png">
<link href="https://satoshun.github.io/tags/linux/index.xml" rel="alternate" type="application/rss+xml" title="stsnブログ" />
<link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet">
<link href='//fonts.googleapis.com/css?family=Raleway:400,300' rel='stylesheet' type='text/css'>
<script src="//ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js"></script>
<script>
WebFont.load({
google: {
families: ['Raleway']
}
});
</script>
<link rel="stylesheet"
href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/styles/agate.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/highlight.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/languages/kotlin.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.13.1/languages/groovy.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
</head>
<body class="theme-dark">
<section class="site-nav">
<header class="container">
<nav id="navigation">
<a href="/" class="home">Home</a>
<a href="/blog">Blog</a>
<a href="/presentation">Presentation</a>
<a href="/book">Book</a>
</nav>
</header>
</section>
<div class="blog-cover">
<section>
<div class="container">
<h1 class="title-container"><a href="https://satoshun.github.io">stsnブログ</a></h1>
<h3>Android, Kotlin, Python, Go, Developer</h3>
<a class="social-icon" href="https://twitter.com/stsn_jp" title="Follow on Twitter" target="_blank"><i class="icon icon-twitter"></i></a>
<a class="social-icon" href="https://github.com/satoshun" title="Follow on Github" target="_blank"><i class="icon icon-github"></i></a>
<a class="social-icon" href="/index.xml" title="RSS Feed">
<i class="icon icon-rss"></i>
</a>
<div class="mb15"></div>
</div>
</section>
</div>
<div class="content container">
<h1 class="title">linux</h1>
<ul class="posts tag-list">
<li class="tag-list-item">
<a href="https://satoshun.github.io/2016/07/linux-perf/">Linux perf: CPU編</a>
<time class="tag-list-item-time">Sun, Jul 17, 2016</time>
</li>
</ul>
</div>
</body>
</html>
| {
"content_hash": "b6a028f81293c3df98b898a8030725f6",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 143,
"avg_line_length": 33.123893805309734,
"alnum_prop": 0.6441357200106866,
"repo_name": "satoshun/satoshun.github.io",
"id": "039905bf8c97cf8b834d35c2eb334aff3b1991a3",
"size": "3769",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "tags/linux/index.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "174264"
},
{
"name": "HTML",
"bytes": "4179614"
}
],
"symlink_target": ""
} |
import java.util.*;
class Main { /* How do you add? */
// top-down
private static int N, K;
private static int[][] memo = new int[110][110];
private static int ways(int N, int K) {
if (K == 1) // only can use 1 number to add up to N
return 1; // the answer is definitely 1, that number itself
else if (memo[N][K] != -1)
return memo[N][K];
// if K > 1, we can choose one number from [0..N] to be one of the number
// and recursively compute the rest
int total_ways = 0;
for (int split = 0; split <= N; split++)
total_ways = (total_ways + ways(N - split, K - 1)) % 1000000; // we just need the modulo 1M
return memo[N][K] = total_ways; // memoize them
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
for (int i = 0; i < 110; i++)
for (int j = 0; j < 110; j++)
memo[i][j] = -1;
while (true) {
N = sc.nextInt();
K = sc.nextInt();
if (N == 0 && K == 0)
break;
System.out.printf("%d\n", ways(N, K)); // some recursion formula + top down DP
}
}
}
| {
"content_hash": "a58e3540f959bd62fbfac98a78aa07eb",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 97,
"avg_line_length": 29.973684210526315,
"alnum_prop": 0.5302897278314311,
"repo_name": "massimo-nocentini/competitive-programming",
"id": "c31b642d42505a19278a9a012880084d5138ebe1",
"size": "1139",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "steven-halim-cp-book-supporting-material/original-archives/ch3/ch3_10_UVa10943.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "13606"
},
{
"name": "C++",
"bytes": "180189"
},
{
"name": "HTML",
"bytes": "6106"
},
{
"name": "Java",
"bytes": "224706"
},
{
"name": "Jupyter Notebook",
"bytes": "309902"
},
{
"name": "Makefile",
"bytes": "864"
},
{
"name": "Python",
"bytes": "71524"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Gallio.Ambience
{
/// <summary>
/// A data set containing Ambient objects.
/// </summary>
public interface IAmbientDataSet<T> : IList<T>
{
}
}
| {
"content_hash": "10739b73edf82a47ac7fabd8eb9b16e8",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 50,
"avg_line_length": 18.666666666666668,
"alnum_prop": 0.6285714285714286,
"repo_name": "xJom/mbunit-v3",
"id": "603c981814148b311fc64509fe93d199af24e8ac",
"size": "970",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "src/Extensions/Ambience/Gallio.Ambience/IAmbientDataSet.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "8718"
},
{
"name": "Batchfile",
"bytes": "31812"
},
{
"name": "C",
"bytes": "1006"
},
{
"name": "C#",
"bytes": "13534505"
},
{
"name": "C++",
"bytes": "136700"
},
{
"name": "CSS",
"bytes": "14400"
},
{
"name": "HTML",
"bytes": "117545"
},
{
"name": "JavaScript",
"bytes": "6632"
},
{
"name": "Objective-C",
"bytes": "1024"
},
{
"name": "PowerShell",
"bytes": "11691"
},
{
"name": "Ruby",
"bytes": "3597212"
},
{
"name": "Visual Basic",
"bytes": "12688"
},
{
"name": "XSLT",
"bytes": "123017"
}
],
"symlink_target": ""
} |
package com.bugtrack.service;
import java.util.ArrayList;
import java.util.List;
import com.bugtrack.config.HibernateUtil;
import com.bugtrack.entity.lemma;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;
import static java.util.stream.Collectors.summingInt;
import static java.util.stream.Collectors.toList;
/**
* The lemmaService provides data structure
* and methods to process lemmas
* @version 0.9.9 15 July 2016
* @author Sergey Samsonov
*/
@Service
public class lemmaService {
private SessionFactory sessionFactory;
public lemmaService() {
try{
this.sessionFactory = HibernateUtil.getSessionFactory();
}catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public void addEntity(lemma lemma) {
if (lemma != null) {
Session session = sessionFactory.openSession();
Transaction tr = null;
try {
tr = session.beginTransaction();
session.save(lemma);
tr.commit();
} catch (HibernateException e) {
if (tr != null) tr.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
public void updateEntity(lemma lemma) {
if (lemma != null) {
Session session = sessionFactory.openSession();
Transaction tr = null;
try {
tr = session.beginTransaction();
session.update(lemma);
tr.commit();
} catch (HibernateException e) {
if (tr != null) tr.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
public void delEntity(lemma lemma) {
if (lemma != null) {
Session session = sessionFactory.openSession();
Transaction tr = null;
try {
tr = session.beginTransaction();
session.delete(lemma);
tr.commit();
} catch (HibernateException e) {
if (tr != null) tr.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
public List<lemma> getLemmasByList(List<String> lemmasList){
if (lemmasList == null) {
return null;
}
Session session = sessionFactory.openSession();
Transaction tr = null;
List<lemma> lemmas = new ArrayList<>();
try {
tr = session.beginTransaction();
Criteria lemmasCriteria = session.createCriteria(lemma.class);
lemmasCriteria.add(Restrictions.in("lemma", lemmasList));
lemmas.addAll(lemmasCriteria.list());
tr.commit();
} catch (HibernateException e) {
if (tr != null) tr.rollback();
e.printStackTrace();
} finally {
session.close();
}
return lemmas;
}
public lemma getLemmaObjByLemma(String lemmastr) {
Session session = sessionFactory.openSession();
Transaction tr = null;
lemma lemma = null;
try {
tr = session.beginTransaction();
Criteria lemmasCriteria = session.createCriteria(lemma.class);
lemmasCriteria.add(Restrictions.eq("lemma", lemmastr));
lemma = (lemma) lemmasCriteria.uniqueResult();
tr.commit();
} catch (HibernateException e) {
if (tr != null) tr.rollback();
e.printStackTrace();
} finally {
session.close();
}
return lemma;
}
public void delAllLemmas() {
String hql = "delete from lemma";
Session session = sessionFactory.openSession();
Transaction tr = null;
try {
tr = session.beginTransaction();
session.createQuery(hql).executeUpdate();
tr.commit();
} catch (HibernateException e) {
if (tr != null) tr.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
| {
"content_hash": "56e082fa0c719e054e11a7705852bfe2",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 79,
"avg_line_length": 30.80952380952381,
"alnum_prop": 0.5570766173548245,
"repo_name": "sergsamsonov/semantictrack",
"id": "d258ee5e6dbb8909aa093899673ea1208a204cee",
"size": "4529",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/Java/com/bugtrack/service/lemmaService.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
using System.Windows;
using System.Windows.Controls;
namespace Cobalt.Views.Controls
{
public class AppLayout : ContentControl
{
static AppLayout()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(AppLayout),
new FrameworkPropertyMetadata(typeof(AppLayout)));
}
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
VisualStateManager.GoToState(this, "Normal", true);
/*
var contentCover = (FrameworkElement)GetTemplateChild("PART_ContentCover");
contentCover.MouseDown += (e, a) =>
{
IsMenuOpen = false;
};*/
}
private static void FrameworkPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
/*
var nav = (AppLayout)d;
if (nav.IsMenuOpen && nav.IsSlideOverMenu)
{
VisualStateManager.GoToState(nav, "SlideDrawerOpen", true);
}
else if (nav.IsMenuOpen)
{
VisualStateManager.GoToState(nav, "DrawerOpen", true);
}
else
{
VisualStateManager.GoToState(nav, "Normal", true);
}*/
}
#region Framework Properties
public AppMenuItemCollection MenuItems
{
get => (AppMenuItemCollection) GetValue(MenuItemsProperty);
set => SetValue(MenuItemsProperty, value);
}
public static readonly DependencyProperty MenuItemsProperty =
DependencyProperty.Register("MenuItems", typeof(AppMenuItemCollection), typeof(AppLayout),
new PropertyMetadata(new AppMenuItemCollection()));
public AppMenuItemCollection OptionItems
{
get => (AppMenuItemCollection) GetValue(OptionItemsProperty);
set => SetValue(OptionItemsProperty, value);
}
public static readonly DependencyProperty OptionItemsProperty =
DependencyProperty.Register("OptionItems", typeof(AppMenuItemCollection), typeof(AppLayout),
new PropertyMetadata(new AppMenuItemCollection()));
public bool IsSlideOverMenu
{
get => (bool) GetValue(IsSlideOverMenuProperty);
set => SetValue(IsSlideOverMenuProperty, value);
}
public static readonly DependencyProperty IsSlideOverMenuProperty =
DependencyProperty.Register("IsSlideOverMenu", typeof(bool), typeof(AppLayout),
new PropertyMetadata(false, FrameworkPropertyChanged));
public bool IsMenuOpen
{
get => (bool) GetValue(IsMenuOpenProperty);
set => SetValue(IsMenuOpenProperty, value);
}
public static readonly DependencyProperty IsMenuOpenProperty =
DependencyProperty.Register("IsMenuOpen", typeof(bool), typeof(AppLayout),
new PropertyMetadata(false, FrameworkPropertyChanged));
public AppMenuItem SelectedItem
{
get => (AppMenuItem) GetValue(SelectedItemProperty);
set => SetValue(SelectedItemProperty, value);
}
public static readonly DependencyProperty SelectedItemProperty =
DependencyProperty.Register("SelectedItem", typeof(AppMenuItem), typeof(AppLayout),
new PropertyMetadata(null));
#endregion
}
} | {
"content_hash": "125474ea8f199d26b0f3532696c576b4",
"timestamp": "",
"source": "github",
"line_count": 98,
"max_line_length": 110,
"avg_line_length": 35.36734693877551,
"alnum_prop": 0.6136757068667051,
"repo_name": "Enigmatrix/Cobalt",
"id": "16a6665cfec8e2c40e060212eff2528027d88841",
"size": "3468",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Cobalt/Views/Controls/AppLayout.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "409560"
},
{
"name": "XSLT",
"bytes": "775"
}
],
"symlink_target": ""
} |
import mock
from oslo.config import cfg
from ironic.common import dhcp_factory
from ironic.common import exception
from ironic.common import keystone
from ironic.common import pxe_utils
from ironic.common import states
from ironic.conductor import task_manager
from ironic.drivers.modules import agent
from ironic import objects
from ironic.tests.conductor import utils as mgr_utils
from ironic.tests.db import base as db_base
from ironic.tests.db import utils as db_utils
from ironic.tests.objects import utils as object_utils
INSTANCE_INFO = db_utils.get_test_agent_instance_info()
DRIVER_INFO = db_utils.get_test_agent_driver_info()
CONF = cfg.CONF
class TestAgentMethods(db_base.DbTestCase):
def setUp(self):
super(TestAgentMethods, self).setUp()
self.node = object_utils.create_test_node(self.context,
driver='fake_agent')
def test_build_agent_options_conf(self):
self.config(api_url='api-url', group='conductor')
options = agent.build_agent_options(self.node)
self.assertEqual('api-url', options['ipa-api-url'])
self.assertEqual('fake_agent', options['ipa-driver-name'])
@mock.patch.object(keystone, 'get_service_url')
def test_build_agent_options_keystone(self, get_url_mock):
self.config(api_url=None, group='conductor')
get_url_mock.return_value = 'api-url'
options = agent.build_agent_options(self.node)
self.assertEqual('api-url', options['ipa-api-url'])
self.assertEqual('fake_agent', options['ipa-driver-name'])
class TestAgentDeploy(db_base.DbTestCase):
def setUp(self):
super(TestAgentDeploy, self).setUp()
mgr_utils.mock_the_extension_manager(driver='fake_agent')
self.driver = agent.AgentDeploy()
n = {
'driver': 'fake_agent',
'instance_info': INSTANCE_INFO,
'driver_info': DRIVER_INFO
}
self.node = object_utils.create_test_node(self.context, **n)
def test_validate(self):
with task_manager.acquire(
self.context, self.node['uuid'], shared=False) as task:
self.driver.validate(task)
def test_validate_exception(self):
self.node.driver_info = {}
self.node.save()
with task_manager.acquire(
self.context, self.node['uuid'], shared=False) as task:
self.assertRaises(exception.InvalidParameterValue,
self.driver.validate, task)
@mock.patch.object(dhcp_factory.DHCPFactory, 'update_dhcp')
@mock.patch('ironic.conductor.utils.node_set_boot_device')
@mock.patch('ironic.conductor.utils.node_power_action')
def test_deploy(self, power_mock, bootdev_mock, dhcp_mock):
with task_manager.acquire(
self.context, self.node['uuid'], shared=False) as task:
dhcp_opts = pxe_utils.dhcp_options_for_instance(task)
driver_return = self.driver.deploy(task)
self.assertEqual(driver_return, states.DEPLOYWAIT)
dhcp_mock.assert_called_once_with(task, dhcp_opts)
bootdev_mock.assert_called_once_with(task, 'pxe', persistent=True)
power_mock.assert_called_once_with(task,
states.REBOOT)
@mock.patch('ironic.conductor.utils.node_power_action')
def test_tear_down(self, power_mock):
with task_manager.acquire(
self.context, self.node['uuid'], shared=False) as task:
driver_return = self.driver.tear_down(task)
power_mock.assert_called_once_with(task, states.POWER_OFF)
self.assertEqual(driver_return, states.DELETED)
def test_prepare(self):
pass
def test_clean_up(self):
pass
@mock.patch.object(dhcp_factory.DHCPFactory, 'update_dhcp')
def test_take_over(self, update_dhcp_mock):
with task_manager.acquire(
self.context, self.node['uuid'], shared=True) as task:
task.driver.deploy.take_over(task)
update_dhcp_mock.assert_called_once_with(
task, CONF.agent.agent_pxe_bootfile_name)
class TestAgentVendor(db_base.DbTestCase):
def setUp(self):
super(TestAgentVendor, self).setUp()
mgr_utils.mock_the_extension_manager(driver="fake_agent")
self.passthru = agent.AgentVendorInterface()
n = {
'driver': 'fake_agent',
'instance_info': INSTANCE_INFO,
'driver_info': DRIVER_INFO
}
self.node = object_utils.create_test_node(self.context, **n)
def test_validate(self):
with task_manager.acquire(self.context, self.node.uuid) as task:
self.passthru.validate(task)
def test_driver_validate(self):
kwargs = {'version': '2'}
method = 'lookup'
self.passthru.driver_validate(method, **kwargs)
def test_driver_validate_invalid_paremeter(self):
method = 'lookup'
kwargs = {'version': '1'}
self.assertRaises(exception.InvalidParameterValue,
self.passthru.driver_validate,
method, **kwargs)
def test_driver_validate_missing_parameter(self):
method = 'lookup'
kwargs = {}
self.assertRaises(exception.MissingParameterValue,
self.passthru.driver_validate,
method, **kwargs)
@mock.patch('ironic.common.image_service.Service')
def test_continue_deploy(self, image_service_mock):
test_temp_url = 'http://image'
expected_image_info = {
'urls': [test_temp_url],
'id': 'fake-image',
'checksum': 'checksum',
'disk_format': 'qcow2',
'container_format': 'bare',
}
client_mock = mock.Mock()
glance_mock = mock.Mock()
glance_mock.show.return_value = {}
glance_mock.swift_temp_url.return_value = test_temp_url
image_service_mock.return_value = glance_mock
self.passthru._client = client_mock
with task_manager.acquire(self.context, self.node.uuid,
shared=False) as task:
self.passthru._continue_deploy(task)
client_mock.prepare_image.assert_called_with(task.node,
expected_image_info)
self.assertEqual(task.node.provision_state, states.DEPLOYING)
def test_lookup_version_not_found(self):
kwargs = {
'version': '999',
}
with task_manager.acquire(self.context, self.node.uuid) as task:
self.assertRaises(exception.InvalidParameterValue,
self.passthru.lookup,
task.context,
**kwargs)
@mock.patch('ironic.drivers.modules.agent.AgentVendorInterface'
'._find_node_by_macs')
def test_lookup_v2(self, find_mock):
kwargs = {
'version': '2',
'inventory': {
'interfaces': [
{
'mac_address': 'aa:bb:cc:dd:ee:ff',
'name': 'eth0'
},
{
'mac_address': 'ff:ee:dd:cc:bb:aa',
'name': 'eth1'
}
]
}
}
find_mock.return_value = self.node
with task_manager.acquire(self.context, self.node.uuid) as task:
node = self.passthru.lookup(task.context, **kwargs)
self.assertEqual(self.node, node['node'])
def test_lookup_v2_missing_inventory(self):
with task_manager.acquire(self.context, self.node.uuid) as task:
self.assertRaises(exception.InvalidParameterValue,
self.passthru.lookup,
task.context)
def test_lookup_v2_empty_inventory(self):
with task_manager.acquire(self.context, self.node.uuid) as task:
self.assertRaises(exception.InvalidParameterValue,
self.passthru.lookup,
task.context,
inventory={})
def test_lookup_v2_empty_interfaces(self):
with task_manager.acquire(self.context, self.node.uuid) as task:
self.assertRaises(exception.NodeNotFound,
self.passthru.lookup,
task.context,
version='2',
inventory={'interfaces': []})
@mock.patch.object(objects.Port, 'get_by_address')
def test_find_ports_by_macs(self, mock_get_port):
fake_port = object_utils.get_test_port(self.context)
mock_get_port.return_value = fake_port
macs = ['aa:bb:cc:dd:ee:ff']
with task_manager.acquire(
self.context, self.node['uuid'], shared=True) as task:
ports = self.passthru._find_ports_by_macs(task, macs)
self.assertEqual(1, len(ports))
self.assertEqual(fake_port.uuid, ports[0].uuid)
self.assertEqual(fake_port.node_id, ports[0].node_id)
@mock.patch.object(objects.Port, 'get_by_address')
def test_find_ports_by_macs_bad_params(self, mock_get_port):
mock_get_port.side_effect = exception.PortNotFound(port="123")
macs = ['aa:bb:cc:dd:ee:ff']
with task_manager.acquire(
self.context, self.node['uuid'], shared=True) as task:
empty_ids = self.passthru._find_ports_by_macs(task, macs)
self.assertEqual([], empty_ids)
@mock.patch('ironic.objects.node.Node.get_by_id')
@mock.patch('ironic.drivers.modules.agent.AgentVendorInterface'
'._get_node_id')
@mock.patch('ironic.drivers.modules.agent.AgentVendorInterface'
'._find_ports_by_macs')
def test_find_node_by_macs(self, ports_mock, node_id_mock, node_mock):
ports_mock.return_value = object_utils.get_test_port(self.context)
node_id_mock.return_value = '1'
node_mock.return_value = self.node
macs = ['aa:bb:cc:dd:ee:ff']
with task_manager.acquire(
self.context, self.node['uuid'], shared=True) as task:
node = self.passthru._find_node_by_macs(task, macs)
self.assertEqual(node, node)
@mock.patch('ironic.drivers.modules.agent.AgentVendorInterface'
'._find_ports_by_macs')
def test_find_node_by_macs_no_ports(self, ports_mock):
ports_mock.return_value = []
macs = ['aa:bb:cc:dd:ee:ff']
with task_manager.acquire(
self.context, self.node['uuid'], shared=True) as task:
self.assertRaises(exception.NodeNotFound,
self.passthru._find_node_by_macs,
task,
macs)
@mock.patch('ironic.objects.node.Node.get_by_uuid')
@mock.patch('ironic.drivers.modules.agent.AgentVendorInterface'
'._get_node_id')
@mock.patch('ironic.drivers.modules.agent.AgentVendorInterface'
'._find_ports_by_macs')
def test_find_node_by_macs_nodenotfound(self, ports_mock, node_id_mock,
node_mock):
port = object_utils.get_test_port(self.context)
ports_mock.return_value = [port]
node_id_mock.return_value = self.node['uuid']
node_mock.side_effect = [self.node,
exception.NodeNotFound(node=self.node)]
macs = ['aa:bb:cc:dd:ee:ff']
with task_manager.acquire(
self.context, self.node['uuid'], shared=True) as task:
self.assertRaises(exception.NodeNotFound,
self.passthru._find_node_by_macs,
task,
macs)
def test_get_node_id(self):
fake_port1 = object_utils.get_test_port(self.context,
node_id=123,
address="aa:bb:cc:dd:ee:fe")
fake_port2 = object_utils.get_test_port(self.context,
node_id=123,
id=42,
address="aa:bb:cc:dd:ee:fb",
uuid='1be26c0b-03f2-4d2e-ae87-'
'c02d7f33c782')
node_id = self.passthru._get_node_id([fake_port1, fake_port2])
self.assertEqual(fake_port2.node_id, node_id)
def test_get_node_id_exception(self):
fake_port1 = object_utils.get_test_port(self.context,
node_id=123,
address="aa:bb:cc:dd:ee:fc")
fake_port2 = object_utils.get_test_port(self.context,
node_id=321,
id=42,
address="aa:bb:cc:dd:ee:fd",
uuid='1be26c0b-03f2-4d2e-ae87-'
'c02d7f33c782')
self.assertRaises(exception.NodeNotFound,
self.passthru._get_node_id,
[fake_port1, fake_port2])
def test_get_interfaces(self):
fake_inventory = {
'interfaces': [
{
'mac_address': 'aa:bb:cc:dd:ee:ff',
'name': 'eth0'
}
]
}
interfaces = self.passthru._get_interfaces(fake_inventory)
self.assertEqual(fake_inventory['interfaces'], interfaces)
def test_get_interfaces_bad(self):
self.assertRaises(exception.InvalidParameterValue,
self.passthru._get_interfaces,
inventory={})
def test_heartbeat(self):
kwargs = {
'agent_url': 'http://127.0.0.1:9999/bar'
}
with task_manager.acquire(
self.context, self.node['uuid'], shared=True) as task:
self.passthru.heartbeat(task, **kwargs)
def test_heartbeat_bad(self):
kwargs = {}
with task_manager.acquire(
self.context, self.node['uuid'], shared=True) as task:
self.assertRaises(exception.MissingParameterValue,
self.passthru.heartbeat, task, **kwargs)
@mock.patch.object(agent, '_set_failed_state')
@mock.patch.object(agent.AgentVendorInterface, '_deploy_is_done')
def test_heartbeat_deploy_done_fails(self, done_mock, failed_mock):
kwargs = {
'agent_url': 'http://127.0.0.1:9999/bar'
}
done_mock.side_effect = Exception
with task_manager.acquire(
self.context, self.node['uuid'], shared=True) as task:
task.node.provision_state = states.DEPLOYING
self.passthru.heartbeat(task, **kwargs)
failed_mock.assert_called_once_with(task, mock.ANY)
def test_vendor_passthru_vendor_routes(self):
expected = ['heartbeat']
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
vendor_routes = task.driver.vendor.vendor_routes
self.assertIsInstance(vendor_routes, dict)
self.assertEqual(expected, list(vendor_routes))
def test_vendor_passthru_driver_routes(self):
expected = ['lookup']
with task_manager.acquire(self.context, self.node.uuid,
shared=True) as task:
driver_routes = task.driver.vendor.driver_routes
self.assertIsInstance(driver_routes, dict)
self.assertEqual(expected, list(driver_routes))
| {
"content_hash": "6dbd84ba94c40b921bbc5e53107795ac",
"timestamp": "",
"source": "github",
"line_count": 386,
"max_line_length": 79,
"avg_line_length": 41.468911917098445,
"alnum_prop": 0.5578809270943962,
"repo_name": "Tehsmash/ironic",
"id": "3eafb39d190926b406788e101cf880101105b101",
"size": "16586",
"binary": false,
"copies": "1",
"ref": "refs/heads/staging/kiloplus",
"path": "ironic/tests/drivers/test_agent.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "2250030"
}
],
"symlink_target": ""
} |
class Reservation < ActiveRecord::Base
include ReservationValidations
include ReservationScopes
include Routing
belongs_to :equipment_model
belongs_to :equipment_item
belongs_to :reserver, class_name: 'User'
belongs_to :checkout_handler, class_name: 'User'
belongs_to :checkin_handler, class_name: 'User'
validates :equipment_model, :start_date, :due_date, presence: true
validates_each :reserver do |record, attr, value|
record.errors.add(attr, 'cannot be a guest') if value.role == 'guest'
end
validate :start_date_before_due_date
validate :matched_item_and_model
validate :check_status
validate :status_final_state
validate :not_in_past, :available, :check_banned, on: :create
nilify_blanks only: [:notes]
# see https://robots.thoughtbot.com/whats-new-in-edge-rails-active-record-enum
enum status: %w(requested reserved denied checked_out missed returned
archived)
# valid bitmask flags
# set by reservation |= FLAGS[:flag]
# check by reservation & FLAGS[:flag]
# = 0 when false
# > 0 when true
# query by where('flags & ? > 0', FLAGS[:flag])
# or where('flags & ? = 0', FLAGS[:flag]) for not flagged
FLAGS = { request: (1 << 1), broken: (1 << 2), lost: (1 << 3),
fined: (1 << 4), missed_email_sent: (1 << 5) }
## Class methods ##
def self.completed_procedures(procedures)
# convert the [{id=>value, id=>value}] input
# to [id, id] format
return [] if procedures.nil?
procedures.collect do |key, val|
key if val == '1'
end
end
def self.unique_equipment_items?(reservations)
item_ids = reservations.map(&:equipment_item_id)
item_ids == item_ids.uniq
end
def self.number_for_model_on_date(date, model_id, source)
# count the number of reservations that overlaps a date within
# a given array of source reservations and that matches
# a specific model id
number_for(date, model_id, source, :equipment_model_id)
end
def self.number_for_category_on_date(date, category_id, reservations)
number_for(date, category_id, reservations, :category_id)
end
def self.number_for(date, value, source, property)
count = 0
source.each do |r|
if r.start_date <= date && r.due_date >= date &&
r.send(property) == value
count += 1
end
end
count
end
def self.number_overdue_for_eq_model(model_id, reservations)
# count the number of overdue reservations for a given
# eq model out of an array of source reservations
#
# used in rendering the catalog in order to save db queries
#
# 0 queries
count = 0
reservations.each do |r|
count += 1 if r.overdue && r.equipment_model_id == model_id
end
count
end
## Getter style instance methods ##
def approved?
flagged?(:request) && !%w(denied requested).include?(status)
end
def flagged?(flag)
flags & FLAGS[flag] > 0
end
def flag(flag)
self.flags |= FLAGS[flag]
end
def unflag(flag)
self.flags - FLAGS[flag]
end
def human_status # rubocop:disable all
if overdue
if status == 'returned'
'returned overdue'
else
'overdue'
end
elsif start_date == Time.zone.today && status == 'reserved'
'starts today'
elsif due_date == Time.zone.today && status == 'checked_out'
'due today'
else
status
end
end
def duration
due_date - start_date + 1
end
def time_checked_out
checked_in.to_date - checked_out.to_date + 1 if checked_out && checked_in
end
def late_fee
return 0 unless overdue
if checked_in
end_date = checked_in.to_date
else
end_date = Time.zone.today
end
fee = equipment_model.late_fee * (end_date - due_date)
if fee < 0
fee = 0
elsif equipment_model.late_fee_max > 0
fee = [fee, equipment_model.late_fee_max].min
end
fee
end
def reserver
User.find(reserver_id)
rescue
# if user's been deleted, return a dummy user
User.new(first_name: 'Deleted',
last_name: 'User',
username: 'deleted',
email: 'deleted.user@invalid.address',
nickname: '',
phone: '555-555-5555',
affiliation: 'Deleted')
end
def fake_reserver_id # this is necessary for autocomplete! delete me not!
end
## Instance method helper/misc ##
def find_renewal_date
# determine the max renewal length for a given reservation
# O(n) queries
renew_extension = dup
renew_extension.start_date = due_date + 1.day
orig_due_date = due_date
eq_model = equipment_model
eq_model.maximum_renewal_length.downto(1).each do |r|
renew_extension.due_date = orig_due_date + r.days
return renew_extension.due_date if renew_extension.validate_renew.empty?
end
due_date
end
def eligible_for_renew? # rubocop:disable all
# determines if a reservation is eligible for renewal, based on how many
# days before the due date it is, the max number of times one is allowed
# to renew, and other factors
#
# check some basic conditions
return false if !checked_out? || overdue? || reserver.role == 'banned'
return false unless equipment_model.maximum_renewal_length > 0
return false unless equipment_model.available_count(due_date + 1.day) > 0
self.times_renewed ||= 0
return false if self.times_renewed >= equipment_model.maximum_renewal_times
return false if (due_date - Time.zone.today).to_i >
equipment_model.maximum_renewal_days_before_due
true
end
def to_cart
temp_cart = Cart.new
temp_cart.start_date = start_date
temp_cart.due_date = due_date
temp_cart.reserver_id = reserver_id
temp_cart.items = { equipment_model_id => 1 }
temp_cart
end
## Instance methods that alter the status of a reservation ##
def renew(user)
# renew the reservation and return error messages if unsuccessful
unless self.eligible_for_renew?
return 'Reservation not eligible for renewal'
end
self.due_date = find_renewal_date
self.notes = "#{notes}" + "\n\n### Renewed on "\
"#{Time.zone.now.to_s(:long)} by #{user.md_link}\n\nThe new due date "\
"is #{due_date.to_s(:long)}."
self.times_renewed += 1
return 'Unable to update reservation dates.' unless save
nil
end
def checkin(checkin_handler, procedures, new_notes)
# Checks in a reservation with the given checkin handler
# and hash of checkin procedures and any manually entered
# notes from the checkin
#
# Returns the unsaved, checked in reservation
self.checkin_handler = checkin_handler
self.checked_in = Time.zone.now
self.status = 'returned'
# gather all the procedure texts that were not
# checked, ie not included in the procedures hash
incomplete_procedures = []
procedures = Reservation.completed_procedures(procedures)
equipment_model.checkin_procedures.each do |checkin_procedure|
if procedures.exclude?(checkin_procedure.id.to_s)
incomplete_procedures << checkin_procedure.step
end
end
make_notes('Checked in', new_notes, incomplete_procedures, checkin_handler)
if checked_in.to_date > due_date
# equipment was overdue, send an email confirmation
AdminMailer.overdue_checked_in_fine_admin(self).deliver
UserMailer.reservation_status_update(self).deliver
end
self
end
def archive(archiver, note)
# set the reservation as checked in if it has been checked out
# used for emergency situations or when equipment is deactivated
# to preserve database sanity (eg, equipment item is deactivated while
# that reseration is checked out)
# returns self
if checked_in.nil?
self.checked_in = Time.zone.now
self.checked_out = Time.zone.now if checked_out.nil?
self.notes = notes.to_s + "\n\n### Archived on "\
"#{checked_in.to_s(:long)} by #{archiver.md_link}\n\n\n#### " \
"Reason:\n#{note}\n\n#### The checkin and checkout dates may "\
'reflect the archive date because the reservation was for a '\
'nonexistent piece of equipment or otherwise problematic.'
self.status = 'archived'
end
self
end
def checkout(eq_item, checkout_handler, procedures, new_notes)
# checks out a reservation with the given equipment item, checkout handler
# and a hash of checkout procedures and any manually entered
# notes from the checkout.
#
# Returns the unsaved, checked out reservation
self.checkout_handler = checkout_handler
self.checked_out = Time.zone.now
self.equipment_item_id = eq_item
self.status = 'checked_out'
incomplete_procedures = []
procedures = Reservation.completed_procedures(procedures)
equipment_model.checkout_procedures.each do |checkout_procedure|
if procedures.exclude?(checkout_procedure.id.to_s)
incomplete_procedures << checkout_procedure.step
end
end
make_notes('Checked out', new_notes, incomplete_procedures,
checkout_handler)
self
end
def update(current_user, new_params, new_notes) # rubocop:disable all
# updates a reservation and records changes in the notes
#
# takes the current user, the new params from the controller that have
# been updated w/ a new equipment item, and the new notes (if any)
assign_attributes(new_params)
changes = self.changes
new_notes = '' unless new_notes
if new_notes.empty? && changes.empty?
return self
else
# write notes header
header = "### Edited on #{Time.zone.now.to_s(:long)} by "\
"#{current_user.md_link}\n"
self.notes = notes ? notes + "\n\n" + header : header
# add notes if they exist
self.notes += "\n\n#### Notes:\n#{new_notes}" unless new_notes.empty?
# record changes
# rubocop:disable BlockNesting
unless changes.empty?
self.notes += "\n\n#### Changes:"
changes.each do |param, diff|
case param
when 'reserver_id'
name = 'Reserver'
old_val = diff[0] ? User.find(diff[0]).md_link : 'nil'
new_val = diff[1] ? User.find(diff[1]).md_link : 'nil'
when 'start_date'
name = 'Start Date'
old_val = diff[0].to_s(:long)
new_val = diff[1].to_s(:long)
when 'due_date'
name = 'Due Date'
old_val = diff[0].to_s(:long)
new_val = diff[1].to_s(:long)
when 'equipment_item_id'
name = 'Item'
old_val = diff[0] ? EquipmentItem.find(diff[0]).md_link : 'nil'
new_val = diff[1] ? EquipmentItem.find(diff[1]).md_link : 'nil'
end
self.notes += "\n#{name} changed from " + old_val + ' to '\
+ new_val + '.'
end
end
# rubocop:enable BlockNesting
self.notes = self.notes.strip
self
end
end
# rubocop:disable PerceivedComplexity
def make_notes(procedure_verb, new_notes, incomplete_procedures,
current_user)
# handles the reservation notes from the new notes
#
# takes the new notes and a string, 'checked in' or 'checked out' as the
# procedure_kind
# write notes header
header = "### #{procedure_verb} on #{Time.zone.now.to_s(:long)} by "\
"#{current_user.md_link}\n"
self.notes = self.notes ? self.notes + "\n\n" + header : header
# If no new notes and no missed procedures, set e-mail flag to false and
# return
if new_notes.empty? && incomplete_procedures.empty?
self.notes += "\n\nAll procedures were performed!"
self.notes_unsent = false
return
else
self.notes_unsent = true
end
# add notes if they exist
self.notes += "\n\n#### Notes:\n#{new_notes}" unless new_notes.empty?
# record note procedure status
if incomplete_procedures.empty?
self.notes += "\n\nAll procedures were performed!"
else
self.notes += "\n\n#### The following procedures were not performed:\n"
self.notes += markdown_listify(incomplete_procedures)
end
self.notes = self.notes.strip
end
# rubocop:enable PerceivedComplexity
# returns a string where each item is begun with a '*'
def markdown_listify(items)
'* ' + items.join("\n* ")
end
def md_link
"[res. \##{id}](#{reservation_url(self, only_path: false)})"
end
end
| {
"content_hash": "db6bb333f8e1f628fc67bf9dede0b537",
"timestamp": "",
"source": "github",
"line_count": 398,
"max_line_length": 80,
"avg_line_length": 31.384422110552762,
"alnum_prop": 0.6403010167320471,
"repo_name": "YaleOutdoors/reservations",
"id": "604f45ead821a296aa18d132dede8a971c5da5cb",
"size": "12521",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/reservation.rb",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "37497"
},
{
"name": "HTML",
"bytes": "158350"
},
{
"name": "JavaScript",
"bytes": "18055"
},
{
"name": "Ruby",
"bytes": "605134"
}
],
"symlink_target": ""
} |
import os, sys, unittest, getopt, time
use_resources = []
class ResourceDenied(Exception):
"""Test skipped because it requested a disallowed resource.
This is raised when a test calls requires() for a resource that
has not be enabled. Resources are defined by test modules.
"""
def is_resource_enabled(resource):
"""Test whether a resource is enabled.
If the caller's module is __main__ then automatically return True."""
if sys._getframe().f_back.f_globals.get("__name__") == "__main__":
return True
result = use_resources is not None and \
(resource in use_resources or "*" in use_resources)
if not result:
_unavail[resource] = None
return result
_unavail = {}
def requires(resource, msg=None):
"""Raise ResourceDenied if the specified resource is not available.
If the caller's module is __main__ then automatically return True."""
# see if the caller's module is __main__ - if so, treat as if
# the resource was set
if sys._getframe().f_back.f_globals.get("__name__") == "__main__":
return
if not is_resource_enabled(resource):
if msg is None:
msg = "Use of the `%s' resource not enabled" % resource
raise ResourceDenied(msg)
def find_package_modules(package, mask):
import fnmatch
if (hasattr(package, "__loader__") and
hasattr(package.__loader__, '_files')):
path = package.__name__.replace(".", os.path.sep)
mask = os.path.join(path, mask)
for fnm in package.__loader__._files.iterkeys():
if fnmatch.fnmatchcase(fnm, mask):
yield os.path.splitext(fnm)[0].replace(os.path.sep, ".")
else:
path = package.__path__[0]
for fnm in os.listdir(path):
if fnmatch.fnmatchcase(fnm, mask):
yield "%s.%s" % (package.__name__, os.path.splitext(fnm)[0])
def get_tests(package, mask, verbosity, exclude=()):
"""Return a list of skipped test modules, and a list of test cases."""
tests = []
skipped = []
for modname in find_package_modules(package, mask):
if modname.split(".")[-1] in exclude:
skipped.append(modname)
if verbosity > 1:
print >> sys.stderr, "Skipped %s: excluded" % modname
continue
try:
mod = __import__(modname, globals(), locals(), ['*'])
except ResourceDenied, detail:
skipped.append(modname)
if verbosity > 1:
print >> sys.stderr, "Skipped %s: %s" % (modname, detail)
continue
except Exception, detail:
print >> sys.stderr, "Warning: could not import %s: %s" % (modname, detail)
continue
for name in dir(mod):
if name.startswith("_"):
continue
o = getattr(mod, name)
if type(o) is type(unittest.TestCase) and issubclass(o, unittest.TestCase):
tests.append(o)
return skipped, tests
def usage():
print __doc__
return 1
def test_with_refcounts(runner, verbosity, testcase):
"""Run testcase several times, tracking reference counts."""
import gc
import ctypes
ptc = ctypes._pointer_type_cache.copy()
cfc = ctypes._c_functype_cache.copy()
wfc = ctypes._win_functype_cache.copy()
# when searching for refcount leaks, we have to manually reset any
# caches that ctypes has.
def cleanup():
ctypes._pointer_type_cache = ptc.copy()
ctypes._c_functype_cache = cfc.copy()
ctypes._win_functype_cache = wfc.copy()
gc.collect()
test = unittest.makeSuite(testcase)
for i in range(5):
rc = sys.gettotalrefcount()
runner.run(test)
cleanup()
COUNT = 5
refcounts = [None] * COUNT
for i in range(COUNT):
rc = sys.gettotalrefcount()
runner.run(test)
cleanup()
refcounts[i] = sys.gettotalrefcount() - rc
if filter(None, refcounts):
print "%s leaks:\n\t" % testcase, refcounts
elif verbosity:
print "%s: ok." % testcase
class TestRunner(unittest.TextTestRunner):
def run(self, test, skipped):
"Run the given test case or test suite."
# Same as unittest.TextTestRunner.run, except that it reports
# skipped tests.
result = self._makeResult()
startTime = time.time()
test(result)
stopTime = time.time()
timeTaken = stopTime - startTime
result.printErrors()
self.stream.writeln(result.separator2)
run = result.testsRun
if _unavail: #skipped:
requested = _unavail.keys()
requested.sort()
self.stream.writeln("Ran %d test%s in %.3fs (%s module%s skipped)" %
(run, run != 1 and "s" or "", timeTaken,
len(skipped),
len(skipped) != 1 and "s" or ""))
self.stream.writeln("Unavailable resources: %s" % ", ".join(requested))
else:
self.stream.writeln("Ran %d test%s in %.3fs" %
(run, run != 1 and "s" or "", timeTaken))
self.stream.writeln()
if not result.wasSuccessful():
self.stream.write("FAILED (")
failed, errored = map(len, (result.failures, result.errors))
if failed:
self.stream.write("failures=%d" % failed)
if errored:
if failed: self.stream.write(", ")
self.stream.write("errors=%d" % errored)
self.stream.writeln(")")
else:
self.stream.writeln("OK")
return result
def main(*packages):
try:
opts, args = getopt.getopt(sys.argv[1:], "rqvu:x:")
except getopt.error:
return usage()
verbosity = 1
search_leaks = False
exclude = []
for flag, value in opts:
if flag == "-q":
verbosity -= 1
elif flag == "-v":
verbosity += 1
elif flag == "-r":
try:
sys.gettotalrefcount
except AttributeError:
print >> sys.stderr, "-r flag requires Python debug build"
return -1
search_leaks = True
elif flag == "-u":
use_resources.extend(value.split(","))
elif flag == "-x":
exclude.extend(value.split(","))
mask = "test_*.py"
if args:
mask = args[0]
for package in packages:
run_tests(package, mask, verbosity, search_leaks, exclude)
def run_tests(package, mask, verbosity, search_leaks, exclude):
skipped, testcases = get_tests(package, mask, verbosity, exclude)
runner = TestRunner(verbosity=verbosity)
suites = [unittest.makeSuite(o) for o in testcases]
suite = unittest.TestSuite(suites)
result = runner.run(suite, skipped)
if search_leaks:
# hunt for refcount leaks
runner = BasicTestRunner()
for t in testcases:
test_with_refcounts(runner, verbosity, t)
return bool(result.errors)
class BasicTestRunner:
def run(self, test):
result = unittest.TestResult()
test(result)
return result
| {
"content_hash": "c3cd49d4058e4b61f626a1312abc5bf0",
"timestamp": "",
"source": "github",
"line_count": 211,
"max_line_length": 87,
"avg_line_length": 34.37440758293839,
"alnum_prop": 0.5688680545980973,
"repo_name": "MalloyPower/parsing-python",
"id": "70d647ba5e215f222249069c6ff85b2628c67564",
"size": "7253",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "front-end/testsuite-python-lib/Python-2.6/Lib/ctypes/test/__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "1963"
},
{
"name": "Lex",
"bytes": "238458"
},
{
"name": "Makefile",
"bytes": "4513"
},
{
"name": "OCaml",
"bytes": "412695"
},
{
"name": "Python",
"bytes": "17319"
},
{
"name": "Rascal",
"bytes": "523063"
},
{
"name": "Yacc",
"bytes": "429659"
}
],
"symlink_target": ""
} |
var data = {chanels: {}} | {
"content_hash": "3f3417118228ff11b88df50a8dc9093a",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 24,
"avg_line_length": 24,
"alnum_prop": 0.5833333333333334,
"repo_name": "svteamMarkup/edupay",
"id": "7f81196248ac46c55b415a42e76524a11b7bab8d",
"size": "24",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "markup/components/chanels/data/data.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "59298"
},
{
"name": "HTML",
"bytes": "53868"
},
{
"name": "JavaScript",
"bytes": "160503"
}
],
"symlink_target": ""
} |
package org.tribbloid.ispark.display.dsl
import java.net.URL
import org.apache.spark.sql.DataFrame
import org.ccil.cowan.tagsoup.jaxp.SAXFactoryImpl
import org.pegdown.{Extensions, PegDownProcessor}
import org.tribbloid.ispark.display.{HTMLDisplayObject, LatexDisplayObject}
import scala.xml._
object Display {
case class Math(math: String) extends LatexDisplayObject {
override val toLatex = "$$" + math + "$$"
}
case class Latex(latex: String) extends LatexDisplayObject {
override val toLatex = latex
}
case class HTML(code: String) extends HTMLDisplayObject {
override val toHTML: String = code
}
object MarkdownProcessor extends PegDownProcessor(Extensions.ALL)
case class Markdown(code: String) extends HTMLDisplayObject {
override val toHTML: String = {
MarkdownProcessor.markdownToHtml(code)
}
}
val TagSoupParser = new SAXFactoryImpl().newSAXParser()
case class Table(
df: DataFrame,
limit:Int = 1000,
parse: Boolean = true,
random: Boolean = true
) extends HTMLDisplayObject {
assert(limit<=1000) //or parsing timeout
override val toHTML: String = {
val thead: Elem =
<thead>
<tr>{df.schema.fieldNames.map(str => <td>{str}</td>)}</tr>
</thead>
df.persist()
val size = df.count()
val rows = if (random) df.rdd.takeSample(withReplacement = false, num = limit)
else df.rdd.take(limit)
df.unpersist()
val info: Elem =
if (size < limit) <h5>returned {size} row(s) in total:</h5>
else <h5>returned {size} rows in total but only {limit} of them are displayed:</h5>
val body: Array[Elem] = rows.map{
row =>
val rowXml = row.toSeq.map{
cell =>
if (parse) {
cell match {
case cell: NodeSeq => <td>{cell}</td>
case cell: NodeBuffer => <td>{cell}</td>
case cell: Any =>
try {
val cellXml = XML.loadXML(Source.fromString(cell.toString), TagSoupParser)
<td>{cellXml}</td>
}
catch {
case e: Throwable => <td>{cell}</td>
}
case _ => <td>{cell}</td>
}
}
else {
<td>{cell}</td>
}
}
<tr>{rowXml}</tr>
}
val tbody: Elem =
<tbody>
{body}
</tbody>
val table: Elem =
<table>
{thead}
{tbody}
</table>
(info ++ table).toString()
}
}
class IFrame(src: URL, width: Int, height: Int) extends HTMLDisplayObject {
override val toHTML: String =
<iframe width={width.toString}
height={height.toString}
src={src.toString}
frameborder="0"
allowfullscreen="allowfullscreen"></iframe> toString()
}
object IFrame {
def apply(src: URL, width: Int, height: Int): IFrame = new IFrame(src, width, height)
def apply(src: String, width: Int, height: Int): IFrame = new IFrame(new URL(src), width, height)
}
case class YouTubeVideo(id: String, width: Int = 400, height: Int = 300)
extends IFrame(new URL("https", "www.youtube.com", s"/embed/$id"), width, height)
case class VimeoVideo(id: String, width: Int = 400, height: Int = 300)
extends IFrame(new URL("https", "player.vimeo.com", s"/video/$id"), width, height)
case class ScribdDocument(id: String, width: Int = 400, height: Int = 300)
extends IFrame(new URL("https", "www.scribd.com", s"/embeds/$id/content"), width, height)
case class ImageURL(url: URL, width: Option[Int], height: Option[Int]) extends HTMLDisplayObject {
override val toHTML: String = <img src={url.toString}
width={width.map(w => xml.Text(w.toString))}
height={height.map(h => xml.Text(h.toString))}></img> toString()
}
object ImageURL {
def apply(url: URL): ImageURL = ImageURL(url, None, None)
def apply(url: String): ImageURL = ImageURL(new URL(url))
def apply(url: URL, width: Int, height: Int): ImageURL = ImageURL(url, Some(width), Some(height))
def apply(url: String, width: Int, height: Int): ImageURL = ImageURL(new URL(url), width, height)
}
//disabled because Json display is only supported in extension
// case class Json[T <: AnyRef](obj: T) extends JSONDisplayObject {
//
// implicit val formats = DefaultFormats
// import org.json4s.jackson.Serialization
//
// override val toJSON: String = {
// Serialization.write(obj) //TODO: Cannot serialize class created in interpreter
// }
// }
} | {
"content_hash": "b7c180fe36069b114730ec579ba7f38e",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 103,
"avg_line_length": 32.10526315789474,
"alnum_prop": 0.5739754098360655,
"repo_name": "tribbloid/ISpark",
"id": "d5c4074b4e3940ec2c2cf811032e626ec34fc401",
"size": "4880",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "display/src/main/scala/org/tribbloid/ispark/display/dsl/Display.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Scala",
"bytes": "137986"
},
{
"name": "Shell",
"bytes": "127"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.