code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 4
991
| language
stringclasses 9
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
# frozen_string_literal: true
shared_context 'survey_assignment' do
before do
ActionMailer::Base.delivery_method = :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries = []
@user = create(:user, username: 'Jonathan', email: 'jonathan@wintr.us')
@user2 = create(:user, username: 'Sage', email: 'sage@wikiedu.org')
@survey1 = create(:survey)
@campaign1 = create(:campaign, title: 'Test', slug: 'test')
# Survey Assignment for Instructors in Courses which end 3 days from today.
@survey_assignment_params = {
published: true,
courses_user_role: 1,
survey_id: @survey1.id,
send_date_days: 3,
send_before: true,
send_date_relative_to: 'end',
email_template: 'instructor_survey'
}
@survey_assignment1 = create(:survey_assignment, @survey_assignment_params)
# Add the Campaign to our survey assignment
@survey_assignment1.campaigns << @campaign1
@survey_assignment1.save
# Un-published Survey Assignment
@survey_assignment2 = create(:survey_assignment,
@survey_assignment_params.merge(published: false))
@survey_assignment2.campaigns << @campaign1
@survey_assignment2.save
# Course with end date that matches Today for the SurveyAssignment
@course_params = {
start: Time.zone.today - 2.months,
# Accounting for end-of-day default end dates, we set the end date as 2 days
# away to makes sure the 'three days until end' covers the end date.
end: Time.zone.now + 2.days,
passcode: 'pizza',
title: 'Underwater basket-weaving'
}
# Add 2 Courses to our Campaign each with an instructor
2.times do |i|
course = create(:course, { id: i + 1 }.merge(@course_params))
course.courses_users << create(:courses_user,
course_id: course.id,
user_id: @user.id,
role: 1) # instructor
course.courses_users << create(:courses_user,
course_id: course.id,
user_id: @user2.id,
role: 1) # instructor
course.save
@campaign1.courses << course
end
@campaign1.save
end
end
|
Wowu/WikiEduDashboard
|
spec/support/shared_contexts/survey_assignment.rb
|
Ruby
|
mit
| 2,341 |
<?php
header("Content-type: text/xml");
$fil = fopen("https://www.yr.no/sted/Norge/%C3%98stfold/Halden/Halden/varsel.xml","r")
while($linjer = fopen($fil)) {
echo $linjer;
}
?>
|
Donslayer/Introduction-to-programming-Javascript-
|
laptopWampInfoFiles/oppgave3/nas.proxy.php
|
PHP
|
mit
| 190 |
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
# GET /users
# GET /users.json
def index
@users = current_admin.admin? ? User.all : current_admin.users
authorize! :read, User
@users.each do |user|
authorize! :read, user
end
end
# GET /users/new
def new
@user = User.new
authorize! :create, @user
end
# GET /users/1/edit
def edit
authorize! :update, @user
end
def edit_password
@user = User.find(params[:id])
authorize! :change_password, @user
end
# POST /users
# POST /users.json
def create
@user = User.new(user_params)
authorize! :update, @user
respond_to do |format|
if @user.save
format.html { redirect_to users_path, notice: 'Postfach wurde erfolgreich angelegt!' }
else
format.html { render :new }
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
authorize! :update, @user
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to users_path, notice: 'Postfach wurde erfolgreich bearbeitet.' }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
def update_password
@user = User.find(params[:id])
authorize! :change_password, @user
if @user.update_attributes(user_params)
redirect_to users_path, notice: 'Passwort wurde erfolgreich bearbeitet!'
else
render :edit_password
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
authorize! :destroy, @user
@user.destroy
#ToDo: Delete Folder in file system
respond_to do |format|
format.html { redirect_to users_url, notice: 'Postfach wurde erfolgreich gelöscht!' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:username, :password, :domain_id)
end
end
|
fate83/MailAdmin
|
app/controllers/users_controller.rb
|
Ruby
|
mit
| 2,318 |
<?php return array (
'ab' => 'Abchazisch',
'ada' => 'Adangme',
'ady' => 'Adygees',
'om' => 'Afaan Oromo',
'aa' => 'Afar',
'afh' => 'Afrihili',
'af' => 'Afrikaans',
'agq' => 'Aghem',
'ain' => 'Ainu',
'ak' => 'Akan',
'akk' => 'Akkadisch',
'ach' => 'Akoli',
'bss' => 'Akoose',
'akz' => 'Alabama',
'sq' => 'Albanees',
'ale' => 'Aleoetisch',
'arq' => 'Algerijns Arabisch',
'en_US' => 'Amerikaans Engels',
'ase' => 'Amerikaanse Gebarentaal',
'am' => 'Amhaars',
'anp' => 'Angika',
'njo' => 'Ao Naga',
'ar' => 'Arabisch',
'an' => 'Aragonees',
'arc' => 'Aramees',
'aro' => 'Araona',
'arp' => 'Arapaho',
'arw' => 'Arawak',
'hy' => 'Armeens',
'rup' => 'Aroemeens',
'frp' => 'Arpitaans',
'as' => 'Assamees',
'ast' => 'Asturisch',
'asa' => 'Asu',
'ace' => 'Atjehs',
'cch' => 'Atsam',
'en_AU' => 'Australisch Engels',
'av' => 'Avarisch',
'ae' => 'Avestisch',
'awa' => 'Awadhi',
'ay' => 'Aymara',
'az' => 'Azerbeidzjaans',
'bfq' => 'Badaga',
'ksf' => 'Bafia',
'bfd' => 'Bafut',
'bqi' => 'Bakhtiari',
'ban' => 'Balinees',
'bm' => 'Bambara',
'bax' => 'Bamoun',
'bjn' => 'Banjar',
'bas' => 'Basa',
'ba' => 'Basjkiers',
'eu' => 'Baskisch',
'bbc' => 'Batak Toba',
'bar' => 'Beiers',
'bej' => 'Beja',
'bal' => 'Beloetsji',
'bem' => 'Bemba',
'bez' => 'Bena',
'bn' => 'Bengaals',
'bew' => 'Betawi',
'bho' => 'Bhojpuri',
'bik' => 'Bikol',
'bin' => 'Bini',
'my' => 'Birmaans',
'bpy' => 'Bishnupriya',
'bi' => 'Bislama',
'byn' => 'Blin',
'zbl' => 'Blissymbolen',
'brx' => 'Bodo',
'bua' => 'Boerjatisch',
'bs' => 'Bosnisch',
'brh' => 'Brahui',
'bra' => 'Braj',
'pt_BR' => 'Braziliaans Portugees',
'br' => 'Bretons',
'en_GB' => 'Brits Engels',
'bug' => 'Buginees',
'bg' => 'Bulgaars',
'bum' => 'Bulu',
'cad' => 'Caddo',
'frc' => 'Cajun-Frans',
'en_CA' => 'Canadees Engels',
'fr_CA' => 'Canadees Frans',
'cps' => 'Capiznon',
'car' => 'Caribisch',
'ca' => 'Catalaans',
'cay' => 'Cayuga',
'ceb' => 'Cebuano',
'chg' => 'Chagatai',
'ch' => 'Chamorro',
'chr' => 'Cherokee',
'chy' => 'Cheyenne',
'chb' => 'Chibcha',
'cgg' => 'Chiga',
'zh' => 'Chinees',
'chn' => 'Chinook Jargon',
'chp' => 'Chipewyan',
'cho' => 'Choctaw',
'chk' => 'Chuukees',
'swc' => 'Congo Swahili',
'kw' => 'Cornish',
'co' => 'Corsicaans',
'cr' => 'Cree',
'mus' => 'Creek',
'dak' => 'Dakota',
'dar' => 'Dargwa',
'dzg' => 'Dazaga',
'da' => 'Deens',
'del' => 'Delaware',
'din' => 'Dinka',
'dv' => 'Divehi',
'doi' => 'Dogri',
'dgr' => 'Dogrib',
'dua' => 'Duala',
'de' => 'Duits',
'dtp' => 'Dusun',
'dyu' => 'Dyula',
'dz' => 'Dzongkha',
'efi' => 'Efik',
'arz' => 'Egyptisch Arabisch',
'eka' => 'Ekajuk',
'elx' => 'Elamitisch',
'ebu' => 'Embu',
'egl' => 'Emiliano',
'en' => 'Engels',
'myv' => 'Erzja',
'eo' => 'Esperanto',
'et' => 'Estisch',
'pt_PT' => 'Europees Portugees',
'es_ES' => 'Europees Spaans',
'ee' => 'Ewe',
'ewo' => 'Ewondo',
'ext' => 'Extremeens',
'fo' => 'Faeröers',
'fan' => 'Fang',
'fat' => 'Fanti',
'fj' => 'Fijisch',
'hif' => 'Fijisch Hindi',
'fil' => 'Filipijns',
'fi' => 'Fins',
'phn' => 'Foenicisch',
'fon' => 'Fon',
'fr' => 'Frans',
'fy' => 'Fries',
'fur' => 'Friulisch',
'ff' => 'Fulah',
'gaa' => 'Ga',
'gag' => 'Gagaoezisch',
'gl' => 'Galicisch',
'gan' => 'Gan Chinese',
'gay' => 'Gayo',
'gba' => 'Gbaya',
'gez' => 'Ge’ez',
'zxx' => 'geen linguïstische inhoud',
'aln' => 'Gegisch',
'ka' => 'Georgisch',
'bbj' => 'Ghomala’',
'ki' => 'Gikuyu',
'glk' => 'Gilaki',
'gil' => 'Gilbertees',
'gom' => 'Goa Konkani',
'gon' => 'Gondi',
'gor' => 'Gorontalo',
'got' => 'Gothisch',
'grb' => 'Grebo',
'el' => 'Grieks',
'kl' => 'Groenlands',
'gn' => 'Guaraní',
'gu' => 'Gujarati',
'gur' => 'Gurune',
'guz' => 'Gusii',
'gwi' => 'Gwichʼin',
'hai' => 'Haida',
'ht' => 'Haïtiaans Creools',
'hak' => 'Hakka',
'ha' => 'Hausa',
'haw' => 'Hawaïaans',
'he' => 'Hebreeuws',
'hz' => 'Herero',
'hit' => 'Hettitisch',
'hil' => 'Hiligaynon',
'hi' => 'Hindi',
'ho' => 'Hiri Motu',
'hmn' => 'Hmong',
'hu' => 'Hongaars',
'hup' => 'Hupa',
'iba' => 'Iban',
'ibb' => 'Ibibio',
'io' => 'Ido',
'ga' => 'Iers',
'ig' => 'Igbo',
'is' => 'IJslands',
'ilo' => 'Iloko',
'smn' => 'Inari-Samisch',
'id' => 'Indonesisch',
'inh' => 'Ingoesjetisch',
'izh' => 'Ingrisch',
'ia' => 'Interlingua',
'ie' => 'Interlingue',
'iu' => 'Inuktitut',
'ik' => 'Inupiaq',
'it' => 'Italiaans',
'sah' => 'Jakoets',
'jam' => 'Jamaicaans Creools',
'ja' => 'Japans',
'jv' => 'Javaans',
'yi' => 'Jiddisch',
'kaj' => 'Jju',
'dyo' => 'Jola-Fonyi',
'jrb' => 'Judeo-Arabisch',
'jpr' => 'Judeo-Perzisch',
'jut' => 'Jutlands',
'quc' => 'K’iche’',
'kea' => 'Kaapverdisch Creools',
'kbd' => 'Kabardisch',
'kab' => 'Kabylisch',
'kac' => 'Kachin',
'kgp' => 'Kaingang',
'kkj' => 'Kako',
'kln' => 'Kalenjin',
'xal' => 'Kalmuks',
'kam' => 'Kamba',
'kbl' => 'Kanembu',
'kn' => 'Kannada',
'yue' => 'Kantonees',
'kr' => 'Kanuri',
'kaa' => 'Karakalpaks',
'krc' => 'Karatsjaj-Balkarisch',
'krl' => 'Karelisch',
'ks' => 'Kasjmiri',
'csb' => 'Kasjoebisch',
'kaw' => 'Kawi',
'kk' => 'Kazachs',
'ken' => 'Kenyang',
'cu' => 'Kerkslavisch',
'kha' => 'Khasi',
'km' => 'Khmer',
'kho' => 'Khotanees',
'khw' => 'Khowar',
'qug' => 'Kichwa',
'kmb' => 'Kimbundu',
'krj' => 'Kinaray-a',
'rw' => 'Kinyarwanda',
'ky' => 'Kirgizisch',
'kiu' => 'Kirmanckî',
'rn' => 'Kirundi',
'lzh' => 'Klassiek Chinees',
'nwc' => 'Klassiek Nepalbhasa',
'syc' => 'Klassiek Syrisch',
'tlh' => 'Klingon',
'kum' => 'Koemuks',
'ku' => 'Koerdisch',
'ksh' => 'Kölsch',
'bkm' => 'Kom',
'kv' => 'Komi',
'koi' => 'Komi-Permjaaks',
'kg' => 'Kongo',
'kok' => 'Konkani',
'cop' => 'Koptisch',
'ko' => 'Koreaans',
'kfo' => 'Koro',
'kos' => 'Kosraeaans',
'avk' => 'Kotava',
'khq' => 'Koyra Chiini',
'ses' => 'Koyraboro Senni',
'kpe' => 'Kpelle',
'crh' => 'Krim-Tataars',
'kri' => 'Krio',
'hr' => 'Kroatisch',
'kj' => 'Kuanyama',
'kru' => 'Kurukh',
'kut' => 'Kutenai',
'lad' => 'Ladino',
'lah' => 'Lahnda',
'lkt' => 'Lakota',
'lam' => 'Lamba',
'lag' => 'Langi',
'lo' => 'Laotiaans',
'la' => 'Latijn',
'es_419' => 'Latijns-Amerikaans Spaans',
'lzz' => 'Lazisch',
'ltg' => 'Letgaals',
'lv' => 'Lets',
'lez' => 'Lezgisch',
'lij' => 'Ligurisch',
'liv' => 'Lijfs',
'li' => 'Limburgs',
'ln' => 'Lingala',
'lfn' => 'Lingua Franca Nova',
'lt' => 'Litouws',
'jbo' => 'Lojban',
'lmo' => 'Lombardisch',
'loz' => 'Lozi',
'lu' => 'Luba-Katanga',
'lua' => 'Luba-Lulua',
'lg' => 'Luganda',
'lui' => 'Luiseno',
'smj' => 'Lule-Samisch',
'lun' => 'Lunda',
'luo' => 'Luo',
'lb' => 'Luxemburgs',
'luy' => 'Luyia',
'mas' => 'Maa',
'mde' => 'Maba',
'mk' => 'Macedonisch',
'jmc' => 'Machame',
'mad' => 'Madoerees',
'maf' => 'Mafa',
'mag' => 'Magahi',
'vmf' => 'Main-Franconian',
'mai' => 'Maithili',
'mak' => 'Makassaars',
'mgh' => 'Makhuwa-Meetto',
'kde' => 'Makonde',
'mg' => 'Malagassisch',
'ml' => 'Malayalam',
'ms' => 'Maleis',
'mt' => 'Maltees',
'mdr' => 'Mandar',
'man' => 'Mandingo',
'mnc' => 'Mantsjoe',
'gv' => 'Manx',
'mi' => 'Maori',
'arn' => 'Mapudungun',
'mr' => 'Marathi',
'chm' => 'Mari',
'ary' => 'Marokkaans Arabisch',
'mh' => 'Marshallees',
'mwr' => 'Marwari',
'mzn' => 'Mazanderani',
'byv' => 'Medumba',
'mul' => 'Meerdere talen',
'mni' => 'Meitei',
'men' => 'Mende',
'mwv' => 'Mentawai',
'mer' => 'Meru',
'mgo' => 'Meta’',
'es_MX' => 'Mexicaans Spaans',
'mic' => 'Mi’kmaq',
'enm' => 'Middelengels',
'frm' => 'Middelfrans',
'gmh' => 'Middelhoogduits',
'mga' => 'Middeliers',
'dum' => 'Middelnederlands',
'min' => 'Minangkabau',
'xmf' => 'Mingreels',
'nan' => 'Minnanyu',
'mwl' => 'Mirandees',
'lus' => 'Mizo',
'ar_001' => 'modern standaard Arabisch',
'moh' => 'Mohawk',
'mdf' => 'Moksja',
'ro_MD' => 'Moldavian',
'lol' => 'Mongo',
'mn' => 'Mongools',
'mfe' => 'Morisyen',
'ttt' => 'Moslim Tat',
'mos' => 'Mossi',
'mua' => 'Mundang',
'mye' => 'Myene',
'nqo' => 'N’Ko',
'naq' => 'Nama',
'nap' => 'Napolitaans',
'na' => 'Nauruaans',
'nv' => 'Navajo',
'ng' => 'Ndonga',
'nl' => 'Nederlands',
'nds' => 'Nedersaksisch',
'dsb' => 'Nedersorbisch',
'ne' => 'Nepalees',
'new' => 'Newari',
'sba' => 'Ngambay',
'nnh' => 'Ngiemboon',
'jgo' => 'Ngomba',
'nmg' => 'Ngumba',
'yrl' => 'Nheengatu',
'nia' => 'Nias',
'niu' => 'Niueaans',
'nog' => 'Nogai',
'frr' => 'Noord-Fries',
'nd' => 'Noord-Ndebele',
'se' => 'Noord-Samisch',
'nso' => 'Noord-Sotho',
'no' => 'Noors',
'nb' => 'Noors - Bokmål',
'nn' => 'Noors - Nynorsk',
'nov' => 'Novial',
'nus' => 'Nuer',
'nym' => 'Nyamwezi',
'ny' => 'Nyanja',
'nyn' => 'Nyankole',
'tog' => 'Nyasa Tonga',
'nyo' => 'Nyoro',
'nzi' => 'Nzima',
'oc' => 'Occitaans; Provençaals',
'or' => 'Odia',
'udm' => 'Oedmoerts',
'uga' => 'Oegaritisch',
'ug' => 'Oeigoers',
'uk' => 'Oekraïens',
'uz' => 'Oezbeeks',
'oj' => 'Ojibwa',
'und' => 'onbekende taal',
'frs' => 'Oost-Fries',
'de_AT' => 'Oostenrijks Duits',
'hsb' => 'Oppersorbisch',
'osa' => 'Osage',
'os' => 'Ossetisch',
'ota' => 'Ottomaans-Turks',
'egy' => 'Oudegyptisch',
'ang' => 'Oudengels',
'fro' => 'Oudfrans',
'grc' => 'Oudgrieks',
'goh' => 'Oudhoogduits',
'sga' => 'Oudiers',
'non' => 'Oudnoors',
'peo' => 'Oudperzisch',
'pro' => 'Oudprovençaals',
'prg' => 'Oudpruisisch',
'pal' => 'Pahlavi',
'pau' => 'Palaus',
'pi' => 'Pali',
'pfl' => 'Paltsisch',
'pam' => 'Pampanga',
'pag' => 'Pangasinan',
'pap' => 'Papiaments',
'ps' => 'Pasjtoe',
'pdc' => 'Pennsylvania-Duits',
'fa' => 'Perzisch',
'pcd' => 'Picardisch',
'pms' => 'Piëmontees',
'pdt' => 'Plautdietsch',
'pon' => 'Pohnpeiaans',
'pnt' => 'Pontisch',
'pl' => 'Pools',
'pt' => 'Portugees',
'pa' => 'Punjabi',
'qu' => 'Quechua',
'raj' => 'Rajasthani',
'rap' => 'Rapanui',
'rar' => 'Rarotongan',
'rm' => 'Reto-Romaans',
'rif' => 'Riffijns',
'ro' => 'Roemeens',
'rue' => 'Roetheens',
'rgn' => 'Romagnol',
'rom' => 'Romani',
'rof' => 'Rombo',
'root' => 'Root',
'rtm' => 'Rotumaans',
'rug' => 'Roviana',
'ru' => 'Russisch',
'rwk' => 'Rwa',
'ssy' => 'Saho',
'sam' => 'Samaritaans-Aramees',
'saq' => 'Samburu',
'sm' => 'Samoaans',
'sgs' => 'Samogitisch',
'sad' => 'Sandawe',
'sg' => 'Sango',
'sbp' => 'Sangu',
'sa' => 'Sanskriet',
'sat' => 'Santali',
'sc' => 'Sardijns',
'sas' => 'Sasak',
'sdc' => 'Sassarees',
'stq' => 'Saterfries',
'saz' => 'Saurashtra',
'sco' => 'Schots',
'gd' => 'Schots-Gaelisch',
'sly' => 'Selayar',
'sel' => 'Selkoeps',
'seh' => 'Sena',
'see' => 'Seneca',
'srr' => 'Serer',
'sei' => 'Seri',
'sr' => 'Servisch',
'sh' => 'Servo-Kroatisch',
'ksb' => 'Shambala',
'shn' => 'Shan',
'swb' => 'Shimaore',
'sn' => 'Shona',
'scn' => 'Siciliaans',
'sid' => 'Sidamo',
'bla' => 'Siksika',
'szl' => 'Silezisch',
'sli' => 'Silezisch Duits',
'sd' => 'Sindhi',
'si' => 'Singalees',
'sms' => 'Skolt-Samisch',
'den' => 'Slavey',
'sl' => 'Sloveens',
'sk' => 'Slowaaks',
'sux' => 'Soemerisch',
'su' => 'Soendanees',
'sus' => 'Soesoe',
'xog' => 'Soga',
'sog' => 'Sogdisch',
'so' => 'Somalisch',
'snk' => 'Soninke',
'ckb' => 'Soranî',
'es' => 'Spaans',
'srn' => 'Sranantongo',
'zgh' => 'Standaard Marokkaanse Tamazight',
'suk' => 'Sukuma',
'sw' => 'Swahili',
'ss' => 'Swazi',
'syr' => 'Syrisch',
'tg' => 'Tadzjieks',
'tl' => 'Tagalog',
'ty' => 'Tahitiaans',
'dav' => 'Taita',
'tly' => 'Talysh',
'tmh' => 'Tamashek',
'tzm' => 'Tamazight (Centraal-Marokko)',
'ta' => 'Tamil',
'trv' => 'Taroko',
'twq' => 'Tasawaq',
'shi' => 'Tashelhiyt',
'tt' => 'Tataars',
'te' => 'Telugu',
'ter' => 'Tereno',
'teo' => 'Teso',
'tet' => 'Tetun',
'th' => 'Thais',
'bo' => 'Tibetaans',
'tig' => 'Tigre',
'ti' => 'Tigrinya',
'tem' => 'Timne',
'tiv' => 'Tiv',
'tli' => 'Tlingit',
'tum' => 'Toemboeka',
'tyv' => 'Toevaans',
'tpi' => 'Tok Pisin',
'tkl' => 'Tokelaus',
'to' => 'Tongaans',
'fit' => 'Tornedal-Fins',
'zh_Hant' => 'traditioneel Chinees',
'tkr' => 'Tsakhur',
'tsd' => 'Tsakonisch',
'tsi' => 'Tsimshian',
'shu' => 'Tsjadisch Arabisch',
'cs' => 'Tsjechisch',
'ce' => 'Tsjetsjeens',
'cv' => 'Tsjoevasjisch',
'ts' => 'Tsonga',
'tn' => 'Tswana',
'tcy' => 'Tulu',
'aeb' => 'Tunesisch Arabisch',
'tk' => 'Turkmeens',
'tr' => 'Turks',
'tru' => 'Turoyo',
'tvl' => 'Tuvaluaans',
'tw' => 'Twi',
'kcg' => 'Tyap',
'umb' => 'Umbundu',
'ur' => 'Urdu',
'vai' => 'Vai',
've' => 'Venda',
'vec' => 'Venetiaans',
'zh_Hans' => 'vereenvoudigd Chinees',
'vi' => 'Vietnamees',
'nl_BE' => 'Vlaams',
'vo' => 'Volapük',
'vro' => 'Võro',
'vot' => 'Votisch',
'vun' => 'Vunjo',
'wa' => 'Waals',
'wae' => 'Walser',
'war' => 'Waray',
'was' => 'Washo',
'guc' => 'Wayuu',
'cy' => 'Welsh',
'vep' => 'Wepsisch',
'mrj' => 'West-Mari',
'vls' => 'West-Vlaams',
'be' => 'Wit-Russisch',
'wal' => 'Wolaytta',
'wo' => 'Wolof',
'wuu' => 'Wuyu',
'xh' => 'Xhosa',
'hsn' => 'Xiangyu',
'yav' => 'Yangben',
'yao' => 'Yao',
'yap' => 'Yapees',
'ybb' => 'Yemba',
'ii' => 'Yi',
'yo' => 'Yoruba',
'esu' => 'Yupik',
'zap' => 'Zapotec',
'dje' => 'Zarma',
'zza' => 'Zaza',
'zea' => 'Zeeuws',
'zen' => 'Zenaga',
'za' => 'Zhuang',
'zu' => 'Zoeloe',
'gbz' => 'Zoroastrisch Dari',
'alt' => 'Zuid-Altaïsch',
'azb' => 'Zuid-Azerbeidzjaans Arabisch',
'nr' => 'Zuid-Ndbele',
'sma' => 'Zuid-Samisch',
'st' => 'Zuid-Sotho',
'zun' => 'Zuni',
'sv' => 'Zweeds',
'gsw' => 'Zwitserduits',
'fr_CH' => 'Zwitsers Frans',
'de_CH' => 'Zwitsers Hoogduits',
);
|
aanton03/language-list
|
data/nl_BE/language.php
|
PHP
|
mit
| 14,046 |
/*
* The MIT License
* Copyright (c) 2012 Microsoft Corporation
*
* 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.
*/
package microsoft.exchange.webservices.data.core.service.schema;
import microsoft.exchange.webservices.data.attribute.Schema;
import microsoft.exchange.webservices.data.core.XmlElementNames;
import microsoft.exchange.webservices.data.enumeration.ExchangeVersion;
import microsoft.exchange.webservices.data.enumeration.Importance;
import microsoft.exchange.webservices.data.enumeration.PropertyDefinitionFlags;
import microsoft.exchange.webservices.data.enumeration.Sensitivity;
import microsoft.exchange.webservices.data.property.complex.ConversationId;
import microsoft.exchange.webservices.data.property.complex.FolderId;
import microsoft.exchange.webservices.data.property.complex.ICreateComplexPropertyDelegate;
import microsoft.exchange.webservices.data.property.complex.InternetMessageHeaderCollection;
import microsoft.exchange.webservices.data.property.complex.ItemId;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
import microsoft.exchange.webservices.data.property.complex.MimeContent;
import microsoft.exchange.webservices.data.property.complex.StringList;
import microsoft.exchange.webservices.data.property.complex.UniqueBody;
import microsoft.exchange.webservices.data.property.definition.AttachmentsPropertyDefinition;
import microsoft.exchange.webservices.data.property.definition.BoolPropertyDefinition;
import microsoft.exchange.webservices.data.property.definition.ByteArrayPropertyDefinition;
import microsoft.exchange.webservices.data.property.definition.ComplexPropertyDefinition;
import microsoft.exchange.webservices.data.property.definition.DateTimePropertyDefinition;
import microsoft.exchange.webservices.data.property.definition.EffectiveRightsPropertyDefinition;
import microsoft.exchange.webservices.data.property.definition.GenericPropertyDefinition;
import microsoft.exchange.webservices.data.property.definition.IntPropertyDefinition;
import microsoft.exchange.webservices.data.property.definition.PropertyDefinition;
import microsoft.exchange.webservices.data.property.definition.ResponseObjectsPropertyDefinition;
import microsoft.exchange.webservices.data.property.definition.StringPropertyDefinition;
import java.util.EnumSet;
/**
* Represents the schema for generic item.
*/
@Schema
public class ItemSchema extends ServiceObjectSchema {
/**
* The Interface FieldUris.
*/
private static interface FieldUris {
/**
* The Item id.
*/
String ItemId = "item:ItemId";
/**
* The Parent folder id.
*/
String ParentFolderId = "item:ParentFolderId";
/**
* The Item class.
*/
String ItemClass = "item:ItemClass";
/**
* The Mime content.
*/
String MimeContent = "item:MimeContent";
/**
* The Attachments.
*/
String Attachments = "item:Attachments";
/**
* The Subject.
*/
String Subject = "item:Subject";
/**
* The Date time received.
*/
String DateTimeReceived = "item:DateTimeReceived";
/**
* The Size.
*/
String Size = "item:Size";
/**
* The Categories.
*/
String Categories = "item:Categories";
/**
* The Has attachments.
*/
String HasAttachments = "item:HasAttachments";
/**
* The Importance.
*/
String Importance = "item:Importance";
/**
* The In reply to.
*/
String InReplyTo = "item:InReplyTo";
/**
* The Internet message headers.
*/
String InternetMessageHeaders = "item:InternetMessageHeaders";
/**
* The Is associated.
*/
String IsAssociated = "item:IsAssociated";
/**
* The Is draft.
*/
String IsDraft = "item:IsDraft";
/**
* The Is from me.
*/
String IsFromMe = "item:IsFromMe";
/**
* The Is resend.
*/
String IsResend = "item:IsResend";
/**
* The Is submitted.
*/
String IsSubmitted = "item:IsSubmitted";
/**
* The Is unmodified.
*/
String IsUnmodified = "item:IsUnmodified";
/**
* The Date time sent.
*/
String DateTimeSent = "item:DateTimeSent";
/**
* The Date time created.
*/
String DateTimeCreated = "item:DateTimeCreated";
/**
* The Body.
*/
String Body = "item:Body";
/**
* The Response objects.
*/
String ResponseObjects = "item:ResponseObjects";
/**
* The Sensitivity.
*/
String Sensitivity = "item:Sensitivity";
/**
* The Reminder due by.
*/
String ReminderDueBy = "item:ReminderDueBy";
/**
* The Reminder is set.
*/
String ReminderIsSet = "item:ReminderIsSet";
/**
* The Reminder minutes before start.
*/
String ReminderMinutesBeforeStart = "item:ReminderMinutesBeforeStart";
/**
* The Display to.
*/
String DisplayTo = "item:DisplayTo";
/**
* The Display cc.
*/
String DisplayCc = "item:DisplayCc";
/**
* The Culture.
*/
String Culture = "item:Culture";
/**
* The Effective rights.
*/
String EffectiveRights = "item:EffectiveRights";
/**
* The Last modified name.
*/
String LastModifiedName = "item:LastModifiedName";
/**
* The Last modified time.
*/
String LastModifiedTime = "item:LastModifiedTime";
/**
* The Web client read form query string.
*/
String WebClientReadFormQueryString =
"item:WebClientReadFormQueryString";
/**
* The Web client edit form query string.
*/
String WebClientEditFormQueryString =
"item:WebClientEditFormQueryString";
/**
* The Conversation id.
*/
String ConversationId = "item:ConversationId";
/**
* The Unique body.
*/
String UniqueBody = "item:UniqueBody";
String StoreEntryId = "item:StoreEntryId";
}
/**
* Defines the Id property.
*/
public static final PropertyDefinition Id = new ComplexPropertyDefinition<ItemId>(
ItemId.class,
XmlElementNames.ItemId, FieldUris.ItemId, EnumSet
.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1,
new ICreateComplexPropertyDelegate<ItemId>() {
public ItemId createComplexProperty() {
return new ItemId();
}
});
/**
* Defines the Body property.
*/
public static final PropertyDefinition Body = new
ComplexPropertyDefinition<MessageBody>(
MessageBody.class,
XmlElementNames.Body, FieldUris.Body, EnumSet.of(
PropertyDefinitionFlags.CanSet,
PropertyDefinitionFlags.CanUpdate,
PropertyDefinitionFlags.CanDelete),
ExchangeVersion.Exchange2007_SP1,
new ICreateComplexPropertyDelegate<MessageBody>() {
public MessageBody createComplexProperty() {
return new MessageBody();
}
});
/**
* Defines the ItemClass property.
*/
public static final PropertyDefinition ItemClass = new StringPropertyDefinition(
XmlElementNames.ItemClass, FieldUris.ItemClass, EnumSet.of(
PropertyDefinitionFlags.CanSet,
PropertyDefinitionFlags.CanUpdate,
PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the Subject property.
*/
public static final PropertyDefinition Subject = new
StringPropertyDefinition(
XmlElementNames.Subject, FieldUris.Subject, EnumSet.of(
PropertyDefinitionFlags.CanSet,
PropertyDefinitionFlags.CanUpdate,
PropertyDefinitionFlags.CanDelete,
PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the MimeContent property.
*/
public static final PropertyDefinition MimeContent =
new ComplexPropertyDefinition<microsoft.exchange.webservices.data.property.complex.MimeContent>(
MimeContent.class,
XmlElementNames.MimeContent, FieldUris.MimeContent, EnumSet.of(
PropertyDefinitionFlags.CanSet,
PropertyDefinitionFlags.CanUpdate,
PropertyDefinitionFlags.MustBeExplicitlyLoaded),
ExchangeVersion.Exchange2007_SP1,
new ICreateComplexPropertyDelegate<MimeContent>() {
public MimeContent createComplexProperty() {
return new MimeContent();
}
});
/**
* Defines the ParentFolderId property.
*/
public static final PropertyDefinition ParentFolderId =
new ComplexPropertyDefinition<FolderId>(
FolderId.class,
XmlElementNames.ParentFolderId, FieldUris.ParentFolderId,
ExchangeVersion.Exchange2007_SP1,
new ICreateComplexPropertyDelegate<FolderId>() {
public FolderId createComplexProperty() {
return new FolderId();
}
});
/**
* Defines the Sensitivity property.
*/
public static final PropertyDefinition Sensitivity =
new GenericPropertyDefinition<microsoft.exchange.webservices.data.enumeration.Sensitivity>(
Sensitivity.class,
XmlElementNames.Sensitivity, FieldUris.Sensitivity, EnumSet.of(
PropertyDefinitionFlags.CanSet,
PropertyDefinitionFlags.CanUpdate,
PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the Attachments property.
*/
public static final PropertyDefinition Attachments = new AttachmentsPropertyDefinition();
/**
* Defines the DateTimeReceived property.
*/
public static final PropertyDefinition DateTimeReceived =
new DateTimePropertyDefinition(
XmlElementNames.DateTimeReceived, FieldUris.DateTimeReceived,
EnumSet.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the Size property.
*/
public static final PropertyDefinition Size = new IntPropertyDefinition(
XmlElementNames.Size, FieldUris.Size, EnumSet
.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the Categories property.
*/
public static final PropertyDefinition Categories =
new ComplexPropertyDefinition<StringList>(
StringList.class,
XmlElementNames.Categories, FieldUris.Categories, EnumSet.of(
PropertyDefinitionFlags.AutoInstantiateOnRead,
PropertyDefinitionFlags.CanSet,
PropertyDefinitionFlags.CanUpdate,
PropertyDefinitionFlags.CanDelete,
PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1,
new ICreateComplexPropertyDelegate<StringList>() {
public StringList createComplexProperty() {
return new StringList();
}
});
/**
* Defines the Importance property.
*/
public static final PropertyDefinition Importance =
new GenericPropertyDefinition<microsoft.exchange.webservices.data.enumeration.Importance>(
Importance.class,
XmlElementNames.Importance, FieldUris.Importance, EnumSet.of(
PropertyDefinitionFlags.CanSet,
PropertyDefinitionFlags.CanUpdate,
PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the InReplyTo property.
*/
public static final PropertyDefinition InReplyTo =
new StringPropertyDefinition(
XmlElementNames.InReplyTo, FieldUris.InReplyTo, EnumSet.of(
PropertyDefinitionFlags.CanSet,
PropertyDefinitionFlags.CanUpdate,
PropertyDefinitionFlags.CanDelete,
PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the IsSubmitted property.
*/
public static final PropertyDefinition IsSubmitted =
new BoolPropertyDefinition(
XmlElementNames.IsSubmitted, FieldUris.IsSubmitted, EnumSet
.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the IsAssociated property.
*/
public static final PropertyDefinition IsAssociated =
new BoolPropertyDefinition(
XmlElementNames.IsAssociated, FieldUris.IsAssociated, EnumSet.of(
PropertyDefinitionFlags.CanSet,
PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2010);
/**
* Defines the IsDraft property.
*/
public static final PropertyDefinition IsDraft = new BoolPropertyDefinition(
XmlElementNames.IsDraft, FieldUris.IsDraft, EnumSet
.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the IsFromMe property.
*/
public static final PropertyDefinition IsFromMe =
new BoolPropertyDefinition(
XmlElementNames.IsFromMe, FieldUris.IsFromMe, EnumSet
.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the IsResend property.
*/
public static final PropertyDefinition IsResend =
new BoolPropertyDefinition(
XmlElementNames.IsResend, FieldUris.IsResend, EnumSet
.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the IsUnmodified property.
*/
public static final PropertyDefinition IsUnmodified =
new BoolPropertyDefinition(
XmlElementNames.IsUnmodified, FieldUris.IsUnmodified, EnumSet
.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the InternetMessageHeaders property.
*/
public static final PropertyDefinition InternetMessageHeaders =
new ComplexPropertyDefinition<InternetMessageHeaderCollection>(
InternetMessageHeaderCollection.class,
XmlElementNames.InternetMessageHeaders,
FieldUris.InternetMessageHeaders,
EnumSet.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1,
new ICreateComplexPropertyDelegate
<InternetMessageHeaderCollection>() {
public InternetMessageHeaderCollection createComplexProperty() {
return new InternetMessageHeaderCollection();
}
});
/**
* Defines the DateTimeSent property.
*/
public static final PropertyDefinition DateTimeSent =
new DateTimePropertyDefinition(
XmlElementNames.DateTimeSent, FieldUris.DateTimeSent, EnumSet
.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the DateTimeCreated property.
*/
public static final PropertyDefinition DateTimeCreated =
new DateTimePropertyDefinition(
XmlElementNames.DateTimeCreated, FieldUris.DateTimeCreated, EnumSet
.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the AllowedResponseActions property.
*/
public static final PropertyDefinition AllowedResponseActions =
new ResponseObjectsPropertyDefinition(
XmlElementNames.ResponseObjects, FieldUris.ResponseObjects,
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the ReminderDueBy property.
*/
public static final PropertyDefinition ReminderDueBy =
new DateTimePropertyDefinition(
XmlElementNames.ReminderDueBy, FieldUris.ReminderDueBy, EnumSet.of(
PropertyDefinitionFlags.CanSet,
PropertyDefinitionFlags.CanUpdate,
PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the IsReminderSet property.
*/
public static final PropertyDefinition IsReminderSet =
new BoolPropertyDefinition(
XmlElementNames.ReminderIsSet, // Note: server-side the name is
// ReminderIsSet
FieldUris.ReminderIsSet, EnumSet.of(PropertyDefinitionFlags.CanSet,
PropertyDefinitionFlags.CanUpdate,
PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the ReminderMinutesBeforeStart property.
*/
public static final PropertyDefinition ReminderMinutesBeforeStart =
new IntPropertyDefinition(
XmlElementNames.ReminderMinutesBeforeStart,
FieldUris.ReminderMinutesBeforeStart, EnumSet.of(
PropertyDefinitionFlags.CanSet,
PropertyDefinitionFlags.CanUpdate,
PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the DisplayCc property.
*/
public static final PropertyDefinition DisplayCc =
new StringPropertyDefinition(
XmlElementNames.DisplayCc, FieldUris.DisplayCc, EnumSet
.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the DisplayTo property.
*/
public static final PropertyDefinition DisplayTo =
new StringPropertyDefinition(
XmlElementNames.DisplayTo, FieldUris.DisplayTo, EnumSet
.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the HasAttachments property.
*/
public static final PropertyDefinition HasAttachments =
new BoolPropertyDefinition(
XmlElementNames.HasAttachments, FieldUris.HasAttachments, EnumSet
.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the Culture property.
*/
public static final PropertyDefinition Culture =
new StringPropertyDefinition(
XmlElementNames.Culture, FieldUris.Culture, EnumSet.of(
PropertyDefinitionFlags.CanSet,
PropertyDefinitionFlags.CanUpdate,
PropertyDefinitionFlags.CanDelete,
PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the EffectiveRights property.
*/
public static final PropertyDefinition EffectiveRights =
new EffectiveRightsPropertyDefinition(
XmlElementNames.EffectiveRights, FieldUris.EffectiveRights, EnumSet
.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the LastModifiedName property.
*/
public static final PropertyDefinition LastModifiedName =
new StringPropertyDefinition(
XmlElementNames.LastModifiedName, FieldUris.LastModifiedName,
EnumSet.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the LastModifiedTime property.
*/
public static final PropertyDefinition LastModifiedTime =
new DateTimePropertyDefinition(
XmlElementNames.LastModifiedTime, FieldUris.LastModifiedTime,
EnumSet.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2007_SP1);
/**
* Defines the WebClientReadFormQueryString property.
*/
public static final PropertyDefinition WebClientReadFormQueryString =
new StringPropertyDefinition(
XmlElementNames.WebClientReadFormQueryString,
FieldUris.WebClientReadFormQueryString, EnumSet
.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2010);
/**
* Defines the WebClientEditFormQueryString property.
*/
public static final PropertyDefinition WebClientEditFormQueryString =
new StringPropertyDefinition(
XmlElementNames.WebClientEditFormQueryString,
FieldUris.WebClientEditFormQueryString, EnumSet
.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2010);
/**
* Defines the ConversationId property.
*/
public static final PropertyDefinition ConversationId =
new ComplexPropertyDefinition<microsoft.exchange.webservices.data.property.complex.ConversationId>(
ConversationId.class,
XmlElementNames.ConversationId, FieldUris.ConversationId, EnumSet
.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2010,
new ICreateComplexPropertyDelegate<ConversationId>() {
public ConversationId createComplexProperty() {
return new ConversationId();
}
});
/**
* Defines the UniqueBody property.
*/
public static final PropertyDefinition UniqueBody =
new ComplexPropertyDefinition<microsoft.exchange.webservices.data.property.complex.UniqueBody>(
UniqueBody.class,
XmlElementNames.UniqueBody, FieldUris.UniqueBody, EnumSet
.of(PropertyDefinitionFlags.MustBeExplicitlyLoaded),
ExchangeVersion.Exchange2010,
new ICreateComplexPropertyDelegate<UniqueBody>() {
public UniqueBody createComplexProperty() {
return new UniqueBody();
}
});
/**
* Defines the StoreEntryId property.
*/
public static final PropertyDefinition StoreEntryId =
new ByteArrayPropertyDefinition(
XmlElementNames.StoreEntryId,
FieldUris.StoreEntryId,
EnumSet
.of(PropertyDefinitionFlags.CanFind),
ExchangeVersion.Exchange2010_SP2);
/**
* The Constant Instance.
*/
protected static final ItemSchema Instance = new ItemSchema();
/**
* Gets the single instance of ItemSchema.
*
* @return single instance of ItemSchema
*/
public static ItemSchema getInstance() {
return Instance;
}
/**
* Registers property.
* <p/>
* IMPORTANT NOTE: PROPERTIES MUST BE REGISTERED IN SCHEMA ORDER (i.e. the
* same order as they are defined in types.xsd)
*/
@Override
protected void registerProperties() {
super.registerProperties();
this.registerProperty(MimeContent);
this.registerProperty(Id);
this.registerProperty(ParentFolderId);
this.registerProperty(ItemClass);
this.registerProperty(Subject);
this.registerProperty(Sensitivity);
this.registerProperty(Body);
this.registerProperty(Attachments);
this.registerProperty(DateTimeReceived);
this.registerProperty(Size);
this.registerProperty(Categories);
this.registerProperty(Importance);
this.registerProperty(InReplyTo);
this.registerProperty(IsSubmitted);
this.registerProperty(IsDraft);
this.registerProperty(IsFromMe);
this.registerProperty(IsResend);
this.registerProperty(IsUnmodified);
this.registerProperty(InternetMessageHeaders);
this.registerProperty(DateTimeSent);
this.registerProperty(DateTimeCreated);
this.registerProperty(AllowedResponseActions);
this.registerProperty(ReminderDueBy);
this.registerProperty(IsReminderSet);
this.registerProperty(ReminderMinutesBeforeStart);
this.registerProperty(DisplayCc);
this.registerProperty(DisplayTo);
this.registerProperty(HasAttachments);
this.registerProperty(ServiceObjectSchema.extendedProperties);
this.registerProperty(Culture);
this.registerProperty(EffectiveRights);
this.registerProperty(LastModifiedName);
this.registerProperty(LastModifiedTime);
this.registerProperty(IsAssociated);
this.registerProperty(WebClientReadFormQueryString);
this.registerProperty(WebClientEditFormQueryString);
this.registerProperty(ConversationId);
this.registerProperty(UniqueBody);
this.registerProperty(StoreEntryId);
}
/**
* Initializes a new instance.
*/
protected ItemSchema() {
super();
}
}
|
relateiq/ews-java-api
|
src/main/java/microsoft/exchange/webservices/data/core/service/schema/ItemSchema.java
|
Java
|
mit
| 24,413 |
// this exports a "masked" version of the WrapUp class.
var WrapUp = require("./wrapup")
module.exports = function(x){
return new WrapUp(x)
}
|
kentaromiura/sugo
|
node_modules/wrapup/node_modules/prime/cov/node_modules/wrapup/lib/main.js
|
JavaScript
|
mit
| 145 |
#Practica realizada por: Miguel Aurelio García González y Daura Hernández Díaz
#En esta practica desarrollamos tres clases, la clase Matriz, MatrizDensa y MatrizDispersa.
#La clase Matriz será la madre de las otras dos.
class Matriz
attr_accessor :m, :t
#definición del método initialize, donde crearemos la matriz que usaremos posteriormente y obtendremos su tamaño
def initialize(matriz)
if matriz != nil
@t = matriz.size-1
end
@m = matriz
end
def get_t
return @t
end
def + (other)
end
def - (other)
end
def * (other)
end
def pos(a, b)
end
def to_s
end
end
#Definición e implementación de la clas MatrizDensa, que como vemos hereda de la clase Matriz definida anteriormente.
class MatrizDensa < Matriz
private_class_method :new
#Hacemos el new privado, utilizandolo posteriormente en un método que hemos creado, dentro del cual llamamos al constructor de la clase Matriz
def Matriz.densa (matriz)
new(matriz)
end
#Max es un método que nos devolverá el mayor elemento que contenga la matriz densa
# El valor que tendremos como referencia es el que se encuentre en la posición (0,0) de la matriz, comparandolo luego con el resto de los valores
def max
elemenmax = @m[0][0]
for i in 0..@t
for j in 0..@t
if(elemenmax < @m[i][j])
elemenmax = @m[i][j]
end
end
end
return elemenmax
end
# El método min devolverá el elemento mínimo de la matriz
def min
elemenmin = @m[0][0]
for i in 0..@t
for j in 0..@t
if(elemenmin > @m[i][j])
elemenmin = @m[i][j]
end
end
end
return elemenmin
end
#El siguiente método realiza la suma entre dos matrices, pueden ser densa-densa o densa-dispersa
def +(m2)
if m2.instance_of?MatrizDispersa
result = MatrizDensa.densa(@m)
(@t+1).times do |i|
(@t+1).times do |j|
encontrado = 0
(m2.arrayi.size+1).times do |k|
if (i==m2.arrayi[k] and j==m2.arrayj[k] and encontrado==0)
result.m[i][j] = (result.m[i][j]) + (m2.valores[k])
encontrado = 1
end
end
end
end
else
result = MatrizDensa.densa(m2.m)
(@t+1).times do |i|
(@t+1).times do |j|
result.m[i][j] = @m[i][j] + result.m[i][j]
end
end
end
return result
end
# El siguiente método realiza la resta de dos matrices, como comentabamos anteriormente las matrices pueden ser densa-densa o densa-dispersa
def -(m2)
if m2.instance_of?MatrizDispersa
result = MatrizDensa.densa(@m)
for i in (0..@t)
for j in (0..@t)
encontrado = 0
for k in (0...m2.arrayi.size)
if (i==m2.arrayi[k] and j==m2.arrayj[k] and encontrado==0)
result.m[i][j] = (result.m[i][j]) - (m2.valores[k])
encontrado = 1
end
end
end
end
else
result = MatrizDensa.densa(m2.m)
for i in 0..@t do
for j in 0..@t do
result.m[i][j] = @m[i][j] - result.m[i][j]
end
end
end
return result
end
# El método * realiza la multiplicación entre dos matrices densas
def *(m2)
mat = Array.new(@t+1){Array.new(@t+1)}
(@t+1).times do |i|
(@t+1).times do |j|
mat[i][j]=0;
end
end
m_resultado = Matriz.new(mat)
(@t+1).times do |i|
(@t+1).times do |j|
(@t+1).times do |k|
m_resultado.m[i][j] += @m[i][k] * m2.m[k][j]
end
end
end
return m_resultado
end
#Con este método podemos acceder al valor de una posición determinada de la matriz
def pos(a, b)
@m[a][b]
end
#El método to_s devuelve la matriz en otro formato
def to_s
"#{@mat}"
end
def encontrar
(@t+2).times do |i|
(@t+2).times do |j|
if yield(@m[i][j])
return [i,j]
end
end
end
end
end
#Definición e implementación de la clase MatrizDispersa
#MatrizDispersa hereda de Matriz
class MatrizDispersa < Matriz
attr_accessor :arrayi, :arrayj , :valores
#Dentro del método initialize creamos tres vectores, el vector arrayi contendrá las posiciones de i, arrayj las posiciones de j y valores contendrá
# los valores no nulos que contenga la matriz.
def initialize(i, j, v)
@arrayi = i
@arrayj = j
@valores = v
end
# El método pos nos permite acceder al valor de una posición determinada
def pos(a,b)
for i in 0...@arrayi.size
if((@arrayi[i] == a) and (@arrayj[i] == b))
return @valores[i]
end
end
return nil
end
#Método max para devolver el mayor elemento de la matriz
def max
elemenmax = @valores[0]
for i in 0...@arrayi.size
if(elemenmax < @valores[i])
elemenmax = @valores[i]
end
end
return elemenmax
end
#Método min que devuelve el menor elemento de la matriz
def min
elemenmin = @valores[0]
for i in 0...@arrayi.size
if(elemenmin > @valores[i])
elemenmin = @valores[i]
end
end
return elemenmin
end
#Suma de matrices, bien pueden ser dispersa-dispersa o dispersa-densa
def +(m2)
if m2.instance_of?MatrizDensa
result = MatrizDensa.densa(m2.m)
(m2.t+1).times do |i|
(m2.t+1).times do |j|
encontrado = 0
(@arrayi.size).times do |k|
if (i==@arrayi[k] and j==@arrayj[k] and encontrado==0)
result.m[i][j] = (result.m[i][j]) + (@valores[k])
encontrado = 1
end
end
end
end
return result
else
result = MatrizDispersa.new(@arrayi, @arrayj, @valores)
(m2.arrayi.size).times do |j|
encontrado = false
(m2.arrayi.size+1).times do |k|
if((m2.arrayi[j]) == result.arrayi[k] and m2.arrayj[j] == result.arrayj[k])
result.valores[k] = result.valores[k] + m2.valores[j]
encontrado = true
end
end
if(encontrado == false)
result.arrayi << m2.arrayi[j]
result.arrayj << m2.arrayj[j]
result.valores << m2.valores[j]
end
end
return result
end
end
#Resta de dos matrices
def -(m2)
if m2.instance_of?MatrizDensa
result = MatrizDensa.densa(m2.m)
for i in (0..m2.t)
for j in (0..m2.t)
encontrado = 0
for k in (0...@arrayi.size)
if (i==@arrayi[k] and j==@arrayj[k] and encontrado==0)
result.m[i][j] = (result.m[i][j]) - (@valores[k])
encontrado = 1
end
end
end
end
return result
else
result = MatrizDispersa.new(@arrayi, @arrayj, @valores)
for j in (0...m2.arrayi.size)
encontrado = false
for k in (0...m2.arrayi.size)
if((m2.arrayi[j]) == result.arrayi[k] and m2.arrayj[j] == result.arrayj[k])
result.valores[k] = result.valores[k] - m2.valores[j]
encontrado = true
end
end
if(encontrado == false)
result.arrayi << m2.arrayi[j]
result.arrayj << m2.arrayj[j]
result.valores << m2.valores[j]
end
end
return result
end
end
#Multiplicacion de dos matrices dispersa*dispersa
def *(m2)
result = MatrizDispersa.new(@arrayi, @arrayj, @valores)
(m2.arrayi.size).times do |j|
(m2.arrayi.size).times do |k|
#for j in (0...m2.arrayi.size)
#for k in (0...m2.arrayi.size)
if((m2.arrayi[j]) == result.arrayi[k] and m2.arrayj[j] == result.arrayj[k])
result.valores[k] = result.valores[k] * m2.valores[j]
end
end
end
return result
end
end
|
alu0100600643/Practica12
|
lib/matriz.rb
|
Ruby
|
mit
| 7,713 |
#include "overviewpage.h"
#include "ui_overviewpage.h"
#include "walletmodel.h"
#include "bitcoinunits.h"
#include "optionsmodel.h"
#include "transactiontablemodel.h"
#include "transactionfilterproxy.h"
#include "guiutil.h"
#include "guiconstants.h"
#include "askpassphrasedialog.h"
#include "util.h"
#include <QAbstractItemDelegate>
#include <QPainter>
#define DECORATION_SIZE 64
#define NUM_ITEMS 3
class TxViewDelegate : public QAbstractItemDelegate
{
Q_OBJECT
public:
TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC)
{
}
inline void paint(QPainter *painter, const QStyleOptionViewItem &option,
const QModelIndex &index ) const
{
painter->save();
QIcon icon = qvariant_cast<QIcon>(index.data(Qt::DecorationRole));
QRect mainRect = option.rect;
QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE));
int xspace = DECORATION_SIZE + 8;
int ypad = 6;
int halfheight = (mainRect.height() - 2*ypad)/2;
QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight);
QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight);
icon.paint(painter, decorationRect);
QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime();
QString address = index.data(Qt::DisplayRole).toString();
qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong();
bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool();
QVariant value = index.data(Qt::ForegroundRole);
QColor foreground = option.palette.color(QPalette::Text);
if(qVariantCanConvert<QColor>(value))
{
foreground = qvariant_cast<QColor>(value);
}
painter->setPen(foreground);
painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address);
if(amount < 0)
{
foreground = COLOR_NEGATIVE;
}
else if(!confirmed)
{
foreground = COLOR_UNCONFIRMED;
}
else
{
foreground = option.palette.color(QPalette::Text);
}
painter->setPen(foreground);
QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true);
if(!confirmed)
{
amountText = QString("[") + amountText + QString("]");
}
painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText);
painter->setPen(option.palette.color(QPalette::Text));
painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date));
painter->restore();
}
inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
return QSize(DECORATION_SIZE, DECORATION_SIZE);
}
int unit;
};
#include "overviewpage.moc"
OverviewPage::OverviewPage(QWidget *parent) :
QWidget(parent),
ui(new Ui::OverviewPage),
currentBalance(-1),
currentStake(0),
currentUnconfirmedBalance(-1),
currentImmatureBalance(-1),
txdelegate(new TxViewDelegate()),
filter(0)
{
ui->setupUi(this);
// Recent transactions
ui->listTransactions->setItemDelegate(txdelegate);
ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE));
ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2));
ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false);
connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex)));
// init "out of sync" warning labels
ui->labelWalletStatus->setText("(" + tr("out of sync") + ")");
ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")");
// start with displaying the "out of sync" warnings
showOutOfSyncWarning(true);
}
void OverviewPage::handleTransactionClicked(const QModelIndex &index)
{
if(filter)
emit transactionClicked(filter->mapToSource(index));
}
OverviewPage::~OverviewPage()
{
delete ui;
}
void OverviewPage::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance)
{
int unit = model->getOptionsModel()->getDisplayUnit();
currentBalance = balance;
currentStake = stake;
currentUnconfirmedBalance = unconfirmedBalance;
currentImmatureBalance = immatureBalance;
ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance));
ui->labelStake->setText(BitcoinUnits::formatWithUnit(unit, stake));
ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance));
ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance));
ui->labelTotal->setText(BitcoinUnits::formatWithUnit(unit, balance + stake + unconfirmedBalance + immatureBalance));
// only show immature (newly mined) balance if it's non-zero, so as not to complicate things
// for the non-mining users
bool showImmature = immatureBalance != 0;
ui->labelImmature->setVisible(showImmature);
ui->labelImmatureText->setVisible(showImmature);
}
void OverviewPage::unlockWallet()
{
if(model->getEncryptionStatus() == WalletModel::Locked)
{
AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this);
dlg.setModel(model);
if(dlg.exec() == QDialog::Accepted)
{
// ui->unlockWalletButton->setText(QString("Lock Wallet"));
}
}
else
{
model->setWalletLocked(true);
// ui->unlockWalletButton->setText(QString("Unlock Wallet"));
}
}
void OverviewPage::setModel(WalletModel *model)
{
this->model = model;
if(model && model->getOptionsModel())
{
// Set up transaction list
filter = new TransactionFilterProxy();
filter->setSourceModel(model->getTransactionTableModel());
filter->setLimit(NUM_ITEMS);
filter->setDynamicSortFilter(true);
filter->setSortRole(Qt::EditRole);
filter->setShowInactive(false);
filter->sort(TransactionTableModel::Status, Qt::DescendingOrder);
ui->listTransactions->setModel(filter);
ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress);
// Keep up to date with wallet
setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance());
connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64)));
connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
// Unlock wallet button
WalletModel::EncryptionStatus status = model->getEncryptionStatus();
if(status == WalletModel::Unencrypted)
{
// ui->unlockWalletButton->setDisabled(true);
// ui->unlockWalletButton->setText(QString("Wallet is not encrypted!"));
}
else
{
// ui->unlockWalletButton->setText(QString("Unlock wallet"));
}
// connect(ui->unlockWalletButton, SIGNAL(clicked()), this, SLOT(unlockWallet()));
}
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void OverviewPage::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
if(currentBalance != -1)
setBalance(currentBalance, model->getStake(), currentUnconfirmedBalance, currentImmatureBalance);
// Update txdelegate->unit with the current unit
txdelegate->unit = model->getOptionsModel()->getDisplayUnit();
ui->listTransactions->update();
}
}
void OverviewPage::showOutOfSyncWarning(bool fShow)
{
ui->labelWalletStatus->setVisible(fShow);
ui->labelTransactionsStatus->setVisible(fShow);
}
|
mammix2/boostcoin-core
|
src/qt/overviewpage.cpp
|
C++
|
mit
| 7,949 |
import * as React from 'react';
import PropTypes from 'prop-types';
import debounce from '../utils/debounce';
import useForkRef from '../utils/useForkRef';
import useEnhancedEffect from '../utils/useEnhancedEffect';
import ownerWindow from '../utils/ownerWindow';
function getStyleValue(computedStyle, property) {
return parseInt(computedStyle[property], 10) || 0;
}
const styles = {
/* Styles applied to the shadow textarea element. */
shadow: {
// Visibility needed to hide the extra text area on iPads
visibility: 'hidden',
// Remove from the content flow
position: 'absolute',
// Ignore the scrollbar width
overflow: 'hidden',
height: 0,
top: 0,
left: 0,
// Create a new layer, increase the isolation of the computed values
transform: 'translateZ(0)',
},
};
const TextareaAutosize = React.forwardRef(function TextareaAutosize(props, ref) {
const { onChange, maxRows, minRows = 1, style, value, ...other } = props;
const { current: isControlled } = React.useRef(value != null);
const inputRef = React.useRef(null);
const handleRef = useForkRef(ref, inputRef);
const shadowRef = React.useRef(null);
const renders = React.useRef(0);
const [state, setState] = React.useState({});
const syncHeight = React.useCallback(() => {
const input = inputRef.current;
const containerWindow = ownerWindow(input);
const computedStyle = containerWindow.getComputedStyle(input);
// If input's width is shrunk and it's not visible, don't sync height.
if (computedStyle.width === '0px') {
return;
}
const inputShallow = shadowRef.current;
inputShallow.style.width = computedStyle.width;
inputShallow.value = input.value || props.placeholder || 'x';
if (inputShallow.value.slice(-1) === '\n') {
// Certain fonts which overflow the line height will cause the textarea
// to report a different scrollHeight depending on whether the last line
// is empty. Make it non-empty to avoid this issue.
inputShallow.value += ' ';
}
const boxSizing = computedStyle['box-sizing'];
const padding =
getStyleValue(computedStyle, 'padding-bottom') + getStyleValue(computedStyle, 'padding-top');
const border =
getStyleValue(computedStyle, 'border-bottom-width') +
getStyleValue(computedStyle, 'border-top-width');
// The height of the inner content
const innerHeight = inputShallow.scrollHeight;
// Measure height of a textarea with a single row
inputShallow.value = 'x';
const singleRowHeight = inputShallow.scrollHeight;
// The height of the outer content
let outerHeight = innerHeight;
if (minRows) {
outerHeight = Math.max(Number(minRows) * singleRowHeight, outerHeight);
}
if (maxRows) {
outerHeight = Math.min(Number(maxRows) * singleRowHeight, outerHeight);
}
outerHeight = Math.max(outerHeight, singleRowHeight);
// Take the box sizing into account for applying this value as a style.
const outerHeightStyle = outerHeight + (boxSizing === 'border-box' ? padding + border : 0);
const overflow = Math.abs(outerHeight - innerHeight) <= 1;
setState((prevState) => {
// Need a large enough difference to update the height.
// This prevents infinite rendering loop.
if (
renders.current < 20 &&
((outerHeightStyle > 0 &&
Math.abs((prevState.outerHeightStyle || 0) - outerHeightStyle) > 1) ||
prevState.overflow !== overflow)
) {
renders.current += 1;
return {
overflow,
outerHeightStyle,
};
}
if (process.env.NODE_ENV !== 'production') {
if (renders.current === 20) {
console.error(
[
'Material-UI: Too many re-renders. The layout is unstable.',
'TextareaAutosize limits the number of renders to prevent an infinite loop.',
].join('\n'),
);
}
}
return prevState;
});
}, [maxRows, minRows, props.placeholder]);
React.useEffect(() => {
const handleResize = debounce(() => {
renders.current = 0;
syncHeight();
});
const containerWindow = ownerWindow(inputRef.current);
containerWindow.addEventListener('resize', handleResize);
return () => {
handleResize.clear();
containerWindow.removeEventListener('resize', handleResize);
};
}, [syncHeight]);
useEnhancedEffect(() => {
syncHeight();
});
React.useEffect(() => {
renders.current = 0;
}, [value]);
const handleChange = (event) => {
renders.current = 0;
if (!isControlled) {
syncHeight();
}
if (onChange) {
onChange(event);
}
};
return (
<React.Fragment>
<textarea
value={value}
onChange={handleChange}
ref={handleRef}
// Apply the rows prop to get a "correct" first SSR paint
rows={minRows}
style={{
height: state.outerHeightStyle,
// Need a large enough difference to allow scrolling.
// This prevents infinite rendering loop.
overflow: state.overflow ? 'hidden' : null,
...style,
}}
{...other}
/>
<textarea
aria-hidden
className={props.className}
readOnly
ref={shadowRef}
tabIndex={-1}
style={{
...styles.shadow,
...style,
padding: 0,
}}
/>
</React.Fragment>
);
});
TextareaAutosize.propTypes /* remove-proptypes */ = {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* @ignore
*/
className: PropTypes.string,
/**
* Maximum number of rows to display.
*/
maxRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* Minimum number of rows to display.
* @default 1
*/
minRows: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
/**
* @ignore
*/
onChange: PropTypes.func,
/**
* @ignore
*/
placeholder: PropTypes.string,
/**
* @ignore
*/
style: PropTypes.object,
/**
* @ignore
*/
value: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.string),
PropTypes.number,
PropTypes.string,
]),
};
export default TextareaAutosize;
|
callemall/material-ui
|
packages/material-ui/src/TextareaAutosize/TextareaAutosize.js
|
JavaScript
|
mit
| 6,538 |
# -*- coding: utf-8 -
#
# This file is part of socketpool.
# See the NOTICE for more information.
import errno
import os
import platform
import select
import socket
import sys
try:
from importlib import import_module
except ImportError:
import sys
def _resolve_name(name, package, level):
"""Return the absolute name of the module to be imported."""
if not hasattr(package, 'rindex'):
raise ValueError("'package' not set to a string")
dot = len(package)
for x in range(level, 1, -1):
try:
dot = package.rindex('.', 0, dot)
except ValueError:
raise ValueError("attempted relative import beyond top-level "
"package")
return "%s.%s" % (package[:dot], name)
def import_module(name, package=None):
"""Import a module.
The 'package' argument is required when performing a relative import. It
specifies the package to use as the anchor point from which to resolve the
relative import to an absolute import.
"""
if name.startswith('.'):
if not package:
raise TypeError("relative imports require the 'package' argument")
level = 0
for character in name:
if character != '.':
break
level += 1
name = _resolve_name(name[level:], package, level)
__import__(name)
return sys.modules[name]
def load_backend(backend_name):
""" load pool backend. If this is an external module it should be
passed as "somelib.backend_mod", for socketpool backend you can just
pass the name.
Supported backend are :
- thread: connection are maintained in a threadsafe queue.
- gevent: support gevent
- eventlet: support eventlet
"""
try:
if len(backend_name.split(".")) > 1:
mod = import_module(backend_name)
else:
mod = import_module("socketpool.backend_%s" % backend_name)
return mod
except ImportError:
error_msg = "%s isn't a socketpool backend" % backend_name
raise ImportError(error_msg)
def can_use_kqueue():
# See Issue #15. kqueue doesn't work on OS X 10.6 and below.
if not hasattr(select, "kqueue"):
return False
if platform.system() == 'Darwin' and platform.mac_ver()[0] < '10.7':
return False
return True
def is_connected(skt):
try:
fno = skt.fileno()
except socket.error as e:
if e[0] == errno.EBADF:
return False
raise
try:
if hasattr(select, "epoll"):
ep = select.epoll()
ep.register(fno, select.EPOLLOUT | select.EPOLLIN)
events = ep.poll(0)
for fd, ev in events:
if fno == fd and \
(ev & select.EPOLLOUT or ev & select.EPOLLIN):
ep.unregister(fno)
return True
ep.unregister(fno)
elif hasattr(select, "poll"):
p = select.poll()
p.register(fno, select.POLLOUT | select.POLLIN)
events = p.poll(0)
for fd, ev in events:
if fno == fd and \
(ev & select.POLLOUT or ev & select.POLLIN):
p.unregister(fno)
return True
p.unregister(fno)
elif can_use_kqueue():
kq = select.kqueue()
events = [
select.kevent(fno, select.KQ_FILTER_READ, select.KQ_EV_ADD),
select.kevent(fno, select.KQ_FILTER_WRITE, select.KQ_EV_ADD)
]
kq.control(events, 0)
kevents = kq.control(None, 4, 0)
for ev in kevents:
if ev.ident == fno:
if ev.flags & select.KQ_EV_ERROR:
return False
else:
return True
# delete
events = [
select.kevent(fno, select.KQ_FILTER_READ, select.KQ_EV_DELETE),
select.kevent(fno, select.KQ_FILTER_WRITE, select.KQ_EV_DELETE)
]
kq.control(events, 0)
kq.close()
return True
else:
r, _, _ = select.select([fno], [], [], 0)
if not r:
return True
except IOError:
pass
except (ValueError, select.error,) as e:
pass
return False
|
benoitc/socketpool
|
socketpool/util.py
|
Python
|
mit
| 4,541 |
version https://git-lfs.github.com/spec/v1
oid sha256:ec9603f026a2a1295d751178e7e48bf8b945506e9b05818112c5166e1e950a67
size 9557
|
yogeshsaroya/new-cdnjs
|
ajax/libs/yui/3.8.0/calendarnavigator/calendarnavigator.js
|
JavaScript
|
mit
| 129 |
require 'thread'
require 'core_ext/module/prepend_to'
module Travis
module Async
require 'travis/support/async/inline'
require 'travis/support/async/sidekiq'
require 'travis/support/async/threaded'
class << self
attr_writer :enabled
def enabled?
!!@enabled
end
def run(target, method, options, *args, &block)
if enabled?
options[:queue] ||= target.is_a?(Module) ? target.name : target.class.name
strategy = strategy(options.delete(:use))
puts "Enqueueing target: #{target}, method: #{method} to #{options[:queue]} using #{strategy}" if options[:debug] || Travis.respond_to?(:config) && Travis.config.log_level == :debug
strategy.run(target, method, options, *args, &block)
elsif method.is_a?(Method)
method.call(*args, &block)
else
target.send(method, *args, &block)
end
rescue Exception => e
puts "Exception caught in #{name}.call. Exceptions should be caught in client code"
puts e.message, e.backtrace
end
def strategy(name)
const_get(camelize(name || 'inline'))
end
def camelize(string)
string.to_s.gsub(/^.{1}|_.{1}/) { |char| char.gsub('_', '').upcase }
end
end
def async(name, options = {})
prepend_to name do |target, method, *args, &block|
Async.run(target, method, options, *args, &block)
end
end
end
end
|
final-ci/travis-support
|
lib/travis/support/async.rb
|
Ruby
|
mit
| 1,467 |
<?php
/**
* kitFramework::Basic
*
* @author Team phpManufaktur <team@phpmanufaktur.de>
* @link https://kit2.phpmanufaktur.de
* @copyright 2013 Ralf Hertsch <ralf.hertsch@phpmanufaktur.de>
* @license MIT License (MIT) http://www.opensource.org/licenses/MIT
*/
namespace phpManufaktur\Basic\Control\CMS\LEPTON;
use phpManufaktur\Basic\Control\CMS\WebsiteBaker\InstallSearch as WebsiteBakerInstallSearch;
class InstallSearch extends WebsiteBakerInstallSearch
{
// nothing to extend or to change
}
|
phpManufakturHeirs/kfBasic
|
Control/CMS/LEPTON/InstallSearch.php
|
PHP
|
mit
| 509 |
package Feb2021Leetcode;
import java.util.Arrays;
public class _1051HeightChecker {
public static void main(String[] args) {
System.out.println(heightChecker(new int[] { 1, 1, 4, 2, 1, 3 }));
System.out.println(heightChecker(new int[] { 5, 1, 2, 3, 4 }));
System.out.println(heightChecker(new int[] { 1, 2, 3, 4, 5 }));
}
public static int heightChecker(int[] heights) {
}
}
|
darshanhs90/Java-Coding
|
src/Feb2021Leetcode/_1051HeightChecker.java
|
Java
|
mit
| 390 |
# encoding: utf-8
require File.expand_path("../spec_helper", __FILE__)
describe "Pre" do
before :each do
browser.goto(WatirSpec.url_for("non_control_elements.html"))
end
# Exists method
describe "#exist?" do
it "returns true if the 'p' exists" do
expect(browser.pre(id: "rspec")).to exist
expect(browser.pre(id: /rspec/)).to exist
expect(browser.pre(text: 'browser.pre(id: "rspec").should exist')).to exist
expect(browser.pre(text: /browser\.pre/)).to exist
expect(browser.pre(class: "ruby")).to exist
expect(browser.pre(class: /ruby/)).to exist
expect(browser.pre(index: 0)).to exist
expect(browser.pre(xpath: "//pre[@id='rspec']")).to exist
end
it "returns the first pre if given no args" do
expect(browser.pre).to exist
end
it "returns false if the 'p' doesn't exist" do
expect(browser.pre(id: "no_such_id")).to_not exist
expect(browser.pre(id: /no_such_id/)).to_not exist
expect(browser.pre(text: "no_such_text")).to_not exist
expect(browser.pre(text: /no_such_text/)).to_not exist
expect(browser.pre(class: "no_such_class")).to_not exist
expect(browser.pre(class: /no_such_class/)).to_not exist
expect(browser.pre(index: 1337)).to_not exist
expect(browser.pre(xpath: "//pre[@id='no_such_id']")).to_not exist
end
it "raises TypeError when 'what' argument is invalid" do
expect { browser.pre(id: 3.14).exists? }.to raise_error(TypeError)
end
it "raises MissingWayOfFindingObjectException when 'how' argument is invalid" do
expect { browser.pre(no_such_how: 'some_value').exists? }.to raise_error(Watir::Exception::MissingWayOfFindingObjectException)
end
end
# Attribute methods
describe "#class_name" do
it "returns the class attribute" do
expect(browser.pre(id: 'rspec').class_name).to eq 'ruby'
end
it "returns an empty string if the element exists and the attribute doesn't" do
expect(browser.pre(index: 0).class_name).to eq ''
end
it "raises UnknownObjectException if the p doesn't exist" do
expect { browser.pre(id: 'no_such_id').class_name }.to raise_error(Watir::Exception::UnknownObjectException)
end
end
describe "#id" do
it "returns the id attribute" do
expect(browser.pre(class: 'ruby').id).to eq "rspec"
end
it "returns an empty string if the element exists and the attribute doesn't" do
expect(browser.pre(index: 0).id).to eq ''
end
it "raises UnknownObjectException if the pre doesn't exist" do
expect { browser.pre(id: "no_such_id").id }.to raise_error(Watir::Exception::UnknownObjectException)
expect { browser.pre(index: 1337).id }.to raise_error(Watir::Exception::UnknownObjectException)
end
end
describe "#title" do
it "returns the title attribute" do
expect(browser.pre(class: 'brainfuck').title).to eq 'The brainfuck language is an esoteric programming language noted for its extreme minimalism'
end
it "returns an empty string if the element exists and the attribute doesn't" do
expect(browser.pre(index: 0).title).to eq ''
end
it "raises UnknownObjectException if the pre doesn't exist" do
expect { browser.pre(id: 'no_such_id').title }.to raise_error(Watir::Exception::UnknownObjectException)
expect { browser.pre(xpath: "//pre[@id='no_such_id']").title }.to raise_error(Watir::Exception::UnknownObjectException)
end
end
describe "#text" do
it "returns the text of the pre" do
expect(browser.pre(class: 'haskell').text).to eq 'main = putStrLn "Hello World"'
end
it "returns an empty string if the element doesn't contain any text" do
expect(browser.pre(index: 0).text).to eq ''
end
it "raises UnknownObjectException if the pre doesn't exist" do
expect { browser.pre(id: 'no_such_id').text }.to raise_error(Watir::Exception::UnknownObjectException)
expect { browser.pre(:xpath , "//pre[@id='no_such_id']").text }.to raise_error(Watir::Exception::UnknownObjectException)
end
end
describe "#respond_to?" do
it "returns true for all attribute methods" do
expect(browser.image(index: 0)).to respond_to(:class_name)
expect(browser.image(index: 0)).to respond_to(:id)
expect(browser.image(index: 0)).to respond_to(:title)
expect(browser.image(index: 0)).to respond_to(:text)
end
end
end
|
watir/watirspec
|
pre_spec.rb
|
Ruby
|
mit
| 4,436 |
/**
* Converts an RGB color value to HSL. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes r, g, and b are contained in the set [0, 255] and
* returns h, s, and l in the set [0, 1].
*
* @param Number r The red color value
* @param Number g The green color value
* @param Number b The blue color value
* @return Array The HSL representation
*/
function rgbToHsl(r, g, b) {
r /= 255, g /= 255, b /= 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, l = (max + min) / 2;
if (max == min) {
h = s = 0; // achromatic
} else {
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
//alert(h*360+","+ s*100+","+ l*100 );
return [ h*360, s*100, l*100 ];
}
/**
* Converts an HSL color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes h, s, and l are contained in the set [0, 1] (CHANGED, they get divided in function so that they are within 0,1)and
* returns r, g, and b in the set [0, 255].
*
* @param Number h The hue
* @param Number s The saturation
* @param Number l The lightness
* @return Array The RGB representation
*/
function hslToRgb(h, s, l) {
h=h/360,s=s/100,l=l/100;
var r, g, b;
if (s == 0) {
r = g = b = l; // achromatic
} else {
function hue2rgb(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1/6) return p + (q - p) * 6 * t;
if (t < 1/2) return q;
if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
return p;
}
var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
var p = 2 * l - q;
r = hue2rgb(p, q, h + 1/3);
g = hue2rgb(p, q, h);
b = hue2rgb(p, q, h - 1/3);
}
//alert(r * 255+","+ g * 255+","+ b * 255);
return [ r * 255, g * 255, b * 255 ];
}
/**
* Converts an RGB color value to HSV. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSV_color_space.
* Assumes r, g, and b are contained in the set [0, 255] and
* returns h, s, and v in the set [0, 1].
*
* @param Number r The red color value
* @param Number g The green color value
* @param Number b The blue color value
* @return Array The HSV representation
*/
function rgbToHsv(r, g, b) {
r /= 255, g /= 255, b /= 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, v = max;
var d = max - min;
s = max == 0 ? 0 : d / max;
if (max == min) {
h = 0; // achromatic
} else {
switch (max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return [ h*360, s*100, v*100 ];
}
/**
* Converts an HSV color value to RGB. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSV_color_space.
* Assumes h, s, and v are contained in the set [0, 1] and
* returns r, g, and b in the set [0, 255].
*
* @param Number h The hue
* @param Number s The saturation
* @param Number v The value
* @return Array The RGB representation
*/
function hsvToRgb(h, s, v) {
h=h/360,s=s/100,v=v/100;
var r, g, b;
var i = Math.floor(h * 6);
var f = h * 6 - i;
var p = v * (1 - s);
var q = v * (1 - f * s);
var t = v * (1 - (1 - f) * s);
switch (i % 6) {
case 0: r = v, g = t, b = p; break;
case 1: r = q, g = v, b = p; break;
case 2: r = p, g = v, b = t; break;
case 3: r = p, g = q, b = v; break;
case 4: r = t, g = p, b = v; break;
case 5: r = v, g = p, b = q; break;
}
return [ r * 255, g * 255, b * 255 ];
}
|
ericoporto/Pixel.Tools
|
color_conversion.js
|
JavaScript
|
mit
| 3,896 |
/**
* ELASTICSEARCH CONFIDENTIAL
* _____________________________
*
* [2014] Elasticsearch Incorporated All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of Elasticsearch Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to Elasticsearch Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from Elasticsearch Incorporated.
*/
// The ui had different columns in different order depending on the
// $scope.pane.view variable. This provides a lookup for the column headers
// labels are linked to view from public/directives/shard_allocation/lib/changeData.js
export default {
index: ['Nodes'], // "index detail" page shows nodes on which index shards are allocated
node: ['Indices'], // "node detail" page shows the indexes that have shards on this node
indexWithUnassigned: ['Unassigned', 'Nodes'] // NOTE: is this unused or is there even an indexWithUnassigned view?
};
|
ashnewport/elasticsearch
|
kibana-5.0.2-linux-x86_64/plugins/x-pack/plugins/monitoring/public/directives/shard_allocation/lib/labels.js
|
JavaScript
|
mit
| 1,250 |
/**
* OnFire
* Copyright (c) 2013 - 2015 Itzy Sabo
* Licensed under the MIT License: https://github.com/isabo/onfire/blob/master/LICENSE
*/
var onfire = {};
/**
* An analogue of a Firebase reference.
* @see https://www.firebase.com/docs/web/api/firebase/constructor.html
*
* @param {string|!Firebase} urlOrRef A Firebase URL or a Firebase reference instance.
* @constructor
* @final
*/
onfire.Ref = function(urlOrRef) {};
/**
* Firebase.authAnonymously() wrapped in a promise.
* @see https://www.firebase.com/docs/web/api/firebase/authanonymously.html
*
* @param {!Object=} opt_options
* @return
{
!Promise<!Firebase.AuthCallbackData,!Error>
|
!goog.Promise<!Firebase.AuthCallbackData,!Error>
} A promise which resolves to the authData, or is rejected with an error.
*/
onfire.Ref.prototype.authAnonymously = function(opt_options) {};
/**
* Firebase.authWithCustomToken() wrapped in a promise.
* @see https://www.firebase.com/docs/web/api/firebase/authwithcustomtoken.html
*
* @param {string} authToken
* @param {!Object=} opt_options
* @return
{
!Promise<!Firebase.AuthCallbackData,!Error>
|
!goog.Promise<!Firebase.AuthCallbackData,!Error>
} A promise which resolves to the authData, or is rejected with an error.
*/
onfire.Ref.prototype.authWithCustomToken = function(authToken, opt_options) {};
/**
* Firebase.authWithOAuthPopup() wrapped in a promise.
* @see https://www.firebase.com/docs/web/api/firebase/authwithoauthpopup.html
*
* @param {string} provider
* @param {!Object=} opt_options
* @return
{
!Promise<!Firebase.AuthCallbackData,!Error>
|
!goog.Promise<!Firebase.AuthCallbackData,!Error>
} A promise which resolves to the authData, or is rejected with an error.
*/
onfire.Ref.prototype.authWithOAuthPopup = function(provider, opt_options) {};
/**
* Firebase.authWithOAuthRedirect() wrapped in a promise.
* @see https://www.firebase.com/docs/web/api/firebase/authwithoauthredirect.html
*
* @param {string} provider
* @param {!Object=} opt_options
* @return {!Promise<null,!Error>|!goog.Promise<null,!Error>} A promise which is rejected with an
* error if the authentication fails.
*/
onfire.Ref.prototype.authWithOAuthRedirect = function(provider, opt_options) {};
/**
* Firebase.authWithOAuthToken() wrapped in a promise.
* @see https://www.firebase.com/docs/web/api/firebase/authwithoauthtoken.html
*
* @param {string} provider
* @param {string|!Object} credentials
* @param {!Object=} opt_options
* @return
{
!Promise<!Firebase.AuthCallbackData,!Error>
|
!goog.Promise<!Firebase.AuthCallbackData,!Error>
} A promise which resolves to the authData, or is rejected with an error.
*/
onfire.Ref.prototype.authWithOAuthToken = function(provider, credentials, opt_options) {};
/**
* Firebase.authWithPassword() wrapped in a promise.
* @see https://www.firebase.com/docs/web/api/firebase/authwithpassword.html
*
* @param {!Firebase.AuthPasswordCredentials} credentials
* @param {!Object=} opt_options
* @return
{
!Promise<!Firebase.AuthCallbackData,!Error>
|
!goog.Promise<!Firebase.AuthCallbackData,!Error>
} A promise which resolves to the authData, or is rejected with an error.
*/
onfire.Ref.prototype.authWithPassword = function(credentials, opt_options) {};
/**
* Firebase.changeEmail() wrapped in a promise.
* @see https://www.firebase.com/docs/web/api/firebase/changeemail.html
*
* @param {!{oldEmail:string, password:string, newEmail:string}} credentials
* @return {!Promise<null,!Error>|!goog.Promise<null,!Error>} A promise which resolves when the
* operation is complete, or is rejected with an error.
*/
onfire.Ref.prototype.changeEmail = function(credentials) {};
/**
* Firebase.changePassword() wrapped in a promise.
* @see https://www.firebase.com/docs/web/api/firebase/changepassword.html
*
* @param {!{email:string, oldPassword:string, newPassword:string}} credentials
* @return {!Promise<null,!Error>|!goog.Promise<null,!Error>} A promise which resolves when the
* operation is complete, or is rejected with an error.
*/
onfire.Ref.prototype.changePassword = function(credentials) {};
/**
* Firebase.createUser() wrapped in a promise.
* @see https://www.firebase.com/docs/web/api/firebase/createuser.html
*
* @param {!Firebase.AuthPasswordCredentials} credentials
* @return {!Promise<!{uid:string},!Error>|!goog.Promise<!{uid:string},!Error>} A promise which
* resolves to a userData object, or is rejected with an error.
*/
onfire.Ref.prototype.createUser = function (credentials) {};
/**
* Returns a reference that is relative to the current location.
* @see https://www.firebase.com/docs/web/api/firebase/child.html
*
* @param {string} childPath
* @return {!onfire.Ref} A reference that is relative to the current location.
* @nosideeffects
*/
onfire.Ref.prototype.child = function(childPath) {};
/**
* Generates a push ID. This takes the place of .push() when all we want is a unique ID, via a
* synchronous method instead of a promise, which is what .push() returns.
*
* @return {string} A unique ID.
*/
onfire.Ref.prototype.generateId = function() {};
/**
* A proxy for Firebase.getAuth().
* @see https://www.firebase.com/docs/web/api/firebase/getauth.html
*
* @return {Firebase.AuthCallbackData}
* @nosideeffects
*/
onfire.Ref.prototype.getAuth = function() {};
/**
* A proxy for Firebase.goOnline().
* @see https://www.firebase.com/docs/web/api/firebase/goonline.html
*/
onfire.Ref.prototype.goOnline = function() {};
/**
* A proxy for Firebase.goOffline().
* @see https://www.firebase.com/docs/web/api/firebase/gooffline.html
*/
onfire.Ref.prototype.goOffline = function() {};
/**
* Returns the key of the current location.
* @see https://www.firebase.com/docs/web/api/firebase/key.html
*
* @return {string} The key of the current location.
* @nosideeffects
*/
onfire.Ref.prototype.key = function() {};
/**
* Deregisters a previously registered callback.
* @see https://www.firebase.com/docs/web/api/query/off.html
*
* @param {string=} opt_eventType
* @param {!Firebase.EventCallback=} opt_callback If provided, this MUST be the *wrapped* callback
* returned by the .on() method.
* @param {!Object=} opt_context
*/
onfire.Ref.prototype.off = function(opt_eventType, opt_callback, opt_context) {};
/**
* A proxy for Firebase.offAuth().
* @see https://www.firebase.com/docs/web/api/firebase/offauth.html
*
* @param {!function(Firebase.AuthCallbackData)} onComplete
* @param {!Object=} opt_context
*/
onfire.Ref.prototype.offAuth = function(onComplete, opt_context) {};
/**
* Deregisters a previously registered .onValue() callback.
*
* @param {!function(Firebase.Value)} callback This MUST be the *wrapped* callback returned
* by .onValue().
* @param {!Object=} context
*/
onfire.Ref.prototype.offValue = function(callback, context) {};
/**
* Registers a callback for an event of a specified type at the current location. Make sure to keep
* the return value for use when turning this off -- see the off() method.
* @see https://www.firebase.com/docs/web/api/query/on.html
*
* @param {string} eventType
* @param {!Firebase.EventCallback} callback
* @param {function(!Error)=} cancelCallback
* @param {Object=} context
* @return {!function(!Firebase.DataSnapshot, ?string=)} A handler function that may be needed when
* deregistering the callback.
*/
onfire.Ref.prototype.on = function(eventType, callback, cancelCallback, context) {};
/**
* A proxy for Firebase.onAuth().
* @see https://www.firebase.com/docs/web/api/firebase/onauth.html
*
* @param {!function(Firebase.AuthCallbackData)} onComplete
* @param {!Object=} opt_context
*/
onfire.Ref.prototype.onAuth = function(onComplete, opt_context) {};
/**
* Waits for the first event of a specified type at the current location. A promisified analogue
* of Firebase's .once() method.
* @see https://www.firebase.com/docs/web/api/query/once.html
*
* @param {string} eventType
* @return {!Promise<!Firebase.DataSnapshot,!Error>|!goog.Promise<!Firebase.DataSnapshot,!Error>} A
* promise that resolves to a Firebase snapshot, or is rejected with an error.
*/
onfire.Ref.prototype.once = function(eventType) {};
/**
* Retrieves the value that is stored at the current location. This is shorthand for calling .once()
* for the 'value' event and then extracting the value of the returned snapshot.
*
* @return {!Promise<Firebase.Value,!Error>|!goog.Promise<Firebase.Value,!Error>} A promise that
* resolves to the value stored at the current location, or is rejected with an error.
*/
onfire.Ref.prototype.onceValue = function() {};
/**
* Registers a callback for value changes at the current location. This is shorthand for calling
* .on() for the 'value' event and then extracting the value of each returned snapshot. Make sure to
* keep the return value for when you want to turn this off. See the .offValue() method.
*
* @param {!function(Firebase.Value)} callback
* @param {!function(!Error)=} cancelCallback
* @param {!Object=} context
* @return {!function(!Firebase.DataSnapshot)}
*/
onfire.Ref.prototype.onValue = function(callback, cancelCallback, context) {};
/**
* Returns a reference to the parent of the current location.
* @see https://www.firebase.com/docs/web/api/firebase/parent.html
*
* @return {onfire.Ref} A reference to the parent of the current location.
* @nosideeffects
*/
onfire.Ref.prototype.parent = function() {};
/**
* Returns the path of this reference relative to the root, i.e. not including the firebaseio.com
* domain.
*
* @return {string} The path of this reference relative to the root.
* @nosideeffects
*/
onfire.Ref.prototype.path = function() {};
/**
* Pushes a value under the current location. A promisified analogue of Firebase's .push() method.
* @see https://www.firebase.com/docs/web/api/firebase/push.html
*
* @param {Firebase.Value=} opt_value
* @return {!Promise<!onfire.Ref,!Error>|!goog.Promise<!onfire.Ref,!Error>} A promise that resolves
* to the Ref of the newly pushed child.
*/
onfire.Ref.prototype.push = function(opt_value) {};
/**
* Returns an unwrapped Firebase reference to the current location.
*
* @return {!Firebase} An unwrapped Firebase reference to the current location.
* @nosideeffects
*/
onfire.Ref.prototype.ref = function() {};
/**
* Removes the data that is stored at the current location. A promisified analogue of Firebase's
* .remove() method.
* @see https://www.firebase.com/docs/web/api/firebase/remove.html
*
* @return {!Promise<null,!Error>|!goog.Promise<null,!Error>} A promise that resolves when the
* operation is complete, or is rejected with an error.
*/
onfire.Ref.prototype.remove = function() {};
/**
* Firebase.removeUser() wrapped in a promise.
* @see https://www.firebase.com/docs/web/api/firebase/removeuser.html
*
* @param {!Firebase.AuthPasswordCredentials} credentials
* @return {!Promise<null,!Error>|!goog.Promise<null,!Error>} A promise which resolves when the
* operation is complete, or is rejected with an error.
*/
onfire.Ref.prototype.removeUser = function(credentials) {};
/**
* Firebase.resetPassword() wrapped in a promise.
* @see https://www.firebase.com/docs/web/api/firebase/resetpassword.html
*
* @param {!{email:string}} credentials
* @return {!Promise<null,!Error>|!goog.Promise<null,!Error>} A promise which resolves when the
* operation is complete, or is rejected with an error.
*/
onfire.Ref.prototype.resetPassword = function(credentials) {};
/**
* Returns a reference that represents the root of the tree.
* @see https://www.firebase.com/docs/web/api/firebase/root.html
*
* @return {!onfire.Ref} A reference that represents the root of the tree.
* @nosideeffects
*/
onfire.Ref.prototype.root = function() {};
/**
* Stores a value at the current location. A promisified analogue of Firebase's .set() method.
* @see https://www.firebase.com/docs/web/api/firebase/set.html
*
* @param {Firebase.Value} value
* @return {!Promise<null,!Error>|!goog.Promise<null,!Error>} A promise that resolves when the
* operation is complete, or is rejected with an error.
*/
onfire.Ref.prototype.set = function(value) {};
/**
* Sets a the values stored at the current location, atomically. A promisified analogue of
* Firebase's .transaction() method.
* @see https://www.firebase.com/docs/web/api/firebase/transaction.html
*
* @param {Firebase.TransactionUpdateFunction} updateFn
* @return
{
!Promise<!{{isCommitted:boolean,snapshot:Firebase.DataSnapshot}},!Error>
|
!goog.Promise<!{{isCommitted:boolean,snapshot:Firebase.DataSnapshot}},!Error>
} A promise that resolves when the operation is complete, or is rejected with an error. The
value provided when the promise resolves is an object with two properties:
isCommitted: whether the operation actually committed a value to the database.
snapshot: a snapshot of the current data.
*/
onfire.Ref.prototype.transaction = function(updateFn) {};
/**
* A proxy for Firebase.unauth().
* @see https://www.firebase.com/docs/web/api/firebase/unauth.html
*/
onfire.Ref.prototype.unauth = function() {};
/**
* Updates multiple key/value pairs stored at the current location. A promisified analogue of
* Firebase's .update() method.
* @see https://www.firebase.com/docs/web/api/firebase/update.html
*
* @param {!Object<string,Firebase.Value>} values An object containing the key/value pairs.
* @return {!Promise<null,!Error>|goog.Promise<null,!Error>} A promise that resolves when the
* operation is complete, or is rejected with an error.
*/
onfire.Ref.prototype.update = function(values) {};
/**
* Generates a subclass of onfire.model.Model or onfire.model.Collection with a baked in schema.
*
* @param {!Object} schema A schema object.
* @return {!function(new:onfire.model.Model, !onfire.Ref)} A model constructor.
* @throws {Error}
*/
onfire.defineModel = function(schema) {};
onfire.model = {};
/**
* Base class to represent objects that live in Firebase.
*
* @param {!onfire.Ref} ref The reference of the current object.
* @constructor
*/
onfire.model.Model = function(ref) {};
/**
* Releases resources used by the model. Call this when you no longer need the instance.
*/
onfire.model.Model.prototype.dispose = function() {};
/**
* Determines whether the underlying data exists. We may have retrieved a non-existent object, or
* it may have subsequently been deleted.
*
* @return {boolean} Whether the underlying data actually exists.
* @throws {Error}
*/
onfire.model.Model.prototype.exists = function() {};
/**
* Synchronously retrieves the value associated with a key. If the value is not a primitive, a model
* instance will be returned, in which case .whenLoaded() should be called on the returned model in
* order to know when it is ready to use. If the key is already known to represent a model, it is
* better to obtain it via the asynchronous .fetch() method.
* If the key is specified in the schema, its value, or a model representing its value, will be
* returned. If the key represents a primitive but missing value, the return value will be null.
* If the key is not specified in the schema, but does have a value in the underlying data, that
* value will be returned. Otherwise, an exception will be thrown.
*
* @param {string} key
* @return {Firebase.Value|onfire.model.Model} A primitive value or a model instance.
* @throws {Error}
*/
onfire.model.Model.prototype.get = function(key) {};
/**
* Synchronously retrieves the primitive value associated with a key. If the value is an object, it
* is returned unwrapped, i.e. not as a model instance.
* If the key is specified in the schema, its value will be returned. If the key does not have a
* value the return value will be null.
* If the key is not specified in the schema, but does have a value in the underlying data, that
* value will be returned. Otherwise, an exception will be thrown.
*
* @param {string} key The key under which the value is stored.
* @return {Firebase.Value} The value or unwrapped object associated with the key.
* @throws {Error}
*/
onfire.model.Model.prototype.getBasicValue = function(key) {};
/**
* Synchronously retrieves the model instance that represents a non-primitive value that is
* associated with a key. Make sure to call .whenLoaded() on the returned model in order to know when
* it is ready to use. In many cases it may be more convenient to call the asynchronous .fetch()
* method instead.
* If the key is not specified in the schema, an exception will be thrown.
*
* @param {string} key
* @return {!onfire.model.Model}
* @throws {Error}
*/
onfire.model.Model.prototype.getModel = function(key) {};
/**
* Determines whether there are any unsaved changes on this model.
*
* @return {boolean} Whether there are any unsaved changes on this model.
*/
onfire.model.Model.prototype.hasChanges = function() {};
/**
* Returns the key of the model's reference.
*
* @return {string} The key of the model's reference
*/
onfire.model.Model.prototype.key = function() {};
/**
* Register the callback function that will be called whenever the model is updated. To deregister
* an existing callback, just pass null as the callback argument.
*
* @param {function()|null} callback
*/
onfire.model.Model.prototype.onValueChanged = function(callback) {};
/**
* Asynchronously commits the outstanding changes.
*
* @return {!Promise<!onfire.model.Model,!Error>|!goog.Promise<!onfire.model.Model,!Error>} A
* promise that resolves to this model instance when the operation completes successfully, or
* is rejected with an error.
* @throws {Error} if called when model is not yet loaded.
*/
onfire.model.Model.prototype.save = function() {};
/**
* Registers the desire to change the primitive value associated with a key. The value will be
* committed only when .save() is called. Returns a reference to the current model to allow
* chaining, e.g.,
* person.set('firstName', 'John').set('lastName', 'Smith').save()
* Throws an error if the key is not specified in the schema and does not already have a value in
* the underlying data.
*
* @param {string} key The name of a property.
* @param {Firebase.Value} value The primitive value to assign to the property.
* @return {!onfire.model.Model} This model instance, in order to make the method chainable.
* @throws {Error}
*/
onfire.model.Model.prototype.set = function(key, value) {};
/**
* Returns a promise that is resolved to this instance when the data has been loaded.
*
* @return {!Promise<!onfire.model.Model,!Error>|!goog.Promise<!onfire.model.Model,!Error>} A
* promise resolves to this instance when the data has been loaded.
*/
onfire.model.Model.prototype.whenLoaded = function() {};
/**
* Exposes the schema. This is only exposed on generated models, and is included here for
* documentation purposes only.
*
* @return {!Object}
*/
onfire.model.Model.getSchema = function() {};
/**
* Base class for collections that live in Firebase. If collection members are not primitives, they
* are lazily loaded -- only when requested.
*
* @param {!onfire.Ref} ref The reference of the current object.
* @param {!function(new:onfire.model.Model, !onfire.Ref, number=)=} opt_memberCtor The model
* constructor to use for instances of collection members. If the members are primitives,
* this should not be supplied.
* @constructor
* @extends {onfire.model.Model}
*/
onfire.model.Collection = function(ref, opt_memberCtor) {};
/**
* Determines whether the collection already has an entry for the provided key.
*
* @param {string} key
* @return {boolean}
* @throws {Error}
*/
onfire.model.Collection.prototype.containsKey = function(key) {};
/**
* Returns the number of values in the collection.
*
* @return {number} The number of values in the collection.
* @throws {Error}
*/
onfire.model.Collection.prototype.count = function() {};
/**
* Asynchronously creates a model instance and adds it as a member of the collection, with an
* automatically generated key.
*
* @param {!Object<string,Firebase.Value>=} opt_values An object containing the property/value pairs
* to initialize the new object with.
* @return {!Promise<!onfire.model.Model,!Error>|!goog.Promise<!onfire.model.Model,!Error>} A
* promise that resolves to a model instance, or is rejected with an error.
* @throws {Error}
*/
onfire.model.Collection.prototype.create = function(opt_values) {};
/**
* Asynchronously retrieves a model instance that represents a member of the collection. Throws an
* exception if the key does not exist.
*
* @param {string} key The key of the member.
* @return {!Promise<!onfire.model.Model,!Error>|!goog.Promise<!onfire.model.Model,!Error>} A
* promise that resolves to a model instance, or is rejected with an error.
* @throws {Error}
*/
onfire.model.Collection.prototype.fetch = function(key) {};
/**
* Asynchronously retrieves an existing item by its key, or creates it if it does not yet exist, and
* adds it to the collection.
*
* @param {string} key
* @param {!Object<string,Firebase.Value>=} values A set of property/value pairs to assign if
* created. If null, don't set any values. The object will come into existence only when a
* value is set and committed to the database.
* @return {!Promise<!onfire.model.Model,!Error>|!goog.Promise<!onfire.model.Model,!Error>} A
* promise that resolves to a model instance, or is rejected with an error.
* @throws {Error}
*/
onfire.model.Collection.prototype.fetchOrCreate = function(key, values) {};
/**
* Calls a callback for each member of the collection. Returns a promise that is resolved once all
* the callbacks have been invoked, and any promises returned by callbacks have themselves been
* resolved.
* The callback function should accept a primitive value or a model instance, according to the type
* of members in the collection. It does not need to return anything, but if it returns a promise,
* the main return value of this method (a promise) will depend on it.
*
* @param {
!function((!onfire.model.Model|Firebase.Value), string=):(!Promise|!goog.Promise|undefined)
} callback
* @return {(!Promise|!goog.Promise)} A promise that in resolved when all callbacks have completed.
* @throws {Error}
*/
onfire.model.Collection.prototype.forEach = function(callback) {};
/**
* Synchronously retrieves the value associated with a key. If the collection members are not
* primitive values, a model instance will be returned, in which case .whenLoaded() should be called
* on the returned model in order to know when it is ready to use. Consider using the asynchronous
* .fetch() method instead.
* Throws an exception if the key does not have a value in the underlying data.
*
* @override
* @param {string} key An key of an item in the collection.
* @return {Firebase.Value|onfire.model.Model} A primitive value or a model instance.
* @throws {Error}
*/
onfire.model.Collection.prototype.get = function(key) {};
/**
* Synchronously retrieves the primitive value associated with a key. If the value is an object, it
* is returned unwrapped, i.e. not as a model instance.
* Throws an exception if the key does not have a value in the underlying data.
*
* @param {string} key The key of the desired value.
* @return {Firebase.Value}
* @throws {Error}
*/
onfire.model.Collection.prototype.getBasicValue = function(key) {};
/**
* Synchronously retrieves the value associated with a key and wraps it in a model instance. Make
* sure to call .whenLoaded() on the returned model in order to know when it is ready to use.
* Consider using the asynchronous .fetch() method instead.
* Throws an exception if the key does not have a value in the underlying data.
*
* @param {string} key The key of the desired item.
* @return {!onfire.model.Model} A model instance.
* @throws {Error}
*/
onfire.model.Collection.prototype.getModel = function(key) {};
/**
* Returns an array of the keys of members in the collection.
*
* @return {!Array<string>} An array of the keys of members in the collection.
* @throws {Error}
*/
onfire.model.Collection.prototype.keys = function() {};
/**
* Register the callback function that will be called whenever a child is added. To deregister
* an existing callback, just pass null as the callback argument.
*
* @param {function(string)|null} callback A function that will be called with the key of the new
* child.
*/
onfire.model.Collection.prototype.onChildAdded = function(callback) {};
/**
* Register the callback function that will be called whenever a child is removed. To deregister
* an existing callback, just pass null as the callback argument.
*
* @param {function(string)|null} callback A function that will be called with the key of the
* removed child.
*/
onfire.model.Collection.prototype.onChildRemoved = function(callback) {};
/**
* Asynchronously removes the specified member of the collection. The promise is not rejected if the
* member is not present.
*
* @param {string} key The key of the member.
* @return {!Promise<null,!Error>|!goog.Promise<null,!Error>} A promise that resolves when the
* operation is complete, or is rejected with an error.
* @throws {Error}
*/
onfire.model.Collection.prototype.remove = function(key) {};
/**
* Registers the desire to change the primitive value associated with a key. The value will be
* committed only when .save() is called. Returns a reference to the current model to allow
* chaining, e.g.,
* person.set('firstName', 'John').set('lastName', 'Smith').save()
* Throws an error if the key is not specified in the schema and does not already have a value in
* the underlying data.
*
* @override return type.
* @param {string} key The name of a property.
* @param {Firebase.Value} value The primitive value to assign to the property.
* @return {!onfire.model.Collection}
* @throws {Error}
*/
onfire.model.Collection.prototype.set = function(key, value) {};
/**
* @override the return type.
* @return {!Promise<!onfire.model.Collection,!Error>|!goog.Promise<!onfire.model.Collection,!Error>}
*/
onfire.model.Collection.prototype.save;
/**
* @override the return type.
* @return {!Promise<!onfire.model.Collection,!Error>|!goog.Promise<!onfire.model.Collection,!Error>}
*/
onfire.model.Collection.prototype.whenLoaded;
/**
* Exposes the type of members in the collection. This is only exposed on generated models, and is
* dincluded here for ocumentation purposes only.
*
* @return {function(new:onfire.model.Model, !onfire.Ref)|undefined}
*/
onfire.model.Collection.getMemberCtor = function() {};
/**
* Error messages that are thrown.
*
* @enum {string}
*/
onfire.model.Error = {};
/**
* Thrown when the argument provided to the model constructor is not an onfire.Ref instance.
*
* @type {string}
*/
onfire.model.Error.INVALID_REF;
/**
* Thrown when a property or method is accessed before the model has finished loading, and the
* result would be incorrect or unavailable.
*
* @type {string}
*/
onfire.model.Error.NOT_LOADED;
/**
* Thrown when an attempt is made to get or set the value of a key that is not specified in the
* schema and does not exist in the underlying data.
*
* @type {string}
*/
onfire.model.Error.NO_SUCH_KEY;
/**
* Thrown when an attempt is made to obtain a model to represent a primitive value, e.g. calling
* .getModel('abc') when .abc has an integer value according to the schema or in reality.
* Another example is calling a collection's .create(), .fetch() or fetchOrCreate() methods
* when the collection is a colection of primitive values and not models.
*
* @type {string}
*/
onfire.model.Error.NOT_A_MODEL;
/**
* Thrown when an attempt is made to assign a value to a key that represents a model. Any
* changes need to be assigned via the model itself. In order to add a model instance to a
* collection use .create() or .fetchOrCreate() instead of .set().
*
* @type {string}
*/
onfire.model.Error.NOT_A_PRIMITIVE;
|
isabo/onfire
|
src/externs/outgoing/onfire-externs.js
|
JavaScript
|
mit
| 28,432 |
// ==========================================================================
// Project: SproutCore Metal
// Copyright: ©2011 Strobe Inc. and contributors.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
/*globals sc_assert */
require('sproutcore-metal/core');
require('sproutcore-metal/platform');
require('sproutcore-metal/utils');
require('sproutcore-metal/accessors');
var AFTER_OBSERVERS = ':change';
var BEFORE_OBSERVERS = ':before';
var guidFor = SC.guidFor;
var normalizePath = SC.normalizePath;
var suspended = 0;
var array_Slice = Array.prototype.slice;
var ObserverSet = function(iterateable) {
this.set = {};
if (iterateable) { this.array = []; }
}
ObserverSet.prototype.add = function(target, name) {
var set = this.set, guid = SC.guidFor(target), array;
if (!set[guid]) { set[guid] = {}; }
set[guid][name] = true;
if (array = this.array) {
array.push([target, name]);
}
};
ObserverSet.prototype.contains = function(target, name) {
var set = this.set, guid = SC.guidFor(target), nameSet = set[guid];
return nameSet && nameSet[name];
};
ObserverSet.prototype.empty = function() {
this.set = {};
this.array = [];
};
ObserverSet.prototype.forEach = function(fn) {
var q = this.array;
this.empty();
q.forEach(function(item) {
fn(item[0], item[1]);
});
};
var queue = new ObserverSet(true), beforeObserverSet = new ObserverSet();
function notifyObservers(obj, eventName, forceNotification) {
if (suspended && !forceNotification) {
// if suspended add to the queue to send event later - but only send
// event once.
if (!queue.contains(obj, eventName)) {
queue.add(obj, eventName);
}
} else {
SC.sendEvent(obj, eventName);
}
}
function flushObserverQueue() {
beforeObserverSet.empty();
if (!queue || queue.array.length===0) return ;
queue.forEach(function(target, event){ SC.sendEvent(target, event); });
}
SC.beginPropertyChanges = function() {
suspended++;
return this;
};
SC.endPropertyChanges = function() {
suspended--;
if (suspended<=0) flushObserverQueue();
};
function changeEvent(keyName) {
return keyName+AFTER_OBSERVERS;
}
function beforeEvent(keyName) {
return keyName+BEFORE_OBSERVERS;
}
function changeKey(eventName) {
return eventName.slice(0, -7);
}
function beforeKey(eventName) {
return eventName.slice(0, -7);
}
function xformForArgs(args) {
return function (target, method, params) {
var obj = params[0], keyName = changeKey(params[1]), val;
if (method.length>2) val = SC.getPath(obj, keyName);
args.unshift(obj, keyName, val);
method.apply(target, args);
}
}
var xformChange = xformForArgs([]);
function xformBefore(target, method, params) {
var obj = params[0], keyName = beforeKey(params[1]), val;
if (method.length>2) val = SC.getPath(obj, keyName);
method.call(target, obj, keyName, val);
}
SC.addObserver = function(obj, path, target, method) {
path = normalizePath(path);
var xform;
if (arguments.length > 4) {
var args = array_Slice.call(arguments, 4);
xform = xformForArgs(args);
} else {
xform = xformChange;
}
SC.addListener(obj, changeEvent(path), target, method, xform);
SC.watch(obj, path);
return this;
};
/** @private */
SC.observersFor = function(obj, path) {
return SC.listenersFor(obj, changeEvent(path));
};
SC.removeObserver = function(obj, path, target, method) {
path = normalizePath(path);
SC.unwatch(obj, path);
SC.removeListener(obj, changeEvent(path), target, method);
return this;
};
SC.addBeforeObserver = function(obj, path, target, method) {
path = normalizePath(path);
SC.addListener(obj, beforeEvent(path), target, method, xformBefore);
SC.watch(obj, path);
return this;
};
/** @private */
SC.beforeObserversFor = function(obj, path) {
return SC.listenersFor(obj, beforeEvent(path));
};
SC.removeBeforeObserver = function(obj, path, target, method) {
path = normalizePath(path);
SC.unwatch(obj, path);
SC.removeListener(obj, beforeEvent(path), target, method);
return this;
};
/** @private */
SC.notifyObservers = function(obj, keyName) {
notifyObservers(obj, changeEvent(keyName));
};
/** @private */
SC.notifyBeforeObservers = function(obj, keyName) {
var guid, set, forceNotification = false;
if (suspended) {
if (!beforeObserverSet.contains(obj, keyName)) {
beforeObserverSet.add(obj, keyName);
forceNotification = true;
} else {
return;
}
}
notifyObservers(obj, beforeEvent(keyName), forceNotification);
};
|
crofty/sensor_js_message_parsing
|
vendor/sproutcore-metal/lib/observer.js
|
JavaScript
|
mit
| 4,614 |
#
# converted from the gitrb project
#
# authors:
# Matthias Lederhofer <matled@gmx.net>
# Simon 'corecode' Schubert <corecode@fs.ei.tum.de>
#
# provides native ruby access to git objects and pack files
#
begin
require 'mmap'
rescue LoadError
module GitRuby
module Raw
module Internal
class Mmap
def initialize(file)
@file = file
@offset = nil
end
def unmap
@file = nil
end
def [](*idx)
idx = idx[0] if idx.length == 1
case idx
when Range
offset = idx.first
len = idx.last - idx.first + idx.exclude_end? ? 0 : 1
when Fixnum
offset = idx
len = nil
when Array
offset, len = idx
else
raise RuntimeError, "invalid index param: #{idx.class}"
end
if @offset != offset
@file.seek(offset)
end
@offset = offset + len ? len : 1
if not len
@file.read(1)[0]
else
@file.read(len)
end
end
end
end
end
end
end # rescue LoadError
|
schacon/git-ruby
|
lib/git-ruby/raw/internal/mmap.rb
|
Ruby
|
mit
| 1,176 |
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Bridges\ApplicationLatte;
use Latte;
use Latte\CompileException;
use Latte\MacroNode;
use Latte\PhpWriter;
use Nette;
use Nette\Utils\Strings;
/**
* Macros for Nette\Application\UI.
*
* - {link destination ...} control link
* - {plink destination ...} presenter link
* - {snippet ?} ... {/snippet ?} control snippet
* - n:nonce
*/
class UIMacros extends Latte\Macros\MacroSet
{
/** @var bool|string */
private $extends;
public static function install(Latte\Compiler $compiler)
{
$me = new static($compiler);
$me->addMacro('control', [$me, 'macroControl']);
$me->addMacro('href', null, null, function (MacroNode $node, PhpWriter $writer) use ($me) {
return ' ?> href="<?php ' . $me->macroLink($node, $writer) . ' ?>"<?php ';
});
$me->addMacro('plink', [$me, 'macroLink']);
$me->addMacro('link', [$me, 'macroLink']);
$me->addMacro('ifCurrent', [$me, 'macroIfCurrent'], '}'); // deprecated; use n:class="$presenter->linkCurrent ? ..."
$me->addMacro('extends', [$me, 'macroExtends']);
$me->addMacro('layout', [$me, 'macroExtends']);
$me->addMacro('nonce', null, null, 'echo $this->global->uiNonce ? " nonce=\"{$this->global->uiNonce}\"" : "";');
}
/**
* Initializes before template parsing.
* @return void
*/
public function initialize()
{
$this->extends = false;
}
/**
* Finishes template parsing.
* @return array(prolog, epilog)
*/
public function finalize()
{
return [$this->extends . 'Nette\Bridges\ApplicationLatte\UIRuntime::initialize($this, $this->parentName, $this->blocks);'];
}
/********************* macros ****************d*g**/
/**
* {control name[:method] [params]}
*/
public function macroControl(MacroNode $node, PhpWriter $writer)
{
$words = $node->tokenizer->fetchWords();
if (!$words) {
throw new CompileException('Missing control name in {control}');
}
$name = $writer->formatWord($words[0]);
$method = isset($words[1]) ? ucfirst($words[1]) : '';
$method = Strings::match($method, '#^\w*\z#') ? "render$method" : "{\"render$method\"}";
$tokens = $node->tokenizer;
$pos = $tokens->position;
$param = $writer->formatArray();
$tokens->position = $pos;
while ($tokens->nextToken()) {
if ($tokens->isCurrent('=>') && !$tokens->depth) {
$wrap = true;
break;
}
}
if (empty($wrap)) {
$param = substr($param, 1, -1); // removes array() or []
}
return "/* line $node->startLine */ "
. ($name[0] === '$' ? "if (is_object($name)) \$_tmp = $name; else " : '')
. '$_tmp = $this->global->uiControl->getComponent(' . $name . '); '
. 'if ($_tmp instanceof Nette\Application\UI\IRenderable) $_tmp->redrawControl(null, false); '
. ($node->modifiers === ''
? "\$_tmp->$method($param);"
: $writer->write("ob_start(function () {}); \$_tmp->$method($param); echo %modify(ob_get_clean());")
);
}
/**
* {link destination [,] [params]}
* {plink destination [,] [params]}
* n:href="destination [,] [params]"
*/
public function macroLink(MacroNode $node, PhpWriter $writer)
{
$node->modifiers = preg_replace('#\|safeurl\s*(?=\||\z)#i', '', $node->modifiers);
return $writer->using($node)
->write('echo %escape(%modify('
. ($node->name === 'plink' ? '$this->global->uiPresenter' : '$this->global->uiControl')
. '->link(%node.word, %node.array?)))'
);
}
/**
* {ifCurrent destination [,] [params]}
*/
public function macroIfCurrent(MacroNode $node, PhpWriter $writer)
{
if ($node->modifiers) {
throw new CompileException('Modifiers are not allowed in ' . $node->getNotation());
}
return $writer->write($node->args
? 'if ($this->global->uiPresenter->isLinkCurrent(%node.word, %node.array?)) {'
: 'if ($this->global->uiPresenter->getLastCreatedRequestFlag("current")) {'
);
}
/**
* {extends auto}
*/
public function macroExtends(MacroNode $node, PhpWriter $writer)
{
if ($node->modifiers || $node->parentNode || $node->args !== 'auto') {
return $this->extends = false;
}
$this->extends = $writer->write('$this->parentName = $this->global->uiPresenter->findLayoutTemplateFile();');
}
/** @deprecated */
public static function renderSnippets(Nette\Application\UI\Control $control, \stdClass $local, array $params)
{
trigger_error(__METHOD__ . '() is deprecated.', E_USER_DEPRECATED);
UIRuntime::renderSnippets($control, $local, $params);
}
}
|
Aprila/laboratory
|
vendor/nette/application/src/Bridges/ApplicationLatte/UIMacros.php
|
PHP
|
mit
| 4,523 |
// This is Generated Source.
import PathSegment from "../PathSegment";
import FaxCoverPage from "./FaxCoverPage";
import Greeting from "./Greeting";
import Language from "./Language";
import Country from "./Country";
import Location from "./Location";
import State from "./State";
import Timezone from "./Timezone";
import Device from "./Device";
import LicenseTypes from "./LicenseTypes";
export default class Dictionary extends PathSegment {
constructor(prv: PathSegment, id?: string, service?) {
super("dictionary", id, prv, service);
}
/**
*
*/
faxCoverPage(id?: string) {
return new FaxCoverPage(this, id);
}
/**
*
*/
greeting(id?: string) {
return new Greeting(this, id);
}
/**
* Internal identifier of a language
*/
language(id?: string) {
return new Language(this, id);
}
/**
* Internal identifier of a country
*/
country(id?: string) {
return new Country(this, id);
}
/**
*
*/
location(id?: string) {
return new Location(this, id);
}
/**
* Internal identifier of a state
*/
state(id?: string) {
return new State(this, id);
}
/**
* Internal identifier of a timezone
*/
timezone(id?: string) {
return new Timezone(this, id);
}
/**
*
*/
device(id?: string) {
return new Device(this, id);
}
/**
*
*/
licenseTypes(id?: string) {
return new LicenseTypes(this, id);
}
}
|
ringcentral/ringcentral-js-client
|
src/paths/Dictionary.ts
|
TypeScript
|
mit
| 1,573 |
'use strict';
System.register('flarum/akismet/components/AkismetSettingsModal', ['flarum/components/SettingsModal'], function (_export, _context) {
var SettingsModal, AkismetSettingsModal;
return {
setters: [function (_flarumComponentsSettingsModal) {
SettingsModal = _flarumComponentsSettingsModal.default;
}],
execute: function () {
AkismetSettingsModal = function (_SettingsModal) {
babelHelpers.inherits(AkismetSettingsModal, _SettingsModal);
function AkismetSettingsModal() {
babelHelpers.classCallCheck(this, AkismetSettingsModal);
return babelHelpers.possibleConstructorReturn(this, Object.getPrototypeOf(AkismetSettingsModal).apply(this, arguments));
}
babelHelpers.createClass(AkismetSettingsModal, [{
key: 'className',
value: function className() {
return 'AkismetSettingsModal Modal--small';
}
}, {
key: 'title',
value: function title() {
return app.translator.trans('flarum-akismet.admin.akismet_settings.title');
}
}, {
key: 'form',
value: function form() {
return [m(
'div',
{ className: 'Form-group' },
m(
'label',
null,
app.translator.trans('flarum-akismet.admin.akismet_settings.api_key_label')
),
m('input', { className: 'FormControl', bidi: this.setting('flarum-akismet.api_key') })
)];
}
}]);
return AkismetSettingsModal;
}(SettingsModal);
_export('default', AkismetSettingsModal);
}
};
});;
'use strict';
System.register('flarum/akismet/main', ['flarum/app', 'flarum/akismet/components/AkismetSettingsModal'], function (_export, _context) {
var app, AkismetSettingsModal;
return {
setters: [function (_flarumApp) {
app = _flarumApp.default;
}, function (_flarumAkismetComponentsAkismetSettingsModal) {
AkismetSettingsModal = _flarumAkismetComponentsAkismetSettingsModal.default;
}],
execute: function () {
app.initializers.add('flarum-akismet', function () {
app.extensionSettings['flarum-akismet'] = function () {
return app.modal.show(new AkismetSettingsModal());
};
});
}
};
});
|
namjoker/flarumfull
|
vendor/flarum/flarum-ext-akismet/js/admin/dist/extension.js
|
JavaScript
|
mit
| 2,370 |
package org.knowm.xchange.luno.dto.trade;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonProperty;
public class LunoOrders {
private final Order[] orders;
public LunoOrders(@JsonProperty(value = "orders", required = true) Order[] orders) {
this.orders = orders != null ? orders : new Order[0];
}
public Order[] getOrders() {
Order[] copy = new Order[orders.length];
System.arraycopy(orders, 0, copy, 0, orders.length);
return copy;
}
@Override
public String toString() {
return "LunoOrders [orders(" + orders.length + ")=" + Arrays.toString(orders) + "]";
}
public static class Order {
public final String orderId;
public final long creationTimestamp;
public final long expirationTimestamp;
public final long completedTimestamp;
public final OrderType type;
public final State state;
public final BigDecimal limitPrice;
public final BigDecimal limitVolume;
public final BigDecimal base;
public final BigDecimal counter;
public final BigDecimal feeBase;
public final BigDecimal feeCounter;
public final String pair;
public Order(
@JsonProperty(value = "order_id", required = true) String orderId
, @JsonProperty(value = "creation_timestamp", required = true) long creationTimestamp
, @JsonProperty(value = "expiration_timestamp", required = true) long expirationTimestamp
, @JsonProperty(value = "completed_timestamp", required = true) long completedTimestamp
, @JsonProperty(value = "type", required = false) OrderType type
, @JsonProperty(value = "state", required = false) State state
, @JsonProperty(value = "limit_price", required = true) BigDecimal limitPrice
, @JsonProperty(value = "limit_volume", required = true) BigDecimal limitVolume
, @JsonProperty(value = "base", required = true) BigDecimal base
, @JsonProperty(value = "counter", required = true) BigDecimal counter
, @JsonProperty(value = "fee_base", required = true) BigDecimal feeBase
, @JsonProperty(value = "fee_counter", required = true) BigDecimal feeCounter
, @JsonProperty(value = "pair", required = false) String pair
) {
this.orderId = orderId;
this.creationTimestamp = creationTimestamp;
this.expirationTimestamp = expirationTimestamp;
this.completedTimestamp = completedTimestamp;
this.type = type;
this.state = state;
this.limitPrice = limitPrice;
this.limitVolume = limitVolume;
this.base = base;
this.counter = counter;
this.feeBase = feeBase;
this.feeCounter = feeCounter;
this.pair = pair;
}
public Date getCreationTimestamp() {
return new Date(creationTimestamp);
}
public Date getExpirationTimestamp() {
return expirationTimestamp == 0 ? null : new Date(expirationTimestamp);
}
public Date getCompletedTimestamp() {
return completedTimestamp == 0 ? null : new Date(completedTimestamp);
}
@Override
public String toString() {
return "Order [orderId=" + orderId + ", type=" + type + ", state=" + state + ", limitPrice=" + limitPrice
+ ", limitVolume=" + limitVolume + ", base=" + base + ", counter=" + counter + ", feeBase=" + feeBase
+ ", feeCounter=" + feeCounter + ", pair=" + pair + ", getCreationTimestamp()=" + getCreationTimestamp()
+ ", getExpirationTimestamp()=" + getExpirationTimestamp() + ", getCompletedTimestamp()="
+ getCompletedTimestamp() + "]";
}
}
}
|
gaborkolozsy/XChange
|
xchange-luno/src/main/java/org/knowm/xchange/luno/dto/trade/LunoOrders.java
|
Java
|
mit
| 3,625 |
require 'minitest/autorun'
require 'theusual'
TheUsual::load :numeric
class NumericTest < Minitest::Test
def test_delimiter
# Integers
assert_equal(
'1,000',
1_000.with_delimiter
)
assert_equal(
'1,000,000',
1_000_000.with_delimiter
)
assert_equal(
'1_000',
1_000.with_delimiter('_')
)
# Floats
assert_equal(
'1,000.0',
1_000.0.with_delimiter
)
assert_equal(
'1,000.123',
1_000.123.with_delimiter
)
end
end
|
dpep/theusualrb
|
test/test_numeric.rb
|
Ruby
|
mit
| 527 |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Threading;
using osu.Game.Graphics;
using osu.Game.Tournament.Components;
using osu.Game.Tournament.Screens;
using osu.Game.Tournament.Screens.Drawings;
using osu.Game.Tournament.Screens.Editors;
using osu.Game.Tournament.Screens.Gameplay;
using osu.Game.Tournament.Screens.Ladder;
using osu.Game.Tournament.Screens.MapPool;
using osu.Game.Tournament.Screens.Schedule;
using osu.Game.Tournament.Screens.Setup;
using osu.Game.Tournament.Screens.Showcase;
using osu.Game.Tournament.Screens.TeamIntro;
using osu.Game.Tournament.Screens.TeamWin;
using osuTK;
using osuTK.Graphics;
namespace osu.Game.Tournament
{
[Cached]
public class TournamentSceneManager : CompositeDrawable
{
private Container screens;
private TourneyVideo video;
public const float CONTROL_AREA_WIDTH = 160;
public const float STREAM_AREA_WIDTH = 1366;
public const double REQUIRED_WIDTH = CONTROL_AREA_WIDTH * 2 + STREAM_AREA_WIDTH;
[Cached]
private TournamentMatchChatDisplay chat = new TournamentMatchChatDisplay();
private Container chatContainer;
private FillFlowContainer buttons;
public TournamentSceneManager()
{
RelativeSizeAxes = Axes.Both;
}
[BackgroundDependencyLoader]
private void load()
{
InternalChildren = new Drawable[]
{
new Container
{
RelativeSizeAxes = Axes.Y,
X = CONTROL_AREA_WIDTH,
FillMode = FillMode.Fit,
FillAspectRatio = 16 / 9f,
Anchor = Anchor.TopLeft,
Origin = Anchor.TopLeft,
Width = STREAM_AREA_WIDTH,
//Masking = true,
Children = new Drawable[]
{
video = new TourneyVideo("main", true)
{
Loop = true,
RelativeSizeAxes = Axes.Both,
},
screens = new Container
{
RelativeSizeAxes = Axes.Both,
Children = new Drawable[]
{
new SetupScreen(),
new ScheduleScreen(),
new LadderScreen(),
new LadderEditorScreen(),
new TeamEditorScreen(),
new RoundEditorScreen(),
new ShowcaseScreen(),
new MapPoolScreen(),
new TeamIntroScreen(),
new SeedingScreen(),
new DrawingsScreen(),
new GameplayScreen(),
new TeamWinScreen()
}
},
chatContainer = new Container
{
RelativeSizeAxes = Axes.Both,
Child = chat
},
}
},
new Container
{
RelativeSizeAxes = Axes.Y,
Width = CONTROL_AREA_WIDTH,
Children = new Drawable[]
{
new Box
{
Colour = Color4.Black,
RelativeSizeAxes = Axes.Both,
},
buttons = new FillFlowContainer
{
RelativeSizeAxes = Axes.Both,
Direction = FillDirection.Vertical,
Spacing = new Vector2(5),
Padding = new MarginPadding(5),
Children = new Drawable[]
{
new ScreenButton(typeof(SetupScreen)) { Text = "Setup", RequestSelection = SetScreen },
new Separator(),
new ScreenButton(typeof(TeamEditorScreen)) { Text = "Team Editor", RequestSelection = SetScreen },
new ScreenButton(typeof(RoundEditorScreen)) { Text = "Rounds Editor", RequestSelection = SetScreen },
new ScreenButton(typeof(LadderEditorScreen)) { Text = "Bracket Editor", RequestSelection = SetScreen },
new Separator(),
new ScreenButton(typeof(ScheduleScreen)) { Text = "Schedule", RequestSelection = SetScreen },
new ScreenButton(typeof(LadderScreen)) { Text = "Bracket", RequestSelection = SetScreen },
new Separator(),
new ScreenButton(typeof(TeamIntroScreen)) { Text = "Team Intro", RequestSelection = SetScreen },
new ScreenButton(typeof(SeedingScreen)) { Text = "Seeding", RequestSelection = SetScreen },
new Separator(),
new ScreenButton(typeof(MapPoolScreen)) { Text = "Map Pool", RequestSelection = SetScreen },
new ScreenButton(typeof(GameplayScreen)) { Text = "Gameplay", RequestSelection = SetScreen },
new Separator(),
new ScreenButton(typeof(TeamWinScreen)) { Text = "Win", RequestSelection = SetScreen },
new Separator(),
new ScreenButton(typeof(DrawingsScreen)) { Text = "Drawings", RequestSelection = SetScreen },
new ScreenButton(typeof(ShowcaseScreen)) { Text = "Showcase", RequestSelection = SetScreen },
}
},
},
},
};
foreach (var drawable in screens)
drawable.Hide();
SetScreen(typeof(SetupScreen));
}
private float depth;
private Drawable currentScreen;
private ScheduledDelegate scheduledHide;
private Drawable temporaryScreen;
public void SetScreen(Drawable screen)
{
currentScreen?.Hide();
currentScreen = null;
screens.Add(temporaryScreen = screen);
}
public void SetScreen(Type screenType)
{
temporaryScreen?.Expire();
var target = screens.FirstOrDefault(s => s.GetType() == screenType);
if (target == null || currentScreen == target) return;
if (scheduledHide?.Completed == false)
{
scheduledHide.RunTask();
scheduledHide.Cancel(); // see https://github.com/ppy/osu-framework/issues/2967
scheduledHide = null;
}
var lastScreen = currentScreen;
currentScreen = target;
if (currentScreen is IProvideVideo)
{
video.FadeOut(200);
// delay the hide to avoid a double-fade transition.
scheduledHide = Scheduler.AddDelayed(() => lastScreen?.Hide(), TournamentScreen.FADE_DELAY);
}
else
{
lastScreen?.Hide();
video.Show();
}
screens.ChangeChildDepth(currentScreen, depth--);
currentScreen.Show();
switch (currentScreen)
{
case MapPoolScreen _:
chatContainer.FadeIn(TournamentScreen.FADE_DELAY);
chatContainer.ResizeWidthTo(1, 500, Easing.OutQuint);
break;
case GameplayScreen _:
chatContainer.FadeIn(TournamentScreen.FADE_DELAY);
chatContainer.ResizeWidthTo(0.5f, 500, Easing.OutQuint);
break;
default:
chatContainer.FadeOut(TournamentScreen.FADE_DELAY);
break;
}
foreach (var s in buttons.OfType<ScreenButton>())
s.IsSelected = screenType == s.Type;
}
private class Separator : CompositeDrawable
{
public Separator()
{
RelativeSizeAxes = Axes.X;
Height = 20;
}
}
private class ScreenButton : TourneyButton
{
public readonly Type Type;
public ScreenButton(Type type)
{
Type = type;
BackgroundColour = OsuColour.Gray(0.2f);
Action = () => RequestSelection?.Invoke(type);
RelativeSizeAxes = Axes.X;
}
private bool isSelected;
public Action<Type> RequestSelection;
public bool IsSelected
{
get => isSelected;
set
{
if (value == isSelected)
return;
isSelected = value;
BackgroundColour = isSelected ? Color4.SkyBlue : OsuColour.Gray(0.2f);
SpriteText.Colour = isSelected ? Color4.Black : Color4.White;
}
}
}
}
}
|
peppy/osu
|
osu.Game.Tournament/TournamentSceneManager.cs
|
C#
|
mit
| 9,933 |
using Microsoft.ServiceFabric.Services.Runtime;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace WebFrontEnd
{
internal static class Program
{
/// <summary>
/// This is the entry point of the service host process.
/// </summary>
private static void Main()
{
try
{
// The ServiceManifest.XML file defines one or more service type names.
// Registering a service maps a service type name to a .NET type.
// When Service Fabric creates an instance of this service type,
// an instance of the class is created in this host process.
ServiceRuntime.RegisterServiceAsync("WebFrontEndType",
context => new WebFrontEnd(context)).GetAwaiter().GetResult();
ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(WebFrontEnd).Name);
// Prevents this host process from terminating so services keeps running.
Thread.Sleep(Timeout.Infinite);
}
catch (Exception e)
{
ServiceEventSource.Current.ServiceHostInitializationFailed(e.ToString());
throw;
}
}
}
}
|
brentstineman/PersonalStuff
|
Presentations/Service Fabric/RealWorldDemo/WebFrontEnd/Program.cs
|
C#
|
mit
| 1,348 |
module.exports = function createItemTweet (url, user, callback) {
var fs = require("fs");
var https = require('https');
var models = require('../../models');
var itemTypes = require('../../models/item/itemTypes.json');
var tweetUrl = url;
var options = {
host: 'publish.twitter.com',
path: '/oembed?format=json&url='+ encodeURI(tweetUrl)
};
var twCallback = function(response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
var response = JSON.parse(str);
var itemTweet = new models.ItemTweet();
itemTweet.url = response.url;
itemTweet.html = response.html;
itemTweet.author_name = response.author_name;
itemTweet.author_url = response.author_url;
itemTweet.width = response.width;
itemTweet.height = response.height;
itemTweet.type = response.type;
itemTweet.provider_name = response.provider_name;
itemTweet.version = response.version;
itemTweet._user = user._id;
itemTweet.save(function(err){
if(err)callback(err)
callback(null, itemTypes.TWEET, itemTweet)
})
});
response.on('error', function () {
callback(JSON.parse(str));
});
};
https.request(options, twCallback).end();
}
|
OlivierCoue/invow
|
server/helpers/item-content/createItemTweet.js
|
JavaScript
|
mit
| 1,490 |
import * as React from 'react'
import {
AutocompletingTextArea,
AutocompletingInput,
IAutocompletionProvider,
} from '../autocompletion'
import { CommitIdentity } from '../../models/commit-identity'
import { ICommitMessage } from '../../lib/app-state'
import { Dispatcher } from '../../lib/dispatcher'
import { IGitHubUser } from '../../lib/databases/github-user-database'
import { Repository } from '../../models/repository'
import { Button } from '../lib/button'
import { Avatar } from '../lib/avatar'
import { Loading } from '../lib/loading'
import { structuralEquals } from '../../lib/equality'
interface ICommitMessageProps {
readonly onCreateCommit: (message: ICommitMessage) => Promise<boolean>
readonly branch: string | null
readonly commitAuthor: CommitIdentity | null
readonly gitHubUser: IGitHubUser | null
readonly anyFilesSelected: boolean
readonly commitMessage: ICommitMessage | null
readonly contextualCommitMessage: ICommitMessage | null
readonly repository: Repository
readonly dispatcher: Dispatcher
readonly autocompletionProviders: ReadonlyArray<IAutocompletionProvider<any>>
readonly isCommitting: boolean
}
interface ICommitMessageState {
readonly summary: string
readonly description: string | null
/** The last contextual commit message we've received. */
readonly lastContextualCommitMessage: ICommitMessage | null
}
export class CommitMessage extends React.Component<
ICommitMessageProps,
ICommitMessageState
> {
public constructor(props: ICommitMessageProps) {
super(props)
this.state = {
summary: '',
description: '',
lastContextualCommitMessage: null,
}
}
public componentWillMount() {
this.receiveProps(this.props, true)
}
public componentWillUnmount() {
// We're unmounting, likely due to the user switching to the history tab.
// Let's persist our commit message in the dispatcher.
this.props.dispatcher.setCommitMessage(this.props.repository, this.state)
}
public componentWillReceiveProps(nextProps: ICommitMessageProps) {
this.receiveProps(nextProps, false)
}
private receiveProps(nextProps: ICommitMessageProps, initializing: boolean) {
// If we're switching away from one repository to another we'll persist
// our commit message in the dispatcher.
if (nextProps.repository.id !== this.props.repository.id) {
this.props.dispatcher.setCommitMessage(this.props.repository, this.state)
}
// This is rather gnarly. We want to persist the commit message (summary,
// and description) in the dispatcher on a per-repository level (git-store).
//
// Our dispatcher is asynchronous and only emits and update on animation
// frames. This is a great thing for performance but it gets real messy
// when you throw text boxes into the mix. If we went for a traditional
// approach of persisting the textbox values in the dispatcher and updating
// the virtual dom when we get new props there's an interim state which
// means that the browser can't keep track of the cursor for us, see:
//
// http://stackoverflow.com/a/28922465
//
// So in order to work around that we keep the text values in the component
// state. Whenever they get updated we submit the update to the dispatcher
// but we disregard the message that flows to us on the subsequent animation
// frame unless we have switched repositories.
//
// Then there's the case when we're being mounted (think switching between
// history and changes tabs. In that case we have to rely on what's in the
// dispatcher since we don't have any state of our own.
const nextContextualCommitMessage = nextProps.contextualCommitMessage
const lastContextualCommitMessage = this.state.lastContextualCommitMessage
// If the contextual commit message changed, we'll use it as our commit
// message.
if (
nextContextualCommitMessage &&
(!lastContextualCommitMessage ||
!structuralEquals(
nextContextualCommitMessage,
lastContextualCommitMessage
))
) {
this.setState({
summary: nextContextualCommitMessage.summary,
description: nextContextualCommitMessage.description,
lastContextualCommitMessage: nextContextualCommitMessage,
})
} else if (
initializing ||
this.props.repository.id !== nextProps.repository.id
) {
// We're either initializing (ie being mounted) or someone has switched
// repositories. If we receive a message we'll take it
if (nextProps.commitMessage) {
// Don't update dispatcher here, we're receiving it, could cause never-
// ending loop.
this.setState({
summary: nextProps.commitMessage.summary,
description: nextProps.commitMessage.description,
lastContextualCommitMessage: nextContextualCommitMessage,
})
} else {
// No message, assume clean slate
this.setState({
summary: '',
description: null,
lastContextualCommitMessage: nextContextualCommitMessage,
})
}
} else {
this.setState({
lastContextualCommitMessage: nextContextualCommitMessage,
})
}
}
private clearCommitMessage() {
this.setState({ summary: '', description: null })
}
private onSummaryChanged = (summary: string) => {
this.setState({ summary })
}
private onDescriptionChanged = (description: string) => {
this.setState({ description })
}
private onSubmit = () => {
this.createCommit()
}
private async createCommit() {
if (!this.canCommit) {
return
}
const success = await this.props.onCreateCommit({
// We know that summary is non-null thanks to canCommit
summary: this.state.summary!,
description: this.state.description,
})
if (success) {
this.clearCommitMessage()
}
}
private canCommit(): boolean {
return (
this.props.anyFilesSelected &&
this.state.summary !== null &&
this.state.summary.length > 0
)
}
private onKeyDown = (event: React.KeyboardEvent<Element>) => {
const isShortcutKey = __DARWIN__ ? event.metaKey : event.ctrlKey
if (isShortcutKey && event.key === 'Enter' && this.canCommit()) {
this.createCommit()
event.preventDefault()
}
}
private renderAvatar() {
const commitAuthor = this.props.commitAuthor
const avatarTitle = commitAuthor
? `Committing as ${commitAuthor.name} <${commitAuthor.email}>`
: undefined
let avatarUser = undefined
if (commitAuthor && this.props.gitHubUser) {
avatarUser = {
email: commitAuthor.email,
name: commitAuthor.name,
avatarURL: this.props.gitHubUser.avatarURL,
}
}
return <Avatar user={avatarUser} title={avatarTitle} />
}
public render() {
const branchName = this.props.branch ? this.props.branch : 'master'
const buttonEnabled = this.canCommit() && !this.props.isCommitting
const loading = this.props.isCommitting ? <Loading /> : undefined
return (
<div id="commit-message" role="group" aria-label="Create commit">
<div className="summary">
{this.renderAvatar()}
<AutocompletingInput
className="summary-field"
placeholder="Summary"
value={this.state.summary}
onValueChanged={this.onSummaryChanged}
onKeyDown={this.onKeyDown}
autocompletionProviders={this.props.autocompletionProviders}
/>
</div>
<AutocompletingTextArea
className="description-field"
placeholder="Description"
value={this.state.description || ''}
onValueChanged={this.onDescriptionChanged}
onKeyDown={this.onKeyDown}
autocompletionProviders={this.props.autocompletionProviders}
/>
<Button
type="submit"
className="commit-button"
onClick={this.onSubmit}
disabled={!buttonEnabled}
>
{loading}
<span title={`Commit to ${branchName}`}>
{loading ? 'Committing' : 'Commit'} to <strong>{branchName}</strong>
</span>
</Button>
</div>
)
}
}
|
hjobrien/desktop
|
app/src/ui/changes/commit-message.tsx
|
TypeScript
|
mit
| 8,310 |
/**
* Context Object
*
* @author Zongmin Lei<leizongmin@gmail.com>
*/
var utils = require('./utils');
var parser = require('./parser');
var filters = require('./filters');
var vm = require('./vm');
var OPCODE = require('./opcode');
var debug = utils.debug('Context');
var merge = utils.merge;
/**
* Context
*
* @param {Object} options
* - {Object} filters
* - {Object} asyncFilters
* - {Object} locals
* - {Object} syncLocals
* - {Object} asyncLocals
* - {Object} blocks
* - {Boolean} isLayout default:false
* - {Integer} timeout unit:ms, default:120000
* - {Object} parent
*/
var Context = module.exports = exports = function (options) {
options = options || {};
this._locals = {};
this._syncLocals = {};
this._asyncLocals = {};
this._asyncLocals2 = [];
this._filters = merge(filters, options.filters);
this._asyncFilters = {};
this._cycles = {};
this._buffer = '';
this._forloops = [];
this._isInForloop = false;
this._tablerowloops = [];
this._isInTablerowloop = false;
this._includeFileHandler = null;
this._position = {line: 0, column: 0};
this._astCache = {};
this._filenameStack = [];
this._filterCache = {};
this._blocks = {};
this._isLayout = !!options.isLayout;
// default configuration
options = merge({
timeout: 120000
}, options);
this.options = options;
// parent
this._parent = options.parent || null;
// initialize the configuration
var me = this;
var set = function (name) {
if (options[name] && typeof(options[name]) === 'object') {
Object.keys(options[name]).forEach(function (i) {
me['_' + name][i] = options[name][i];
});
}
};
set('locals');
set('syncLocals');
set('asyncLocals');
set('asyncLocals2');
set('filters');
set('blocks');
if (options.asyncFilters && typeof options.asyncFilters === 'object') {
Object.keys(options.asyncFilters).forEach(function (i) {
me.setAsyncFilter(i, options.asyncFilters[i]);
});
}
};
/**
* Copy the configuration from other context object
*
* @param {Object} from
* @return {Object}
*/
Context.prototype.from = function (from) {
var me = this;
var set = function (name) {
if (from[name] && typeof(from[name]) === 'object') {
for (var i in from[name]) {
if (i in me[name]) continue;
me[name][i] = from[name][i];
}
} else if (typeof(from[name] === 'function')) {
if (!me[name]) {
me[name] = from[name];
}
}
}
set('_locals');
set('_syncLocals');
set('_asyncLocals');
set('_asyncLocals2');
set('_filters');
set('_asyncFilters');
set('options');
set('_onErrorHandler');
set('_includeFileHandler');
set('_filterCache');
set('_blocks');
if (Array.isArray(from._filenameStack)) {
me._filenameStack = from._filenameStack.slice();
}
for (var i in from) {
if (i in me) continue;
me[i] = from[i];
}
me._isInForloop = from._isInForloop;
me._forloops = from._forloops.slice();
me._isInTablerowloop = from._isInTablerowloop;
me._tablerowloops = from._tablerowloops;
me._isLayout = from._isLayout;
return this;
};
/* constants */
Context.prototype.STATIC_LOCALS = 0; // normal locals
Context.prototype.SYNC_LOCALS = 1; // get value from a sync function
Context.prototype.ASYNC_LOCALS = 2; // get value from a async function
Context.prototype.SYNC_FILTER = 0; // normal filter
Context.prototype.ASYNC_FILTER = 1; // async filter
/**
* Set Timeout
*
* @param {Integer} ms
*/
Context.prototype.setTimeout = function (ms) {
ms = parseInt(ms, 10);
if (ms > 0) this.options.timeout = ms;
};
/**
* Run AST
*
* @param {Array} astList
* @param {Function} callback
*/
Context.prototype.run = function (astList, callback) {
return vm.run(astList, this, callback);
};
/**
* Register normal locals
*
* @param {String} name
* @param {Function} val
*/
Context.prototype.setLocals = function (name, val) {
this._locals[name] = val;
if (this._parent) {
this._parent.setLocals(name, val);
}
};
/**
* Register sync locals
*
* @param {String} name
* @param {Function} val
*/
Context.prototype.setSyncLocals = function (name, fn) {
this._syncLocals[name] = fn;
};
/**
* Register async locals
*
* @param {String} name
* @param {Function} fn
*/
Context.prototype.setAsyncLocals = function (name, fn) {
if (name instanceof RegExp) {
var name2 = name.toString();
// remove the same name
for (var i = 0, len = this._asyncLocals2; i < len; i++) {
var item = this._asyncLocals2[i];
if (item[0].toString() === name2) {
this._asyncLocals2.splice(i, 1);
break;
}
}
this._asyncLocals2.push([name, fn]);
} else {
this._asyncLocals[name] = fn;
}
};
/**
* Register normal filter
*
* @param {String} name
* @param {Function} fn
*/
Context.prototype.setFilter = function (name, fn) {
this._filters[name.trim()] = fn;
};
/**
* Register async filter
*
* @param {String} name
* @param {Function} fn
*/
Context.prototype.setAsyncFilter = function (name, fn) {
if (fn.enableCache) fn = utils.wrapFilterCache(name, fn);
this._asyncFilters[name.trim()] = fn;
};
/**
* Set layout file
*
* @param {String} filename
*/
Context.prototype.setLayout = function (filename) {
this._layout = filename;
};
/**
* Set block
*
* @param {String} name
* @param {String} buf
*/
Context.prototype.setBlock = function (name, buf) {
this._blocks[name] = buf;
if (this._parent) {
this._parent.setBlock(name, buf);
}
};
/**
* Set block if empty
*
* @param {String} name
* @param {String} buf
*/
Context.prototype.setBlockIfEmpty = function (name, buf) {
if (!(name in this._blocks)) {
this._blocks[name] = buf;
}
};
/**
* Get block
*
* @param {String} name
* @return {String}
*/
Context.prototype.getBlock = function (name) {
return this._blocks[name] || null;
};
/**
* Get locals
*
* @param {String} name
* @return {Array} [type, value, isAllowCache] return null if the locals not found
*/
Context.prototype.getLocals = function (name) {
if (name in this._locals) return [this.STATIC_LOCALS, this._locals[name]];
if (name in this._syncLocals) return [this.SYNC_LOCALS, this._syncLocals[name], true];
if (name in this._asyncLocals) return [this.ASYNC_LOCALS, this._asyncLocals[name], true];
for (var i = 0, len = this._asyncLocals2.length; i < len; i++) {
var item = this._asyncLocals2[i];
if (item[0].test(name)) {
return [this.ASYNC_LOCALS, item[1], true];
}
}
return null;
};
/**
* Fetch Single Locals
*
* @param {String} name
* @param {Function} callback
*/
Context.prototype.fetchSingleLocals = function (name, callback) {
var me = this;
var info = me.getLocals(name);
if (!info) return callback(null, info);
switch (info[0]) {
case me.STATIC_LOCALS:
callback(null, info[1]);
break;
case me.SYNC_LOCALS:
var v = info[1](name, me);
if (info[2]) me.setLocals(name, v);
callback(null, v);
break;
case me.ASYNC_LOCALS:
info[1](name, function (err, v) {
if (err) return callback(err);
if (info[2]) me.setLocals(name, v);
callback(null, v);
}, me);
break;
default:
callback(me.throwLocalsUndefinedError(name));
}
};
/**
* Fetch locals
*
* @param {Array|String} list
* @param {Function} callback
*/
Context.prototype.fetchLocals = function (list, callback) {
var me = this;
if (Array.isArray(list)) {
var values = [];
utils.asyncEach(list, function (name, i, done) {
me.fetchSingleLocals(name, function (err, val) {
if (err) {
values[i] = err;
} else {
values[i] = val;
}
done();
});
}, callback, null, values);
} else {
me.fetchSingleLocals(list, callback);
}
};
/**
* Get filter
*
* @param {String} name
* @return {Array} [type, function] return null if the filter not found
*/
Context.prototype.getFilter = function (name) {
name = name.trim();
if (name in this._filters) return [this.SYNC_FILTER, this._filters[name]];
if (name in this._asyncFilters) return [this.ASYNC_FILTER, this._asyncFilters[name]];
return null;
};
/**
* Call filter
*
* @param {String} method
* @param {Array} args
* @param {Function} callback
*/
Context.prototype.callFilter = function (method, args, callback) {
if (arguments.length < 3) {
callback = args;
args = [];
}
var info = this.getFilter(method);
if (!info) return callback(this.throwFilterUndefinedError(method));
if (info[0] === this.ASYNC_FILTER) {
args.push(callback);
args.push(this);
info[1].apply(null, args);
} else {
args.push(this);
callback(null, info[1].apply(null, args));
}
};
/**
* Print HTML
*
* @param {Object} str
*/
Context.prototype.print = function (str) {
this._buffer += (str === null || typeof(str) === 'undefined') ? '' : str;
};
/**
* Set buffer
*
* @param {String} buf
*/
Context.prototype.setBuffer = function (buf) {
this._buffer = buf;
};
/**
* Get buffer
*
* @return {String}
*/
Context.prototype.getBuffer = function () {
return this._buffer;
};
/**
* Clear buffer
*
* @return {String}
*/
Context.prototype.clearBuffer = function () {
var buf = this.getBuffer();
this.setBuffer('');
return buf;
};
/**
* Set cycle
*
* @param {String} name
* @param {Array} list
*/
Context.prototype.setCycle = function (name, list) {
this._cycles[name] = {index: 0, length: list.length, list: list};
};
/**
* Get the index of the cycle
*
* @param {String} name
* @return {Integer}
*/
Context.prototype.getCycleIndex = function (name) {
var cycle = this._cycles[name];
if (cycle) {
cycle.index++;
if (cycle.index >= cycle.length) cycle.index = 0;
return cycle.index;
} else {
return null;
}
};
/**
* Enter a forloop
*
* @param {Integer} length
* @param {String} itemName
*/
Context.prototype.forloopEnter = function (length, itemName) {
this._forloops.push({
length: length,
itemName: itemName
});
this._isInForloop = true;
};
/**
* Set the forloop item value
*
* @param {Object} item
* @param {Integer} index
*/
Context.prototype.forloopItem = function (item, index) {
var loop = this._forloops[this._forloops.length - 1];
loop.item = item;
loop.index = index;
};
/**
* Set the forloop information
*
* @return {Object}
*/
Context.prototype.forloopInfo = function () {
return this._forloops[this._forloops.length - 1];
};
/**
* Exit the current forloop
*/
Context.prototype.forloopEnd = function () {
this._forloops.pop();
if (this._forloops.length < 1) {
this._isInForloop = false;
}
};
/**
* Enter a tablerowloop
*
* @param {Integer} length
* @param {String} itemName
* @param {Integer} columns
*/
Context.prototype.tablerowloopEnter = function (length, itemName, columns) {
this._tablerowloops.push({
length: length,
itemName: itemName,
columns: columns
});
this._isInTablerowloop = true;
};
/**
* Set the tablerowloop item value
*
* @param {Object} item
* @param {Integer} index
* @param {Integer} colIndex
*/
Context.prototype.tablerowloopItem = function (item, index, colIndex) {
var loop = this._tablerowloops[this._tablerowloops.length - 1];
loop.item = item;
loop.index = index;
loop.colIndex = colIndex;
};
/**
* Get the tablerow information
*
* @return {Object}
*/
Context.prototype.tablerowloopInfo = function () {
return this._tablerowloops[this._tablerowloops.length - 1];
};
/**
* Exit the current tablerowloop
*/
Context.prototype.tablerowloopEnd = function () {
this._tablerowloops.pop();
if (this._tablerowloops.length < 1) {
this._isInTablerowloop = false;
}
};
/**
* Include a template file
*
* @param {String} name
* @param {Array} localsAst
* @param {Array} headerAst
* @param {Function} callback
*/
Context.prototype.include = function (name, localsAst, headerAst, callback) {
if (typeof headerAst === 'function') {
callback = headerAst;
headerAst = null;
}
var me = this;
if (typeof(this._includeFileHandler) === 'function') {
this._includeFileHandler(name, function (err, astList) {
if (err) return callback(err);
// all include files run on new context
var c = new Context({parent: me});
c.from(me);
function start () {
c.run(astList, function (err) {
//console.log(err, c.getBuffer(), headerAst);
me.print(c.clearBuffer());
callback(err);
});
}
if (headerAst && headerAst.length > 0) {
astList = [me._position.line, me._position.column,OPCODE.LIST, headerAst, astList];
}
if (localsAst) {
me.run(localsAst, function (err, locals) {
if (err) locals = {};
Object.keys(locals).forEach(function (n) {
c._locals[n] = locals[n];
});
start();
});
} else {
start();
}
});
} else {
return callback(new Error('please set an include file handler'));
}
};
/**
* Extends layout
*
* @param {String} name
* @param {Function} callback
*/
Context.prototype.extends = function (name, callback) {
if (typeof(this._includeFileHandler) === 'function') {
this._includeFileHandler(name, callback);
} else {
return callback(new Error('please set an include file handler'));
}
};
/**
* Set the include file handler
*
* @param {Function} fn format: function (name, callback)
* callback format: function (err, astList)
*/
Context.prototype.onInclude = function (fn) {
this._includeFileHandler = fn;
};
/**
* Throw locals undefined error
*
* @param {String} name
* @return {Object}
*/
Context.prototype.throwLocalsUndefinedError = function (name) {
debug('Locals ' + name + ' is undefined');
return null;
};
/**
* Throw loop item undefined error
*
* @param {String} name
* @return {Object}
*/
Context.prototype.throwLoopItemUndefinedError = function (name) {
debug('Loop item ' + name + ' is undefined');
return null;
};
/**
* Throw forloop/tablerow locals undefined error
*
* @param {String} name
* @return {Object}
*/
Context.prototype.throwLoopLocalsUndefinedError = function (name) {
debug('Loop locals ' + name + ' is undefined');
return null;
};
/**
* Throw filter undefined error
*
* @param {String} name
* @return {Object}
*/
Context.prototype.throwFilterUndefinedError = function (name) {
var err = new Error('Filter ' + name + ' is undefined ' + this.getCurrentPosition(true));
err.code = 'UNDEFINED_FILTER';
err = this.wrapCurrentPosition(err);
return err;
}
/**
* Throw unknown opcode error
*
* @param {String} code
* @return {Object}
*/
Context.prototype.throwUnknownOpcodeError = function (code) {
var err = new Error('Unknown opcode ' + code + ' ' + this.getCurrentPosition(true));
err.code = 'UNKNOWN_OPCODE';
err = this.wrapCurrentPosition(err);
return err;
};
/**
* Throw unknown tag error
*
* @param {String} name
* @param {String} body
* @return {Object}
*/
Context.prototype.throwUnknownTagError = function (name, body) {
var err = new Error('Unknown tag "' + (name + ' ' + body).trim() + '" ' + this.getCurrentPosition(true));
err.code = 'UNKNOWN_TAG';
err = this.wrapCurrentPosition(err);
return err;
};
/**
* Set current position
*
* @param {Integer} line
* @param {Integer} column
*/
Context.prototype.setCurrentPosition = function (line, column) {
this._position.line = line;
this._position.column = column;
};
/**
* Get current position
*
* @param {Boolean} getString
* @return {Object}
*/
Context.prototype.getCurrentPosition = function (getString) {
if (getString) {
return 'at line ' + this._position.line + ', column ' + this._position.column;
} else {
return this._position;
}
};
/**
* Wrap current position on a error object
*
* @param {Object} err
* @return {Object}
*/
Context.prototype.wrapCurrentPosition = function (err) {
err = err || {};
err.line = this._position.line;
err.column = this._position.column;
return err;
};
/**
* Push Filename
*
* @param {String} filename
* @return {String}
*/
Context.prototype.pushFilename = function (filename) {
this._filenameStack.push(filename);
return filename;
};
/**
* Pop Filename
*
* @return {String}
*/
Context.prototype.popFilename = function () {
return this._filenameStack.pop();
};
/**
* Get filename
*
* @return {String}
*/
Context.prototype.getFilename = function () {
return this._filenameStack[this._filenameStack.length - 1];
};
|
jddeeds/jddeeds.github.io
|
node_modules/tinyliquid/lib/context.js
|
JavaScript
|
mit
| 16,661 |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2015-2019 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "primitives/block.h"
#include "hash.h"
#include "script/standard.h"
#include "script/sign.h"
#include "tinyformat.h"
#include "utilstrencodings.h"
#include "util.h"
uint256 CBlockHeader::GetHash() const
{
if (nVersion < 4)
return HashQuark(BEGIN(nVersion), END(nNonce));
if (nVersion < 7)
return Hash(BEGIN(nVersion), END(nAccumulatorCheckpoint));
return Hash(BEGIN(nVersion), END(nNonce));
}
std::string CBlock::ToString() const
{
std::stringstream s;
s << strprintf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%u)\n",
GetHash().ToString(),
nVersion,
hashPrevBlock.ToString(),
hashMerkleRoot.ToString(),
nTime, nBits, nNonce,
vtx.size());
for (unsigned int i = 0; i < vtx.size(); i++)
{
s << " " << vtx[i].ToString() << "\n";
}
return s.str();
}
void CBlock::print() const
{
LogPrintf("%s", ToString());
}
bool CBlock::IsZerocoinStake() const
{
return IsProofOfStake() && vtx[1].HasZerocoinSpendInputs();
}
|
Mrs-X/PIVX
|
src/primitives/block.cpp
|
C++
|
mit
| 1,381 |
require 'rails_helper'
describe Artefact do
it { should respond_to(:name) }
it { should respond_to(:description) }
it { should respond_to(:museum_identifier) }
it { should have_many(:images).dependent(:destroy) }
it { should have_many(:sketchfabs).dependent(:destroy) }
describe '.new' do
let(:artefact) { Artefact.new }
it 'sets an UUID' do
expect(artefact.uuid).to_not be_nil
end
end
describe 'artefact has many models' do
let(:artefact) { create(:artefact) }
let(:sketchfab) { create(:sketchfab, :with_artefact) }
it 'should find artefacts without models' do
expect(Artefact.sketchfabless).to_not include(sketchfab.artefact)
end
it 'should find artefacts with models' do
expect(Artefact.with_sketchfabs).to include(sketchfab.artefact)
end
end
end
|
neshmi/projectmosul
|
spec/models/artefact_spec.rb
|
Ruby
|
mit
| 828 |
import sys
from pycsp import *
|
IanField90/Coursework
|
Part 3/SE3AC11/eticket/eticket_uint.py
|
Python
|
mit
| 30 |
#include "optionsmodel.h"
#include "bitcoinunits.h"
#include "init.h"
#include "walletdb.h"
#include "guiutil.h"
#include <QSettings>
OptionsModel::OptionsModel(QObject *parent) :
QAbstractListModel(parent)
{
Init();
}
bool static ApplyProxySettings()
{
QSettings settings;
CService addrProxy(settings.value("addrProxy", "127.0.0.1:9042").toString().toStdString());
int nSocksVersion(settings.value("nSocksVersion", 5).toInt());
if (!settings.value("fUseProxy", false).toBool()) {
addrProxy = CService();
nSocksVersion = 0;
return false;
}
if (nSocksVersion && !addrProxy.IsValid())
return false;
if (!IsLimited(NET_IPV4))
SetProxy(NET_IPV4, addrProxy, nSocksVersion);
if (nSocksVersion > 4) {
#ifdef USE_IPV6
if (!IsLimited(NET_IPV6))
SetProxy(NET_IPV6, addrProxy, nSocksVersion);
#endif
SetNameProxy(addrProxy, nSocksVersion);
}
return true;
}
void OptionsModel::Init()
{
QSettings settings;
// These are Qt-only settings:
nDisplayUnit = settings.value("nDisplayUnit", BitcoinUnits::LND).toInt();
bDisplayAddresses = settings.value("bDisplayAddresses", false).toBool();
fMinimizeToTray = settings.value("fMinimizeToTray", false).toBool();
fMinimizeOnClose = settings.value("fMinimizeOnClose", false).toBool();
nTransactionFee = settings.value("nTransactionFee").toLongLong();
language = settings.value("language", "").toString();
// These are shared with core Landcoin; we want
// command-line options to override the GUI settings:
if (settings.contains("fUseUPnP"))
SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool());
if (settings.contains("addrProxy") && settings.value("fUseProxy").toBool())
SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString());
if (settings.contains("nSocksVersion") && settings.value("fUseProxy").toBool())
SoftSetArg("-socks", settings.value("nSocksVersion").toString().toStdString());
if (!language.isEmpty())
SoftSetArg("-lang", language.toStdString());
}
void OptionsModel::Reset()
{
QSettings settings;
// Remove all entries in this QSettings object
settings.clear();
// default setting for OptionsModel::StartAtStartup - disabled
if (GUIUtil::GetStartOnSystemStartup())
GUIUtil::SetStartOnSystemStartup(false);
// Re-Init to get default values
Init();
// Ensure Upgrade() is not running again by setting the bImportFinished flag
settings.setValue("bImportFinished", true);
}
bool OptionsModel::Upgrade()
{
QSettings settings;
if (settings.contains("bImportFinished"))
return false; // Already upgraded
settings.setValue("bImportFinished", true);
// Move settings from old wallet.dat (if any):
CWalletDB walletdb("wallet.dat");
QList<QString> intOptions;
intOptions << "nDisplayUnit" << "nTransactionFee";
foreach(QString key, intOptions)
{
int value = 0;
if (walletdb.ReadSetting(key.toStdString(), value))
{
settings.setValue(key, value);
walletdb.EraseSetting(key.toStdString());
}
}
QList<QString> boolOptions;
boolOptions << "bDisplayAddresses" << "fMinimizeToTray" << "fMinimizeOnClose" << "fUseProxy" << "fUseUPnP";
foreach(QString key, boolOptions)
{
bool value = false;
if (walletdb.ReadSetting(key.toStdString(), value))
{
settings.setValue(key, value);
walletdb.EraseSetting(key.toStdString());
}
}
try
{
CAddress addrProxyAddress;
if (walletdb.ReadSetting("addrProxy", addrProxyAddress))
{
settings.setValue("addrProxy", addrProxyAddress.ToStringIPPort().c_str());
walletdb.EraseSetting("addrProxy");
}
}
catch (std::ios_base::failure &e)
{
// 0.6.0rc1 saved this as a CService, which causes failure when parsing as a CAddress
CService addrProxy;
if (walletdb.ReadSetting("addrProxy", addrProxy))
{
settings.setValue("addrProxy", addrProxy.ToStringIPPort().c_str());
walletdb.EraseSetting("addrProxy");
}
}
ApplyProxySettings();
Init();
return true;
}
int OptionsModel::rowCount(const QModelIndex & parent) const
{
return OptionIDRowCount;
}
QVariant OptionsModel::data(const QModelIndex & index, int role) const
{
if(role == Qt::EditRole)
{
QSettings settings;
switch(index.row())
{
case StartAtStartup:
return QVariant(GUIUtil::GetStartOnSystemStartup());
case MinimizeToTray:
return QVariant(fMinimizeToTray);
case MapPortUPnP:
#ifdef USE_UPNP
return settings.value("fUseUPnP", GetBoolArg("-upnp", true));
#else
return QVariant(false);
#endif
case MinimizeOnClose:
return QVariant(fMinimizeOnClose);
case ProxyUse: {
proxyType proxy;
return QVariant(GetProxy(NET_IPV4, proxy));
}
case ProxyIP: {
proxyType proxy;
if (GetProxy(NET_IPV4, proxy))
return QVariant(QString::fromStdString(proxy.first.ToStringIP()));
else
return QVariant(QString::fromStdString("127.0.0.1"));
}
case ProxyPort: {
proxyType proxy;
if (GetProxy(NET_IPV4, proxy))
return QVariant(proxy.first.GetPort());
else
return QVariant(9042);
}
case ProxySocksVersion: {
proxyType proxy;
if (GetProxy(NET_IPV4, proxy))
return QVariant(proxy.second);
else
return QVariant(5);
}
case Fee:
return QVariant(nTransactionFee);
case DisplayUnit:
return QVariant(nDisplayUnit);
case DisplayAddresses:
return QVariant(bDisplayAddresses);
case Language:
return settings.value("language", "");
default:
return QVariant();
}
}
return QVariant();
}
bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role)
{
bool successful = true; /* set to false on parse error */
if(role == Qt::EditRole)
{
QSettings settings;
switch(index.row())
{
case StartAtStartup:
successful = GUIUtil::SetStartOnSystemStartup(value.toBool());
break;
case MinimizeToTray:
fMinimizeToTray = value.toBool();
settings.setValue("fMinimizeToTray", fMinimizeToTray);
break;
case MapPortUPnP:
settings.setValue("fUseUPnP", value.toBool());
MapPort(value.toBool());
break;
case MinimizeOnClose:
fMinimizeOnClose = value.toBool();
settings.setValue("fMinimizeOnClose", fMinimizeOnClose);
break;
case ProxyUse:
settings.setValue("fUseProxy", value.toBool());
successful = ApplyProxySettings();
break;
case ProxyIP: {
proxyType proxy;
proxy.first = CService("127.0.0.1", 9042);
GetProxy(NET_IPV4, proxy);
CNetAddr addr(value.toString().toStdString());
proxy.first.SetIP(addr);
settings.setValue("addrProxy", proxy.first.ToStringIPPort().c_str());
successful = ApplyProxySettings();
}
break;
case ProxyPort: {
proxyType proxy;
proxy.first = CService("127.0.0.1", 9042);
GetProxy(NET_IPV4, proxy);
proxy.first.SetPort(value.toInt());
settings.setValue("addrProxy", proxy.first.ToStringIPPort().c_str());
successful = ApplyProxySettings();
}
break;
case ProxySocksVersion: {
proxyType proxy;
proxy.second = 5;
GetProxy(NET_IPV4, proxy);
proxy.second = value.toInt();
settings.setValue("nSocksVersion", proxy.second);
successful = ApplyProxySettings();
}
break;
case Fee:
nTransactionFee = value.toLongLong();
settings.setValue("nTransactionFee", nTransactionFee);
break;
case DisplayUnit:
nDisplayUnit = value.toInt();
settings.setValue("nDisplayUnit", nDisplayUnit);
emit displayUnitChanged(nDisplayUnit);
break;
case DisplayAddresses:
bDisplayAddresses = value.toBool();
settings.setValue("bDisplayAddresses", bDisplayAddresses);
break;
case Language:
settings.setValue("language", value);
break;
default:
break;
}
}
emit dataChanged(index, index);
return successful;
}
qint64 OptionsModel::getTransactionFee()
{
return nTransactionFee;
}
|
landcoin-project/landcoin
|
src/qt/optionsmodel.cpp
|
C++
|
mit
| 9,070 |
const { assign } = require('lodash')
const proxyquire = require('proxyquire')
const contact = require('../../../../../test/unit/data/contacts/contact.json')
describe('Contact controller', () => {
beforeEach(() => {
this.getContactStub = sinon.stub().resolves(contact)
this.getDitCompanyStub = sinon.stub().resolves(contact.company)
this.transformerStub = sinon.stub()
this.contactController = proxyquire('../details', {
'../repos': {
getContact: this.getContactStub,
},
'../../companies/repos': {
getDitCompany: this.getDitCompanyStub,
},
'../transformers': {
transformContactToView: this.transformerStub,
},
})
this.req = {
session: {
token: 'abcd',
},
params: {
contactId: '12651151-2149-465e-871b-ac45bc568a62',
},
}
this.res = {
locals: {},
breadcrumb: sinon.stub().returnsThis(),
render: sinon.spy(),
}
this.next = sinon.spy()
})
describe('#getCommon', () => {
it('should get the contact ID', async () => {
await this.contactController.getCommon(this.req, this.res, this.next)
expect(this.res.locals.id).to.equal(this.req.params.contactId)
expect(this.next).to.have.been.calledOnce
})
it('should get the reason for archive options', async () => {
await this.contactController.getCommon(this.req, this.res, this.next)
const expected = [
'Left the company',
'Does not want to be contacted',
'Changed role/responsibility',
]
expect(this.res.locals.reasonForArchiveOptions).to.deep.equal(expected)
expect(this.next).to.have.been.calledOnce
})
it('should get the reason for archive options prefix', async () => {
await this.contactController.getCommon(this.req, this.res, this.next)
expect(this.res.locals.reasonForArchiveOptionsPrefix).to.equal(
'This contact has:'
)
expect(this.next).to.have.been.calledOnce
})
it('should handle an error', async () => {
const error = Error('error')
this.getContactStub.rejects(error)
await this.contactController.getCommon(this.req, this.res, this.next)
expect(this.next).to.be.calledWith(
sinon.match({ message: error.message })
)
expect(this.next).to.have.been.calledOnce
})
})
describe('#getDetails', () => {
context('when called with a contact', () => {
beforeEach(() => {
this.res.locals = assign({}, this.res.locals, { contact })
this.res.locals.features = assign({}, this.res.locals.features)
this.contactController.getDetails(this.req, this.res, this.next)
})
it('should return the contact details', () => {
const options = this.res.render.firstCall.args[1]
expect(options).to.have.property('contactDetails')
})
it('should call the details transformer', () => {
expect(this.transformerStub).to.be.calledWith(contact)
})
it('should render the contact details view', () => {
expect(this.res.render).to.be.calledWith('contacts/views/details')
})
})
})
})
|
uktrade/data-hub-fe-beta2
|
src/apps/contacts/controllers/__test__/details.test.js
|
JavaScript
|
mit
| 3,180 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* jkl
*/
package com.microsoft.azure.management.apimanagement.v2019_01_01.implementation;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import com.microsoft.azure.management.apimanagement.v2019_01_01.Subscriptions;
import rx.Completable;
import rx.functions.Func1;
import rx.Observable;
import com.microsoft.azure.Page;
import com.microsoft.azure.management.apimanagement.v2019_01_01.ProductSubscriptionContract;
class SubscriptionsImpl extends WrapperImpl<SubscriptionsInner> implements Subscriptions {
private final ApiManagementManager manager;
SubscriptionsImpl(ApiManagementManager manager) {
super(manager.inner().subscriptions());
this.manager = manager;
}
public ApiManagementManager manager() {
return this.manager;
}
@Override
public SubscriptionContractImpl define(String name) {
return wrapModel(name);
}
private SubscriptionContractImpl wrapModel(SubscriptionContractInner inner) {
return new SubscriptionContractImpl(inner, manager());
}
private SubscriptionContractImpl wrapModel(String name) {
return new SubscriptionContractImpl(name, this.manager());
}
@Override
public Observable<ProductSubscriptionContract> listAsync(final String resourceGroupName, final String serviceName) {
SubscriptionsInner client = this.inner();
return client.listAsync(resourceGroupName, serviceName)
.flatMapIterable(new Func1<Page<SubscriptionContractInner>, Iterable<SubscriptionContractInner>>() {
@Override
public Iterable<SubscriptionContractInner> call(Page<SubscriptionContractInner> page) {
return page.items();
}
})
.map(new Func1<SubscriptionContractInner, ProductSubscriptionContract>() {
@Override
public ProductSubscriptionContract call(SubscriptionContractInner inner) {
return new ProductSubscriptionContractImpl(inner, manager());
}
});
}
@Override
public Completable getEntityTagAsync(String resourceGroupName, String serviceName, String sid) {
SubscriptionsInner client = this.inner();
return client.getEntityTagAsync(resourceGroupName, serviceName, sid).toCompletable();
}
@Override
public Observable<ProductSubscriptionContract> getAsync(String resourceGroupName, String serviceName, String sid) {
SubscriptionsInner client = this.inner();
return client.getAsync(resourceGroupName, serviceName, sid)
.map(new Func1<SubscriptionContractInner, ProductSubscriptionContract>() {
@Override
public ProductSubscriptionContract call(SubscriptionContractInner inner) {
return new ProductSubscriptionContractImpl(inner, manager());
}
});
}
@Override
public Completable deleteAsync(String resourceGroupName, String serviceName, String sid, String ifMatch) {
SubscriptionsInner client = this.inner();
return client.deleteAsync(resourceGroupName, serviceName, sid, ifMatch).toCompletable();
}
@Override
public Completable regeneratePrimaryKeyAsync(String resourceGroupName, String serviceName, String sid) {
SubscriptionsInner client = this.inner();
return client.regeneratePrimaryKeyAsync(resourceGroupName, serviceName, sid).toCompletable();
}
@Override
public Completable regenerateSecondaryKeyAsync(String resourceGroupName, String serviceName, String sid) {
SubscriptionsInner client = this.inner();
return client.regenerateSecondaryKeyAsync(resourceGroupName, serviceName, sid).toCompletable();
}
}
|
selvasingh/azure-sdk-for-java
|
sdk/apimanagement/mgmt-v2019_01_01/src/main/java/com/microsoft/azure/management/apimanagement/v2019_01_01/implementation/SubscriptionsImpl.java
|
Java
|
mit
| 3,940 |
#!/usr/bin/python3
import os
import re
import requests
def download_file(url):
out_file = os.path.join("SOURCES", url.rsplit("/")[-1])
r = requests.get(url, stream=True)
print("Downloading {} to {}".format(url, out_file))
with open(out_file, "wb") as out:
for chunk in r.iter_content(chunk_size=None):
if chunk:
out.write(chunk)
spec = "{}.spec".format(os.environ['CIRCLE_PROJECT_REPONAME'])
with open(spec, 'r') as f:
for line in f.readlines():
if line.startswith("Version:"):
NGINX_VERSION = re.search("([0-9.])+", line).group()
if line.startswith("%define nps_version"):
NPS_VERSION = re.search("([0-9.])+", line).group()
ngx_files = [
"https://nginx.org/download/nginx-{NGINX_VERSION}.tar.gz",
"https://nginx.org/download/nginx-{NGINX_VERSION}.tar.gz.asc"
]
for f in ngx_files:
download_file(f.format(NGINX_VERSION=NGINX_VERSION))
nps_files = [
"https://github.com/pagespeed/ngx_pagespeed/archive/v{NPS_VERSION}-beta.zip",
"https://dl.google.com/dl/page-speed/psol/{NPS_VERSION}-x64.tar.gz",
"https://dl.google.com/dl/page-speed/psol/{NPS_VERSION}-ia32.tar.gz"
]
for f in nps_files:
download_file(f.format(NPS_VERSION=NPS_VERSION))
|
kyl191/nginx-pagespeed
|
download_sources.py
|
Python
|
mit
| 1,266 |
<?php
/**
* Include the SDK by using the autoloader from Composer.
*/
require __DIR__ . '/../../vendor/autoload.php';
/**
* Include the configuration values.
*
* Ensure that you have edited the configuration.php file
* to include your application keys.
*/
$config = require __DIR__ . '/../../configuration.php';
$apiKey = $config ['apiKey'];
$appSid = $config ['appSid'];
$out_folder = $config ['outFolder'];
$data_folder = '../../data/'; // resouece data folder
/**
* The namespaces provided by the SDK.
*/
use Aspose\Barcode\BarcodeApi;
use Aspose\Storage\StorageApi;
// ExStart:1
\Aspose\Storage\AsposeApp::$apiKey = $apiKey;
\Aspose\Storage\AsposeApp::$appSID = $appSid;
\Aspose\Barcode\AsposeApp::$apiKey = $apiKey;
\Aspose\Barcode\AsposeApp::$appSID = $appSid;
;
// Instantiate Aspose Storage Cloud API SDK
$storageApi = new StorageApi ();
// Instantiate Aspose BarCode Cloud API SDK
$barcodeApi = new BarcodeApi ();
// Set input file name
$name = "sample-barcode.jpeg";
// The barcode type.
// If this parameter is empty, autodetection of all supported types is used.
$type = "";
// Set mode for checksum validation during recognition
$checksumValidation = "On";
// Set if FNC symbol stripping should be performed.
$stripFnc = "True";
// Set recognition of rotated barcode
$rotationAngle = "";
// Set exact number of barcodes to recognize
$barcodesCount = "1";
// Set recognition of barcode inside specified Rectangle region
$rectX = 0;
$rectY = 0;
$rectWidth = 0;
$rectHeight = 0;
// Set 3rd party cloud storage server (if any)
$storage = "";
// Set folder location at cloud storage
$folder = "";
// Set local file (if any)
$file = null;
try {
// upload file to aspose cloud storage
$result = $storageApi->PutCreate ( $name, "", $storage, $data_folder . $name );
// invoke Aspose.BarCode Cloud SDK API to read barcode
$response = $barcodeApi->GetBarcodeRecognize ( $name, $type, $checksumValidation, $stripFnc, $rotationAngle, $barcodesCount, $rectX, $rectY, $rectWidth, $rectHeight, $storage, $folder );
if ($response != null && $response->Status = "OK") {
print_r ( $response->Barcode );
}
} catch ( \Aspose\Barcode\ApiException $exp ) {
echo "Exception:" . $exp->getMessage ();
}
//ExEnd:1
|
farooqsheikhpk/Aspose.BarCode-for-Cloud
|
Examples/PHP/managing-recognition/cloud-storage/recognize-specified-count-of-barcodes.php
|
PHP
|
mit
| 2,244 |
const inherits = require('util').inherits
const async = require('async')
const ethUtil = require('ethereumjs-util')
const Account = require('ethereumjs-account')
const FakeMerklePatriciaTree = require('fake-merkle-patricia-tree')
const VM = require('./index.js')
const ZERO_BUFFER = new Buffer('0000000000000000000000000000000000000000000000000000000000000000', 'hex')
module.exports = createHookedVm
module.exports.fromWeb3Provider = fromWeb3Provider
/*
This is a helper for creating a vm with modified state lookups
this should be made obsolete by a better public API for StateManager
```js
var vm = createHookedVm({
enableHomestead: true,
}, {
fetchAccountBalance: function(addressHex, cb){ ... },
fetchAccountNonce: function(addressHex, cb){ ... },
fetchAccountCode: function(addressHex, cb){ ... },
fetchAccountStorage: function(addressHex, keyHex, cb){ ... },
})
vm.runTx(txParams, cb)
```
*/
function createHookedVm (opts, hooks) {
var codeStore = new FallbackAsyncStore(hooks.fetchAccountCode.bind(hooks))
var vm = new VM(opts)
vm.stateManager._lookupStorageTrie = createAccountStorageTrie
vm.stateManager.cache._lookupAccount = loadAccount
vm.stateManager.getContractCode = codeStore.get.bind(codeStore)
vm.stateManager.setContractCode = codeStore.set.bind(codeStore)
return vm
function createAccountStorageTrie (address, cb) {
var addressHex = ethUtil.addHexPrefix(address.toString('hex'))
var storageTrie = new FallbackStorageTrie({
fetchStorage: function (key, cb) {
hooks.fetchAccountStorage(addressHex, ethUtil.addHexPrefix(key), cb)
}
})
cb(null, storageTrie)
}
function loadAccount (address, cb) {
var addressHex = ethUtil.addHexPrefix(address.toString('hex'))
async.parallel({
nonce: hooks.fetchAccountNonce.bind(hooks, addressHex),
balance: hooks.fetchAccountBalance.bind(hooks, addressHex)
}, function (err, results) {
if (err) return cb(err)
results._exists = results.nonce !== '0x0' || results.balance !== '0x0' || results._code !== '0x'
// console.log('fetch account results:', results)
var account = new Account(results)
// not used but needs to be anything but the default (ethUtil.SHA3_NULL)
// code lookups are handled by `codeStore`
account.codeHash = ZERO_BUFFER.slice()
cb(null, account)
})
}
}
/*
Additional helper for creating a vm with rpc state lookups
blockNumber to query against is fixed
*/
function fromWeb3Provider (provider, blockNumber, opts) {
return createHookedVm(opts, {
fetchAccountBalance: createRpcFunction(provider, 'eth_getBalance', blockNumber),
fetchAccountNonce: createRpcFunction(provider, 'eth_getTransactionCount', blockNumber),
fetchAccountCode: createRpcFunction(provider, 'eth_getCode', blockNumber),
fetchAccountStorage: createRpcFunction(provider, 'eth_getStorageAt', blockNumber)
})
function createRpcFunction (provider, method, blockNumber) {
return function sendRpcRequest () {
// prepare arguments
var args = [].slice.call(arguments)
var cb = args.pop()
args.push(blockNumber)
// send rpc payload
provider.sendAsync({
id: 1,
jsonrpc: '2.0',
method: method,
params: args
}, function (err, res) {
if (err) return cb(err)
cb(null, res.result)
})
}
}
}
//
// FallbackStorageTrie
//
// is a FakeMerklePatriciaTree that will let lookups
// fallback to the fetchStorage fn. writes shadow the underlying fetchStorage value.
// doesn't bother with a stateRoot
//
inherits(FallbackStorageTrie, FakeMerklePatriciaTree)
function FallbackStorageTrie (opts) {
const self = this
FakeMerklePatriciaTree.call(self)
self._fetchStorage = opts.fetchStorage
}
FallbackStorageTrie.prototype.get = function (key, cb) {
const self = this
var _super = FakeMerklePatriciaTree.prototype.get.bind(self)
_super(key, function (err, value) {
if (err) return cb(err)
if (value) return cb(null, value)
// if value not in tree, try network
var keyHex = key.toString('hex')
self._fetchStorage(keyHex, function (err, rawValue) {
if (err) return cb(err)
var value = ethUtil.toBuffer(rawValue)
value = ethUtil.unpad(value)
var encodedValue = ethUtil.rlp.encode(value)
cb(null, encodedValue)
})
})
}
//
// FallbackAsyncStore
//
// is an async key-value store that will let lookups
// fallback to the network. puts are not sent.
//
function FallbackAsyncStore (fetchFn) {
// console.log('FallbackAsyncStore - new')
const self = this
self.fetch = fetchFn
self.cache = {}
}
FallbackAsyncStore.prototype.get = function (address, cb) {
// console.log('FallbackAsyncStore - get', arguments)
const self = this
var addressHex = '0x' + address.toString('hex')
var code = self.cache[addressHex]
if (code !== undefined) {
cb(null, code)
} else {
// console.log('FallbackAsyncStore - fetch init')
self.fetch(addressHex, function (err, value) {
// console.log('FallbackAsyncStore - fetch return', arguments)
if (err) return cb(err)
value = ethUtil.toBuffer(value)
self.cache[addressHex] = value
cb(null, value)
})
}
}
FallbackAsyncStore.prototype.set = function (address, code, cb) {
// console.log('FallbackAsyncStore - set', arguments)
const self = this
var addressHex = '0x' + address.toString('hex')
self.cache[addressHex] = code
cb()
}
|
giulidb/ticket_dapp
|
node_modules/ethereumjs-vm/lib/hooked.js
|
JavaScript
|
mit
| 5,536 |
<?php
/**
* Mockery
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://github.com/padraic/mockery/blob/master/LICENSE
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to padraic@php.net so we can send you a copy immediately.
*
* @category Mockery
* @package Mockery
* @copyright Copyright (c) 2010 Pádraic Brady (http://blog.astrumfutura.com)
* @license http://github.com/padraic/mockery/blob/master/LICENSE New BSD License
*/
namespace Mockery\Generator;
use Mockery\Generator\StringManipulation\Pass\Pass;
use Mockery\Generator\StringManipulation\Pass\RemoveDestructorPass;
use Mockery\Generator\StringManipulation\Pass\CallTypeHintPass;
use Mockery\Generator\StringManipulation\Pass\MagicMethodTypeHintsPass;
use Mockery\Generator\StringManipulation\Pass\ClassNamePass;
use Mockery\Generator\StringManipulation\Pass\ClassPass;
use Mockery\Generator\StringManipulation\Pass\TraitPass;
use Mockery\Generator\StringManipulation\Pass\InstanceMockPass;
use Mockery\Generator\StringManipulation\Pass\InterfacePass;
use Mockery\Generator\StringManipulation\Pass\MethodDefinitionPass;
use Mockery\Generator\StringManipulation\Pass\RemoveBuiltinMethodsThatAreFinalPass;
use Mockery\Generator\StringManipulation\Pass\RemoveUnserializeForInternalSerializableClassesPass;
class StringManipulationGenerator implements Generator
{
protected $passes = array();
/**
* Creates a new StringManipulationGenerator with the default passes
*
* @return StringManipulationGenerator
*/
public static function withDefaultPasses()
{
return new static([
new CallTypeHintPass(),
new MagicMethodTypeHintsPass(),
new ClassPass(),
new TraitPass(),
new ClassNamePass(),
new InstanceMockPass(),
new InterfacePass(),
new MethodDefinitionPass(),
new RemoveUnserializeForInternalSerializableClassesPass(),
new RemoveBuiltinMethodsThatAreFinalPass(),
new RemoveDestructorPass(),
]);
}
public function __construct(array $passes)
{
$this->passes = $passes;
}
public function generate(MockConfiguration $config)
{
$code = file_get_contents(__DIR__ . '/../Mock.php');
$className = $config->getName() ?: $config->generateName();
$namedConfig = $config->rename($className);
foreach ($this->passes as $pass) {
$code = $pass->apply($code, $namedConfig);
}
return new MockDefinition($namedConfig, $code);
}
public function addPass(Pass $pass)
{
$this->passes[] = $pass;
}
}
|
Anjeyster/Dimento
|
vendor/mockery/mockery/library/Mockery/Generator/StringManipulationGenerator.php
|
PHP
|
mit
| 2,895 |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace BookClient.Data
{
public class BookManager
{
const string Url = "http://xam150.azurewebsites.net/api/books/";
private string authorizationKey;
private async Task<HttpClient> GetClient()
{
HttpClient client = new HttpClient();
if (string.IsNullOrEmpty(authorizationKey))
{
authorizationKey = await client.GetStringAsync(Url + "login");
authorizationKey = JsonConvert.DeserializeObject<string>(authorizationKey);
}
client.DefaultRequestHeaders.Add("Authorization", authorizationKey);
client.DefaultRequestHeaders.Add("Accept", "application/json");
return client;
}
public async Task<IEnumerable<Book>> GetAllAsync()
{
HttpClient client = await GetClient();
string result = await client.GetStringAsync(Url);
return JsonConvert.DeserializeObject<IEnumerable<Book>>(result);
}
public async Task<Book> Add(string title, string author, string genre)
{
Book book = new Book()
{
Title = title,
Authors = new List<string>(new[] { author }),
ISBN = string.Empty,
Genre = genre,
PublishDate = DateTime.Now.Date,
};
HttpClient client = await GetClient();
var response = await client.PostAsync(Url,
new StringContent(
JsonConvert.SerializeObject(book),
Encoding.UTF8, "application/json"));
return JsonConvert.DeserializeObject<Book>(
await response.Content.ReadAsStringAsync());
}
public async Task Update(Book book)
{
HttpClient client = await GetClient();
await client.PutAsync(Url + "/" + book.ISBN,
new StringContent(
JsonConvert.SerializeObject(book),
Encoding.UTF8, "application/json"));
}
public async Task Delete(string isbn)
{
HttpClient client = await GetClient();
await client.DeleteAsync(Url + isbn);
}
}
}
|
eliancruz29/Xamarin_university
|
MobileCerti/[XAM150]/xam150-ex3-start/BookClient/BookClient/Data/BookManager.cs
|
C#
|
mit
| 2,399 |
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
#pragma warning disable IDE0051
namespace GM.Utilities.DevelopRetrieval
{
class ParseSplitSample
{
private string[] ParseHtmlSplitTables(string urlLink)
{
string[] result = new string[] { };
HtmlDocument htmlDoc = new HtmlWeb().Load(urlLink);
HtmlNodeCollection tableNodes = htmlDoc.DocumentNode.SelectNodes("//table");
if (tableNodes != null)
{
result = Array.ConvertAll<HtmlNode, string>(tableNodes.ToArray(), n => n.OuterHtml);
}
return result;
}
DataTable ToDataTable(List<List<KeyValuePair<string, string>>> list)
{
DataTable result = new DataTable();
if (list.Count == 0)
return result;
result.Columns.AddRange(
list.First().Select(r => new DataColumn(r.Value)).ToArray()
);
list = list.Skip(1).ToArray().ToList();
list.ForEach(r => result.Rows.Add(r.Select(c => c.Value).Cast<object>().ToArray()));
return result;
}
}
}
|
govmeeting/govmeeting
|
Utilities/DevelopRetrieval/ParseSplitSample.cs
|
C#
|
mit
| 1,250 |
package crypto
import (
"bytes"
"testing"
"github.com/NebulousLabs/Sia/encoding"
"github.com/NebulousLabs/fastrand"
)
// TestUnitSignatureEncoding creates and encodes a public key, and verifies
// that it decodes correctly, does the same with a signature.
func TestUnitSignatureEncoding(t *testing.T) {
// Create a dummy key pair.
var sk SecretKey
sk[0] = 4
sk[32] = 5
pk := sk.PublicKey()
// Marshal and unmarshal the public key.
marshalledPK := encoding.Marshal(pk)
var unmarshalledPK PublicKey
err := encoding.Unmarshal(marshalledPK, &unmarshalledPK)
if err != nil {
t.Fatal(err)
}
// Test the public keys for equality.
if pk != unmarshalledPK {
t.Error("pubkey not the same after marshalling and unmarshalling")
}
// Create a signature using the secret key.
var signedData Hash
fastrand.Read(signedData[:])
sig := SignHash(signedData, sk)
// Marshal and unmarshal the signature.
marshalledSig := encoding.Marshal(sig)
var unmarshalledSig Signature
err = encoding.Unmarshal(marshalledSig, &unmarshalledSig)
if err != nil {
t.Fatal(err)
}
// Test signatures for equality.
if sig != unmarshalledSig {
t.Error("signature not same after marshalling and unmarshalling")
}
}
// TestUnitSigning creates a bunch of keypairs and signs random data with each of
// them.
func TestUnitSigning(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
// Try a bunch of signatures because at one point there was a library that
// worked around 98% of the time. Tests would usually pass, but 200
// iterations would normally cause a failure.
iterations := 200
for i := 0; i < iterations; i++ {
// Create dummy key pair.
sk, pk := GenerateKeyPair()
// Generate and sign the data.
var randData Hash
fastrand.Read(randData[:])
sig := SignHash(randData, sk)
// Verify the signature.
err := VerifyHash(randData, pk, sig)
if err != nil {
t.Fatal(err)
}
// Attempt to verify after the data has been altered.
randData[0]++
err = VerifyHash(randData, pk, sig)
if err != ErrInvalidSignature {
t.Fatal(err)
}
// Restore the data and make sure the signature is valid again.
randData[0]--
err = VerifyHash(randData, pk, sig)
if err != nil {
t.Fatal(err)
}
// Attempt to verify after the signature has been altered.
sig[0]++
err = VerifyHash(randData, pk, sig)
if err != ErrInvalidSignature {
t.Fatal(err)
}
}
}
// TestIntegrationSigKeyGenerate is an integration test checking that
// GenerateKeyPair and GenerateKeyPairDeterminisitc accurately create keys.
func TestIntegrationSigKeyGeneration(t *testing.T) {
if testing.Short() {
t.SkipNow()
}
message := HashBytes([]byte{'m', 's', 'g'})
// Create a random key and use it.
randSecKey, randPubKey := GenerateKeyPair()
sig := SignHash(message, randSecKey)
err := VerifyHash(message, randPubKey, sig)
if err != nil {
t.Error(err)
}
// Corrupt the signature
sig[0]++
err = VerifyHash(message, randPubKey, sig)
if err == nil {
t.Error("corruption failed")
}
// Create a deterministic key and use it.
var detEntropy [EntropySize]byte
detEntropy[0] = 35
detSecKey, detPubKey := GenerateKeyPairDeterministic(detEntropy)
sig = SignHash(message, detSecKey)
err = VerifyHash(message, detPubKey, sig)
if err != nil {
t.Error(err)
}
// Corrupt the signature
sig[0]++
err = VerifyHash(message, detPubKey, sig)
if err == nil {
t.Error("corruption failed")
}
}
// TestReadWriteSignedObject tests the ReadSignObject and WriteSignedObject
// functions, which are inverses of each other.
func TestReadWriteSignedObject(t *testing.T) {
sk, pk := GenerateKeyPair()
// Write signed object into buffer.
b := new(bytes.Buffer)
err := WriteSignedObject(b, "foo", sk)
if err != nil {
t.Fatal(err)
}
// Keep a copy of b's bytes.
buf := b.Bytes()
// Read and verify object.
var read string
err = ReadSignedObject(b, &read, 11, pk)
if err != nil {
t.Fatal(err)
}
if read != "foo" {
t.Fatal("encode/decode mismatch: expected 'foo', got", []byte(read))
}
// Check that maxlen is being respected.
b = bytes.NewBuffer(buf) // reset b
err = ReadSignedObject(b, &read, 10, pk)
if err == nil || err.Error() != "length 11 exceeds maxLen of 10" {
t.Fatal("expected length error, got", err)
}
// Disrupt the decoding to get coverage on the failure branch.
err = ReadSignedObject(b, &read, 11, pk)
if err == nil || err.Error() != "could not decode type crypto.Signature: unexpected EOF" {
t.Fatal(err)
}
// Try with an invalid signature.
buf[0]++ // alter the first byte of the signature, invalidating it.
b = bytes.NewBuffer(buf) // reset b
err = ReadSignedObject(b, &read, 11, pk)
if err != ErrInvalidSignature {
t.Fatal(err)
}
}
// TestUnitPublicKey tests the PublicKey method
func TestUnitPublicKey(t *testing.T) {
for i := 0; i < 1000; i++ {
sk, pk := GenerateKeyPair()
if sk.PublicKey() != pk {
t.Error("PublicKey does not match actual public key:", pk, sk.PublicKey())
}
}
}
|
mharkus/Sia
|
crypto/signatures_test.go
|
GO
|
mit
| 5,005 |
title('Entity-relationship diagram.');
description('Make your database structure visible.');
dimension(800, 250);
var erd = Joint.dia.erd;
Joint.paper("world", 800, 250);
var e1 = erd.Entity.create({
rect: { x: 220, y: 70, width: 100, height: 60 },
label: "Entity"
});
var e2 = erd.Entity.create({
rect: { x: 520, y: 70, width: 100, height: 60 },
label: "Weak Entity",
weak: true
});
var r1 = erd.Relationship.create({
rect: { x: 400, y: 72, width: 55, height: 55 },
label: "Relationship"
});
var a1 = erd.Attribute.create({
ellipse: { x: 90, y: 30, rx: 50, ry: 20 },
label: "primary",
primaryKey: true
});
var a2 = erd.Attribute.create({
ellipse: { x: 90, y: 80, rx: 50, ry: 20 },
label: "multivalued",
multivalued: true
});
var a3 = erd.Attribute.create({
ellipse: { x: 90, y: 130, rx: 50, ry: 20 },
label: "derived",
derived: true
});
var a4 = erd.Attribute.create({
ellipse: { x: 90, y: 180, rx: 50, ry: 20 },
label: "normal"
});
a1.joint(e1, erd.arrow);
a2.joint(e1, erd.arrow);
a3.joint(e1, erd.arrow);
a4.joint(e1, erd.arrow);
e1.joint(r1, erd.toMany);
r1.joint(e2, erd.oneTo);
|
dee-bee/decisionz
|
decisionz/lib/JointJS/www/demos/erd.js
|
JavaScript
|
mit
| 1,130 |
//
// generic/seq_packet_protocol.cpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Disable autolinking for unit tests.
#if !defined(BOOST_ALL_NO_LIB)
#define BOOST_ALL_NO_LIB 1
#endif // !defined(BOOST_ALL_NO_LIB)
// Test that header file is self-contained.
#include "asio/generic/seq_packet_protocol.hpp"
#include <cstring>
#include "asio/io_context.hpp"
#include "../unit_test.hpp"
#if defined(__cplusplus_cli) || defined(__cplusplus_winrt)
# define generic cpp_generic
#endif
//------------------------------------------------------------------------------
// generic_seq_packet_protocol_socket_compile test
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// The following test checks that all public member functions on the class
// generic::seq_packet_socket::socket compile and link correctly. Runtime
// failures are ignored.
namespace generic_seq_packet_protocol_socket_compile {
void connect_handler(const asio::error_code&)
{
}
void send_handler(const asio::error_code&, std::size_t)
{
}
void receive_handler(const asio::error_code&, std::size_t)
{
}
void test()
{
using namespace asio;
namespace generic = asio::generic;
typedef generic::seq_packet_protocol spp;
const int af_inet = ASIO_OS_DEF(AF_INET);
const int sock_seqpacket = ASIO_OS_DEF(SOCK_SEQPACKET);
try
{
io_context ioc;
char mutable_char_buffer[128] = "";
const char const_char_buffer[128] = "";
const socket_base::message_flags in_flags = 0;
socket_base::message_flags out_flags = 0;
socket_base::send_buffer_size socket_option;
socket_base::bytes_readable io_control_command;
asio::error_code ec;
// basic_seq_packet_socket constructors.
spp::socket socket1(ioc);
spp::socket socket2(ioc, spp(af_inet, 0));
spp::socket socket3(ioc, spp::endpoint());
#if !defined(ASIO_WINDOWS_RUNTIME)
spp::socket::native_handle_type native_socket1
= ::socket(af_inet, sock_seqpacket, 0);
spp::socket socket4(ioc, spp(af_inet, 0), native_socket1);
#endif // !defined(ASIO_WINDOWS_RUNTIME)
#if defined(ASIO_HAS_MOVE)
spp::socket socket5(std::move(socket4));
#endif // defined(ASIO_HAS_MOVE)
// basic_seq_packet_socket operators.
#if defined(ASIO_HAS_MOVE)
socket1 = spp::socket(ioc);
socket1 = std::move(socket2);
#endif // defined(ASIO_HAS_MOVE)
// basic_io_object functions.
spp::socket::executor_type ex = socket1.get_executor();
(void)ex;
#if !defined(ASIO_NO_DEPRECATED)
io_context& ioc_ref = socket1.get_io_context();
(void)ioc_ref;
io_context& ioc_ref2 = socket1.get_io_service();
(void)ioc_ref2;
#endif // !defined(ASIO_NO_DEPRECATED)
// basic_socket functions.
spp::socket::lowest_layer_type& lowest_layer = socket1.lowest_layer();
(void)lowest_layer;
socket1.open(spp(af_inet, 0));
socket1.open(spp(af_inet, 0), ec);
#if !defined(ASIO_WINDOWS_RUNTIME)
spp::socket::native_handle_type native_socket2
= ::socket(af_inet, sock_seqpacket, 0);
socket1.assign(spp(af_inet, 0), native_socket2);
spp::socket::native_handle_type native_socket3
= ::socket(af_inet, sock_seqpacket, 0);
socket1.assign(spp(af_inet, 0), native_socket3, ec);
#endif // !defined(ASIO_WINDOWS_RUNTIME)
bool is_open = socket1.is_open();
(void)is_open;
socket1.close();
socket1.close(ec);
spp::socket::native_handle_type native_socket4 = socket1.native_handle();
(void)native_socket4;
socket1.cancel();
socket1.cancel(ec);
bool at_mark1 = socket1.at_mark();
(void)at_mark1;
bool at_mark2 = socket1.at_mark(ec);
(void)at_mark2;
std::size_t available1 = socket1.available();
(void)available1;
std::size_t available2 = socket1.available(ec);
(void)available2;
socket1.bind(spp::endpoint());
socket1.bind(spp::endpoint(), ec);
socket1.connect(spp::endpoint());
socket1.connect(spp::endpoint(), ec);
socket1.async_connect(spp::endpoint(), connect_handler);
socket1.set_option(socket_option);
socket1.set_option(socket_option, ec);
socket1.get_option(socket_option);
socket1.get_option(socket_option, ec);
socket1.io_control(io_control_command);
socket1.io_control(io_control_command, ec);
spp::endpoint endpoint1 = socket1.local_endpoint();
spp::endpoint endpoint2 = socket1.local_endpoint(ec);
spp::endpoint endpoint3 = socket1.remote_endpoint();
spp::endpoint endpoint4 = socket1.remote_endpoint(ec);
socket1.shutdown(socket_base::shutdown_both);
socket1.shutdown(socket_base::shutdown_both, ec);
// basic_seq_packet_socket functions.
socket1.send(buffer(mutable_char_buffer), in_flags);
socket1.send(buffer(const_char_buffer), in_flags);
socket1.send(null_buffers(), in_flags);
socket1.send(buffer(mutable_char_buffer), in_flags, ec);
socket1.send(buffer(const_char_buffer), in_flags, ec);
socket1.send(null_buffers(), in_flags, ec);
socket1.async_send(buffer(mutable_char_buffer), in_flags, send_handler);
socket1.async_send(buffer(const_char_buffer), in_flags, send_handler);
socket1.async_send(null_buffers(), in_flags, send_handler);
socket1.receive(buffer(mutable_char_buffer), out_flags);
socket1.receive(null_buffers(), out_flags);
socket1.receive(buffer(mutable_char_buffer), in_flags, out_flags);
socket1.receive(null_buffers(), in_flags, out_flags);
socket1.receive(buffer(mutable_char_buffer), in_flags, out_flags, ec);
socket1.receive(null_buffers(), in_flags, out_flags, ec);
socket1.async_receive(buffer(mutable_char_buffer), out_flags,
receive_handler);
socket1.async_receive(null_buffers(), out_flags, receive_handler);
socket1.async_receive(buffer(mutable_char_buffer), in_flags,
out_flags, receive_handler);
socket1.async_receive(null_buffers(), in_flags, out_flags, receive_handler);
}
catch (std::exception&)
{
}
}
} // namespace generic_seq_packet_protocol_socket_compile
//------------------------------------------------------------------------------
ASIO_TEST_SUITE
(
"generic/seq_packet_protocol",
ASIO_TEST_CASE(generic_seq_packet_protocol_socket_compile::test)
)
|
mojmir-svoboda/BlackBoxTT
|
3rd_party/asio/src/tests/unit/generic/seq_packet_protocol.cpp
|
C++
|
mit
| 6,415 |
/*
* Copyright (c) 2015-2022, Antonio Gabriel Muñoz Conejo <antoniogmc at gmail dot com>
* Distributed under the terms of the MIT License
*/
package com.github.tonivade.claudb.data;
import static com.github.tonivade.claudb.data.DatabaseValue.score;
import static com.github.tonivade.resp.protocol.SafeString.safeString;
import static java.util.Collections.unmodifiableSet;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
import org.junit.Test;
public class SortedSetTest {
@Test
public void testSet() {
SortedSet set = new SortedSet();
assertThat(set.add(score(1, safeString("a"))), is(true));
assertThat(set.add(score(2, safeString("a"))), is(false));
assertThat(set.add(score(2, safeString("b"))), is(true));
assertThat(set.contains(score(0, safeString("a"))), is(true));
assertThat(set.contains(score(0, safeString("b"))), is(true));
assertThat(set.contains(score(0, safeString("c"))), is(false));
assertThat(set.score(safeString("a")), is(1.0));
assertThat(set.score(safeString("b")), is(2.0));
assertThat(set.ranking(safeString("a")), is(0));
assertThat(set.ranking(safeString("b")), is(1));
assertThat(set.remove(score(0, safeString("a"))), is(true));
assertThat(set.contains(score(0, safeString("a"))), is(false));
}
@Test
public void testEquals() {
SortedSet setA = new SortedSet();
setA.add(score(1, safeString("a")));
setA.add(score(2, safeString("b")));
SortedSet setB = new SortedSet();
setB.add(score(1, safeString("a")));
setB.add(score(2, safeString("b")));
assertThat(setA, is(setB));
assertThat(unmodifiableSet(setA), is(unmodifiableSet(setB)));
}
@Test
public void testNotEquals() {
SortedSet setA = new SortedSet();
setA.add(score(1, safeString("a")));
SortedSet setB = new SortedSet();
setB.add(score(1, safeString("a")));
setB.add(score(2, safeString("b")));
assertThat(setA, not(is(setB)));
}
@Test
public void testScore() {
SortedSet set = new SortedSet();
set.add(score(1, safeString("a")));
set.add(score(2, safeString("b")));
set.add(score(3, safeString("c")));
set.add(score(4, safeString("d")));
set.add(score(5, safeString("e")));
set.add(score(6, safeString("f")));
set.add(score(7, safeString("g")));
set.add(score(8, safeString("h")));
set.add(score(9, safeString("i")));
assertThat(set.tailSet(score(3, safeString(""))).first(), is(score(3.0, safeString("c"))));
assertThat(set.headSet(score(4, safeString(""))).last(), is(score(3.0, safeString("c"))));
}
}
|
tonivade/claudb
|
lib/src/test/java/com/github/tonivade/claudb/data/SortedSetTest.java
|
Java
|
mit
| 2,686 |
<?php
/**
* Delivers the daily production in Wh/kWh
*
* URL format:
* .../<GUID>.json?m= for Wh data
* .../<GUID>.json?u=kWh&m= for kWh data
*
* kWh format is hightly suggested!
*
* http://wiki.sonnenertrag.eu/datenimport:json
*
* @author Knut Kohl <github@knutkohl.de>
* @copyright 2012-2013 Knut Kohl
* @license GNU General Public License http://www.gnu.org/licenses/gpl.txt
* @version 1.0.0
*/
namespace Channel\Sonnenertrag;
/**
*
*/
class JSON extends \Channel {
/**
* Accept only childs of the same entity type
*/
public function addChild( $guid ) {
$childs = $this->getChilds();
if (empty($childs)) {
// Add 1st child
return parent::addChild($guid);
}
// Check if the new child have the same type as the 1st (and any other) child
$first = self::byID($childs[0]['entity']);
$new = self::byGUID($guid);
if ($first->type == $new->type) {
// ok, add new child
return parent::addChild($guid);
}
throw new Exception('"'.$this->name.'" accepts only childs of type "'.$first->type.'"', 400);
}
/**
*
*/
public function read( $request, $attributes=FALSE ) {
$this->year = date('Y');
$this->month = (array_key_exists('m', $request) AND $request['m'])
? $request['m']
: date('n');
$this->factor = (array_key_exists('u', $request) AND $request['u'] == 'kWh')
? 1000
: 1;
if ($this->month > date('n')) $this->year--;
$request['start'] = $this->year . '-' . $this->month . '-01';
$request['end'] = $this->year . '-' . $this->month . '-01+1month';
$request['period'] = '1day';
$request['full'] = TRUE;
$request['format'] = 'json';
$this->before_read($request);
$childs = $this->getChilds();
// no childs, return empty file
if (count($childs) == 0) {
return $this->finish();
}
$buffer = $childs[0]->read($request);
// only one child, use as is
if (count($childs) == 1) {
$result = $buffer;
}
// combine all data for same timestamp
for ($i=1; $i<count($childs); $i++) {
$next = $childs[$i]->read($request);
$row1 = $buffer->rewind()->current();
$row2 = $next->rewind()->current();
$result = new \Buffer;
while (!empty($row1) OR !empty($row2)) {
if ($buffer->key() == $next->key()) {
// same timestamp, combine
$row1['consumption'] += $row2['consumption'];
$result->write($row1, $buffer->key());
// read both next rows
$row1 = $buffer->next()->current();
$row2 = $next->next()->current();
} elseif ($buffer->key() AND $buffer->key() < $next->key() OR
$next->key() == '') {
// missing row 2, save row 1 as is
$result->write($row1, $buffer->key());
// read only row 1
$row1 = $buffer->next()->current();
} else /* $buffer->key() > $next->key() */ {
// missing row 1, save row 2 as is
$result->write($row2, $next->key());
// read only row 2
$row2 = $next->next()->current();
}
}
$buffer = $result;
}
$data = array();
foreach ($result as $row) {
$data[] = round($row['consumption'] / $this->factor, 3);
}
return $this->finish($data);
}
/**
* r2
*/
public function GET ( &$request ) {
$request['format'] = 'json';
return $this->read($request);
}
// -----------------------------------------------------------------------
// PROTECTED
// -----------------------------------------------------------------------
protected function finish( $data=array() ) {
// Provide full information...
return array(
'un' => $this->factor == 1 ? 'Wh' : 'kWh',
'tm' => sprintf('%04d-%02d-01T00:00:00', $this->year, $this->month),
'dt' => 86400,
'val' => $data
);
}
}
|
KKoPV/PVLng
|
core/Channel/Sonnenertrag/JSON.php
|
PHP
|
mit
| 4,502 |
package com.hearthsim.card.classic.spell.rare;
import com.hearthsim.card.minion.Minion;
import com.hearthsim.card.spellcard.SpellTargetableCard;
import com.hearthsim.event.effect.EffectCharacter;
import com.hearthsim.event.filter.FilterCharacter;
import com.hearthsim.event.filter.FilterCharacterTargetedSpell;
public class BlessedChampion extends SpellTargetableCard {
public static final EffectCharacter effect = (originSide, origin, targetSide, targetCharacterIndex, boardState) -> {
Minion targetCharacter = boardState.data_.getCharacter(targetSide, targetCharacterIndex);
targetCharacter.setAttack((byte) (2 * targetCharacter.getTotalAttack()));
return boardState;
};
/**
* Constructor
*
* @param hasBeenUsed Whether the card has already been used or not
*/
@Deprecated
public BlessedChampion(boolean hasBeenUsed) {
this();
this.hasBeenUsed = hasBeenUsed;
}
/**
* Constructor
*
* Defaults to hasBeenUsed = false
*/
public BlessedChampion() {
super();
}
@Override
public FilterCharacter getTargetableFilter() {
return FilterCharacterTargetedSpell.ALL_MINIONS;
}
/**
*
* Use the card on the given target
*
* Double a minion's Attack
*
*
*
* @param side
* @param boardState The BoardState before this card has performed its action. It will be manipulated and returned.
*
* @return The boardState is manipulated and returned
*/
@Override
public EffectCharacter getTargetableEffect() {
return BlessedChampion.effect;
}
}
|
relimited/HearthSim
|
src/main/java/com/hearthsim/card/classic/spell/rare/BlessedChampion.java
|
Java
|
mit
| 1,657 |
package format
import (
"github.com/nareix/joy4/av/avutil"
"github.com/nareix/joy4/format/aac"
"github.com/nareix/joy4/format/flv"
"github.com/nareix/joy4/format/mp4"
"github.com/nareix/joy4/format/rtmp"
"github.com/nareix/joy4/format/rtsp"
"github.com/nareix/joy4/format/ts"
)
func RegisterAll() {
avutil.DefaultHandlers.Add(mp4.Handler)
avutil.DefaultHandlers.Add(ts.Handler)
avutil.DefaultHandlers.Add(rtmp.Handler)
avutil.DefaultHandlers.Add(rtsp.Handler)
avutil.DefaultHandlers.Add(flv.Handler)
avutil.DefaultHandlers.Add(aac.Handler)
}
|
scbizu/letschat
|
vendor/github.com/nareix/joy4/format/format.go
|
GO
|
mit
| 557 |
<?php
// Controlador subir apunte hecho por FVieira
//Includes iniciales
require_once '../views/templateEngine.php';
require_once '../model/driver.php';
require_once '../model/Apunte.php';
require_once '../model/Usuario.php';
require_once '../model/Materia.php';
require_once '../model/Materia_Usuario.php';
require_once '../model/Notificacion.php';
require_once 'navbar.php';
require_once 'comboboxes.php';
require_once 'modal.php';
session_start(); // se inicia el manejo de sesiones
//Cancerbero
require_once '../cancerbero/cancerbero.php';
$cerb = new Cancerbero('AP_SubirApunte');
$cerb->handleAuto();
$db = Driver::getInstance();
//Instancias TemplateEngine, renderizan elementos
$renderMain = new TemplateEngine();
$renderSubirApunte = new TemplateEngine();
$usuarios = new Usuario($db);
$usuario = $usuarios->findBy('user_name',$_SESSION['name']);
$renderSubirApunte->materias = $usuario[0]->materias(); //se renderiza el combobox materia
$renderSubirApunte->modal = null;
//FUNCIONES DEL CONTROLADOR
$renderMain->title = "SubirApunte"; //Titulo y cabecera de la pagina
if(isset($_FILES['apunteUploaded'])){
//inicio colecta de datos para ser introducidos en la bd
$apunte = new Apunte($db);
$id = $usuario[0]->getUser_id();
$apunte->setUser_id($id);
$apunte->setApunte_name($_POST['name']);
$apunte->setMat_id($_POST['materia']);
$apunte->setAnho_academico($_POST['anho']);
//fin colecta de datos
//inicio operacion subir archivo
$titulo = "Archivo subido correctamente";
$contenido = "gracias por su colaboración con la comunidad";
$target = "../apuntes/";
$hashedName = md5_file($_FILES['apunteUploaded']['tmp_name']); //en el servidor su guarda como filename el hash md5
//resultante de hashear el archivo. Asi si dos archivos son diferentes tendran diferente filename
$target = $target . basename( $hashedName ) ;
$ok=1;
if($_FILES["apunteUploaded"]["type"] == "application/pdf"){
if(is_uploaded_file($_FILES['apunteUploaded']['tmp_name'])){
if(move_uploaded_file($_FILES['apunteUploaded']['tmp_name'], $target)) {
$titulo = "El apunte ". basename( $_FILES['apunteUploaded']['name']). " ha sido subido correctamente";
$matuser= new Materia_usuario($db);
$notificacion= new Notificacion($db);
$materia= new Materia($db);
$date = getdate();
$buffer = $date['year']."-".$date['mon']."-".$date['mday'];
$mat= $materia->findBy('mat_id',$apunte->getMat_id())[0]->getMat_name();
$array=$matuser->findBy('mat_id',$apunte->getMat_id());
foreach($array as $arrays){
$notificacion->setFecha($buffer);
$notificacion->setContenido("Nuevos apuntes en " .$mat);
$notificacion->setUser_id($arrays->getUser_id());
$notificacion->create();
}
} else {
$titulo = "Error subiendo el apunte.";
$contenido = "Ha ocurrido un error inesperado. Compruebe los datos de entrada, pruebe otra vez y si el error sigue ocurriendo contacte con un administrador";
}
}
}else{
$titulo = "fichero invalido";
$contenido = "compruebe que su fichero es .pdf";
}
//fin operacion subir archivo
$apunte->setRuta($hashedName);
$apunte->create(); //se crea en la BD el nuevo apunte
$renderSubirApunte->modal = renderModal($titulo,$contenido);
}
//RENDERIZADO FINAL
$renderSubirApunte->comboboxAnho = anhoRenderComboBox(); // se renderiza el combobox de año
$renderMain->navbar = renderNavBar(); //Inserción de navBar en la pagina. Omitible si no la necesita
$renderMain->content = $renderSubirApunte->render('subirApunte_v.php'); //Inserción del contenido de la página
echo $renderMain->renderMain(); // Dibujado de la página al completo
?>
|
nemoNoboru/ET3
|
controllers/subirApunte.php
|
PHP
|
mit
| 4,059 |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResource
from twilio.base.list_resource import ListResource
from twilio.base.page import Page
from twilio.rest.video.v1.room.room_participant.room_participant_published_track import PublishedTrackList
from twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule import SubscribeRulesList
from twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track import SubscribedTrackList
class ParticipantList(ListResource):
def __init__(self, version, room_sid):
"""
Initialize the ParticipantList
:param Version version: Version that contains the resource
:param room_sid: The SID of the participant's room
:returns: twilio.rest.video.v1.room.room_participant.ParticipantList
:rtype: twilio.rest.video.v1.room.room_participant.ParticipantList
"""
super(ParticipantList, self).__init__(version)
# Path Solution
self._solution = {'room_sid': room_sid, }
self._uri = '/Rooms/{room_sid}/Participants'.format(**self._solution)
def stream(self, status=values.unset, identity=values.unset,
date_created_after=values.unset, date_created_before=values.unset,
limit=None, page_size=None):
"""
Streams ParticipantInstance records from the API as a generator stream.
This operation lazily loads records as efficiently as possible until the limit
is reached.
The results are returned as a generator, so this operation is memory efficient.
:param ParticipantInstance.Status status: Read only the participants with this status
:param unicode identity: Read only the Participants with this user identity value
:param datetime date_created_after: Read only Participants that started after this date in UTC ISO 8601 format
:param datetime date_created_before: Read only Participants that started before this date in ISO 8601 format
:param int limit: Upper limit for the number of records to return. stream()
guarantees to never return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, stream() will attempt to read the
limit with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.video.v1.room.room_participant.ParticipantInstance]
"""
limits = self._version.read_limits(limit, page_size)
page = self.page(
status=status,
identity=identity,
date_created_after=date_created_after,
date_created_before=date_created_before,
page_size=limits['page_size'],
)
return self._version.stream(page, limits['limit'])
def list(self, status=values.unset, identity=values.unset,
date_created_after=values.unset, date_created_before=values.unset,
limit=None, page_size=None):
"""
Lists ParticipantInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param ParticipantInstance.Status status: Read only the participants with this status
:param unicode identity: Read only the Participants with this user identity value
:param datetime date_created_after: Read only Participants that started after this date in UTC ISO 8601 format
:param datetime date_created_before: Read only Participants that started before this date in ISO 8601 format
:param int limit: Upper limit for the number of records to return. list() guarantees
never to return more than limit. Default is no limit
:param int page_size: Number of records to fetch per request, when not set will use
the default value of 50 records. If no page_size is defined
but a limit is defined, list() will attempt to read the limit
with the most efficient page size, i.e. min(limit, 1000)
:returns: Generator that will yield up to limit results
:rtype: list[twilio.rest.video.v1.room.room_participant.ParticipantInstance]
"""
return list(self.stream(
status=status,
identity=identity,
date_created_after=date_created_after,
date_created_before=date_created_before,
limit=limit,
page_size=page_size,
))
def page(self, status=values.unset, identity=values.unset,
date_created_after=values.unset, date_created_before=values.unset,
page_token=values.unset, page_number=values.unset,
page_size=values.unset):
"""
Retrieve a single page of ParticipantInstance records from the API.
Request is executed immediately
:param ParticipantInstance.Status status: Read only the participants with this status
:param unicode identity: Read only the Participants with this user identity value
:param datetime date_created_after: Read only Participants that started after this date in UTC ISO 8601 format
:param datetime date_created_before: Read only Participants that started before this date in ISO 8601 format
:param str page_token: PageToken provided by the API
:param int page_number: Page Number, this value is simply for client state
:param int page_size: Number of records to return, defaults to 50
:returns: Page of ParticipantInstance
:rtype: twilio.rest.video.v1.room.room_participant.ParticipantPage
"""
data = values.of({
'Status': status,
'Identity': identity,
'DateCreatedAfter': serialize.iso8601_datetime(date_created_after),
'DateCreatedBefore': serialize.iso8601_datetime(date_created_before),
'PageToken': page_token,
'Page': page_number,
'PageSize': page_size,
})
response = self._version.page(method='GET', uri=self._uri, params=data, )
return ParticipantPage(self._version, response, self._solution)
def get_page(self, target_url):
"""
Retrieve a specific page of ParticipantInstance records from the API.
Request is executed immediately
:param str target_url: API-generated URL for the requested results page
:returns: Page of ParticipantInstance
:rtype: twilio.rest.video.v1.room.room_participant.ParticipantPage
"""
response = self._version.domain.twilio.request(
'GET',
target_url,
)
return ParticipantPage(self._version, response, self._solution)
def get(self, sid):
"""
Constructs a ParticipantContext
:param sid: The SID that identifies the resource to fetch
:returns: twilio.rest.video.v1.room.room_participant.ParticipantContext
:rtype: twilio.rest.video.v1.room.room_participant.ParticipantContext
"""
return ParticipantContext(self._version, room_sid=self._solution['room_sid'], sid=sid, )
def __call__(self, sid):
"""
Constructs a ParticipantContext
:param sid: The SID that identifies the resource to fetch
:returns: twilio.rest.video.v1.room.room_participant.ParticipantContext
:rtype: twilio.rest.video.v1.room.room_participant.ParticipantContext
"""
return ParticipantContext(self._version, room_sid=self._solution['room_sid'], sid=sid, )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Video.V1.ParticipantList>'
class ParticipantPage(Page):
def __init__(self, version, response, solution):
"""
Initialize the ParticipantPage
:param Version version: Version that contains the resource
:param Response response: Response from the API
:param room_sid: The SID of the participant's room
:returns: twilio.rest.video.v1.room.room_participant.ParticipantPage
:rtype: twilio.rest.video.v1.room.room_participant.ParticipantPage
"""
super(ParticipantPage, self).__init__(version, response)
# Path Solution
self._solution = solution
def get_instance(self, payload):
"""
Build an instance of ParticipantInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.video.v1.room.room_participant.ParticipantInstance
:rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance
"""
return ParticipantInstance(self._version, payload, room_sid=self._solution['room_sid'], )
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
return '<Twilio.Video.V1.ParticipantPage>'
class ParticipantContext(InstanceContext):
def __init__(self, version, room_sid, sid):
"""
Initialize the ParticipantContext
:param Version version: Version that contains the resource
:param room_sid: The SID of the room with the Participant resource to fetch
:param sid: The SID that identifies the resource to fetch
:returns: twilio.rest.video.v1.room.room_participant.ParticipantContext
:rtype: twilio.rest.video.v1.room.room_participant.ParticipantContext
"""
super(ParticipantContext, self).__init__(version)
# Path Solution
self._solution = {'room_sid': room_sid, 'sid': sid, }
self._uri = '/Rooms/{room_sid}/Participants/{sid}'.format(**self._solution)
# Dependents
self._published_tracks = None
self._subscribed_tracks = None
self._subscribe_rules = None
def fetch(self):
"""
Fetch the ParticipantInstance
:returns: The fetched ParticipantInstance
:rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance
"""
payload = self._version.fetch(method='GET', uri=self._uri, )
return ParticipantInstance(
self._version,
payload,
room_sid=self._solution['room_sid'],
sid=self._solution['sid'],
)
def update(self, status=values.unset):
"""
Update the ParticipantInstance
:param ParticipantInstance.Status status: The new status of the resource
:returns: The updated ParticipantInstance
:rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance
"""
data = values.of({'Status': status, })
payload = self._version.update(method='POST', uri=self._uri, data=data, )
return ParticipantInstance(
self._version,
payload,
room_sid=self._solution['room_sid'],
sid=self._solution['sid'],
)
@property
def published_tracks(self):
"""
Access the published_tracks
:returns: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackList
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackList
"""
if self._published_tracks is None:
self._published_tracks = PublishedTrackList(
self._version,
room_sid=self._solution['room_sid'],
participant_sid=self._solution['sid'],
)
return self._published_tracks
@property
def subscribed_tracks(self):
"""
Access the subscribed_tracks
:returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackList
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackList
"""
if self._subscribed_tracks is None:
self._subscribed_tracks = SubscribedTrackList(
self._version,
room_sid=self._solution['room_sid'],
participant_sid=self._solution['sid'],
)
return self._subscribed_tracks
@property
def subscribe_rules(self):
"""
Access the subscribe_rules
:returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesList
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesList
"""
if self._subscribe_rules is None:
self._subscribe_rules = SubscribeRulesList(
self._version,
room_sid=self._solution['room_sid'],
participant_sid=self._solution['sid'],
)
return self._subscribe_rules
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Video.V1.ParticipantContext {}>'.format(context)
class ParticipantInstance(InstanceResource):
class Status(object):
CONNECTED = "connected"
DISCONNECTED = "disconnected"
def __init__(self, version, payload, room_sid, sid=None):
"""
Initialize the ParticipantInstance
:returns: twilio.rest.video.v1.room.room_participant.ParticipantInstance
:rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance
"""
super(ParticipantInstance, self).__init__(version)
# Marshaled Properties
self._properties = {
'sid': payload.get('sid'),
'room_sid': payload.get('room_sid'),
'account_sid': payload.get('account_sid'),
'status': payload.get('status'),
'identity': payload.get('identity'),
'date_created': deserialize.iso8601_datetime(payload.get('date_created')),
'date_updated': deserialize.iso8601_datetime(payload.get('date_updated')),
'start_time': deserialize.iso8601_datetime(payload.get('start_time')),
'end_time': deserialize.iso8601_datetime(payload.get('end_time')),
'duration': deserialize.integer(payload.get('duration')),
'url': payload.get('url'),
'links': payload.get('links'),
}
# Context
self._context = None
self._solution = {'room_sid': room_sid, 'sid': sid or self._properties['sid'], }
@property
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ParticipantContext for this ParticipantInstance
:rtype: twilio.rest.video.v1.room.room_participant.ParticipantContext
"""
if self._context is None:
self._context = ParticipantContext(
self._version,
room_sid=self._solution['room_sid'],
sid=self._solution['sid'],
)
return self._context
@property
def sid(self):
"""
:returns: The unique string that identifies the resource
:rtype: unicode
"""
return self._properties['sid']
@property
def room_sid(self):
"""
:returns: The SID of the participant's room
:rtype: unicode
"""
return self._properties['room_sid']
@property
def account_sid(self):
"""
:returns: The SID of the Account that created the resource
:rtype: unicode
"""
return self._properties['account_sid']
@property
def status(self):
"""
:returns: The status of the Participant
:rtype: ParticipantInstance.Status
"""
return self._properties['status']
@property
def identity(self):
"""
:returns: The string that identifies the resource's User
:rtype: unicode
"""
return self._properties['identity']
@property
def date_created(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was created
:rtype: datetime
"""
return self._properties['date_created']
@property
def date_updated(self):
"""
:returns: The ISO 8601 date and time in GMT when the resource was last updated
:rtype: datetime
"""
return self._properties['date_updated']
@property
def start_time(self):
"""
:returns: The time of participant connected to the room in ISO 8601 format
:rtype: datetime
"""
return self._properties['start_time']
@property
def end_time(self):
"""
:returns: The time when the participant disconnected from the room in ISO 8601 format
:rtype: datetime
"""
return self._properties['end_time']
@property
def duration(self):
"""
:returns: Duration of time in seconds the participant was connected
:rtype: unicode
"""
return self._properties['duration']
@property
def url(self):
"""
:returns: The absolute URL of the resource
:rtype: unicode
"""
return self._properties['url']
@property
def links(self):
"""
:returns: The URLs of related resources
:rtype: unicode
"""
return self._properties['links']
def fetch(self):
"""
Fetch the ParticipantInstance
:returns: The fetched ParticipantInstance
:rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance
"""
return self._proxy.fetch()
def update(self, status=values.unset):
"""
Update the ParticipantInstance
:param ParticipantInstance.Status status: The new status of the resource
:returns: The updated ParticipantInstance
:rtype: twilio.rest.video.v1.room.room_participant.ParticipantInstance
"""
return self._proxy.update(status=status, )
@property
def published_tracks(self):
"""
Access the published_tracks
:returns: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackList
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_published_track.PublishedTrackList
"""
return self._proxy.published_tracks
@property
def subscribed_tracks(self):
"""
Access the subscribed_tracks
:returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackList
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribed_track.SubscribedTrackList
"""
return self._proxy.subscribed_tracks
@property
def subscribe_rules(self):
"""
Access the subscribe_rules
:returns: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesList
:rtype: twilio.rest.video.v1.room.room_participant.room_participant_subscribe_rule.SubscribeRulesList
"""
return self._proxy.subscribe_rules
def __repr__(self):
"""
Provide a friendly representation
:returns: Machine friendly representation
:rtype: str
"""
context = ' '.join('{}={}'.format(k, v) for k, v in self._solution.items())
return '<Twilio.Video.V1.ParticipantInstance {}>'.format(context)
|
twilio/twilio-python
|
twilio/rest/video/v1/room/room_participant/__init__.py
|
Python
|
mit
| 20,355 |
require "spec_helper"
require "dependency_container"
describe DependencyContainer do
class ExampleClass; end
it "builds object instances from a factory defined by a passed-in block" do
container = DependencyContainer.new
container.define_factory(:example) { ExampleClass.new }
expect(container.get(:example)).to be_a ExampleClass
expect(container.get(:example)).to_not equal container.get(:example)
end
it "fetches registered object instances" do
my_instance = ExampleClass.new
container = DependencyContainer.new
container.define_instance(:example, my_instance)
expect(container.get(:example)).to equal my_instance
end
it "fetches registered object instances defined by block" do
my_instance = ExampleClass.new
container = DependencyContainer.new
container.define_instance(:example) { my_instance }
expect(container.get(:example)).to equal my_instance
end
it "builds a single instance of singleton factories" do
container = DependencyContainer.new
container.define_singleton(:example) { ExampleClass.new }
expect(container.get(:example)).to be_a ExampleClass
expect(container.get(:example)).to equal container.get(:example)
end
it "allows initial wiring to be defined in block passed to constructor" do
container = DependencyContainer.new do
define_singleton(:example) { ExampleClass.new }
end
expect(container.get(:example)).to be_a ExampleClass
end
describe "#inject_into" do
let(:container) {
DependencyContainer.new.tap { |c|
c.define_singleton(:example) { ExampleClass.new }
}
}
let(:target_class) { Class.new }
context "without a visibity option" do
it "injects private helper methods for all defined dependencies" do
container.inject_into(target_class)
expect(target_class.private_instance_methods).to include(:example)
expect(target_class.new.send(:example)).to be_a ExampleClass
end
end
context "with visibility option set to public" do
it "injects private helper methods for all defined dependencies" do
container.inject_into(target_class, visibility: :public)
expect(target_class.public_instance_methods).to include(:example)
expect(target_class.new.send(:example)).to be_a ExampleClass
end
end
context "with visibility option set to protected" do
it "injects protected helper methods for all defined dependencies" do
container.inject_into(target_class, visibility: :protected)
expect(target_class.protected_instance_methods).to include(:example)
expect(target_class.new.send(:example)).to be_a ExampleClass
end
end
end
context "a class with a constructor dependency" do
before(:all) do
class PublishingService
attr_reader :logger
def initialize(logger)
@logger = logger
end
end
MyLogger = Class.new
end
before(:each) do
@container = DependencyContainer.new
@container.define_factory(:publishing_service) do
PublishingService.new(get(:logger))
end
@container.define_factory(:logger) do
MyLogger.new
end
end
it "gives the factory access to the container to allow dependencies to be fetched" do
publishing_service_instance = @container.get(:publishing_service)
expect(publishing_service_instance).to be_a PublishingService
expect(publishing_service_instance.logger).to be_a MyLogger
end
it "can build an object with dependencies based on the initializer's arguments" do
@container.define_factory(:another_publishing_service) do
build_with_dependencies(PublishingService)
end
publishing_service_instance = @container.get(:another_publishing_service)
expect(publishing_service_instance).to be_a PublishingService
expect(publishing_service_instance.logger).to be_a MyLogger
end
it "can build a Struct with dependencies based on the struct members" do
struct = Struct.new(:logger)
@container.define_factory(:my_struct) do
build_with_dependencies(struct)
end
instance = @container.get(:my_struct)
expect(instance).to be_a struct
expect(instance.logger).to be_a MyLogger
end
it "will set optional dependencies if defined" do
my_class = Class.new do
def initialize(logger = nil, not_defined = nil)
end
end
@container.define_factory(:test)
end
end
end
|
ministryofjustice/specialist-publisher
|
spec/dependency_container_spec.rb
|
Ruby
|
mit
| 4,540 |
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM7.07 18.28c.43-.9 3.05-1.78 4.93-1.78s4.51.88 4.93 1.78C15.57 19.36 13.86 20 12 20s-3.57-.64-4.93-1.72zm11.29-1.45c-1.43-1.74-4.9-2.33-6.36-2.33s-4.93.59-6.36 2.33C4.62 15.49 4 13.82 4 12c0-4.41 3.59-8 8-8s8 3.59 8 8c0 1.82-.62 3.49-1.64 4.83zM12 6c-1.94 0-3.5 1.56-3.5 3.5S10.06 13 12 13s3.5-1.56 3.5-3.5S13.94 6 12 6zm0 5c-.83 0-1.5-.67-1.5-1.5S11.17 8 12 8s1.5.67 1.5 1.5S12.83 11 12 11z"
}), 'AccountCircleOutlined');
exports.default = _default;
|
oliviertassinari/material-ui
|
packages/mui-icons-material/lib/AccountCircleOutlined.js
|
JavaScript
|
mit
| 934 |
package fuzzytime
// DateTime represents a set of fields for date and time, any of which may
// be unset. The default initialisation is a valid empty datetime with no
// fields set.
type DateTime struct {
Date
Time
}
// Equals returns true if dates and times match
func (dt *DateTime) Equals(other *DateTime) bool {
return dt.Date.Equals(&other.Date) && dt.Time.Equals(&other.Time)
}
// String returns "YYYY-MM-DD hh:mm:ss tz" with question marks in place of
// any missing values (except for timezone, which will be blank if missing)
func (dt *DateTime) String() string {
return dt.Date.String() + " " + dt.Time.String()
}
// Empty tests if datetime is blank (ie all fields unset)
func (dt *DateTime) Empty() bool {
return dt.Time.Empty() && dt.Date.Empty()
}
// ISOFormat returns the most precise-possible datetime given the available
// data.
// Aims for "YYYY-MM-DDTHH:MM:SS+TZ" but will drop off
// higher-precision components as required eg "YYYY-MM"
func (dt *DateTime) ISOFormat() string {
if dt.Time.Empty() {
// just the date.
return dt.Date.ISOFormat()
}
return dt.Date.ISOFormat() + "T" + dt.Time.ISOFormat()
}
// HasFullDate returns true if Year, Month and Day are all set
func (dt *DateTime) HasFullDate() bool {
return dt.HasYear() && dt.HasMonth() && dt.HasDay()
}
// Conflicts returns true if the two datetimes conflict.
// Note that this is not the same as the two being equal - one
// datetime can be more precise than the other. They are only in
// conflict if they have different values set for the same field.
// eg "2012-01-01T03:34:10" doesn't conflict with "03:34"
func (dt *DateTime) Conflicts(other *DateTime) bool {
return dt.Time.Conflicts(&other.Time) || dt.Date.Conflicts(&other.Date)
}
|
cardigann/cardigann
|
vendor/github.com/bcampbell/fuzzytime/datetime.go
|
GO
|
mit
| 1,739 |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using UnityEngine;
public class LogUploader : MonoBehaviour
{
public string log { get; private set; }
public IRCConnection ircConnection = null;
[HideInInspector]
public string analysisUrl = null;
[HideInInspector]
public bool postOnComplete = false;
[HideInInspector]
public string LOGPREFIX;
private string output;
private OrderedDictionary domainNames = new OrderedDictionary
{
// In order of preference (favourite first)
// The integer value is the data size limit in bytes
{ "hastebin.com", 400000 },
{ "ktane.w00ty.com", 2000000 }
};
public void OnEnable()
{
LOGPREFIX = "[" + GetType().Name + "] ";
Application.logMessageReceived += HandleLog;
}
public void OnDisable()
{
Application.logMessageReceived -= HandleLog;
}
public void Clear()
{
log = "";
}
public string Flush()
{
string result = log;
log = "";
return result;
}
public void Post(bool postToChat = true)
{
analysisUrl = null;
postOnComplete = false;
StartCoroutine( DoPost(log, postToChat) );
}
private IEnumerator DoPost(string data, bool postToChat)
{
// This first line is necessary as the Log Analyser uses it as an identifier
data = "Initialize engine version: Twitch Plays\n" + data;
byte[] encodedData = System.Text.Encoding.UTF8.GetBytes(data);
int dataLength = encodedData.Length;
bool tooLong = false;
foreach (DictionaryEntry domain in domainNames)
{
string domainName = (string)domain.Key;
int maxLength = (int)domain.Value;
tooLong = false;
if (dataLength >= maxLength)
{
Debug.LogFormat(LOGPREFIX + "Data ({0}B) is too long for {1} ({2}B)", dataLength, domainName, maxLength);
tooLong = true;
continue;
}
Debug.Log(LOGPREFIX + "Posting new log to " + domainName);
string url = "https://" + domainName + "/documents";
WWW www = new WWW(url, encodedData);
yield return www;
if (www.error == null)
{
// example result
// {"key":"oxekofidik"}
string key = www.text;
key = key.Substring(0, key.Length - 2);
key = key.Substring(key.LastIndexOf("\"") + 1);
string rawUrl = "https://" + domainName + "/raw/" + key;
Debug.Log(LOGPREFIX + "Paste now available at " + rawUrl);
analysisUrl = TwitchPlaysService.urlHelper.LogAnalyserFor(rawUrl);
if (postOnComplete)
{
PostToChat();
}
break;
}
else
{
Debug.Log(LOGPREFIX + "Error: " + www.error);
}
}
if (tooLong)
{
ircConnection.SendMessage("BibleThump The bomb log is too big to upload to any of the supported services, sorry!");
}
yield break;
}
public bool PostToChat(string format = "Analysis for this bomb: {0}", string emote = "copyThis")
{
if (string.IsNullOrEmpty(analysisUrl))
{
Debug.Log(LOGPREFIX + "No analysis URL available, can't post to chat");
return false;
}
Debug.Log(LOGPREFIX + "Posting analysis URL to chat");
emote = " " + emote + " ";
ircConnection.SendMessage(string.Format(emote + format, analysisUrl));
return true;
}
private void HandleLog(string message, string stackTrace, LogType type)
{
log += message + "\n";
}
}
|
CaitSith2/ktanemod-twitchplays
|
Assets/Scripts/Helpers/LogUploader.cs
|
C#
|
mit
| 3,929 |
/*
Ratings and how they work:
-2: Extremely detrimental
The sort of ability that relegates Pokemon with Uber-level BSTs
into NU.
ex. Slow Start, Truant
-1: Detrimental
An ability that does more harm than good.
ex. Defeatist, Normalize
0: Useless
An ability with no net effect on a Pokemon during a battle.
ex. Pickup, Illuminate
1: Ineffective
An ability that has a minimal effect. Should never be chosen over
any other ability.
ex. Damp, Shell Armor
2: Situationally useful
An ability that can be useful in certain situations.
ex. Blaze, Insomnia
3: Useful
An ability that is generally useful.
ex. Volt Absorb, Iron Fist
4: Very useful
One of the most popular abilities. The difference between 3 and 4
can be ambiguous.
ex. Technician, Protean
5: Essential
The sort of ability that defines metagames.
ex. Drizzle, Shadow Tag
*/
exports.BattleAbilities = {
"adaptability": {
desc: "This Pokemon's attacks that receive STAB (Same Type Attack Bonus) are increased from 50% to 100%.",
shortDesc: "This Pokemon's same-type attack bonus (STAB) is increased from 1.5x to 2x.",
onModifyMove: function (move) {
move.stab = 2;
},
id: "adaptability",
name: "Adaptability",
rating: 3.5,
num: 91
},
"aftermath": {
desc: "If a contact move knocks out this Pokemon, the opponent receives damage equal to one-fourth of its max HP.",
shortDesc: "If this Pokemon is KOed with a contact move, that move's user loses 1/4 its max HP.",
id: "aftermath",
name: "Aftermath",
onAfterDamageOrder: 1,
onAfterDamage: function (damage, target, source, move) {
if (source && source !== target && move && move.isContact && !target.hp) {
this.damage(source.maxhp / 4, source, target, null, true);
}
},
rating: 3,
num: 106
},
"aerilate": {
desc: "Turns all of this Pokemon's Normal-typed attacks into Flying-type and deal 1.3x damage. Does not affect Hidden Power.",
shortDesc: "This Pokemon's Normal moves become Flying-type and do 1.3x damage.",
onModifyMove: function (move, pokemon) {
if (move.type === 'Normal' && move.id !== 'hiddenpower') {
move.type = 'Flying';
if (move.category !== 'Status') pokemon.addVolatile('aerilate');
}
},
effect: {
duration: 1,
onBasePowerPriority: 8,
onBasePower: function (basePower, pokemon, target, move) {
return this.chainModify([0x14CD, 0x1000]);
}
},
id: "aerilate",
name: "Aerilate",
rating: 3,
num: 185
},
"airlock": {
desc: "While this Pokemon is active, all weather conditions and their effects are disabled.",
shortDesc: "While this Pokemon is active, all weather conditions and their effects are disabled.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Air Lock');
},
onAnyModifyPokemon: function (pokemon) {
pokemon.ignore['WeatherTarget'] = true;
},
onAnyTryWeather: false,
id: "airlock",
name: "Air Lock",
rating: 3,
num: 76
},
"analytic": {
desc: "This Pokemon's attacks do 1.3x damage if it is the last to move in a turn.",
shortDesc: "If the user moves last, the power of that move is increased by 30%.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (!this.willMove(defender)) {
this.debug('Analytic boost');
return this.chainModify([0x14CD, 0x1000]); // The Analytic modifier is slightly higher than the normal 1.3 (0x14CC)
}
},
id: "analytic",
name: "Analytic",
rating: 1,
num: 148
},
"angerpoint": {
desc: "If this Pokemon, and not its Substitute, is struck by a Critical Hit, its Attack is boosted to six stages.",
shortDesc: "If this Pokemon is hit by a critical hit, its Attack is boosted by 12.",
onCriticalHit: function (target) {
if (!target.volatiles['substitute']) {
target.setBoost({atk: 6});
this.add('-setboost', target, 'atk', 12, '[from] ability: Anger Point');
}
},
id: "angerpoint",
name: "Anger Point",
rating: 2,
num: 83
},
"anticipation": {
desc: "A warning is displayed if an opposing Pokemon has the moves Fissure, Guillotine, Horn Drill, Sheer Cold, or any attacking move from a type that is considered super effective against this Pokemon (including Counter, Mirror Coat, and Metal Burst). Hidden Power, Judgment, Natural Gift and Weather Ball are considered Normal-type moves. Flying Press is considered a Fighting-type move.",
shortDesc: "On switch-in, this Pokemon shudders if any foe has a super effective or OHKO move.",
onStart: function (pokemon) {
var targets = pokemon.side.foe.active;
for (var i = 0; i < targets.length; i++) {
if (!targets[i] || targets[i].fainted) continue;
for (var j = 0; j < targets[i].moveset.length; j++) {
var move = this.getMove(targets[i].moveset[j].move);
if (move.category !== 'Status' && (this.getImmunity(move.type, pokemon) && this.getEffectiveness(move.type, pokemon) > 0 || move.ohko)) {
this.add('-activate', pokemon, 'ability: Anticipation');
return;
}
}
}
},
id: "anticipation",
name: "Anticipation",
rating: 1,
num: 107
},
"arenatrap": {
desc: "When this Pokemon enters the field, its opponents cannot switch or flee the battle unless they are part Flying-type, have the Levitate ability, are holding Shed Shell, or they use the moves Baton Pass or U-Turn. Flying-type and Levitate Pokemon cannot escape if they are holding Iron Ball or Gravity is in effect. Levitate Pokemon also cannot escape if their ability is disabled through other means, such as Skill Swap or Gastro Acid.",
shortDesc: "Prevents foes from switching out normally unless they have immunity to Ground.",
onFoeModifyPokemon: function (pokemon) {
if (!this.isAdjacent(pokemon, this.effectData.target)) return;
if (!pokemon.runImmunity('Ground', false)) return;
if (!pokemon.hasType('Flying') || pokemon.hasType('ironball') || this.getPseudoWeather('gravity') || pokemon.volatiles['ingrain']) {
pokemon.tryTrap(true);
}
},
onFoeMaybeTrapPokemon: function (pokemon, source) {
if (!source) source = this.effectData.target;
if (!this.isAdjacent(pokemon, source)) return;
if (!pokemon.runImmunity('Ground', false)) return;
if (!pokemon.hasType('Flying') || pokemon.hasType('ironball') || this.getPseudoWeather('gravity') || pokemon.volatiles['ingrain']) {
pokemon.maybeTrapped = true;
}
},
id: "arenatrap",
name: "Arena Trap",
rating: 5,
num: 71
},
"aromaveil": {
desc: "Protects this Pokemon and its allies from Attract, Disable, Encore, Heal Block, Taunt, and Torment.",
shortDesc: "Protects from Attract, Disable, Encore, Heal Block, Taunt, and Torment.",
onAllyTryHit: function (target, source, move) {
if (move && move.id in {attract:1, disable:1, encore:1, healblock:1, taunt:1, torment:1}) {
return false;
}
},
id: "aromaveil",
name: "Aroma Veil",
rating: 3,
num: 165
},
"aurabreak": {
desc: "Reverses the effect of Dark Aura and Fairy Aura.",
shortDesc: "Reverses the effect of Aura abilities.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Aura Break');
},
onAnyTryPrimaryHit: function (target, source, move) {
if (target === source || move.category === 'Status') return;
source.addVolatile('aurabreak');
},
effect: {
duration: 1
},
id: "aurabreak",
name: "Aura Break",
rating: 2,
num: 188
},
"baddreams": {
desc: "If asleep, each of this Pokemon's opponents receives damage equal to one-eighth of its max HP.",
shortDesc: "Causes sleeping adjacent foes to lose 1/8 of their max HP at the end of each turn.",
onResidualOrder: 26,
onResidualSubOrder: 1,
onResidual: function (pokemon) {
if (!pokemon.hp) return;
for (var i = 0; i < pokemon.side.foe.active.length; i++) {
var target = pokemon.side.foe.active[i];
if (!target || !target.hp) continue;
if (target.status === 'slp') {
this.damage(target.maxhp / 8, target);
}
}
},
id: "baddreams",
name: "Bad Dreams",
rating: 2,
num: 123
},
"battlearmor": {
desc: "This Pokemon cannot be struck by a critical hit.",
shortDesc: "Critical Hits cannot strike this Pokemon.",
onCriticalHit: false,
id: "battlearmor",
name: "Battle Armor",
rating: 1,
num: 4
},
"bigpecks": {
desc: "Prevents other Pokemon from lowering this Pokemon's Defense.",
shortDesc: "Prevents the Pokemon's Defense stat from being reduced.",
onBoost: function (boost, target, source, effect) {
if (source && target === source) return;
if (boost['def'] && boost['def'] < 0) {
boost['def'] = 0;
if (!effect.secondaries) this.add("-fail", target, "unboost", "Defense", "[from] ability: Big Pecks", "[of] " + target);
}
},
id: "bigpecks",
name: "Big Pecks",
rating: 1,
num: 145
},
"blaze": {
desc: "When its health reaches one-third or less of its max HP, this Pokemon's Fire-type attacks receive a 50% boost in power.",
shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Fire attacks do 1.5x damage.",
onModifyAtkPriority: 5,
onModifyAtk: function (atk, attacker, defender, move) {
if (move.type === 'Fire' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Blaze boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA: function (atk, attacker, defender, move) {
if (move.type === 'Fire' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Blaze boost');
return this.chainModify(1.5);
}
},
id: "blaze",
name: "Blaze",
rating: 2,
num: 66
},
"bulletproof": {
desc: "This Pokemon is protected from some Ball and Bomb moves.",
shortDesc: "This Pokemon is protected from ball and bomb moves.",
onTryHit: function (pokemon, target, move) {
if (move.flags && move.flags['bullet']) {
this.add('-immune', pokemon, '[msg]', '[from] Bulletproof');
return null;
}
},
id: "bulletproof",
name: "Bulletproof",
rating: 3,
num: 171
},
"cheekpouch": {
desc: "Restores HP when this Pokemon consumes a berry.",
shortDesc: "Restores HP when this Pokemon consumes a berry.",
onEatItem: function (item, pokemon) {
this.heal(pokemon.maxhp / 3);
},
id: "cheekpouch",
name: "Cheek Pouch",
rating: 2,
num: 167
},
"chlorophyll": {
desc: "If this Pokemon is active while Sunny Day is in effect, its speed is temporarily doubled.",
shortDesc: "If Sunny Day is active, this Pokemon's Speed is doubled.",
onModifySpe: function (speMod) {
if (this.isWeather(['sunnyday', 'desolateland'])) {
return this.chain(speMod, 2);
}
},
id: "chlorophyll",
name: "Chlorophyll",
rating: 2,
num: 34
},
"clearbody": {
desc: "Opponents cannot reduce this Pokemon's stats; they can, however, modify stat changes with Power Swap, Guard Swap and Heart Swap and inflict stat boosts with Swagger and Flatter. This ability does not prevent self-inflicted stat reductions.",
shortDesc: "Prevents other Pokemon from lowering this Pokemon's stat stages.",
onBoost: function (boost, target, source, effect) {
if (source && target === source) return;
var showMsg = false;
for (var i in boost) {
if (boost[i] < 0) {
delete boost[i];
showMsg = true;
}
}
if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: Clear Body", "[of] " + target);
},
id: "clearbody",
name: "Clear Body",
rating: 2,
num: 29
},
"cloudnine": {
desc: "While this Pokemon is active, all weather conditions and their effects are disabled.",
shortDesc: "While this Pokemon is active, all weather conditions and their effects are disabled.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Cloud Nine');
},
onAnyModifyPokemon: function (pokemon) {
pokemon.ignore['WeatherTarget'] = true;
},
onAnyTryWeather: false,
id: "cloudnine",
name: "Cloud Nine",
rating: 3,
num: 13
},
"colorchange": {
desc: "This Pokemon's type changes according to the type of the last move that hit this Pokemon.",
shortDesc: "This Pokemon's type changes to match the type of the last move that hit it.",
onAfterMoveSecondary: function (target, source, move) {
if (target.isActive && move && move.effectType === 'Move' && move.category !== 'Status') {
if (!target.hasType(move.type)) {
if (!target.setType(move.type)) return false;
this.add('-start', target, 'typechange', move.type, '[from] Color Change');
target.update();
}
}
},
id: "colorchange",
name: "Color Change",
rating: 2,
num: 16
},
"competitive": {
desc: "Raises the user's Special Attack stat by two stages when a stat is lowered, including the Special Attack stat. This does not include self-induced stat drops like those from Close Combat.",
shortDesc: "This Pokemon's SpAtk is boosted by 2 for each of its stats that is lowered by a foe.",
onAfterEachBoost: function (boost, target, source) {
if (!source || target.side === source.side) {
return;
}
var statsLowered = false;
for (var i in boost) {
if (boost[i] < 0) {
statsLowered = true;
}
}
if (statsLowered) {
this.boost({spa: 2});
}
},
id: "competitive",
name: "Competitive",
rating: 2,
num: 172
},
"compoundeyes": {
desc: "The accuracy of this Pokemon's moves receives a 30% increase; for example, a 75% accurate move becomes 97.5% accurate.",
shortDesc: "This Pokemon's moves have their accuracy boosted to 1.3x.",
onSourceAccuracy: function (accuracy) {
if (typeof accuracy !== 'number') return;
this.debug('compoundeyes - enhancing accuracy');
return accuracy * 1.3;
},
id: "compoundeyes",
name: "Compound Eyes",
rating: 3.5,
num: 14
},
"contrary": {
desc: "If this Pokemon has a stat boosted it is lowered instead, and vice versa.",
shortDesc: "Stat changes are inverted.",
onBoost: function (boost) {
for (var i in boost) {
boost[i] *= -1;
}
},
id: "contrary",
name: "Contrary",
rating: 4,
num: 126
},
"cursedbody": {
desc: "30% chance of disabling one of the opponent's moves when attacked. This works even if the attacker is behind a Substitute, but will not activate if the Pokemon with Cursed Body is behind a Substitute.",
shortDesc: "If this Pokemon is hit by an attack, there is a 30% chance that move gets Disabled.",
onAfterDamage: function (damage, target, source, move) {
if (!source || source.volatiles['disable']) return;
if (source !== target && move && move.effectType === 'Move') {
if (this.random(10) < 3) {
source.addVolatile('disable');
}
}
},
id: "cursedbody",
name: "Cursed Body",
rating: 2,
num: 130
},
"cutecharm": {
desc: "If an opponent of the opposite gender directly attacks this Pokemon, there is a 30% chance that the opponent will become Attracted to this Pokemon.",
shortDesc: "30% chance of infatuating Pokemon of the opposite gender if they make contact.",
onAfterDamage: function (damage, target, source, move) {
if (move && move.isContact) {
if (this.random(10) < 3) {
source.addVolatile('attract', target);
}
}
},
id: "cutecharm",
name: "Cute Charm",
rating: 1,
num: 56
},
"damp": {
desc: "While this Pokemon is active, no Pokemon on the field can use Selfdestruct or Explosion.",
shortDesc: "While this Pokemon is active, Selfdestruct, Explosion, and Aftermath do not work.",
id: "damp",
onAnyTryMove: function (target, source, effect) {
if (effect.id === 'selfdestruct' || effect.id === 'explosion') {
this.attrLastMove('[still]');
this.add('-activate', this.effectData.target, 'ability: Damp');
return false;
}
},
onAnyDamage: function (damage, target, source, effect) {
if (effect && effect.id === 'aftermath') {
return false;
}
},
name: "Damp",
rating: 0.5,
num: 6
},
"darkaura": {
desc: "Increases the power of all Dark-type moves in battle to 1.33x.",
shortDesc: "Increases the power of all Dark-type moves in battle to 1.33x.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Dark Aura');
},
onAnyTryPrimaryHit: function (target, source, move) {
if (target === source || move.category === 'Status') return;
if (move.type === 'Dark') {
source.addVolatile('aura');
}
},
id: "darkaura",
name: "Dark Aura",
rating: 3,
num: 186
},
"defeatist": {
desc: "When this Pokemon has 1/2 or less of its max HP, its Attack and Sp. Atk are halved.",
shortDesc: "Attack and Special Attack are halved when HP is less than half.",
onModifyAtkPriority: 5,
onModifyAtk: function (atk, pokemon) {
if (pokemon.hp < pokemon.maxhp / 2) {
return this.chainModify(0.5);
}
},
onModifySpAPriority: 5,
onModifySpA: function (atk, pokemon) {
if (pokemon.hp < pokemon.maxhp / 2) {
return this.chainModify(0.5);
}
},
onResidual: function (pokemon) {
pokemon.update();
},
id: "defeatist",
name: "Defeatist",
rating: -1,
num: 129
},
"defiant": {
desc: "Raises the user's Attack stat by two stages when a stat is lowered, including the Attack stat. This does not include self-induced stat drops like those from Close Combat.",
shortDesc: "This Pokemon's Attack is boosted by 2 for each of its stats that is lowered by a foe.",
onAfterEachBoost: function (boost, target, source) {
if (!source || target.side === source.side) {
return;
}
var statsLowered = false;
for (var i in boost) {
if (boost[i] < 0) {
statsLowered = true;
}
}
if (statsLowered) {
this.boost({atk: 2});
}
},
id: "defiant",
name: "Defiant",
rating: 2,
num: 128
},
"deltastream": {
desc: "When this Pokemon enters the battlefield, the weather becomes strong winds for as long as this Pokemon remains on the battlefield with Delta Stream.",
shortDesc: "The weather becomes strong winds until this Pokemon leaves battle.",
onStart: function (source) {
this.setWeather('deltastream');
},
onEnd: function (pokemon) {
if (this.weatherData.source !== pokemon) return;
for (var i = 0; i < this.sides.length; i++) {
for (var j = 0; j < this.sides[i].active.length; j++) {
var target = this.sides[i].active[j];
if (target === pokemon) continue;
if (target && target.hp && target.ability === 'deltastream' && target.ignore['Ability'] !== true) {
this.weatherData.source = target;
return;
}
}
}
this.clearWeather();
},
id: "deltastream",
name: "Delta Stream",
rating: 5,
num: 191
},
"desolateland": {
desc: "When this Pokemon enters the battlefield, the weather becomes harsh sun for as long as this Pokemon remains on the battlefield with Desolate Land.",
shortDesc: "The weather becomes harsh sun until this Pokemon leaves battle.",
onStart: function (source) {
this.setWeather('desolateland');
},
onEnd: function (pokemon) {
if (this.weatherData.source !== pokemon) return;
for (var i = 0; i < this.sides.length; i++) {
for (var j = 0; j < this.sides[i].active.length; j++) {
var target = this.sides[i].active[j];
if (target === pokemon) continue;
if (target && target.hp && target.ability === 'desolateland' && target.ignore['Ability'] !== true) {
this.weatherData.source = target;
return;
}
}
}
this.clearWeather();
},
id: "desolateland",
name: "Desolate Land",
rating: 5,
num: 190
},
"download": {
desc: "If this Pokemon switches into an opponent with equal Defenses or higher Defense than Special Defense, this Pokemon's Special Attack receives a 50% boost. If this Pokemon switches into an opponent with higher Special Defense than Defense, this Pokemon's Attack receive a 50% boost.",
shortDesc: "On switch-in, Attack or Sp. Atk is boosted by 1 based on the foes' weaker Defense.",
onStart: function (pokemon) {
var foeactive = pokemon.side.foe.active;
var totaldef = 0;
var totalspd = 0;
for (var i = 0; i < foeactive.length; i++) {
if (!foeactive[i] || foeactive[i].fainted) continue;
totaldef += foeactive[i].getStat('def', false, true);
totalspd += foeactive[i].getStat('spd', false, true);
}
if (totaldef && totaldef >= totalspd) {
this.boost({spa:1});
} else if (totalspd) {
this.boost({atk:1});
}
},
id: "download",
name: "Download",
rating: 4,
num: 88
},
"drizzle": {
desc: "When this Pokemon enters the battlefield, the weather becomes Rain Dance (for 5 turns normally, or 8 turns while holding Damp Rock).",
shortDesc: "On switch-in, the weather becomes Rain Dance.",
onStart: function (source) {
if (this.isWeather(['desolateland', 'primordialsea', 'deltastream'])) {
this.add('-ability', source, 'Drizzle', '[from] ' + this.effectiveWeather(), '[fail]');
return null;
}
this.setWeather('raindance');
},
id: "drizzle",
name: "Drizzle",
rating: 5,
num: 2
},
"drought": {
desc: "When this Pokemon enters the battlefield, the weather becomes Sunny Day (for 5 turns normally, or 8 turns while holding Heat Rock).",
shortDesc: "On switch-in, the weather becomes Sunny Day.",
onStart: function (source) {
if (this.isWeather(['desolateland', 'primordialsea', 'deltastream'])) {
this.add('-ability', source, 'Drought', '[from] ' + this.effectiveWeather(), '[fail]');
return null;
}
this.setWeather('sunnyday');
},
id: "drought",
name: "Drought",
rating: 5,
num: 70
},
"dryskin": {
desc: "This Pokemon absorbs Water attacks and gains a weakness to Fire attacks. If Sunny Day is in effect, this Pokemon takes damage. If Rain Dance is in effect, this Pokemon recovers health.",
shortDesc: "This Pokemon is healed 1/4 by Water, 1/8 by Rain; is hurt 1.25x by Fire, 1/8 by Sun.",
onTryHit: function (target, source, move) {
if (target !== source && move.type === 'Water') {
if (!this.heal(target.maxhp / 4)) {
this.add('-immune', target, '[msg]');
}
return null;
}
},
onBasePowerPriority: 7,
onFoeBasePower: function (basePower, attacker, defender, move) {
if (this.effectData.target !== defender) return;
if (move.type === 'Fire') {
return this.chainModify(1.25);
}
},
onWeather: function (target, source, effect) {
if (effect.id === 'raindance' || effect.id === 'primordialsea') {
this.heal(target.maxhp / 8);
} else if (effect.id === 'sunnyday' || effect.id === 'desolateland') {
this.damage(target.maxhp / 8);
}
},
id: "dryskin",
name: "Dry Skin",
rating: 3.5,
num: 87
},
"earlybird": {
desc: "This Pokemon will remain asleep for half as long as it normally would; this includes both opponent-induced sleep and user-induced sleep via Rest.",
shortDesc: "This Pokemon's sleep status lasts half as long as usual, self-induced or not.",
id: "earlybird",
name: "Early Bird",
isHalfSleep: true,
rating: 2.5,
num: 48
},
"effectspore": {
desc: "If an opponent directly attacks this Pokemon, there is a 30% chance that the opponent will become either poisoned, paralyzed or put to sleep. There is an equal chance to inflict each status.",
shortDesc: "30% chance of poisoning, paralyzing, or causing sleep on Pokemon making contact.",
onAfterDamage: function (damage, target, source, move) {
if (move && move.isContact && !source.status && source.runImmunity('powder')) {
var r = this.random(100);
if (r < 11) {
source.setStatus('slp', target);
} else if (r < 21) {
source.setStatus('par', target);
} else if (r < 30) {
source.setStatus('psn', target);
}
}
},
id: "effectspore",
name: "Effect Spore",
rating: 2,
num: 27
},
"fairyaura": {
desc: "Increases the power of all Fairy-type moves in battle to 1.33x.",
shortDesc: "Increases the power of all Fairy-type moves in battle to 1.33x.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Fairy Aura');
},
onAnyTryPrimaryHit: function (target, source, move) {
if (target === source || move.category === 'Status') return;
if (move.type === 'Fairy') {
source.addVolatile('aura');
}
},
id: "fairyaura",
name: "Fairy Aura",
rating: 3,
num: 187
},
"filter": {
desc: "This Pokemon receives one-fourth reduced damage from Super Effective attacks.",
shortDesc: "This Pokemon receives 3/4 damage from super effective attacks.",
onSourceModifyDamage: function (damage, source, target, move) {
if (target.runEffectiveness(move) > 0) {
this.debug('Filter neutralize');
return this.chainModify(0.75);
}
},
id: "filter",
name: "Filter",
rating: 3,
num: 111
},
"flamebody": {
desc: "If an opponent directly attacks this Pokemon, there is a 30% chance that the opponent will become burned.",
shortDesc: "30% chance of burning a Pokemon making contact with this Pokemon.",
onAfterDamage: function (damage, target, source, move) {
if (move && move.isContact) {
if (this.random(10) < 3) {
source.trySetStatus('brn', target, move);
}
}
},
id: "flamebody",
name: "Flame Body",
rating: 2,
num: 49
},
"flareboost": {
desc: "When the user with this ability is burned, its Special Attack is raised by 50%.",
shortDesc: "When this Pokemon is burned, its special attacks do 1.5x damage.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (attacker.status === 'brn' && move.category === 'Special') {
return this.chainModify(1.5);
}
},
id: "flareboost",
name: "Flare Boost",
rating: 3,
num: 138
},
"flashfire": {
desc: "This Pokemon is immune to all Fire-type attacks; additionally, its own Fire-type attacks receive a 50% boost if a Fire-type move hits this Pokemon. Multiple boosts do not occur if this Pokemon is hit with multiple Fire-type attacks.",
shortDesc: "This Pokemon's Fire attacks do 1.5x damage if hit by one Fire move; Fire immunity.",
onTryHit: function (target, source, move) {
if (target !== source && move.type === 'Fire') {
move.accuracy = true;
if (!target.addVolatile('flashfire')) {
this.add('-immune', target, '[msg]');
}
return null;
}
},
effect: {
noCopy: true, // doesn't get copied by Baton Pass
onStart: function (target) {
this.add('-start', target, 'ability: Flash Fire');
},
onModifyAtkPriority: 5,
onModifyAtk: function (atk, attacker, defender, move) {
if (move.type === 'Fire') {
this.debug('Flash Fire boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA: function (atk, attacker, defender, move) {
if (move.type === 'Fire') {
this.debug('Flash Fire boost');
return this.chainModify(1.5);
}
}
},
id: "flashfire",
name: "Flash Fire",
rating: 3,
num: 18
},
"flowergift": {
desc: "If this Pokemon is active while Sunny Day is in effect, its Attack and Special Defense stats (as well as its partner's stats in double battles) receive a 50% boost.",
shortDesc: "If user is Cherrim and Sunny Day is active, it and allies' Attack and Sp. Def are 1.5x.",
onStart: function (pokemon) {
delete this.effectData.forme;
},
onUpdate: function (pokemon) {
if (!pokemon.isActive || pokemon.speciesid !== 'cherrim') return;
if (this.isWeather(['sunnyday', 'desolateland'])) {
if (this.effectData.forme !== 'Sunshine') {
this.effectData.forme = 'Sunshine';
this.add('-formechange', pokemon, 'Cherrim-Sunshine', '[msg]');
}
} else {
if (this.effectData.forme) {
delete this.effectData.forme;
this.add('-formechange', pokemon, 'Cherrim', '[msg]');
}
}
},
onModifyAtkPriority: 3,
onAllyModifyAtk: function (atk) {
if (this.effectData.target.template.speciesid !== 'cherrim') return;
if (this.isWeather(['sunnyday', 'desolateland'])) {
return this.chainModify(1.5);
}
},
onModifySpDPriority: 4,
onAllyModifySpD: function (spd) {
if (this.effectData.target.template.speciesid !== 'cherrim') return;
if (this.isWeather(['sunnyday', 'desolateland'])) {
return this.chainModify(1.5);
}
},
id: "flowergift",
name: "Flower Gift",
rating: 3,
num: 122
},
"flowerveil": {
desc: "Prevents ally Grass-type Pokemon from being statused or having their stats lowered.",
shortDesc: "Prevents lowering of ally Grass-type Pokemon's stats.",
onAllyBoost: function (boost, target, source, effect) {
if ((source && target === source) || !target.hasType('Grass')) return;
var showMsg = false;
for (var i in boost) {
if (boost[i] < 0) {
delete boost[i];
showMsg = true;
}
}
if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: Flower Veil", "[of] " + target);
},
onAllySetStatus: function (status, target) {
if (target.hasType('Grass')) return false;
},
id: "flowerveil",
name: "Flower Veil",
rating: 0,
num: 166
},
"forecast": {
desc: "This Pokemon's type changes according to the current weather conditions: it becomes Fire-type during Sunny Day, Water-type during Rain Dance, Ice-type during Hail and remains its regular type otherwise.",
shortDesc: "Castform's type changes to the current weather condition's type, except Sandstorm.",
onUpdate: function (pokemon) {
if (pokemon.baseTemplate.species !== 'Castform' || pokemon.transformed) return;
var forme = null;
switch (this.effectiveWeather()) {
case 'sunnyday':
case 'desolateland':
if (pokemon.template.speciesid !== 'castformsunny') forme = 'Castform-Sunny';
break;
case 'raindance':
case 'primordialsea':
if (pokemon.template.speciesid !== 'castformrainy') forme = 'Castform-Rainy';
break;
case 'hail':
if (pokemon.template.speciesid !== 'castformsnowy') forme = 'Castform-Snowy';
break;
default:
if (pokemon.template.speciesid !== 'castform') forme = 'Castform';
break;
}
if (pokemon.isActive && forme) {
pokemon.formeChange(forme);
this.add('-formechange', pokemon, forme, '[msg]');
}
},
id: "forecast",
name: "Forecast",
rating: 4,
num: 59
},
"forewarn": {
desc: "On switch-in, this Pokemon is alerted to the foes' move with the highest Base Power.",
shortDesc: "The move with the highest Base Power in the opponent's moveset is revealed.",
onStart: function (pokemon) {
var targets = pokemon.side.foe.active;
var warnMoves = [];
var warnBp = 1;
for (var i = 0; i < targets.length; i++) {
if (targets[i].fainted) continue;
for (var j = 0; j < targets[i].moveset.length; j++) {
var move = this.getMove(targets[i].moveset[j].move);
var bp = move.basePower;
if (move.ohko) bp = 160;
if (move.id === 'counter' || move.id === 'metalburst' || move.id === 'mirrorcoat') bp = 120;
if (!bp && move.category !== 'Status') bp = 80;
if (bp > warnBp) {
warnMoves = [[move, targets[i]]];
warnBp = bp;
} else if (bp === warnBp) {
warnMoves.push([move, targets[i]]);
}
}
}
if (!warnMoves.length) return;
var warnMove = warnMoves[this.random(warnMoves.length)];
this.add('-activate', pokemon, 'ability: Forewarn', warnMove[0], warnMove[1]);
},
id: "forewarn",
name: "Forewarn",
rating: 1,
num: 108
},
"friendguard": {
desc: "Reduces the damage received from an ally in a double or triple battle.",
shortDesc: "This Pokemon's allies receive 3/4 damage from other Pokemon's attacks.",
id: "friendguard",
name: "Friend Guard",
onAnyModifyDamage: function (damage, source, target, move) {
if (target !== this.effectData.target && target.side === this.effectData.target.side) {
this.debug('Friend Guard weaken');
return this.chainModify(0.75);
}
},
rating: 0,
num: 132
},
"frisk": {
desc: "When this Pokemon enters the field, it identifies all the opponent's held items.",
shortDesc: "On switch-in, this Pokemon identifies the foe's held items.",
onStart: function (pokemon) {
var foeactive = pokemon.side.foe.active;
for (var i = 0; i < foeactive.length; i++) {
if (!foeactive[i] || foeactive[i].fainted) continue;
if (foeactive[i].item) {
this.add('-item', foeactive[i], foeactive[i].getItem().name, '[from] ability: Frisk', '[of] ' + pokemon, '[identify]');
}
}
},
id: "frisk",
name: "Frisk",
rating: 1.5,
num: 119
},
"furcoat": {
desc: "This Pokemon's Defense is doubled.",
shortDesc: "This Pokemon's Defense is doubled.",
onModifyDefPriority: 6,
onModifyDef: function (def) {
return this.chainModify(2);
},
id: "furcoat",
name: "Fur Coat",
rating: 3.5,
num: 169
},
"galewings": {
desc: "This Pokemon's Flying-type moves have their priority increased by 1.",
shortDesc: "Gives priority to Flying-type moves.",
onModifyPriority: function (priority, pokemon, target, move) {
if (move && move.type === 'Flying') return priority + 1;
},
id: "galewings",
name: "Gale Wings",
rating: 4.5,
num: 177
},
"gluttony": {
desc: "This Pokemon consumes its held berry when its health reaches 50% max HP or lower.",
shortDesc: "When this Pokemon has 1/2 or less of its max HP, it uses certain Berries early.",
id: "gluttony",
name: "Gluttony",
rating: 1.5,
num: 82
},
"gooey": {
desc: "Contact with this Pokemon lowers the attacker's Speed stat by 1.",
shortDesc: "Contact with this Pokemon lowers the attacker's Speed.",
onAfterDamage: function (damage, target, source, effect) {
if (effect && effect.isContact) this.boost({spe: -1}, source, target);
},
id: "gooey",
name: "Gooey",
rating: 3,
num: 183
},
"grasspelt": {
desc: "This Pokemon's Defense is boosted in Grassy Terrain.",
shortDesc: "This Pokemon's Defense is boosted in Grassy Terrain.",
onModifyDefPriority: 6,
onModifyDef: function (pokemon) {
if (this.isTerrain('grassyterrain')) return this.chainModify(1.5);
},
id: "grasspelt",
name: "Grass Pelt",
rating: 2,
num: 179
},
"guts": {
desc: "When this Pokemon is poisoned (including Toxic), burned, paralyzed or asleep (including self-induced Rest), its Attack stat receives a 50% boost; the burn status' Attack drop is also ignored.",
shortDesc: "If this Pokemon is statused, its Attack is 1.5x; burn's Attack drop is ignored.",
onModifyAtkPriority: 5,
onModifyAtk: function (atk, pokemon) {
if (pokemon.status) {
return this.chainModify(1.5);
}
},
id: "guts",
name: "Guts",
rating: 3,
num: 62
},
"harvest": {
desc: "When the user uses a held Berry, it has a 50% chance of having it restored at the end of the turn. This chance becomes 100% during Sunny Day.",
shortDesc: "50% chance this Pokemon's Berry is restored at the end of each turn. 100% in Sun.",
id: "harvest",
name: "Harvest",
onResidualOrder: 26,
onResidualSubOrder: 1,
onResidual: function (pokemon) {
if (this.isWeather(['sunnyday', 'desolateland']) || this.random(2) === 0) {
if (pokemon.hp && !pokemon.item && this.getItem(pokemon.lastItem).isBerry) {
pokemon.setItem(pokemon.lastItem);
this.add('-item', pokemon, pokemon.getItem(), '[from] ability: Harvest');
}
}
},
rating: 2,
num: 139
},
"healer": {
desc: "Has a 30% chance of curing an adjacent ally's status ailment at the end of each turn in Double and Triple Battles.",
shortDesc: "30% chance of curing an adjacent ally's status at the end of each turn.",
id: "healer",
name: "Healer",
onResidualOrder: 5,
onResidualSubOrder: 1,
onResidual: function (pokemon) {
var allyActive = pokemon.side.active;
if (allyActive.length === 1) {
return;
}
for (var i = 0; i < allyActive.length; i++) {
if (allyActive[i] && this.isAdjacent(pokemon, allyActive[i]) && allyActive[i].status && this.random(10) < 3) {
allyActive[i].cureStatus();
}
}
},
rating: 0,
num: 131
},
"heatproof": {
desc: "This Pokemon receives half damage from both Fire-type attacks and residual burn damage.",
shortDesc: "This Pokemon receives half damage from Fire-type attacks and burn damage.",
onBasePowerPriority: 7,
onSourceBasePower: function (basePower, attacker, defender, move) {
if (move.type === 'Fire') {
return this.chainModify(0.5);
}
},
onDamage: function (damage, target, source, effect) {
if (effect && effect.id === 'brn') {
return damage / 2;
}
},
id: "heatproof",
name: "Heatproof",
rating: 2.5,
num: 85
},
"heavymetal": {
desc: "The user's weight is doubled. This increases user's base power of Heavy Slam and Heat Crash, as well as damage taken from the opponent's Low Kick and Grass Knot, due to these moves being calculated by the target's weight.",
shortDesc: "This Pokemon's weight is doubled.",
onModifyPokemon: function (pokemon) {
pokemon.weightkg *= 2;
},
id: "heavymetal",
name: "Heavy Metal",
rating: -1,
num: 134
},
"honeygather": {
desc: "If it is not already holding an item, this Pokemon may find and be holding Honey after a battle.",
shortDesc: "No competitive use.",
id: "honeygather",
name: "Honey Gather",
rating: 0,
num: 118
},
"hugepower": {
desc: "This Pokemon's Attack stat is doubled. Therefore, if this Pokemon's Attack stat on the status screen is 200, it effectively has an Attack stat of 400; which is then subject to the full range of stat boosts and reductions.",
shortDesc: "This Pokemon's Attack is doubled.",
onModifyAtkPriority: 5,
onModifyAtk: function (atk) {
return this.chainModify(2);
},
id: "hugepower",
name: "Huge Power",
rating: 5,
num: 37
},
"hustle": {
desc: "This Pokemon's Attack receives a 50% boost but its Physical attacks receive a 20% drop in Accuracy. For example, a 100% accurate move would become an 80% accurate move. The accuracy of moves that never miss, such as Aerial Ace, remains unaffected.",
shortDesc: "This Pokemon's Attack is 1.5x and accuracy of its physical attacks is 0.8x.",
// This should be applied directly to the stat as opposed to chaining witht he others
onModifyAtkPriority: 5,
onModifyAtk: function (atk) {
return this.modify(atk, 1.5);
},
onModifyMove: function (move) {
if (move.category === 'Physical' && typeof move.accuracy === 'number') {
move.accuracy *= 0.8;
}
},
id: "hustle",
name: "Hustle",
rating: 3,
num: 55
},
"hydration": {
desc: "If this Pokemon is active while Rain Dance is in effect, it recovers from poison, paralysis, burn, sleep and freeze at the end of the turn.",
shortDesc: "This Pokemon has its status cured at the end of each turn if Rain Dance is active.",
onResidualOrder: 5,
onResidualSubOrder: 1,
onResidual: function (pokemon) {
if (pokemon.status && this.isWeather(['raindance', 'primordialsea'])) {
this.debug('hydration');
pokemon.cureStatus();
}
},
id: "hydration",
name: "Hydration",
rating: 2,
num: 93
},
"hypercutter": {
desc: "Opponents cannot reduce this Pokemon's Attack stat; they can, however, modify stat changes with Power Swap or Heart Swap and inflict a stat boost with Swagger. This ability does not prevent self-inflicted stat reductions.",
shortDesc: "Prevents other Pokemon from lowering this Pokemon's Attack.",
onBoost: function (boost, target, source, effect) {
if (source && target === source) return;
if (boost['atk'] && boost['atk'] < 0) {
boost['atk'] = 0;
if (!effect.secondaries) this.add("-fail", target, "unboost", "Attack", "[from] ability: Hyper Cutter", "[of] " + target);
}
},
id: "hypercutter",
name: "Hyper Cutter",
rating: 1.5,
num: 52
},
"icebody": {
desc: "If active while Hail is in effect, this Pokemon recovers one-sixteenth of its max HP after each turn. If a non-Ice-type Pokemon receives this ability through Skill Swap, Role Play or the Trace ability, it will not take damage from Hail.",
shortDesc: "If Hail is active, this Pokemon heals 1/16 of its max HP each turn; immunity to Hail.",
onWeather: function (target, source, effect) {
if (effect.id === 'hail') {
this.heal(target.maxhp / 16);
}
},
onImmunity: function (type, pokemon) {
if (type === 'hail') return false;
},
id: "icebody",
name: "Ice Body",
rating: 3,
num: 115
},
"illuminate": {
desc: "When this Pokemon is in the first slot of the player's party, it doubles the rate of wild encounters.",
shortDesc: "No competitive use.",
id: "illuminate",
name: "Illuminate",
rating: 0,
num: 35
},
"illusion": {
desc: "Illusion will change the appearance of the Pokemon to a different species. This is dependent on the last Pokemon in the player's party. Along with the species itself, Illusion is broken when the user is damaged, but is not broken by Substitute, weather conditions, status ailments, or entry hazards. Illusion will replicate the type of Poke Ball, the species name, and the gender of the Pokemon it is masquerading as.",
shortDesc: "This Pokemon appears as the last Pokemon in the party until it takes direct damage.",
onBeforeSwitchIn: function (pokemon) {
pokemon.illusion = null;
var i;
for (i = pokemon.side.pokemon.length - 1; i > pokemon.position; i--) {
if (!pokemon.side.pokemon[i]) continue;
if (!pokemon.side.pokemon[i].fainted) break;
}
if (!pokemon.side.pokemon[i]) return;
if (pokemon === pokemon.side.pokemon[i]) return;
pokemon.illusion = pokemon.side.pokemon[i];
},
// illusion clearing is hardcoded in the damage function
id: "illusion",
name: "Illusion",
rating: 4.5,
num: 149
},
"immunity": {
desc: "This Pokemon cannot be poisoned. Gaining this Ability while poisoned cures it.",
shortDesc: "This Pokemon cannot become poisoned nor Toxic poisoned.",
onUpdate: function (pokemon) {
if (pokemon.status === 'psn' || pokemon.status === 'tox') {
pokemon.cureStatus();
}
},
onImmunity: function (type) {
if (type === 'psn') return false;
},
id: "immunity",
name: "Immunity",
rating: 1,
num: 17
},
"imposter": {
desc: "As soon as the user comes into battle, it Transforms into its opponent, copying the opponent's stats exactly, with the exception of HP. Imposter copies all stat changes on the target originating from moves and abilities such as Swords Dance and Intimidate, but not from items such as Choice Specs. Imposter will not Transform the user if the opponent is an Illusion or if the opponent is behind a Substitute.",
shortDesc: "On switch-in, this Pokemon copies the foe it's facing; stats, moves, types, Ability.",
onStart: function (pokemon) {
var target = pokemon.side.foe.active[pokemon.side.foe.active.length - 1 - pokemon.position];
if (target) {
pokemon.transformInto(target, pokemon);
}
},
id: "imposter",
name: "Imposter",
rating: 5,
num: 150
},
"infiltrator": {
desc: "This Pokemon's moves ignore the target's Light Screen, Mist, Reflect, Safeguard, and Substitute.",
shortDesc: "Ignores Light Screen, Mist, Reflect, Safeguard, and Substitute.",
onModifyMove: function (move) {
move.notSubBlocked = true;
move.ignoreScreens = true;
},
id: "infiltrator",
name: "Infiltrator",
rating: 2.5,
num: 151
},
"innerfocus": {
desc: "This Pokemon cannot be made to flinch.",
shortDesc: "This Pokemon cannot be made to flinch.",
onFlinch: false,
id: "innerfocus",
name: "Inner Focus",
rating: 1,
num: 39
},
"insomnia": {
desc: "This Pokemon cannot be put to sleep; this includes both opponent-induced sleep as well as user-induced sleep via Rest.",
shortDesc: "This Pokemon cannot fall asleep. Gaining this Ability while asleep cures it.",
onUpdate: function (pokemon) {
if (pokemon.status === 'slp') {
pokemon.cureStatus();
}
},
onImmunity: function (type, pokemon) {
if (type === 'slp') return false;
},
id: "insomnia",
name: "Insomnia",
rating: 2,
num: 15
},
"intimidate": {
desc: "When this Pokemon enters the field, the Attack stat of each of its opponents lowers by one stage.",
shortDesc: "On switch-in, this Pokemon lowers adjacent foes' Attack by 1.",
onStart: function (pokemon) {
var foeactive = pokemon.side.foe.active;
for (var i = 0; i < foeactive.length; i++) {
if (!foeactive[i] || !this.isAdjacent(foeactive[i], pokemon)) continue;
if (foeactive[i].volatiles['substitute']) {
// does it give a message?
this.add('-activate', foeactive[i], 'Substitute', 'ability: Intimidate', '[of] ' + pokemon);
} else {
this.add('-ability', pokemon, 'Intimidate', '[of] ' + foeactive[i]);
this.boost({atk: -1}, foeactive[i], pokemon);
}
}
},
id: "intimidate",
name: "Intimidate",
rating: 3.5,
num: 22
},
"ironbarbs": {
desc: "All moves that make contact with the Pokemon with Iron Barbs will damage the user by 1/8 of their maximum HP after damage is dealt.",
shortDesc: "This Pokemon causes other Pokemon making contact to lose 1/8 of their max HP.",
onAfterDamageOrder: 1,
onAfterDamage: function (damage, target, source, move) {
if (source && source !== target && move && move.isContact) {
this.damage(source.maxhp / 8, source, target, null, true);
}
},
id: "ironbarbs",
name: "Iron Barbs",
rating: 3,
num: 160
},
"ironfist": {
desc: "This Pokemon receives a 20% power boost for the following attacks: Bullet Punch, Comet Punch, Dizzy Punch, Drain Punch, Dynamicpunch, Fire Punch, Focus Punch, Hammer Arm, Ice Punch, Mach Punch, Mega Punch, Meteor Mash, Shadow Punch, Sky Uppercut, and Thunderpunch. Sucker Punch, which is known Ambush in Japan, is not boosted.",
shortDesc: "This Pokemon's punch-based attacks do 1.2x damage. Sucker Punch is not boosted.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (move.isPunchAttack) {
this.debug('Iron Fist boost');
return this.chainModify(1.2);
}
},
id: "ironfist",
name: "Iron Fist",
rating: 3,
num: 89
},
"justified": {
desc: "Will raise the user's Attack stat one level when hit by any Dark-type moves. Unlike other abilities with immunity to certain typed moves, the user will still receive damage from the attack. Justified will raise Attack one level for each hit of a multi-hit move like Beat Up.",
shortDesc: "This Pokemon's Attack is boosted by 1 after it is damaged by a Dark-type attack.",
onAfterDamage: function (damage, target, source, effect) {
if (effect && effect.type === 'Dark') {
this.boost({atk:1});
}
},
id: "justified",
name: "Justified",
rating: 2,
num: 154
},
"keeneye": {
desc: "Prevents other Pokemon from lowering this Pokemon's accuracy.",
shortDesc: "This Pokemon's Accuracy cannot be lowered.",
onBoost: function (boost, target, source, effect) {
if (source && target === source) return;
if (boost['accuracy'] && boost['accuracy'] < 0) {
boost['accuracy'] = 0;
if (!effect.secondaries) this.add("-fail", target, "unboost", "accuracy", "[from] ability: Keen Eye", "[of] " + target);
}
},
onModifyMove: function (move) {
move.ignoreEvasion = true;
},
id: "keeneye",
name: "Keen Eye",
rating: 1,
num: 51
},
"klutz": {
desc: "This Pokemon ignores both the positive and negative effects of its held item, other than the speed-halving and EV-enhancing effects of Macho Brace, Power Anklet, Power Band, Power Belt, Power Bracer, Power Lens, and Power Weight. Fling cannot be used.",
shortDesc: "This Pokemon's held item has no effect, except Macho Brace. Fling cannot be used.",
onModifyPokemonPriority: 1,
onModifyPokemon: function (pokemon) {
if (pokemon.getItem().megaEvolves) return;
pokemon.ignore['Item'] = true;
},
id: "klutz",
name: "Klutz",
rating: 0,
num: 103
},
"leafguard": {
desc: "If this Pokemon is active while Sunny Day is in effect, it cannot become poisoned, burned, paralyzed or put to sleep (other than user-induced Rest). Leaf Guard does not heal status effects that existed before Sunny Day came into effect.",
shortDesc: "If Sunny Day is active, this Pokemon cannot be statused and Rest will fail for it.",
onSetStatus: function (pokemon) {
if (this.isWeather(['sunnyday', 'desolateland'])) {
return false;
}
},
onTryHit: function (target, source, move) {
if (move && move.id === 'yawn' && this.isWeather(['sunnyday', 'desolateland'])) {
return false;
}
},
id: "leafguard",
name: "Leaf Guard",
rating: 1,
num: 102
},
"levitate": {
desc: "This Pokemon is immune to Ground-type attacks, Spikes, Toxic Spikes and the Arena Trap ability; it loses these immunities while holding Iron Ball, after using Ingrain or if Gravity is in effect.",
shortDesc: "This Pokemon is immune to Ground; Gravity, Ingrain, Smack Down, Iron Ball nullify it.",
onImmunity: function (type) {
if (type === 'Ground') return false;
},
id: "levitate",
name: "Levitate",
rating: 3.5,
num: 26
},
"lightmetal": {
desc: "The user's weight is halved. This decreases the damage taken from Low Kick and Grass Knot, and also lowers user's base power of Heavy Slam and Heat Crash, due these moves being calculated by the target and user's weight.",
shortDesc: "This Pokemon's weight is halved.",
onModifyPokemon: function (pokemon) {
pokemon.weightkg /= 2;
},
id: "lightmetal",
name: "Light Metal",
rating: 1,
num: 135
},
"lightningrod": {
desc: "During double battles, this Pokemon draws any single-target Electric-type attack to itself. If an opponent uses an Electric-type attack that affects multiple Pokemon, those targets will be hit. This ability does not affect Electric Hidden Power or Judgment. The user is immune to Electric and its Special Attack is increased one stage when hit by one.",
shortDesc: "This Pokemon draws Electric moves to itself to boost Sp. Atk by 1; Electric immunity.",
onTryHit: function (target, source, move) {
if (target !== source && move.type === 'Electric') {
if (!this.boost({spa:1})) {
this.add('-immune', target, '[msg]');
}
return null;
}
},
onAnyRedirectTargetPriority: 1,
onAnyRedirectTarget: function (target, source, source2, move) {
if (move.type !== 'Electric') return;
if (this.validTarget(this.effectData.target, source, move.target)) {
return this.effectData.target;
}
},
id: "lightningrod",
name: "Lightning Rod",
rating: 3.5,
num: 32
},
"limber": {
desc: "This Pokemon cannot be paralyzed. Gaining this Ability while paralyzed cures it.",
shortDesc: "This Pokemon cannot become paralyzed.",
onUpdate: function (pokemon) {
if (pokemon.status === 'par') {
pokemon.cureStatus();
}
},
onImmunity: function (type, pokemon) {
if (type === 'par') return false;
},
id: "limber",
name: "Limber",
rating: 2,
num: 7
},
"liquidooze": {
desc: "When another Pokemon uses Absorb, Drain Punch, Dream Eater, Giga Drain, Leech Life, Leech Seed or Mega Drain against this Pokemon, the attacking Pokemon loses the amount of health that it would have gained.",
shortDesc: "This Pokemon damages those draining HP from it for as much as they would heal.",
id: "liquidooze",
onSourceTryHeal: function (damage, target, source, effect) {
this.debug("Heal is occurring: " + target + " <- " + source + " :: " + effect.id);
var canOoze = {drain: 1, leechseed: 1};
if (canOoze[effect.id]) {
this.damage(damage, null, null, null, true);
return 0;
}
},
name: "Liquid Ooze",
rating: 1,
num: 64
},
"magicbounce": {
desc: "This Pokemon blocks certain status moves and uses the move itself.",
shortDesc: "Non-damaging moves are reflected back at the user.",
id: "magicbounce",
name: "Magic Bounce",
onTryHitPriority: 1,
onTryHit: function (target, source, move) {
if (target === source) return;
if (move.hasBounced) return;
if (typeof move.isBounceable === 'undefined') {
move.isBounceable = !!(move.category === 'Status' && (move.status || move.boosts || move.volatileStatus === 'confusion' || move.forceSwitch));
}
if (move.isBounceable) {
var newMove = this.getMoveCopy(move.id);
newMove.hasBounced = true;
this.useMove(newMove, target, source);
return null;
}
},
onAllyTryHitSide: function (target, source, move) {
if (target.side === source.side) return;
if (move.hasBounced) return;
if (typeof move.isBounceable === 'undefined') {
move.isBounceable = !!(move.category === 'Status' && (move.status || move.boosts || move.volatileStatus === 'confusion' || move.forceSwitch));
}
if (move.isBounceable) {
var newMove = this.getMoveCopy(move.id);
newMove.hasBounced = true;
this.useMove(newMove, target, source);
return null;
}
},
effect: {
duration: 1
},
rating: 5,
num: 156
},
"magicguard": {
desc: "This Pokemon can only be damaged by direct attacks.",
shortDesc: "Prevents all damage except from direct attacks.",
onDamage: function (damage, target, source, effect) {
if (effect.effectType !== 'Move') {
return false;
}
},
id: "magicguard",
name: "Magic Guard",
rating: 4.5,
num: 98
},
"magician": {
desc: "If this Pokemon is not holding an item, it steals the held item of a target it hits with a move.",
shortDesc: "This Pokemon steals the held item of a target it hits with a move.",
onSourceHit: function (target, source, move) {
if (!move || !target) return;
if (target !== source && move.category !== 'Status') {
if (source.item) return;
var yourItem = target.takeItem(source);
if (!yourItem) return;
if (!source.setItem(yourItem)) {
target.item = yourItem.id; // bypass setItem so we don't break choicelock or anything
return;
}
this.add('-item', source, yourItem, '[from] ability: Magician', '[of] ' + target);
}
},
id: "magician",
name: "Magician",
rating: 2,
num: 170
},
"magmaarmor": {
desc: "This Pokemon cannot be frozen. Gaining this Ability while frozen cures it.",
shortDesc: "This Pokemon cannot become frozen.",
onUpdate: function (pokemon) {
if (pokemon.status === 'frz') {
pokemon.cureStatus();
}
},
onImmunity: function (type, pokemon) {
if (type === 'frz') return false;
},
id: "magmaarmor",
name: "Magma Armor",
rating: 0.5,
num: 40
},
"magnetpull": {
desc: "When this Pokemon enters the field, Steel-type opponents cannot switch out nor flee the battle unless they are holding Shed Shell or use attacks like U-Turn or Baton Pass.",
shortDesc: "Prevents Steel-type foes from switching out normally.",
onFoeModifyPokemon: function (pokemon) {
if (pokemon.hasType('Steel') && this.isAdjacent(pokemon, this.effectData.target)) {
pokemon.tryTrap(true);
}
},
onFoeMaybeTrapPokemon: function (pokemon, source) {
if (!source) source = this.effectData.target;
if (pokemon.hasType('Steel') && this.isAdjacent(pokemon, source)) {
pokemon.maybeTrapped = true;
}
},
id: "magnetpull",
name: "Magnet Pull",
rating: 4.5,
num: 42
},
"marvelscale": {
desc: "When this Pokemon becomes burned, poisoned (including Toxic), paralyzed, frozen or put to sleep (including self-induced sleep via Rest), its Defense receives a 50% boost.",
shortDesc: "If this Pokemon is statused, its Defense is 1.5x.",
onModifyDefPriority: 6,
onModifyDef: function (def, pokemon) {
if (pokemon.status) {
return this.chainModify(1.5);
}
},
id: "marvelscale",
name: "Marvel Scale",
rating: 3,
num: 63
},
"megalauncher": {
desc: "Boosts the power of Aura and Pulse moves, such as Aura Sphere and Dark Pulse, by 50%.",
shortDesc: "Boosts the power of Aura/Pulse moves by 50%.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (move.flags && move.flags['pulse']) {
return this.chainModify(1.5);
}
},
id: "megalauncher",
name: "Mega Launcher",
rating: 3,
num: 178
},
"minus": {
desc: "This Pokemon's Special Attack receives a 50% boost in double battles if a partner has the Plus or Minus ability.",
shortDesc: "If an ally has the Ability Plus or Minus, this Pokemon's Sp. Atk is 1.5x.",
onModifySpAPriority: 5,
onModifySpA: function (spa, pokemon) {
var allyActive = pokemon.side.active;
if (allyActive.length === 1) {
return;
}
for (var i = 0; i < allyActive.length; i++) {
if (allyActive[i] && allyActive[i].position !== pokemon.position && !allyActive[i].fainted && allyActive[i].hasAbility(['minus', 'plus'])) {
return this.chainModify(1.5);
}
}
},
id: "minus",
name: "Minus",
rating: 0,
num: 58
},
"moldbreaker": {
desc: "When this Pokemon uses any move, it nullifies the Ability of any active Pokemon that hinder or empower this Pokemon's attacks. These abilities include Battle Armor, Clear Body, Damp, Dry Skin, Filter, Flash Fire, Flower Gift, Heatproof, Herbivore, Hyper Cutter, Immunity, Inner Focus, Insomnia, Keen Eye, Leaf Guard, Levitate, Lightningrod, Limber, Magma Armor, Marvel Scale, Motor Drive, Oblivious, Own Tempo, Sand Veil, Shell Armor, Shield Dust, Simple, Snow Cloak, Solid Rock, Soundproof, Sticky Hold, Storm Drain, Sturdy, Suction Cups, Tangled Feet, Thick Fat, Unaware, Vital Spirit, Volt Absorb, Water Absorb, Water Veil, White Smoke and Wonder Guard.",
shortDesc: "This Pokemon's moves ignore any Ability that could modify the effectiveness.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Mold Breaker');
},
onAllyModifyPokemonPriority: 100,
onAllyModifyPokemon: function (pokemon) {
if (this.activePokemon === this.effectData.target && pokemon !== this.activePokemon) {
pokemon.ignore['Ability'] = 'A';
}
},
onFoeModifyPokemonPriority: 100,
onFoeModifyPokemon: function (pokemon) {
if (this.activePokemon === this.effectData.target) {
pokemon.ignore['Ability'] = 'A';
}
},
id: "moldbreaker",
name: "Mold Breaker",
rating: 3,
num: 104
},
"moody": {
desc: "At the end of each turn, the Pokemon raises a random stat that isn't already +6 by two stages, and lowers a random stat that isn't already -6 by one stage. These stats include accuracy and evasion.",
shortDesc: "Boosts a random stat by 2 and lowers another stat by 1 at the end of each turn.",
onResidualOrder: 26,
onResidualSubOrder: 1,
onResidual: function (pokemon) {
var stats = [], i = '';
var boost = {};
for (var i in pokemon.boosts) {
if (pokemon.boosts[i] < 6) {
stats.push(i);
}
}
if (stats.length) {
i = stats[this.random(stats.length)];
boost[i] = 2;
}
stats = [];
for (var j in pokemon.boosts) {
if (pokemon.boosts[j] > -6 && j !== i) {
stats.push(j);
}
}
if (stats.length) {
i = stats[this.random(stats.length)];
boost[i] = -1;
}
this.boost(boost);
},
id: "moody",
name: "Moody",
rating: 5,
num: 141
},
"motordrive": {
desc: "This Pokemon is immune to all Electric-type moves (including Status moves). If hit by an Electric-type attack, its Speed increases by one stage.",
shortDesc: "This Pokemon's Speed is boosted by 1 if hit by an Electric move; Electric immunity.",
onTryHit: function (target, source, move) {
if (target !== source && move.type === 'Electric') {
if (!this.boost({spe:1})) {
this.add('-immune', target, '[msg]');
}
return null;
}
},
id: "motordrive",
name: "Motor Drive",
rating: 3,
num: 78
},
"moxie": {
desc: "If this Pokemon knocks out another Pokemon with a damaging attack, its Attack is raised by one stage.",
shortDesc: "This Pokemon's Attack is boosted by 1 if it attacks and faints another Pokemon.",
onSourceFaint: function (target, source, effect) {
if (effect && effect.effectType === 'Move') {
this.boost({atk:1}, source);
}
},
id: "moxie",
name: "Moxie",
rating: 4,
num: 153
},
"multiscale": {
desc: "If this Pokemon is at full HP, it takes half damage from attacks.",
shortDesc: "If this Pokemon is at full HP, it takes half damage from attacks.",
onSourceModifyDamage: function (damage, source, target, move) {
if (target.hp >= target.maxhp) {
this.debug('Multiscale weaken');
return this.chainModify(0.5);
}
},
id: "multiscale",
name: "Multiscale",
rating: 4,
num: 136
},
"multitype": {
desc: "If this Pokemon is Arceus, its type and sprite change to match its held Plate. Either way, this Pokemon is holding a Plate, the Plate cannot be taken (such as by Trick or Thief). This ability cannot be Skill Swapped, Role Played or Traced.",
shortDesc: "If this Pokemon is Arceus, its type changes to match its held Plate.",
// Multitype's type-changing itself is implemented in statuses.js
id: "multitype",
name: "Multitype",
rating: 4,
num: 121
},
"mummy": {
desc: "When the user is attacked by a contact move, the opposing Pokemon's ability is turned into Mummy as well. Multitype, Wonder Guard and Mummy itself are the only abilities not affected by Mummy. The effect of Mummy is not removed by Mold Breaker, Turboblaze, or Teravolt.",
shortDesc: "Pokemon making contact with this Pokemon have their Ability changed to Mummy.",
id: "mummy",
name: "Mummy",
onAfterDamage: function (damage, target, source, move) {
if (source && source !== target && move && move.isContact) {
var oldAbility = source.setAbility('mummy', source, 'mummy', true);
if (oldAbility) {
this.add('-endability', source, oldAbility, '[from] Mummy');
this.add('-ability', source, 'Mummy', '[from] Mummy');
this.runEvent('EndAbility', source, oldAbility, 'mummy');
}
}
},
rating: 1,
num: 152
},
"naturalcure": {
desc: "When this Pokemon switches out of battle, it is cured of poison (including Toxic), paralysis, burn, freeze and sleep (including self-induced Rest).",
shortDesc: "This Pokemon has its status cured when it switches out.",
onSwitchOut: function (pokemon) {
pokemon.setStatus('');
},
id: "naturalcure",
name: "Natural Cure",
rating: 4,
num: 30
},
"noguard": {
desc: "Every attack used by or against this Pokemon will always hit, even during evasive two-turn moves such as Fly and Dig.",
shortDesc: "Every move used by or against this Pokemon will always hit.",
onAnyAccuracy: function (accuracy, target, source, move) {
if (move && (source === this.effectData.target || target === this.effectData.target)) {
return true;
}
return accuracy;
},
id: "noguard",
name: "No Guard",
rating: 4,
num: 99
},
"normalize": {
desc: "Makes all of this Pokemon's attacks Normal-typed.",
shortDesc: "This Pokemon's moves all become Normal-typed.",
onModifyMove: function (move) {
if (move.id !== 'struggle') {
move.type = 'Normal';
}
},
id: "normalize",
name: "Normalize",
rating: -1,
num: 96
},
"oblivious": {
desc: "This Pokemon cannot be infatuated (by Attract or Cute Charm) or taunted. Gaining this Ability while afflicted by either condition cures it.",
shortDesc: "This Pokemon cannot be infatuated or taunted. Gaining this Ability cures it.",
onUpdate: function (pokemon) {
if (pokemon.volatiles['attract']) {
pokemon.removeVolatile('attract');
this.add('-end', pokemon, 'move: Attract');
}
if (pokemon.volatiles['taunt']) {
pokemon.removeVolatile('taunt');
// Taunt's volatile already sends the -end message when removed
}
},
onImmunity: function (type, pokemon) {
if (type === 'attract') {
this.add('-immune', pokemon, '[from] Oblivious');
return false;
}
},
onTryHit: function (pokemon, target, move) {
if (move.id === 'captivate' || move.id === 'taunt') {
this.add('-immune', pokemon, '[msg]', '[from] Oblivious');
return null;
}
},
id: "oblivious",
name: "Oblivious",
rating: 0.5,
num: 12
},
"overcoat": {
desc: "In battle, the Pokemon does not take damage from weather conditions like Sandstorm or Hail. It is also immune to powder moves.",
shortDesc: "This Pokemon is immune to residual weather damage, and powder moves.",
onImmunity: function (type, pokemon) {
if (type === 'sandstorm' || type === 'hail' || type === 'powder') return false;
},
id: "overcoat",
name: "Overcoat",
rating: 2,
num: 142
},
"overgrow": {
desc: "When its health reaches one-third or less of its max HP, this Pokemon's Grass-type attacks receive a 50% boost in power.",
shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Grass attacks do 1.5x damage.",
onModifyAtkPriority: 5,
onModifyAtk: function (atk, attacker, defender, move) {
if (move.type === 'Grass' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Overgrow boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA: function (atk, attacker, defender, move) {
if (move.type === 'Grass' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Overgrow boost');
return this.chainModify(1.5);
}
},
id: "overgrow",
name: "Overgrow",
rating: 2,
num: 65
},
"owntempo": {
desc: "This Pokemon cannot be confused. Gaining this Ability while confused cures it.",
shortDesc: "This Pokemon cannot be confused. Gaining this Ability while confused cures it.",
onUpdate: function (pokemon) {
if (pokemon.volatiles['confusion']) {
pokemon.removeVolatile('confusion');
}
},
onImmunity: function (type, pokemon) {
if (type === 'confusion') {
this.add('-immune', pokemon, 'confusion');
return false;
}
},
id: "owntempo",
name: "Own Tempo",
rating: 1,
num: 20
},
"parentalbond": {
desc: "Allows the Pokemon to hit twice with the same move in one turn. Second hit has 0.5x base power. Does not affect Status, multihit, or spread moves (in doubles).",
shortDesc: "Hits twice in one turn. Second hit has 0.5x base power.",
onModifyMove: function (move, pokemon, target) {
if (move.category !== 'Status' && !move.selfdestruct && !move.multihit && ((target.side && target.side.active.length < 2) || move.target in {any:1, normal:1, randomNormal:1})) {
move.multihit = 2;
pokemon.addVolatile('parentalbond');
}
},
effect: {
duration: 1,
onBasePowerPriority: 8,
onBasePower: function (basePower) {
if (this.effectData.hit) {
return this.chainModify(0.5);
} else {
this.effectData.hit = true;
}
}
},
id: "parentalbond",
name: "Parental Bond",
rating: 4.5,
num: 184
},
"pickup": {
desc: "If an opponent uses a consumable item, Pickup will give the Pokemon the item used, if it is not holding an item. If multiple Pickup Pokemon are in play, one will pick up a copy of the used Berry, and may or may not use it immediately. Works on Berries, Gems, Absorb Bulb, Focus Sash, Herbs, Cell Battery, Red Card, and anything that is thrown with Fling.",
shortDesc: "If this Pokemon has no item, it finds one used by an adjacent Pokemon this turn.",
onResidualOrder: 26,
onResidualSubOrder: 1,
onResidual: function (pokemon) {
var foe = pokemon.side.foe.randomActive();
if (!foe) return;
if (!pokemon.item && foe.lastItem && foe.usedItemThisTurn && foe.lastItem !== 'airballoon' && foe.lastItem !== 'ejectbutton') {
pokemon.setItem(foe.lastItem);
foe.lastItem = '';
var item = pokemon.getItem();
this.add('-item', pokemon, item, '[from] Pickup');
if (item.isBerry) pokemon.update();
}
},
id: "pickup",
name: "Pickup",
rating: 0,
num: 53
},
"pickpocket": {
desc: "If this Pokemon has no item, it steals an item off an attacking Pokemon making contact.",
shortDesc: "If this Pokemon has no item, it steals an item off a Pokemon making contact.",
onAfterDamage: function (damage, target, source, move) {
if (source && source !== target && move && move.isContact) {
if (target.item) {
return;
}
var yourItem = source.takeItem(target);
if (!yourItem) {
return;
}
if (!target.setItem(yourItem)) {
source.item = yourItem.id;
return;
}
this.add('-item', target, yourItem, '[from] ability: Pickpocket');
}
},
id: "pickpocket",
name: "Pickpocket",
rating: 1,
num: 124
},
"pixilate": {
desc: "Turns all of this Pokemon's Normal-typed attacks into Fairy-type and deal 1.3x damage. Does not affect Hidden Power.",
shortDesc: "This Pokemon's Normal moves become Fairy-type and do 1.3x damage.",
onModifyMove: function (move, pokemon) {
if (move.type === 'Normal' && move.id !== 'hiddenpower') {
move.type = 'Fairy';
if (move.category !== 'Status') pokemon.addVolatile('pixilate');
}
},
effect: {
duration: 1,
onBasePowerPriority: 8,
onBasePower: function (basePower, pokemon, target, move) {
return this.chainModify([0x14CD, 0x1000]);
}
},
id: "pixilate",
name: "Pixilate",
rating: 3,
num: 182
},
"plus": {
desc: "This Pokemon's Special Attack receives a 50% boost in double battles if a partner has the Plus or Minus ability.",
shortDesc: "If an ally has the Ability Plus or Minus, this Pokemon's Sp. Atk is 1.5x.",
onModifySpAPriority: 5,
onModifySpA: function (spa, pokemon) {
var allyActive = pokemon.side.active;
if (allyActive.length === 1) {
return;
}
for (var i = 0; i < allyActive.length; i++) {
if (allyActive[i] && allyActive[i].position !== pokemon.position && !allyActive[i].fainted && allyActive[i].hasAbility(['minus', 'plus'])) {
return this.chainModify(1.5);
}
}
},
id: "plus",
name: "Plus",
rating: 0,
num: 57
},
"poisonheal": {
desc: "If this Pokemon becomes poisoned (including Toxic), it will recover 1/8 of its max HP after each turn.",
shortDesc: "This Pokemon is healed by 1/8 of its max HP each turn when poisoned; no HP loss.",
onDamage: function (damage, target, source, effect) {
if (effect.id === 'psn' || effect.id === 'tox') {
this.heal(target.maxhp / 8);
return false;
}
},
id: "poisonheal",
name: "Poison Heal",
rating: 4,
num: 90
},
"poisonpoint": {
desc: "If an opponent contact attacks this Pokemon, there is a 30% chance that the opponent will become poisoned.",
shortDesc: "30% chance of poisoning a Pokemon making contact with this Pokemon.",
onAfterDamage: function (damage, target, source, move) {
if (move && move.isContact) {
if (this.random(10) < 3) {
source.trySetStatus('psn', target, move);
}
}
},
id: "poisonpoint",
name: "Poison Point",
rating: 2,
num: 38
},
"poisontouch": {
desc: "This Pokemon's contact attacks have a 30% chance of poisoning the target.",
shortDesc: "This Pokemon's contact moves have a 30% chance of poisoning.",
// upokecenter says this is implemented as an added secondary effect
onModifyMove: function (move) {
if (!move || !move.isContact) return;
if (!move.secondaries) {
move.secondaries = [];
}
move.secondaries.push({
chance: 30,
status: 'psn'
});
},
id: "poisontouch",
name: "Poison Touch",
rating: 2,
num: 143
},
"prankster": {
desc: "This Pokemon's Status moves have their priority increased by 1 stage.",
shortDesc: "This Pokemon's Status moves have their priority increased by 1.",
onModifyPriority: function (priority, pokemon, target, move) {
if (move && move.category === 'Status') {
return priority + 1;
}
},
id: "prankster",
name: "Prankster",
rating: 4.5,
num: 158
},
"pressure": {
desc: "If this Pokemon is the target of a foe's move, that move loses one additional PP.",
shortDesc: "If this Pokemon is the target of a foe's move, that move loses one additional PP.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Pressure');
},
onSourceDeductPP: function (pp, target, source) {
if (target.side === source.side) return;
return pp + 1;
},
id: "pressure",
name: "Pressure",
rating: 1.5,
num: 46
},
"primordialsea": {
desc: "When this Pokemon enters the battlefield, the weather becomes heavy rain for as long as this Pokemon remains on the battlefield with Primordial Sea.",
shortDesc: "The weather becomes heavy rain until this Pokemon leaves battle.",
onStart: function (source) {
this.setWeather('primordialsea');
},
onEnd: function (pokemon) {
if (this.weatherData.source !== pokemon) return;
for (var i = 0; i < this.sides.length; i++) {
for (var j = 0; j < this.sides[i].active.length; j++) {
var target = this.sides[i].active[j];
if (target === pokemon) continue;
if (target && target.hp && target.ability === 'primordialsea' && target.ignore['Ability'] !== true) {
this.weatherData.source = target;
return;
}
}
}
this.clearWeather();
},
id: "primordialsea",
name: "Primordial Sea",
rating: 5,
num: 189
},
"protean": {
desc: "Right before this Pokemon uses a move, it changes its type to match that move. Hidden Power is interpreted as its Hidden Power type, rather than Normal.",
shortDesc: "Right before this Pokemon uses a move, it changes its type to match that move.",
onPrepareHit: function (source, target, move) {
var type = move.type;
if (type && type !== '???' && source.getTypes().join() !== type) {
if (!source.setType(type)) return;
this.add('-start', source, 'typechange', type, '[from] Protean');
}
},
id: "protean",
name: "Protean",
rating: 4,
num: 168
},
"purepower": {
desc: "This Pokemon's Attack stat is doubled. Note that this is the Attack stat itself, not the base Attack stat of its species.",
shortDesc: "This Pokemon's Attack is doubled.",
onModifyAtkPriority: 5,
onModifyAtk: function (atk) {
return this.chainModify(2);
},
id: "purepower",
name: "Pure Power",
rating: 5,
num: 74
},
"quickfeet": {
desc: "When this Pokemon is poisoned (including Toxic), burned, paralyzed, asleep (including self-induced Rest) or frozen, its Speed stat receives a 50% boost; the paralysis status' Speed drop is also ignored.",
shortDesc: "If this Pokemon is statused, its Speed is 1.5x; paralysis' Speed drop is ignored.",
onModifySpe: function (speMod, pokemon) {
if (pokemon.status) {
return this.chain(speMod, 1.5);
}
},
id: "quickfeet",
name: "Quick Feet",
rating: 3,
num: 95
},
"raindish": {
desc: "If the weather is Rain Dance, this Pokemon recovers 1/16 of its max HP after each turn.",
shortDesc: "If the weather is Rain Dance, this Pokemon heals 1/16 of its max HP each turn.",
onWeather: function (target, source, effect) {
if (effect.id === 'raindance' || effect.id === 'primordialsea') {
this.heal(target.maxhp / 16);
}
},
id: "raindish",
name: "Rain Dish",
rating: 1.5,
num: 44
},
"rattled": {
desc: "Raises the user's Speed one stage when hit by a Dark-, Bug-, or Ghost-type move.",
shortDesc: "This Pokemon gets +1 Speed if hit by a Dark-, Bug-, or Ghost-type attack.",
onAfterDamage: function (damage, target, source, effect) {
if (effect && (effect.type === 'Dark' || effect.type === 'Bug' || effect.type === 'Ghost')) {
this.boost({spe:1});
}
},
id: "rattled",
name: "Rattled",
rating: 2,
num: 155
},
"reckless": {
desc: "When this Pokemon uses an attack that causes recoil damage, or an attack that has a chance to cause recoil damage such as Jump Kick and High Jump Kick, the attacks's power receives a 20% boost.",
shortDesc: "This Pokemon's attacks with recoil or crash damage do 1.2x damage; not Struggle.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (move.recoil || move.hasCustomRecoil) {
this.debug('Reckless boost');
return this.chainModify(1.2);
}
},
id: "reckless",
name: "Reckless",
rating: 3,
num: 120
},
"refrigerate": {
desc: "Turns all of this Pokemon's Normal-typed attacks into Ice-typed and deal 1.3x damage. Does not affect Hidden Power.",
shortDesc: "This Pokemon's Normal moves become Ice-type and do 1.3x damage.",
onModifyMove: function (move, pokemon) {
if (move.type === 'Normal' && move.id !== 'hiddenpower') {
move.type = 'Ice';
if (move.category !== 'Status') pokemon.addVolatile('refrigerate');
}
},
effect: {
duration: 1,
onBasePowerPriority: 8,
onBasePower: function (basePower, pokemon, target, move) {
return this.chainModify([0x14CD, 0x1000]);
}
},
id: "refrigerate",
name: "Refrigerate",
rating: 3,
num: 174
},
"regenerator": {
desc: "This Pokemon heals 1/3 of its max HP when it switches out.",
shortDesc: "This Pokemon heals 1/3 of its max HP when it switches out.",
onSwitchOut: function (pokemon) {
pokemon.heal(pokemon.maxhp / 3);
},
id: "regenerator",
name: "Regenerator",
rating: 4,
num: 144
},
"rivalry": {
desc: "This Pokemon's attacks do 1.25x damage if their target is the same gender, but 0.75x if their target is the opposite gender.",
shortDesc: "This Pokemon's attacks do 1.25x on same gender targets; 0.75x on opposite gender.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (attacker.gender && defender.gender) {
if (attacker.gender === defender.gender) {
this.debug('Rivalry boost');
return this.chainModify(1.25);
} else {
this.debug('Rivalry weaken');
return this.chainModify(0.75);
}
}
},
id: "rivalry",
name: "Rivalry",
rating: 0.5,
num: 79
},
"rockhead": {
desc: "This Pokemon does not receive recoil damage except from Struggle, Life Orb, or crash damage from Jump Kick or High Jump Kick.",
shortDesc: "This Pokemon does not take recoil damage besides Struggle, Life Orb, crash damage.",
onModifyMove: function (move) {
delete move.recoil;
},
id: "rockhead",
name: "Rock Head",
rating: 3,
num: 69
},
"roughskin": {
desc: "Causes recoil damage equal to 1/8 of the opponent's max HP if an opponent makes contact.",
shortDesc: "This Pokemon causes other Pokemon making contact to lose 1/8 of their max HP.",
onAfterDamageOrder: 1,
onAfterDamage: function (damage, target, source, move) {
if (source && source !== target && move && move.isContact) {
this.damage(source.maxhp / 8, source, target, null, true);
}
},
id: "roughskin",
name: "Rough Skin",
rating: 3,
num: 24
},
"runaway": {
desc: "Unless this Pokemon is under the effects of a trapping move or ability, such as Mean Look or Shadow Tag, it will escape from wild Pokemon battles without fail.",
shortDesc: "No competitive use.",
id: "runaway",
name: "Run Away",
rating: 0,
num: 50
},
"sandforce": {
desc: "Raises the power of this Pokemon's Rock, Ground, and Steel-type moves by 1.3x if the weather is Sandstorm. This Pokemon is also immune to residual Sandstorm damage.",
shortDesc: "This Pokemon's Rock/Ground/Steel attacks do 1.3x in Sandstorm; immunity to it.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (this.isWeather('sandstorm')) {
if (move.type === 'Rock' || move.type === 'Ground' || move.type === 'Steel') {
this.debug('Sand Force boost');
return this.chainModify([0x14CD, 0x1000]); // The Sand Force modifier is slightly higher than the normal 1.3 (0x14CC)
}
}
},
onImmunity: function (type, pokemon) {
if (type === 'sandstorm') return false;
},
id: "sandforce",
name: "Sand Force",
rating: 2,
num: 159
},
"sandrush": {
desc: "This Pokemon's Speed is doubled if the weather is Sandstorm. This Pokemon is also immune to residual Sandstorm damage.",
shortDesc: "If Sandstorm is active, this Pokemon's Speed is doubled; immunity to Sandstorm.",
onModifySpe: function (speMod, pokemon) {
if (this.isWeather('sandstorm')) {
return this.chain(speMod, 2);
}
},
onImmunity: function (type, pokemon) {
if (type === 'sandstorm') return false;
},
id: "sandrush",
name: "Sand Rush",
rating: 2,
num: 146
},
"sandstream": {
desc: "When this Pokemon enters the battlefield, the weather becomes Sandstorm (for 5 turns normally, or 8 turns while holding Smooth Rock).",
shortDesc: "On switch-in, the weather becomes Sandstorm.",
onStart: function (source) {
if (this.isWeather(['desolateland', 'primordialsea', 'deltastream'])) {
this.add('-ability', source, 'Sand Stream', '[from] ' + this.effectiveWeather(), '[fail]');
return null;
}
this.setWeather('sandstorm');
},
id: "sandstream",
name: "Sand Stream",
rating: 4.5,
num: 45
},
"sandveil": {
desc: "This Pokemon's Evasion is boosted by 1.25x if the weather is Sandstorm. This Pokemon is also immune to residual Sandstorm damage.",
shortDesc: "If Sandstorm is active, this Pokemon's evasion is 1.25x; immunity to Sandstorm.",
onImmunity: function (type, pokemon) {
if (type === 'sandstorm') return false;
},
onAccuracy: function (accuracy) {
if (typeof accuracy !== 'number') return;
if (this.isWeather('sandstorm')) {
this.debug('Sand Veil - decreasing accuracy');
return accuracy * 0.8;
}
},
id: "sandveil",
name: "Sand Veil",
rating: 1.5,
num: 8
},
"sapsipper": {
desc: "This Pokemon is immune to Grass moves. If hit by a Grass move, its Attack is increased by one stage (once for each hit of Bullet Seed). Does not affect Aromatherapy, but the move will still trigger an Attack increase.",
shortDesc: "This Pokemon's Attack is boosted by 1 if hit by any Grass move; Grass immunity.",
onTryHit: function (target, source, move) {
if (target !== source && move.type === 'Grass') {
if (!this.boost({atk:1})) {
this.add('-immune', target, '[msg]');
}
return null;
}
},
onAllyTryHitSide: function (target, source, move) {
if (target.side !== source.side) return;
if (move.type === 'Grass') {
this.boost({atk:1}, this.effectData.target);
}
},
id: "sapsipper",
name: "Sap Sipper",
rating: 3.5,
num: 157
},
"scrappy": {
desc: "This Pokemon has the ability to hit Ghost-type Pokemon with Normal-type and Fighting-type moves. Effectiveness of these moves takes into account the Ghost-type Pokemon's other weaknesses and resistances.",
shortDesc: "This Pokemon can hit Ghost-types with Normal- and Fighting-type moves.",
onModifyMovePriority: -5,
onModifyMove: function (move) {
if (move.type in {'Fighting':1, 'Normal':1}) {
move.affectedByImmunities = false;
}
},
id: "scrappy",
name: "Scrappy",
rating: 3,
num: 113
},
"serenegrace": {
desc: "This Pokemon's moves have their secondary effect chance doubled. For example, if this Pokemon uses Ice Beam, it will have a 20% chance to freeze its target.",
shortDesc: "This Pokemon's moves have their secondary effect chance doubled.",
onModifyMove: function (move) {
if (move.secondaries && move.id !== 'secretpower') {
this.debug('doubling secondary chance');
for (var i = 0; i < move.secondaries.length; i++) {
move.secondaries[i].chance *= 2;
}
}
},
id: "serenegrace",
name: "Serene Grace",
rating: 4,
num: 32
},
"shadowtag": {
desc: "When this Pokemon enters the field, its non-Ghost-type opponents cannot switch or flee the battle unless they have the same ability, are holding Shed Shell, or they use the moves Baton Pass or U-Turn.",
shortDesc: "Prevents foes from switching out normally unless they also have this Ability.",
onFoeModifyPokemon: function (pokemon) {
if (!pokemon.hasAbility('shadowtag') && this.isAdjacent(pokemon, this.effectData.target)) {
pokemon.tryTrap(true);
}
},
onFoeMaybeTrapPokemon: function (pokemon, source) {
if (!source) source = this.effectData.target;
if (!pokemon.hasAbility('shadowtag') && this.isAdjacent(pokemon, source)) {
pokemon.maybeTrapped = true;
}
},
id: "shadowtag",
name: "Shadow Tag",
rating: 5,
num: 23
},
"shedskin": {
desc: "At the end of each turn, this Pokemon has a 33% chance to heal itself from poison (including Toxic), paralysis, burn, freeze or sleep (including self-induced Rest).",
shortDesc: "This Pokemon has a 33% chance to have its status cured at the end of each turn.",
onResidualOrder: 5,
onResidualSubOrder: 1,
onResidual: function (pokemon) {
if (pokemon.hp && pokemon.status && this.random(3) === 0) {
this.debug('shed skin');
this.add('-activate', pokemon, 'ability: Shed Skin');
pokemon.cureStatus();
}
},
id: "shedskin",
name: "Shed Skin",
rating: 4,
num: 61
},
"sheerforce": {
desc: "Raises the base power of all moves that have any secondary effects by 30%, but the secondary effects are ignored. Some side effects of moves, such as recoil, draining, stat reduction, and switching out usually aren't considered secondary effects. If a Pokemon with Sheer Force is holding a Life Orb and uses an attack that would be boosted by Sheer Force, then the move gains both boosts and the user receives no Life Orb recoil (only if the attack is boosted by Sheer Force).",
shortDesc: "This Pokemon's attacks with secondary effects do 1.3x damage; nullifies the effects.",
onModifyMove: function (move, pokemon) {
if (move.secondaries) {
delete move.secondaries;
move.negateSecondary = true;
pokemon.addVolatile('sheerforce');
}
},
effect: {
duration: 1,
onBasePowerPriority: 8,
onBasePower: function (basePower, pokemon, target, move) {
return this.chainModify([0x14CD, 0x1000]); // The Sheer Force modifier is slightly higher than the normal 1.3 (0x14CC)
}
},
id: "sheerforce",
name: "Sheer Force",
rating: 4,
num: 125
},
"shellarmor": {
desc: "Attacks targeting this Pokemon can't be critical hits.",
shortDesc: "This Pokemon cannot be struck by a critical hit.",
onCriticalHit: false,
id: "shellarmor",
name: "Shell Armor",
rating: 1,
num: 75
},
"shielddust": {
desc: "If the opponent uses a move that has secondary effects that affect this Pokemon in addition to damage, the move's secondary effects will not trigger (For example, Ice Beam loses its 10% freeze chance).",
shortDesc: "This Pokemon is not affected by the secondary effect of another Pokemon's attack.",
onTrySecondaryHit: function () {
this.debug('Shield Dust prevent secondary');
return null;
},
id: "shielddust",
name: "Shield Dust",
rating: 2,
num: 19
},
"simple": {
desc: "This Pokemon doubles all of its positive and negative stat modifiers. For example, if this Pokemon uses Curse, its Attack and Defense stats increase by two stages and its Speed stat decreases by two stages.",
shortDesc: "This Pokemon has its own stat boosts and drops doubled as they happen.",
onBoost: function (boost) {
for (var i in boost) {
boost[i] *= 2;
}
},
id: "simple",
name: "Simple",
rating: 4,
num: 86
},
"skilllink": {
desc: "When this Pokemon uses an attack that strikes multiple times in one turn, such as Fury Attack or Spike Cannon, such attacks will always strike for the maximum number of hits.",
shortDesc: "This Pokemon's multi-hit attacks always hit the maximum number of times.",
onModifyMove: function (move) {
if (move.multihit && move.multihit.length) {
move.multihit = move.multihit[1];
}
},
id: "skilllink",
name: "Skill Link",
rating: 4,
num: 92
},
"slowstart": {
desc: "After this Pokemon switches into the battle, its Attack and Speed stats are halved for five turns. For example, if this Pokemon has an Attack stat of 400, its Attack will be 200 until the effects of Slow Start wear off.",
shortDesc: "On switch-in, this Pokemon's Attack and Speed are halved for 5 turns.",
onStart: function (pokemon) {
pokemon.addVolatile('slowstart');
},
effect: {
duration: 5,
onStart: function (target) {
this.add('-start', target, 'Slow Start');
},
onModifyAtkPriority: 5,
onModifyAtk: function (atk, pokemon) {
if (pokemon.ignore['Ability'] === true || pokemon.ability !== 'slowstart') {
pokemon.removeVolatile('slowstart');
return;
}
return this.chainModify(0.5);
},
onModifySpe: function (speMod, pokemon) {
if (pokemon.ignore['Ability'] === true || pokemon.ability !== 'slowstart') {
pokemon.removeVolatile('slowstart');
return;
}
return this.chain(speMod, 0.5);
},
onEnd: function (target) {
this.add('-end', target, 'Slow Start');
}
},
id: "slowstart",
name: "Slow Start",
rating: -2,
num: 112
},
"sniper": {
desc: "When this Pokemon lands a Critical Hit, the damage is increased to another 1.5x.",
shortDesc: "If this Pokemon strikes with a critical hit, the damage is increased by 50%.",
onModifyDamage: function (damage, source, target, move) {
if (move.crit) {
this.debug('Sniper boost');
return this.chainModify(1.5);
}
},
id: "sniper",
name: "Sniper",
rating: 1,
num: 97
},
"snowcloak": {
desc: "This Pokemon's Evasion is boosted by 1.25x if the weather is Hail. This Pokemon is also immune to residual Hail damage.",
shortDesc: "If Hail is active, this Pokemon's evasion is 1.25x; immunity to Hail.",
onImmunity: function (type, pokemon) {
if (type === 'hail') return false;
},
onAccuracy: function (accuracy) {
if (typeof accuracy !== 'number') return;
if (this.isWeather('hail')) {
this.debug('Snow Cloak - decreasing accuracy');
return accuracy * 0.8;
}
},
id: "snowcloak",
name: "Snow Cloak",
rating: 1,
num: 81
},
"snowwarning": {
desc: "When this Pokemon enters the battlefield, the weather becomes Hail (for 5 turns normally, or 8 turns while holding Icy Rock).",
shortDesc: "On switch-in, the weather becomes Hail.",
onStart: function (source) {
if (this.isWeather(['desolateland', 'primordialsea', 'deltastream'])) {
this.add('-ability', source, 'Snow Warning', '[from] ' + this.effectiveWeather(), '[fail]');
return null;
}
this.setWeather('hail');
},
id: "snowwarning",
name: "Snow Warning",
rating: 4,
num: 117
},
"solarpower": {
desc: "If the weather is Sunny Day, this Pokemon's Special Attack is 1.5x, but it loses 1/8 of its max HP at the end of every turn.",
shortDesc: "If Sunny Day is active, this Pokemon's Sp. Atk is 1.5x and loses 1/8 max HP per turn.",
onModifySpAPriority: 5,
onModifySpA: function (spa, pokemon) {
if (this.isWeather(['sunnyday', 'desolateland'])) {
return this.chainModify(1.5);
}
},
onWeather: function (target, source, effect) {
if (effect.id === 'sunnyday' || effect.id === 'desolateland') {
this.damage(target.maxhp / 8);
}
},
id: "solarpower",
name: "Solar Power",
rating: 1.5,
num: 94
},
"solidrock": {
desc: "Super-effective attacks only deal 3/4 their usual damage against this Pokemon.",
shortDesc: "This Pokemon receives 3/4 damage from super effective attacks.",
onSourceModifyDamage: function (damage, source, target, move) {
if (target.runEffectiveness(move) > 0) {
this.debug('Solid Rock neutralize');
return this.chainModify(0.75);
}
},
id: "solidrock",
name: "Solid Rock",
rating: 3,
num: 116
},
"soundproof": {
desc: "This Pokemon is immune to the effects of sound-based moves, which are: Bug Buzz, Chatter, Echoed Voice, Grasswhistle, Growl, Heal Bell, Hyper Voice, Metal Sound, Perish Song, Relic Song, Roar, Round, Screech, Sing, Snarl, Snore, Supersonic, and Uproar. This ability doesn't affect Heal Bell.",
shortDesc: "This Pokemon is immune to sound-based moves, except Heal Bell.",
onTryHit: function (target, source, move) {
if (target !== source && move.isSoundBased) {
this.add('-immune', target, '[msg]');
return null;
}
},
id: "soundproof",
name: "Soundproof",
rating: 2,
num: 43
},
"speedboost": {
desc: "At the end of every turn, this Pokemon's Speed increases by one stage (except the turn it switched in).",
shortDesc: "This Pokemon's Speed is boosted by 1 at the end of each full turn on the field.",
onResidualOrder: 26,
onResidualSubOrder: 1,
onResidual: function (pokemon) {
if (pokemon.activeTurns) {
this.boost({spe:1});
}
},
id: "speedboost",
name: "Speed Boost",
rating: 4.5,
num: 3
},
"stall": {
desc: "This Pokemon moves last among Pokemon using the same or greater priority moves.",
shortDesc: "This Pokemon moves last among Pokemon using the same or greater priority moves.",
onModifyPriority: function (priority) {
return priority - 0.1;
},
id: "stall",
name: "Stall",
rating: -1,
num: 100
},
"stancechange": {
desc: "Only affects Aegislash. If this Pokemon uses a Physical or Special move, it changes to Blade forme. If this Pokemon uses King's Shield, it changes to Shield forme.",
shortDesc: "The Pokemon changes form depending on how it battles.",
onBeforeMovePriority: 11,
onBeforeMove: function (attacker, defender, move) {
if (attacker.template.baseSpecies !== 'Aegislash') return;
if (move.category === 'Status' && move.id !== 'kingsshield') return;
var targetSpecies = (move.id === 'kingsshield' ? 'Aegislash' : 'Aegislash-Blade');
if (attacker.template.species !== targetSpecies && attacker.formeChange(targetSpecies)) {
this.add('-formechange', attacker, targetSpecies);
}
},
id: "stancechange",
name: "Stance Change",
rating: 4.5,
num: 176
},
"static": {
desc: "If an opponent contact attacks this Pokemon, there is a 30% chance that the opponent will become paralyzed.",
shortDesc: "30% chance of paralyzing a Pokemon making contact with this Pokemon.",
onAfterDamage: function (damage, target, source, effect) {
if (effect && effect.isContact) {
if (this.random(10) < 3) {
source.trySetStatus('par', target, effect);
}
}
},
id: "static",
name: "Static",
rating: 2,
num: 9
},
"steadfast": {
desc: "If this Pokemon flinches, its Speed increases by one stage.",
shortDesc: "If this Pokemon flinches, its Speed is boosted by 1.",
onFlinch: function (pokemon) {
this.boost({spe: 1});
},
id: "steadfast",
name: "Steadfast",
rating: 1,
num: 80
},
"stench": {
desc: "This Pokemon's damaging moves that don't already have a flinch chance gain a 10% chance to cause flinch.",
shortDesc: "This Pokemon's attacks without a chance to flinch have a 10% chance to flinch.",
onModifyMove: function (move) {
if (move.category !== "Status") {
this.debug('Adding Stench flinch');
if (!move.secondaries) move.secondaries = [];
for (var i = 0; i < move.secondaries.length; i++) {
if (move.secondaries[i].volatileStatus === 'flinch') return;
}
move.secondaries.push({
chance: 10,
volatileStatus: 'flinch'
});
}
},
id: "stench",
name: "Stench",
rating: 0,
num: 1
},
"stickyhold": {
desc: "This Pokemon cannot lose its held item due to another Pokemon's attack.",
shortDesc: "This Pokemon cannot lose its held item due to another Pokemon's attack.",
onTakeItem: function (item, pokemon, source) {
if (source && source !== pokemon) return false;
},
id: "stickyhold",
name: "Sticky Hold",
rating: 1,
num: 60
},
"stormdrain": {
desc: "During double battles, this Pokemon draws any single-target Water-type attack to itself. If an opponent uses an Water-type attack that affects multiple Pokemon, those targets will be hit. This ability does not affect Water Hidden Power, Judgment or Weather Ball. The user is immune to Water and its Special Attack is increased one stage when hit by one.",
shortDesc: "This Pokemon draws Water moves to itself to boost Sp. Atk by 1; Water immunity.",
onTryHit: function (target, source, move) {
if (target !== source && move.type === 'Water') {
if (!this.boost({spa:1})) {
this.add('-immune', target, '[msg]');
}
return null;
}
},
onAnyRedirectTargetPriority: 1,
onAnyRedirectTarget: function (target, source, source2, move) {
if (move.type !== 'Water') return;
if (this.validTarget(this.effectData.target, source, move.target)) {
move.accuracy = true;
return this.effectData.target;
}
},
id: "stormdrain",
name: "Storm Drain",
rating: 3.5,
num: 114
},
"strongjaw": {
desc: "This Pokemon receives a 50% power boost for jaw attacks such as Bite and Crunch.",
shortDesc: "This Pokemon's bite-based attacks do 1.5x damage.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (move.flags && move.flags['bite']) {
return this.chainModify(1.5);
}
},
id: "strongjaw",
name: "Strong Jaw",
rating: 3,
num: 173
},
"sturdy": {
desc: "This Pokemon is immune to OHKO moves, and will survive with 1 HP if hit by an attack which would KO it while at full health.",
shortDesc: "If this Pokemon is at full HP, it lives one hit with at least 1HP. OHKO moves fail on it.",
onDamagePriority: -100,
onDamage: function (damage, target, source, effect) {
if (effect && effect.ohko) {
this.add('-activate', target, 'Sturdy');
return 0;
}
if (target.hp === target.maxhp && damage >= target.hp && effect && effect.effectType === 'Move') {
this.add('-activate', target, 'Sturdy');
return target.hp - 1;
}
},
id: "sturdy",
name: "Sturdy",
rating: 3,
num: 5
},
"suctioncups": {
desc: "This Pokemon cannot be forced to switch out by another Pokemon's attack or item.",
shortDesc: "This Pokemon cannot be forced to switch out by another Pokemon's attack or item.",
onDragOutPriority: 1,
onDragOut: function (pokemon) {
this.add('-activate', pokemon, 'ability: Suction Cups');
return null;
},
id: "suctioncups",
name: "Suction Cups",
rating: 2.5,
num: 21
},
"superluck": {
desc: "This Pokemon's critical hit ratio is boosted by 1.",
shortDesc: "This Pokemon's critical hit ratio is boosted by 1.",
onModifyMove: function (move) {
move.critRatio++;
},
id: "superluck",
name: "Super Luck",
rating: 1,
num: 105
},
"swarm": {
desc: "When its health reaches 1/3 or less of its max HP, this Pokemon's Bug-type attacks do 1.5x damage.",
shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Bug attacks do 1.5x damage.",
onModifyAtkPriority: 5,
onModifyAtk: function (atk, attacker, defender, move) {
if (move.type === 'Bug' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Swarm boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA: function (atk, attacker, defender, move) {
if (move.type === 'Bug' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Swarm boost');
return this.chainModify(1.5);
}
},
id: "swarm",
name: "Swarm",
rating: 2,
num: 68
},
"sweetveil": {
desc: "Prevents allies from being put to Sleep.",
shortDesc: "Prevents allies from being put to Sleep.",
id: "sweetveil",
name: "Sweet Veil",
onAllySetStatus: function (status, target, source, effect) {
if (status.id === 'slp') {
this.debug('Sweet Veil interrupts sleep');
return false;
}
},
onAllyTryHit: function (target, source, move) {
if (move && move.id === 'yawn') {
this.debug('Sweet Veil blocking yawn');
return false;
}
},
rating: 0,
num: 175
},
"swiftswim": {
desc: "If the weather is Rain Dance, this Pokemon's Speed is doubled.",
shortDesc: "If the weather is Rain Dance, this Pokemon's Speed is doubled.",
onModifySpe: function (speMod, pokemon) {
if (this.isWeather(['raindance', 'primordialsea'])) {
return this.chain(speMod, 2);
}
},
id: "swiftswim",
name: "Swift Swim",
rating: 2,
num: 33
},
"symbiosis": {
desc: "This Pokemon immediately passes its item to an ally after their item is consumed.",
shortDesc: "This Pokemon passes its item to an ally after their item is consumed.",
onAllyAfterUseItem: function (item, pokemon) {
var sourceItem = this.effectData.target.getItem();
var noSharing = sourceItem.onTakeItem && sourceItem.onTakeItem(sourceItem, pokemon) === false;
if (!sourceItem || noSharing) {
return;
}
sourceItem = this.effectData.target.takeItem();
if (!sourceItem) {
return;
}
if (pokemon.setItem(sourceItem)) {
this.add('-activate', pokemon, 'ability: Symbiosis', sourceItem, '[of] ' + this.effectData.target);
}
},
id: "symbiosis",
name: "Symbiosis",
rating: 0,
num: 180
},
"synchronize": {
desc: "If an opponent burns, poisons or paralyzes this Pokemon, it receives the same condition.",
shortDesc: "If another Pokemon burns/poisons/paralyzes this Pokemon, it also gets that status.",
onAfterSetStatus: function (status, target, source) {
if (!source || source === target) return;
if (status.id === 'slp' || status.id === 'frz') return;
source.trySetStatus(status, target);
},
id: "synchronize",
name: "Synchronize",
rating: 3,
num: 28
},
"tangledfeet": {
desc: "When this Pokemon is confused, attacks targeting it have a 50% chance of missing.",
shortDesc: "This Pokemon's evasion is doubled as long as it is confused.",
onAccuracy: function (accuracy, target) {
if (typeof accuracy !== 'number') return;
if (target && target.volatiles['confusion']) {
this.debug('Tangled Feet - decreasing accuracy');
return accuracy * 0.5;
}
},
id: "tangledfeet",
name: "Tangled Feet",
rating: 1,
num: 77
},
"technician": {
desc: "When this Pokemon uses an attack that has 60 Base Power or less (including Struggle), the move's Base Power receives a 50% boost. For example, a move with 60 Base Power effectively becomes a move with 90 Base Power.",
shortDesc: "This Pokemon's attacks of 60 Base Power or less do 1.5x damage. Includes Struggle.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (basePower <= 60) {
this.debug('Technician boost');
return this.chainModify(1.5);
}
},
id: "technician",
name: "Technician",
rating: 4,
num: 101
},
"telepathy": {
desc: "This Pokemon will not take damage from its allies' spread moves in double and triple battles.",
shortDesc: "This Pokemon does not take damage from its allies' attacks.",
onTryHit: function (target, source, move) {
if (target.side === source.side && move.category !== 'Status') {
this.add('-activate', target, 'ability: Telepathy');
return null;
}
},
id: "telepathy",
name: "Telepathy",
rating: 0,
num: 140
},
"teravolt": {
desc: "When this Pokemon uses any move, it nullifies the Ability of any active Pokemon that hinder or empower this Pokemon's attacks. These abilities include Battle Armor, Clear Body, Damp, Dry Skin, Filter, Flash Fire, Flower Gift, Heatproof, Herbivore, Hyper Cutter, Immunity, Inner Focus, Insomnia, Keen Eye, Leaf Guard, Levitate, Lightningrod, Limber, Magma Armor, Marvel Scale, Motor Drive, Oblivious, Own Tempo, Sand Veil, Shell Armor, Shield Dust, Simple, Snow Cloak, Solid Rock, Soundproof, Sticky Hold, Storm Drain, Sturdy, Suction Cups, Tangled Feet, Thick Fat, Unaware, Vital Spirit, Volt Absorb, Water Absorb, Water Veil, White Smoke and Wonder Guard.",
shortDesc: "This Pokemon's moves ignore any Ability that could modify the effectiveness.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Teravolt');
},
onAllyModifyPokemon: function (pokemon) {
if (this.activePokemon === this.effectData.target && pokemon !== this.activePokemon) {
pokemon.ignore['Ability'] = 'A';
}
},
onFoeModifyPokemon: function (pokemon) {
if (this.activePokemon === this.effectData.target) {
pokemon.ignore['Ability'] = 'A';
}
},
id: "teravolt",
name: "Teravolt",
rating: 3,
num: 164
},
"thickfat": {
desc: "This Pokemon receives half damage from Ice-type and Fire-type attacks.",
shortDesc: "This Pokemon receives half damage from Fire- and Ice-type attacks.",
onModifyAtkPriority: 6,
onSourceModifyAtk: function (atk, attacker, defender, move) {
if (move.type === 'Ice' || move.type === 'Fire') {
this.debug('Thick Fat weaken');
return this.chainModify(0.5);
}
},
onModifySpAPriority: 5,
onSourceModifySpA: function (atk, attacker, defender, move) {
if (move.type === 'Ice' || move.type === 'Fire') {
this.debug('Thick Fat weaken');
return this.chainModify(0.5);
}
},
id: "thickfat",
name: "Thick Fat",
rating: 3,
num: 47
},
"tintedlens": {
desc: "This Pokemon's attacks that are not very effective on a target do double damage.",
shortDesc: "This Pokemon's attacks that are not very effective on a target do double damage.",
onModifyDamage: function (damage, source, target, move) {
if (target.runEffectiveness(move) < 0) {
this.debug('Tinted Lens boost');
return this.chainModify(2);
}
},
id: "tintedlens",
name: "Tinted Lens",
rating: 4,
num: 110
},
"torrent": {
desc: "When its health reaches 1/3 or less of its max HP, this Pokemon's Water-type attacks do 1.5x damage.",
shortDesc: "When this Pokemon has 1/3 or less of its max HP, its Water attacks do 1.5x damage.",
onModifyAtkPriority: 5,
onModifyAtk: function (atk, attacker, defender, move) {
if (move.type === 'Water' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Torrent boost');
return this.chainModify(1.5);
}
},
onModifySpAPriority: 5,
onModifySpA: function (atk, attacker, defender, move) {
if (move.type === 'Water' && attacker.hp <= attacker.maxhp / 3) {
this.debug('Torrent boost');
return this.chainModify(1.5);
}
},
id: "torrent",
name: "Torrent",
rating: 2,
num: 67
},
"toxicboost": {
desc: "When this Pokemon is poisoned, its physical attacks do 1.5x damage.",
shortDesc: "When this Pokemon is poisoned, its physical attacks do 1.5x damage.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if ((attacker.status === 'psn' || attacker.status === 'tox') && move.category === 'Physical') {
return this.chainModify(1.5);
}
},
id: "toxicboost",
name: "Toxic Boost",
rating: 3,
num: 137
},
"toughclaws": {
desc: "This Pokemon's contact attacks do 33% more damage.",
shortDesc: "This Pokemon's contact attacks do 1.33x damage.",
onBasePowerPriority: 8,
onBasePower: function (basePower, attacker, defender, move) {
if (move.isContact) {
return this.chainModify(1.33);
}
},
id: "toughclaws",
name: "Tough Claws",
rating: 3,
num: 181
},
"trace": {
desc: "When this Pokemon enters the field, it temporarily copies an opponent's ability. This ability remains with this Pokemon until it leaves the field.",
shortDesc: "On switch-in, or when it can, this Pokemon copies a random adjacent foe's Ability.",
onUpdate: function (pokemon) {
var possibleTargets = [];
for (var i = 0; i < pokemon.side.foe.active.length; i++) {
if (pokemon.side.foe.active[i] && !pokemon.side.foe.active[i].fainted) possibleTargets.push(pokemon.side.foe.active[i]);
}
while (possibleTargets.length) {
var rand = 0;
if (possibleTargets.length > 1) rand = this.random(possibleTargets.length);
var target = possibleTargets[rand];
var ability = this.getAbility(target.ability);
var bannedAbilities = {flowergift:1, forecast:1, illusion:1, imposter:1, multitype:1, stancechange:1, trace:1, zenmode:1};
if (bannedAbilities[target.ability]) {
possibleTargets.splice(rand, 1);
continue;
}
this.add('-ability', pokemon, ability, '[from] ability: Trace', '[of] ' + target);
pokemon.setAbility(ability);
return;
}
},
id: "trace",
name: "Trace",
rating: 3.5,
num: 36
},
"truant": {
desc: "After this Pokemon is switched into battle, it skips every other turn.",
shortDesc: "This Pokemon skips every other turn instead of using a move.",
onBeforeMovePriority: 9,
onBeforeMove: function (pokemon, target, move) {
if (pokemon.removeVolatile('truant')) {
this.add('cant', pokemon, 'ability: Truant', move);
return false;
}
pokemon.addVolatile('truant');
},
effect: {
duration: 2
},
id: "truant",
name: "Truant",
rating: -2,
num: 54
},
"turboblaze": {
desc: "When this Pokemon uses any move, it nullifies the Ability of any active Pokemon that hinder or empower this Pokemon's attacks. These abilities include Battle Armor, Clear Body, Damp, Dry Skin, Filter, Flash Fire, Flower Gift, Heatproof, Herbivore, Hyper Cutter, Immunity, Inner Focus, Insomnia, Keen Eye, Leaf Guard, Levitate, Lightningrod, Limber, Magma Armor, Marvel Scale, Motor Drive, Oblivious, Own Tempo, Sand Veil, Shell Armor, Shield Dust, Simple, Snow Cloak, Solid Rock, Soundproof, Sticky Hold, Storm Drain, Sturdy, Suction Cups, Tangled Feet, Thick Fat, Unaware, Vital Spirit, Volt Absorb, Water Absorb, Water Veil, White Smoke and Wonder Guard.",
shortDesc: "This Pokemon's moves ignore any Ability that could modify the effectiveness.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Turboblaze');
},
onAllyModifyPokemon: function (pokemon) {
if (this.activePokemon === this.effectData.target && pokemon !== this.activePokemon) {
pokemon.ignore['Ability'] = 'A';
}
},
onFoeModifyPokemon: function (pokemon) {
if (this.activePokemon === this.effectData.target) {
pokemon.ignore['Ability'] = 'A';
}
},
id: "turboblaze",
name: "Turboblaze",
rating: 3,
num: 163
},
"unaware": {
desc: "This Pokemon ignores an opponent's stat boosts for Attack, Defense, Special Attack and Special Defense. These boosts will still affect Base Power calculation for Punishment and Stored Power.",
shortDesc: "This Pokemon ignores other Pokemon's stat changes when taking or doing damage.",
id: "unaware",
name: "Unaware",
onModifyMove: function (move, user, target) {
move.ignoreEvasion = true;
move.ignoreDefensive = true;
},
onSourceModifyMove: function (move, user, target) {
if (user.hasAbility(['moldbreaker', 'turboblaze', 'teravolt'])) return;
move.ignoreAccuracy = true;
move.ignoreOffensive = true;
},
rating: 3,
num: 109
},
"unburden": {
desc: "Doubles this Pokemon's Speed if it loses its held item (such as by eating Berries, using Gems, or via Thief, Knock Off, etc).",
shortDesc: "Speed is doubled on held item loss; boost is lost if it switches, gets new item/Ability.",
onUseItem: function (item, pokemon) {
pokemon.addVolatile('unburden');
},
onTakeItem: function (item, pokemon) {
pokemon.addVolatile('unburden');
},
effect: {
onModifySpe: function (speMod, pokemon) {
if (pokemon.ignore['Ability'] === true || pokemon.ability !== 'unburden') {
pokemon.removeVolatile('unburden');
return;
}
if (!pokemon.item) {
return this.chain(speMod, 2);
}
}
},
id: "unburden",
name: "Unburden",
rating: 3.5,
num: 84
},
"unnerve": {
desc: "While this Pokemon is active, prevents opposing Pokemon from using their Berries.",
shortDesc: "While this Pokemon is active, prevents opposing Pokemon from using their Berries.",
onStart: function (pokemon) {
this.add('-ability', pokemon, 'Unnerve', pokemon.side.foe);
},
onFoeEatItem: false,
id: "unnerve",
name: "Unnerve",
rating: 1,
num: 127
},
"victorystar": {
desc: "Raises every friendly Pokemon's Accuracy, including this Pokemon's, by 10% (multiplied).",
shortDesc: "This Pokemon and its allies' moves have their accuracy boosted to 1.1x.",
onAllyModifyMove: function (move) {
if (typeof move.accuracy === 'number') {
move.accuracy *= 1.1;
}
},
id: "victorystar",
name: "Victory Star",
rating: 2,
num: 162
},
"vitalspirit": {
desc: "This Pokemon cannot fall asleep (Rest will fail if it tries to use it). Gaining this Ability while asleep cures it.",
shortDesc: "This Pokemon cannot fall asleep. Gaining this Ability while asleep cures it.",
onUpdate: function (pokemon) {
if (pokemon.status === 'slp') {
pokemon.cureStatus();
}
},
onImmunity: function (type) {
if (type === 'slp') return false;
},
id: "vitalspirit",
name: "Vital Spirit",
rating: 2,
num: 72
},
"voltabsorb": {
desc: "This Pokemon is immune to Electric moves. If hit by an Electric move, it recovers 25% of its max HP.",
shortDesc: "This Pokemon heals 1/4 of its max HP when hit by Electric moves; Electric immunity.",
onTryHit: function (target, source, move) {
if (target !== source && move.type === 'Electric') {
if (!this.heal(target.maxhp / 4)) {
this.add('-immune', target, '[msg]');
}
return null;
}
},
id: "voltabsorb",
name: "Volt Absorb",
rating: 3.5,
num: 10
},
"waterabsorb": {
desc: "This Pokemon is immune to Water moves. If hit by an Water move, it recovers 25% of its max HP.",
shortDesc: "This Pokemon heals 1/4 of its max HP when hit by Water moves; Water immunity.",
onTryHit: function (target, source, move) {
if (target !== source && move.type === 'Water') {
if (!this.heal(target.maxhp / 4)) {
this.add('-immune', target, '[msg]');
}
return null;
}
},
id: "waterabsorb",
name: "Water Absorb",
rating: 3.5,
num: 11
},
"waterveil": {
desc: "This Pokemon cannot become burned. Gaining this Ability while burned cures it.",
shortDesc: "This Pokemon cannot be burned. Gaining this Ability while burned cures it.",
onUpdate: function (pokemon) {
if (pokemon.status === 'brn') {
pokemon.cureStatus();
}
},
onImmunity: function (type, pokemon) {
if (type === 'brn') return false;
},
id: "waterveil",
name: "Water Veil",
rating: 1.5,
num: 41
},
"weakarmor": {
desc: "Causes physical moves to lower the Pokemon's Defense and increase its Speed stat by one stage.",
shortDesc: "If a physical attack hits this Pokemon, Defense is lowered 1 and Speed is boosted 1.",
onAfterDamage: function (damage, target, source, move) {
if (move.category === 'Physical') {
this.boost({spe:1, def:-1});
}
},
id: "weakarmor",
name: "Weak Armor",
rating: 0,
num: 133
},
"whitesmoke": {
desc: "Opponents cannot reduce this Pokemon's stats; they can, however, modify stat changes with Power Swap, Guard Swap and Heart Swap and inflict stat boosts with Swagger and Flatter. This ability does not prevent self-inflicted stat reductions. [Field Effect]\u00a0If this Pokemon is in the lead spot, the rate of wild Pokemon battles decreases by 50%.",
shortDesc: "Prevents other Pokemon from lowering this Pokemon's stat stages.",
onBoost: function (boost, target, source, effect) {
if (source && target === source) return;
var showMsg = false;
for (var i in boost) {
if (boost[i] < 0) {
delete boost[i];
showMsg = true;
}
}
if (showMsg && !effect.secondaries) this.add("-fail", target, "unboost", "[from] ability: White Smoke", "[of] " + target);
},
id: "whitesmoke",
name: "White Smoke",
rating: 2,
num: 73
},
"wonderguard": {
desc: "This Pokemon only receives damage from attacks belonging to types that cause Super Effective to this Pokemon. Wonder Guard does not protect a Pokemon from status ailments (burn, freeze, paralysis, poison, sleep, Toxic or any of their side effects or damage), recoil damage nor the moves Beat Up, Bide, Doom Desire, Fire Fang, Future Sight, Hail, Leech Seed, Sandstorm, Spikes, Stealth Rock and Struggle. Wonder Guard cannot be Skill Swapped nor Role Played. Trace, however, does copy Wonder Guard.",
shortDesc: "This Pokemon can only be damaged by super effective moves and indirect damage.",
onTryHit: function (target, source, move) {
if (target === source || move.category === 'Status' || move.type === '???' || move.id === 'struggle' || move.isFutureMove) return;
this.debug('Wonder Guard immunity: ' + move.id);
if (target.runEffectiveness(move) <= 0) {
this.add('-activate', target, 'ability: Wonder Guard');
return null;
}
},
id: "wonderguard",
name: "Wonder Guard",
rating: 5,
num: 25
},
"wonderskin": {
desc: "Causes the chance of a status move working to be halved. It does not affect moves that inflict status as a secondary effect like Thunder's chance to paralyze.",
shortDesc: "All status moves with a set % accuracy are 50% accurate if used on this Pokemon.",
onAccuracyPriority: 10,
onAccuracy: function (accuracy, target, source, move) {
if (move.category === 'Status' && typeof move.accuracy === 'number') {
this.debug('Wonder Skin - setting accuracy to 50');
return 50;
}
},
id: "wonderskin",
name: "Wonder Skin",
rating: 3,
num: 147
},
"zenmode": {
desc: "When Darmanitan's HP drops to below half, it will enter Zen Mode at the end of the turn. If it loses its ability, or recovers HP to above half while in Zen mode, it will change back. This ability only works on Darmanitan, even if it is copied by Role Play, Entrainment, or swapped with Skill Swap.",
shortDesc: "If this Pokemon is Darmanitan, it changes to Zen Mode whenever it is below half HP.",
onResidualOrder: 27,
onResidual: function (pokemon) {
if (pokemon.baseTemplate.species !== 'Darmanitan') {
return;
}
if (pokemon.hp <= pokemon.maxhp / 2 && pokemon.template.speciesid === 'darmanitan') {
pokemon.addVolatile('zenmode');
} else if (pokemon.hp > pokemon.maxhp / 2 && pokemon.template.speciesid === 'darmanitanzen') {
pokemon.removeVolatile('zenmode');
}
},
effect: {
onStart: function (pokemon) {
if (pokemon.formeChange('Darmanitan-Zen')) {
this.add('-formechange', pokemon, 'Darmanitan-Zen');
} else {
return false;
}
},
onEnd: function (pokemon) {
if (pokemon.formeChange('Darmanitan')) {
this.add('-formechange', pokemon, 'Darmanitan');
} else {
return false;
}
},
onUpdate: function (pokemon) {
if (!pokemon.hasAbility('zenmode')) {
pokemon.transformed = false;
pokemon.removeVolatile('zenmode');
}
}
},
id: "zenmode",
name: "Zen Mode",
rating: -1,
num: 161
},
// CAP
"mountaineer": {
desc: "On switch-in, this Pokemon avoids all Rock-type attacks and Stealth Rock.",
shortDesc: "This Pokemon avoids all Rock-type attacks and hazards when switching in.",
onDamage: function (damage, target, source, effect) {
if (effect && effect.id === 'stealthrock') {
return false;
}
},
onImmunity: function (type, target) {
if (type === 'Rock' && !target.activeTurns) {
return false;
}
},
id: "mountaineer",
isNonstandard: true,
name: "Mountaineer",
rating: 3.5,
num: -2
},
"rebound": {
desc: "On switch-in, this Pokemon blocks certain status moves and uses the move itself.",
shortDesc: "It can reflect the effect of status moves when switching in.",
id: "rebound",
isNonstandard: true,
name: "Rebound",
onTryHitPriority: 1,
onTryHit: function (target, source, move) {
if (this.effectData.target.activeTurns) return;
if (target === source) return;
if (move.hasBounced) return;
if (typeof move.isBounceable === 'undefined') {
move.isBounceable = !!(move.category === 'Status' && (move.status || move.boosts || move.volatileStatus === 'confusion' || move.forceSwitch));
}
if (move.isBounceable) {
var newMove = this.getMoveCopy(move.id);
newMove.hasBounced = true;
this.useMove(newMove, target, source);
return null;
}
},
onAllyTryHitSide: function (target, source, move) {
if (this.effectData.target.activeTurns) return;
if (target.side === source.side) return;
if (move.hasBounced) return;
if (typeof move.isBounceable === 'undefined') {
move.isBounceable = !!(move.category === 'Status' && (move.status || move.boosts || move.volatileStatus === 'confusion' || move.forceSwitch));
}
if (move.isBounceable) {
var newMove = this.getMoveCopy(move.id);
newMove.hasBounced = true;
this.useMove(newMove, target, source);
return null;
}
},
effect: {
duration: 1
},
rating: 4,
num: -3
},
"persistent": {
desc: "The duration of certain field effects is increased by 2 turns if used by this Pokemon.",
shortDesc: "Increases the duration of many field effects by two turns when used by this Pokemon.",
id: "persistent",
isNonstandard: true,
name: "Persistent",
// implemented in the corresponding move
rating: 4,
num: -4
}
};
|
Raina4uberz/Showdown-light
|
data/abilities.js
|
JavaScript
|
mit
| 120,010 |
// Source : https://oj.leetcode.com/problems/find-peak-element/
// Author : Hao Chen
// Date : 2014-12-05
/**********************************************************************************
*
* A peak element is an element that is greater than its neighbors.
*
* Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.
*
* You may imagine that num[-1] = num[n] = -∞.
*
* For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
*
* click to show spoilers.
*
* Note:
* Your solution should be in logarithmic complexity.
*
* Credits:Special thanks to @ts for adding this problem and creating all test cases.
*
**********************************************************************************/
#include <iostream>
#include <vector>
using namespace std;
/*
* Binary search is common idea here.
*
* However, you need to think about two senarios:
*
* 1) Becasue we need check `num[mid-1]`, `num[mid]`, `num[mid+1]`,
* So, we need make sure there hasn't out-of-boundary issue.
*
*
*
* 2) There are multiple Peak elements.
*
* For example: [1,2,1,2,1], or [ 1,2,3,1,2,1]
*
* LeetCode doesn't tell you what the expected result is. I guess:
*
* 2.1) for [1,2,1,2,1] you can return either 1 or 3, because both them are peak elements
*
* 2.1) for [1,2,3,2,4,2,1] it should return 4, because num[4] is the real peak. but Leetcode accept either 2 or 4
*
*/
int findPeakElement(const vector<int> &num) {
int n = num.size();
int low = 0;
int high = n - 1;
int mid = 0, v1, v2;
while ( low < high ) {
// Find the index of middle element
mid = low + ( high - low ) / 2;
// Compare middle element with its neighbours (if neighbours exist)
if ( ( mid == 0 || num[mid] > num[mid-1] ) &&
( mid == n-1 || num[mid] > num[mid+1] ) ){
return mid;
}
// If middle element is not peak and its left neighbor is greater than it
// then left half must have a peak element
if (mid >0 && num[mid-1] > num[mid]){
high = mid - 1;
// If middle element is not peak and its right neighbor is greater than it
// then right half must have a peak element
}else{
low = mid + 1;
}
}
return low;
}
void printVector(vector<int> &n) {
cout << "[ ";
int i;
for(i=0; i<n.size(); i++){
cout << n[i] << (i==n.size()-1 ? " ]" : ", ");
}
cout << endl;
}
void test(int a[], int n) {
vector<int> v(a, a+n);
cout << "Peak Index = " << findPeakElement(v) << "\t";
printVector(v);
}
#define TEST(a) test(a, sizeof(a)/sizeof(a[0]))
int main(int argc, char**argv)
{
int n0[] = {1};
TEST(n0);
int n1[] = {1,2};
TEST(n1);
int n2[] = {2,1};
TEST(n2);
int n3[] = {1,2,3};
TEST(n3);
int n4[] = {3,2,1};
TEST(n4);
int n5[] = {1,2,3,2};
TEST(n5);
int n6[] = {0,1,2,9,7,5,4,2,1};
TEST(n6);
int n7[] = {1,2,1,2,1};
TEST(n7);
int n8[] = {1,2,1,2,3,1};
TEST(n8);
int n9[] = {1,2,3,2,4,2,1};
TEST(n9);
int n10[] = {1,3,1,2,1,3,1};
TEST(n10);
return 0;
}
|
jaredkoontz/leetcode
|
algorithms/cpp/findPeakElement/findPeakElement.cpp
|
C++
|
mit
| 3,304 |
import * as React from "react";
import { CarbonIconProps } from "../../";
declare const LetterWw20: React.ForwardRefExoticComponent<
CarbonIconProps & React.RefAttributes<SVGSVGElement>
>;
export default LetterWw20;
|
mcliment/DefinitelyTyped
|
types/carbon__icons-react/lib/letter--Ww/20.d.ts
|
TypeScript
|
mit
| 218 |
<?php
class Checkoutcom_Ckopayment_Block_Customer_Cards extends Mage_Core_Block_Template
{
/**
* Return array with customer card list
*
* @return array
*/
public function getCustomerCardList()
{
$result = array();
$customerId = Mage::getModel('ckopayment/checkoutcomCards')->getCustomerId();
if (empty($customerId)) {
return $result;
}
$customerCardModel = Mage::getModel('ckopayment/customerCard');
$cardCollection = $customerCardModel->getCustomerCardList($customerId);
if (!$cardCollection->count()) {
return $result;
}
foreach ($cardCollection as $index => $card) {
if ($card->getSaveCard() == '') {
continue;
}
$result[$index]['title'] = sprintf('•••• %s', $card->getLastFour());
$result[$index]['value'] = $card->getId(); //$customerCardModel->getCardSecret($card->getId(), $card->getLastFour(), $card->getCardScheme());
$result[$index]['type'] = $card->getCardScheme();
}
return $result;
}
}
|
CKOTech/checkout-magento-plugin
|
app/code/community/Checkoutcom/Ckopayment/Block/Customer/Cards.php
|
PHP
|
mit
| 1,138 |
// -----------------------------------------------------------------------
// <copyright file="AssemblyInfo.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation.
// All rights reserved. 2013
// </copyright>
// -----------------------------------------------------------------------
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 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)]
[assembly: CLSCompliant(true)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("44abc834-bd19-449f-ad64-f8c83ca078ed")]
[assembly: InternalsVisibleTo("Microsoft.ApplicationInsights.NLogTarget.Tests, PublicKey=" + AssemblyInfo.PublicKey)]
internal static class AssemblyInfo
{
#if PUBLIC_RELEASE
// Public key; assemblies are delay signed.
public const string PublicKey = "0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9";
#else
// Internal key; assemblies are public signed.
public const string PublicKey = "0024000004800000940000000602000000240000525341310004000001000100319b35b21a993df850846602dae9e86d8fbb0528a0ad488ecd6414db798996534381825f94f90d8b16b72a51c4e7e07cf66ff3293c1046c045fafc354cfcc15fc177c748111e4a8c5a34d3940e7f3789dd58a928add6160d6f9cc219680253dcea88a034e7d472de51d4989c7783e19343839273e0e63a43b99ab338149dd59f";
#endif
public const string MoqPublicKey = "0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7";
}
|
pharring/ApplicationInsights-dotnet
|
LOGGING/src/NLogTarget/AssemblyInfo.cs
|
C#
|
mit
| 2,225 |
AutoHtml.add_filter(:image) do |text|
text.gsub(/https?:\/\/.+\.(jpg|jpeg|bmp|gif|png)(\?\S+)?/i) do |match|
%|<img src="#{match}" alt=""/>|
end
end
|
amishyn/auto_html
|
lib/auto_html/filters/image.rb
|
Ruby
|
mit
| 156 |
from nltk.corpus import wordnet
import json
import codecs
import sys
import time
major_weight = 1.0
minor_weight = 0.8
similarity_threshold = 0.65
def fn(ss1, ss2, weight):
similarity = ss1.wup_similarity(ss2)
return (ss1, ss2, weight * similarity if similarity else 0 )
def isSynsetForm(s):
return '.n.' in s or '.s.' in s or '.v.' in s
if len(sys.argv) != 3:
print 'usage <seed synset> <kadist.json>'
sys.exit(-1)
else:
candidates = []
source = wordnet.synset(sys.argv[1])
tagged_works = 0
with codecs.open(sys.argv[2], 'rb', 'utf-8') as f:
kadist = json.loads(f.read())
for m in kadist:
if m['major_tags']:
tagged_works += 1
candidates += [(wordnet.synset(tag), major_weight) for tag in m['major_tags'] if isSynsetForm(tag)]
if m['minor_tags']:
candidates += [(wordnet.synset(tag), minor_weight) for tag in m['minor_tags'] if isSynsetForm(tag) ]
start = time.time()
print 'starting similarity calculations on', tagged_works, 'tagged works'
similarities = (fn(source, candidate[0], candidate[1]) for candidate in set([c for c in candidates if c[0] != source]))
for result in (sorted( (sim for sim in similarities if sim[2] >= similarity_threshold), key=lambda x: x[2])):
print result[0].name(), result[1].name(), result[2]
print source.name(), 'occurs as a tag', len([c for c in candidates if c[0] == source]),'times'
print 'number lookups', len(candidates), 'duration', time.time()-start
|
darenr/MOMA-Art
|
kadist/wup.py
|
Python
|
mit
| 1,480 |
<?php
/** @throws RuntimeException */
function maybeThrow920() {
if ( rand() ) {
throw new \RuntimeException;
}
return true;
}
function check920(int $flag) {
try {
maybeThrow920();
} catch ( \RuntimeException $e ) {
$flag = false;
$excep = $e;
} catch (Error $e) {
$flag = 'error';
}
if (rand()) {
'@phan-debug-var $excep, $flag';
return [$flag, $excep ?? null]; // PhanCoalescingNeverUndefined Using $excep ?? null seems unnecessary - the expression appears to always be defined
} else {
'@phan-debug-var $e';
return $e ?? null;
}
}
check920();
|
etsy/phan
|
tests/files/src/0920_flatten.php
|
PHP
|
mit
| 648 |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Collections.Generic;
using SharpDX.Serialization;
namespace SharpDX.Toolkit.Graphics
{
public partial class ModelData
{
/// <summary>
/// Class Mesh
/// </summary>
public sealed class Material : CommonData, IDataSerializable
{
public Material()
{
Textures = new Dictionary<string, List<MaterialTexture>>();
Properties = new PropertyCollection();
}
/// <summary>
/// The textures
/// </summary>
public Dictionary<string, List<MaterialTexture>> Textures;
/// <summary>
/// Gets attributes attached to this material.
/// </summary>
public PropertyCollection Properties;
void IDataSerializable.Serialize(BinarySerializer serializer)
{
if (serializer.Mode == SerializerMode.Write)
{
serializer.Writer.Write(Textures.Count);
foreach (var texture in Textures)
{
var name = texture.Key;
var list = texture.Value;
serializer.Serialize(ref name);
serializer.Serialize(ref list);
}
}
else
{
var count = serializer.Reader.ReadInt32();
Textures = new Dictionary<string, List<MaterialTexture>>(count);
for(int i = 0; i < count; i++)
{
string name = null;
List<MaterialTexture> list = null;
serializer.Serialize(ref name);
serializer.Serialize(ref list);
Textures.Add(name, list);
}
}
serializer.Serialize(ref Properties);
}
}
}
}
|
VirusFree/SharpDX
|
Source/Toolkit/SharpDX.Toolkit/Graphics/ModelData.Material.cs
|
C#
|
mit
| 3,138 |
package com.arkcraft.module.items.common.entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.projectile.EntityThrowable;
import net.minecraft.item.Item;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.World;
import com.arkcraft.module.creature.common.entity.passive.EntityDodo;
import com.arkcraft.module.items.ARKCraftItems;
public class EntityDodoEgg extends EntityThrowable
{
public EntityDodoEgg(World w)
{
super(w);
}
public EntityDodoEgg(World w, EntityLivingBase base)
{
super(w, base);
}
public EntityDodoEgg(World w, double x, double y, double z)
{
super(w, x, y, z);
}
/**
* Called when this EntityThrowable hits a block or entity.
*/
protected void onImpact(MovingObjectPosition pos)
{
if (pos.entityHit != null)
{
pos.entityHit.attackEntityFrom(DamageSource.causeThrownDamage(this, this.getThrower()),
0.0F);
}
if (!this.worldObj.isRemote && this.rand.nextInt(8) == 0)
{
byte b0 = 1;
if (this.rand.nextInt(32) == 0)
{
b0 = 4;
}
for (int i = 0; i < b0; ++i)
{
EntityDodo entitydodo = new EntityDodo(this.worldObj);
entitydodo.setGrowingAge(-24000);
entitydodo.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotationYaw,
0.0F);
this.worldObj.spawnEntityInWorld(entitydodo);
}
}
@SuppressWarnings("unused")
double d0 = 0.08D;
for (int j = 0; j < 8; ++j)
{
// worldObj.spawnParticle(EnumParticleTypes.SNOWBALL, this.posX,
// this.posY, this.posZ, 0.0D, 0.0D, 0.0D);
this.worldObj.spawnParticle(EnumParticleTypes.ITEM_CRACK, this.posX, this.posY,
this.posZ, ((double) this.rand.nextFloat() - 0.5D) * 0.08D,
((double) this.rand.nextFloat() - 0.5D) * 0.08D,
((double) this.rand.nextFloat() - 0.5D) * 0.08D,
new int[] { Item.getIdFromItem(ARKCraftItems.dodo_egg) });
}
if (!this.worldObj.isRemote)
{
this.setDead();
}
}
}
|
SolarCactus/ARKCraft-Code
|
src/main/java/com/arkcraft/module/items/common/entity/EntityDodoEgg.java
|
Java
|
mit
| 2,029 |
//******************************************************************************************************
// RestrictAccessAttribute.cs - Gbtc
//
// Copyright © 2012, Grid Protection Alliance. All Rights Reserved.
//
// Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
// the NOTICE file distributed with this work for additional information regarding copyright ownership.
// The GPA licenses this file to you under the MIT License (MIT), 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.opensource.org/licenses/MIT
//
// Unless agreed to in writing, the subject software distributed under the License is distributed on an
// "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
// License for the specific language governing permissions and limitations.
//
// Code Modification History:
// ----------------------------------------------------------------------------------------------------
// 01/06/2011 - Pinal C. Patel
// Generated original version of source code.
// 12/20/2012 - Starlynn Danyelle Gilliam
// Modified Header.
//
//******************************************************************************************************
using System;
using System.Threading;
namespace GSF.Security
{
/// <summary>
/// Represents an <see cref="Attribute"/> that can be used restrict access to a class when using role-based security.
/// </summary>
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class RestrictAccessAttribute : Attribute
{
#region [ Members ]
// Fields
private string[] m_roles;
#endregion
#region [ Constructors ]
/// <summary>
/// Initializes a new instance of the <see cref="RestrictAccessAttribute"/> class.
/// </summary>
public RestrictAccessAttribute()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RestrictAccessAttribute"/> class.
/// </summary>
/// <param name="roles">List of either roles the current thread principal must have in order to have access.</param>
public RestrictAccessAttribute(params string[] roles)
{
m_roles = roles;
}
#endregion
#region [ Properties ]
/// <summary>
/// Gets or sets the list of either roles the current thread principal must have in order to have access.
/// </summary>
public string[] Roles
{
get
{
return m_roles;
}
set
{
m_roles = value;
}
}
#endregion
#region [ Methods ]
/// <summary>
/// Checks if the current thread principal has at least one of the <see cref="Roles"/> in order to have access.
/// </summary>
/// <returns>true if the current thread principal has access, otherwise false.</returns>
public bool CheckAccess()
{
if (m_roles != null)
{
// One or more roles have been specified.
foreach (string role in m_roles)
{
// Check role against principal's role membership.
if (Thread.CurrentPrincipal.IsInRole(role))
// Principal has membership to the role so allow access.
return true;
}
}
return false;
}
#endregion
}
}
|
GridProtectionAlliance/gsf
|
Source/Libraries/GSF.Security/RestrictAccessAttribute.cs
|
C#
|
mit
| 3,748 |
/* @flow */
import SelectListView from "atom-select-list";
import store from "./store";
import _ from "lodash";
import tildify from "tildify";
import WSKernel from "./ws-kernel";
import { kernelSpecProvidesGrammar } from "./utils";
import type Kernel from "./kernel";
function getName(kernel: Kernel) {
const prefix = kernel instanceof WSKernel ? `${kernel.gatewayName}: ` : "";
return (
prefix +
kernel.displayName +
" - " +
store
.getFilesForKernel(kernel)
.map(tildify)
.join(", ")
);
}
export default class ExistingKernelPicker {
kernelSpecs: Array<Kernelspec>;
selectListView: SelectListView;
panel: ?atom$Panel;
previouslyFocusedElement: ?HTMLElement;
constructor() {
this.selectListView = new SelectListView({
itemsClassList: ["mark-active"],
items: [],
filterKeyForItem: kernel => getName(kernel),
elementForItem: kernel => {
const element = document.createElement("li");
element.textContent = getName(kernel);
return element;
},
didConfirmSelection: kernel => {
const { filePath, editor, grammar } = store;
if (!filePath || !editor || !grammar) return this.cancel();
store.newKernel(kernel, filePath, editor, grammar);
this.cancel();
},
didCancelSelection: () => this.cancel(),
emptyMessage: "No running kernels for this language."
});
}
destroy() {
this.cancel();
return this.selectListView.destroy();
}
cancel() {
if (this.panel != null) {
this.panel.destroy();
}
this.panel = null;
if (this.previouslyFocusedElement) {
this.previouslyFocusedElement.focus();
this.previouslyFocusedElement = null;
}
}
attach() {
this.previouslyFocusedElement = document.activeElement;
if (this.panel == null)
this.panel = atom.workspace.addModalPanel({ item: this.selectListView });
this.selectListView.focus();
this.selectListView.reset();
}
async toggle() {
if (this.panel != null) {
this.cancel();
} else if (store.filePath && store.grammar) {
await this.selectListView.update({
items: store.runningKernels.filter(kernel =>
kernelSpecProvidesGrammar(kernel.kernelSpec, store.grammar)
)
});
store.markers.clear();
this.attach();
}
}
}
|
rgbkrk/hydrogen
|
lib/existing-kernel-picker.js
|
JavaScript
|
mit
| 2,362 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace JSNLog
{
/// <summary>
/// Classes (loggers, etc.) that implement this interface can generate
/// JSON name-value fields based on their properties. These fields are used in the
/// JSON object passed to setOptions.
/// </summary>
public interface ICanCreateJsonFields
{
/// <summary>
/// Creates JSON fields for a JSON object that will be passed to setOptions
/// for the element (logger, etc.) that implementes this interface.
/// </summary>
/// <param name="jsonFields">
/// The JSON fields are added to this.
/// </param>
/// <param name="appenderNames"></param>
/// <param name="virtualToAbsoluteFunc"></param>
void AddJsonFields(IList<string> jsonFields, Dictionary<string, string> appenderNames,
Func<string, string> virtualToAbsoluteFunc);
}
}
|
mperdeck/jsnlog
|
jsnlog/PublicFacing/Configuration/JsnlogConfiguration/ICanCreateJsonFields.cs
|
C#
|
mit
| 977 |
'''@file alignment_decoder.py
contains the AlignmentDecoder'''
import os
import struct
import numpy as np
import tensorflow as tf
import decoder
class AlignmentDecoder(decoder.Decoder):
'''gets the HMM state posteriors'''
def __call__(self, inputs, input_seq_length):
'''decode a batch of data
Args:
inputs: the inputs as a dictionary of [batch_size x time x ...]
tensors
input_seq_length: the input sequence lengths as a dictionary of
[batch_size] vectors
Returns:
- the decoded sequences as a dictionary of outputs
'''
with tf.name_scope('alignment_decoder'):
#create the decoding graph
logits, logits_seq_length = self.model(
inputs, input_seq_length, targets=[],
target_seq_length=[], is_training=False)
#compute the log probabilities
logprobs = tf.log(tf.nn.softmax(logits.values()[0]))
#read the prior if it exists, otherwise use uniform prior
if os.path.exists(self.conf['prior']):
prior = np.load(self.conf['prior'])
else:
print(
'WARNING could not find prior in file %s using uniform'
' prior' % self.conf['prior'])
output_dim = self.model.output_dims.values()[0]
prior = np.ones([output_dim])/output_dim
#compute posterior to pseudo likelihood
loglikes = logprobs - np.log(prior)
outputs = {o:(loglikes, logits_seq_length[o]) for o in logits}
return outputs
def write(self, outputs, directory, names):
'''write the output of the decoder to disk
args:
outputs: the outputs of the decoder
directory: the directory where the results should be written
names: the names of the utterances in outputs
'''
for o in outputs:
if not os.path.isdir(os.path.join(directory, o)):
os.makedirs(os.path.join(directory, o))
batch_size = outputs[o][0].shape[0]
scp_file = os.path.join(directory, o, 'feats.scp')
ark_file = os.path.join(directory, o, 'loglikes.ark')
for i in range(batch_size):
output = outputs[o][0][i, :outputs[o][1][i]]
arkwrite(scp_file, ark_file, names[i], output)
def update_evaluation_loss(self, loss, outputs, references,
reference_seq_length):
'''update the evaluation loss
args:
loss: the current evaluation loss
outputs: the outputs of the decoder as a dictionary
references: the references as a dictionary
reference_seq_length: the sequence lengths of the references
Returns:
an op to update the evalution loss
'''
raise Exception('AlignmentDecoder can not be used to validate')
def arkwrite(scp_file, ark_file, name, array):
'''write the array to the arkfile'''
scp_fid = open(scp_file, 'a')
ark_fid = open(ark_file, 'ab')
rows, cols = array.shape
ark_fid.write(struct.pack('<%ds'%(len(name)), name))
pos = ark_fid.tell()
ark_fid.write(struct.pack('<xcccc', 'B', 'F', 'M', ' '))
ark_fid.write(struct.pack('<bi', 4, rows))
ark_fid.write(struct.pack('<bi', 4, cols))
ark_fid.write(array)
scp_fid.write('%s %s:%s\n' % (name, ark_file, pos))
scp_fid.close()
ark_fid.close()
|
vrenkens/Nabu-asr
|
nabu/neuralnetworks/decoders/alignment_decoder.py
|
Python
|
mit
| 3,558 |
require 'logger'
require 'pathname'
module PactBroker
module Logging
# Need to make this configurable based on the calling app!
LOG_DIR = Pathname.new(File.join(File.dirname(__FILE__), '..', '..', 'log')).cleanpath
LOG_FILE_NAME = "#{ENV['RACK_ENV'] || 'development'}.log"
def self.included(base)
base.extend(self)
end
def logger= logger
@@logger = logger
end
def logger
@@logger ||= begin
FileUtils.mkdir_p(LOG_DIR)
logger = Logger.new(File.join(LOG_DIR, LOG_FILE_NAME))
logger.level = Logger::DEBUG
logger
end
end
end
include Logging
end
|
ThePletch/pact_broker
|
lib/pact_broker/logging.rb
|
Ruby
|
mit
| 645 |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The Las Vegas Coin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "clientversion.h"
#include "init.h"
#include "main.h"
#include "masternodeconfig.h"
#include "noui.h"
#include "rpcserver.h"
#include "ui_interface.h"
#include "util.h"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
/* Introduction text for doxygen: */
/*! \mainpage Developer documentation
*
* \section intro_sec Introduction
*
* This is the developer documentation of the reference client for an experimental new digital currency called Las Vegas Coin (http://www.lasvegascoin.org),
* which enables instant payments to anyone, anywhere in the world. Las Vegas Coin uses peer-to-peer technology to operate
* with no central authority: managing transactions and issuing money are carried out collectively by the network.
*
* The software is a community-driven open source project, released under the MIT license.
*
* \section Navigation
* Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code.
*/
static bool fDaemon;
void DetectShutdownThread(boost::thread_group* threadGroup)
{
bool fShutdown = ShutdownRequested();
// Tell the main threads to shutdown.
while (!fShutdown) {
MilliSleep(200);
fShutdown = ShutdownRequested();
}
if (threadGroup) {
threadGroup->interrupt_all();
threadGroup->join_all();
}
}
//////////////////////////////////////////////////////////////////////////////
//
// Start
//
bool AppInit(int argc, char* argv[])
{
boost::thread_group threadGroup;
boost::thread* detectShutdownThread = NULL;
bool fRet = false;
//
// Parameters
//
// If Qt is used, parameters/lasvegascoin.conf are parsed in qt/lasvegascoin.cpp's main()
ParseParameters(argc, argv);
// Process help and version before taking care about datadir
if (mapArgs.count("-?") || mapArgs.count("-help") || mapArgs.count("-version")) {
std::string strUsage = _("LasVegasCoin Core Daemon") + " " + _("version") + " " + FormatFullVersion() + "\n";
if (mapArgs.count("-version")) {
strUsage += LicenseInfo();
} else {
strUsage += "\n" + _("Usage:") + "\n" +
" lasvegascoind [options] " + _("Start LasVegasCoin Core Daemon") + "\n";
strUsage += "\n" + HelpMessage(HMM_BITCOIND);
}
fprintf(stdout, "%s", strUsage.c_str());
return false;
}
try {
if (!boost::filesystem::is_directory(GetDataDir(false))) {
fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", mapArgs["-datadir"].c_str());
return false;
}
try {
ReadConfigFile(mapArgs, mapMultiArgs);
} catch (std::exception& e) {
fprintf(stderr, "Error reading configuration file: %s\n", e.what());
return false;
}
// Check for -testnet or -regtest parameter (Params() calls are only valid after this clause)
if (!SelectParamsFromCommandLine()) {
fprintf(stderr, "Error: Invalid combination of -regtest and -testnet.\n");
return false;
}
// parse masternode.conf
std::string strErr;
if (!masternodeConfig.read(strErr)) {
fprintf(stderr, "Error reading masternode configuration file: %s\n", strErr.c_str());
return false;
}
// Command-line RPC
bool fCommandLine = false;
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "lasvegascoin:"))
fCommandLine = true;
if (fCommandLine) {
fprintf(stderr, "Error: There is no RPC client functionality in lasvegascoind anymore. Use the lasvegascoin-cli utility instead.\n");
exit(1);
}
#ifndef WIN32
fDaemon = GetBoolArg("-daemon", false);
if (fDaemon) {
fprintf(stdout, "Las Vegas Coin server starting\n");
// Daemonize
pid_t pid = fork();
if (pid < 0) {
fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno);
return false;
}
if (pid > 0) // Parent process, pid is child process id
{
return true;
}
// Child process falls through to rest of initialization
pid_t sid = setsid();
if (sid < 0)
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
SoftSetBoolArg("-server", true);
detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
fRet = AppInit2(threadGroup);
} catch (std::exception& e) {
PrintExceptionContinue(&e, "AppInit()");
} catch (...) {
PrintExceptionContinue(NULL, "AppInit()");
}
if (!fRet) {
if (detectShutdownThread)
detectShutdownThread->interrupt();
threadGroup.interrupt_all();
// threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of
// the startup-failure cases to make sure they don't result in a hang due to some
// thread-blocking-waiting-for-another-thread-during-startup case
}
if (detectShutdownThread) {
detectShutdownThread->join();
delete detectShutdownThread;
detectShutdownThread = NULL;
}
Shutdown();
return fRet;
}
int main(int argc, char* argv[])
{
SetupEnvironment();
// Connect lasvegascoind signal handlers
noui_connect();
return (AppInit(argc, argv) ? 0 : 1);
}
|
keesdewit82/LasVegasCoin
|
src/lasvegascoind.cpp
|
C++
|
mit
| 6,106 |
from unittest import TestCase
from unittest.mock import patch
from genes.apt.get import APTGet
class APTGetInstallTestCase(TestCase):
def test_apt_get_install_no_items_fails(self):
with patch('genes.process.process.Popen') as mock_popen:
apt_get = APTGet()
with self.assertRaises(ValueError):
apt_get.install()
mock_popen.assert_not_called()
def test_apt_get_install_single_item_calls_popen(self):
with patch('genes.process.process.Popen') as mock_popen:
apt_get = APTGet()
apt_get.install('test')
mock_popen.assert_called_with(('apt-get', '-y', 'install', 'test'))
def test_apt_get_install_multiple_items_calls_popen(self):
with patch('genes.process.process.Popen') as mock_popen:
apt_get = APTGet()
apt_get.install('test1', 'test2')
mock_popen.assert_called_once_with(('apt-get', '-y', 'install', 'test1', 'test2'))
class TestAPTGetUpdate(TestCase):
def test_apt_get_update_calls_popen(self):
with patch('genes.process.process.Popen') as mock_popen:
apt_get = APTGet()
apt_get.update()
mock_popen.assert_called_once_with(('apt-get', '-y', 'update'))
class TestAPTGetUpgrade(TestCase):
def test_apt_get_upgrade_with_no_items_calls_popen(self):
with patch('genes.process.process.Popen') as mock_popen:
apt_get = APTGet()
apt_get.upgrade()
mock_popen.assert_called_once_with(('apt-get', '-y', 'upgrade'))
|
hatchery/Genepool2
|
genes/apt/test_get.py
|
Python
|
mit
| 1,570 |
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("ObjectPushSample200CF")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Franson")]
[assembly: AssemblyProduct("ObjectPushSample200CF")]
[assembly: AssemblyCopyright("Copyright © Franson 2006")]
[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("db5a4510-da02-424b-ab1a-6a8cbe3656f7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
|
johanlantz/headsetpresenter
|
HeadsetPresenter_Bluetools/HeadsetPresenter/Bluetools/BlueTools SDK v1.21/dotNetCF200/C#/ObexPushClient/Properties/AssemblyInfo.cs
|
C#
|
mit
| 1,262 |
#include <epicmeter/benchmark.hpp>
#include <blackhole/formatter/string.hpp>
#include <blackhole/logger.hpp>
#include <blackhole/macro.hpp>
#include <blackhole/sink/null.hpp>
#include <blackhole/sink/stream.hpp>
#include "../util.hpp"
#define BH_BASE_LOG(__log__, ...) \
if (auto record = (__log__).open_record()) \
if (blackhole::aux::syntax_check(__VA_ARGS__)) \
blackhole::aux::logger::make_pusher((__log__), record, __VA_ARGS__)
#define BENCHMARK_BASELINE_X(...) void TT_CONCATENATE(f, __LINE__)()
#define BENCHMARK_RELATIVE_X(...) void TT_CONCATENATE(f, __LINE__)()
namespace { enum level_t { debug, info }; }
#define MESSAGE_LONG "Something bad is going on but I can handle it"
static const std::string FORMAT_BASE = "[%(timestamp)s]: %(message)s";
static const std::string FORMAT_VERBOSE = "[%(timestamp)s] [%(severity)s]: %(message)s";
BENCHMARK(LogStringToNull, Baseline) {
static auto log = initialize<
blackhole::verbose_logger_t<level_t>,
blackhole::formatter::string_t,
blackhole::sink::null_t
>().formatter(FORMAT_VERBOSE).sink().log(level_t::debug).get();
BH_LOG(log, level_t::info, MESSAGE_LONG)(
"id", 42,
"info", "le string"
);
}
BENCHMARK_BASELINE(Logger, Base) {
static auto log = initialize<
blackhole::logger_base_t,
blackhole::formatter::string_t,
blackhole::sink::null_t
>().formatter(FORMAT_BASE).sink().log().get();
BH_BASE_LOG(log, MESSAGE_LONG)(
"id", 42,
"info", "le string"
);
}
BENCHMARK(Logger, Verbose) {
static auto log = initialize<
blackhole::verbose_logger_t<level_t>,
blackhole::formatter::string_t,
blackhole::sink::null_t
>().formatter(FORMAT_VERBOSE).sink().log(level_t::debug).get();
BH_LOG(log, level_t::info, MESSAGE_LONG)(
"id", 42,
"info", "le string"
);
}
BENCHMARK_BASELINE_X(Limits, Practical) {
static const char MESSAGE[] = "[1412592701.561182] [0]: Something bad is going on but I can handle it";
std::cout << MESSAGE << std::endl;
}
BENCHMARK_RELATIVE_X(Limits, Experimental) {
static auto log = initialize<
blackhole::verbose_logger_t<level_t>,
blackhole::formatter::string_t,
blackhole::sink::stream_t
>()
.formatter(FORMAT_VERBOSE)
.sink(blackhole::sink::stream_t::output_t::stdout)
.log(level_t::debug)
.get();
BH_LOG(log, level_t::info, MESSAGE_LONG);
}
BENCHMARK_BASELINE(Filtering, Rejected) {
static auto log = initialize<
blackhole::verbose_logger_t<level_t>,
blackhole::formatter::string_t,
blackhole::sink::null_t
>()
.formatter(FORMAT_BASE)
.sink()
.log(level_t::debug)
.mod(std::bind(&filter_by::verbosity<level_t>, std::placeholders::_1, level_t::info))
.get();
BH_LOG(log, level_t::debug, MESSAGE_LONG)(
"id", 42,
"info", "le string"
);
}
BENCHMARK(Filtering, Accepted) {
static auto log = initialize<
blackhole::verbose_logger_t<level_t>,
blackhole::formatter::string_t,
blackhole::sink::null_t
>()
.formatter(FORMAT_BASE)
.sink()
.log(level_t::debug)
.mod(std::bind(&filter_by::verbosity<level_t>, std::placeholders::_1, level_t::info))
.get();
BH_LOG(log, level_t::info, MESSAGE_LONG)(
"id", 42,
"info", "le string"
);
}
|
antmat/blackhole
|
src/benchmark/logger/logger.cpp
|
C++
|
mit
| 3,474 |
package main
import (
"database/sql"
"fmt"
"github.com/PuerkitoBio/goquery"
_ "github.com/go-sql-driver/mysql"
"sync"
"time"
)
type NewsSpider struct {
TargetUrl string
TargetSource string
MysqlDSN string
InsertStmt string
QueryStmt string
Duration int
}
type Paper struct {
Title string
ImgAddr string
Desc string
Content string
Author string
Time string
}
var (
NewsSpiderList = []*NewsSpider{
&NewsSpider{
TargetUrl: "https://news.jin10.com",
TargetSource: "金十数据",
MysqlDSN: "root:123456@tcp(localhost:3306)/phdb?charset=utf8",
InsertStmt: "INSERT INTO consult_info( consult_title, pic_addr, consult_desc, consult_content, consult_source, consult_author, create_date ) VALUES( ?, ?, ?, ?, ?, ?, ? )",
QueryStmt: "SELECT IF(COUNT(*),'true','false') FROM consult_info WHERE consult_title = ?",
Duration: 30,
},
&NewsSpider{
TargetUrl: "https://news.jin10.com",
TargetSource: "金十数据",
MysqlDSN: "root:123456@tcp(localhost:3306)/phdb?charset=utf8",
InsertStmt: "INSERT INTO consult_info( consult_title, pic_addr, consult_desc, consult_content, consult_source, consult_author, create_date ) VALUES( ?, ?, ?, ?, ?, ?, ? )",
QueryStmt: "SELECT IF(COUNT(*),'true','false') FROM consult_info WHERE consult_title = ?",
Duration: 5,
},
}
)
func main() {
var wg sync.WaitGroup
wg.Add(len(NewsSpiderList))
for _, ns := range NewsSpiderList {
go ns.Run(&wg)
}
wg.Wait()
}
func (ns *NewsSpider) Run(wg *sync.WaitGroup) {
defer wg.Done()
ticker := time.NewTicker(time.Duration(ns.Duration) * time.Minute)
ns.newsSpider()
for range ticker.C {
ns.newsSpider()
}
}
// 新闻爬虫
func (ns *NewsSpider) newsSpider() {
// mysql 初始化
db, err := sql.Open("mysql", ns.MysqlDSN)
if nil != err {
time.Sleep(time.Duration(1) * time.Minute)
if db, err = sql.Open("mysql", ns.MysqlDSN); nil != err {
panic(err.Error())
}
}
defer db.Close()
doc, err := goquery.NewDocument(ns.TargetUrl)
if nil != err {
return
}
paper := Paper{}
// 遍历类节点
doc.Find(".jin-newsList__item").Each(func(i int, s *goquery.Selection) {
// 文章封面
a_img := s.Find(".J_lazyImg").Eq(0)
if nil == a_img {
return
}
img, _ := a_img.Attr("data-original")
// 文章链接
a_href := s.Find("a").Eq(0)
if nil == a_href {
return
}
// 抓取详情
article_id, _ := a_href.Attr("href")
article_href := fmt.Sprintf("%s%s", ns.TargetUrl, article_id)
// 获取详情的dom
dom, err := goquery.NewDocument(article_href)
if nil != err {
return
}
// 设定来源
//source := "金十数据"
// 观看次数
// hit := dom.Find(".jin-meta p").Eq(0).Text()
// 评论数
// msg := dom.Find(".jin-meta p").Eq(1).Text()
// paper := Paper{
// Title: dom.Find(".jin-news-article_title").Text(), // 新闻标题
// ImgAddr: img,
// Desc: dom.Find(".jin-news-article_description").Text(), // 文章描述
// Content: dom.Find(".jin-news-article_content").Text(), // 文章内容
// Author: dom.Find(".jin-meta p").Eq(3).Text(),
// Time: dom.Find(".jin-meta p").Eq(2).Text() + " " + s.Find(".jin-newsList__time").Text(), // 发布日期
// }
paper.Title = dom.Find(".jin-news-article_title").Text() // 新闻标题
paper.ImgAddr = img
paper.Desc = dom.Find(".jin-news-article_description").Text() // 文章描述
paper.Content = dom.Find(".jin-news-article_content").Text() // 文章内容
paper.Author = dom.Find(".jin-meta p").Eq(3).Text()
paper.Time = dom.Find(".jin-meta p").Eq(2).Text() + " " + s.Find(".jin-newsList__time").Text() // 发布日期
// mysql 查询
if isExist, err := ns.fetchRow(db, paper.Title); nil == err && !isExist {
ns.insert(db, paper.Title, paper.ImgAddr, paper.Desc, paper.Content, ns.TargetSource, paper.Author, paper.Time)
}
})
}
//插入
func (ns *NewsSpider) insert(db *sql.DB, args ...interface{}) (int64, error) {
stmtIns, err := db.Prepare(ns.InsertStmt)
if err != nil {
return 0, err
}
defer stmtIns.Close()
result, err := stmtIns.Exec(args...)
if err != nil {
return 0, err
}
return result.LastInsertId()
}
//取一行数据,
func (ns *NewsSpider) fetchRow(db *sql.DB, args ...interface{}) (isExist bool, err error) {
stmtOut, err := db.Prepare(ns.QueryStmt)
if err != nil {
return
}
defer stmtOut.Close()
err = stmtOut.QueryRow(args...).Scan(&isExist)
return
}
|
researchlab/golearning
|
news_spider/news_spider_list.go
|
GO
|
mit
| 4,627 |
// Copyright IBM Corp. 2013,2016. All Rights Reserved.
// Node module: loopback-connector-mongodb
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
var g = require('strong-globalize')();
var DataSource = require('loopback-datasource-juggler').DataSource;
var config = require('rc')('loopback', { dev: { mongodb: {}}}).dev.mongodb;
var ds = new DataSource(require('../'), config);
var Customer = ds.createModel('customer', { seq: { type: Number, id: true }, name: String, emails: [
{ label: String, email: String },
], age: Number });
Customer.destroyAll(function(err) {
Customer.create({
seq: 1,
name: 'John1',
emails: [
{ label: 'work', email: 'john@x.com' },
{ label: 'home', email: 'john@y.com' },
],
age: 30,
}, function(err, customer1) {
console.log(customer1.toObject());
Customer.create({
seq: 2,
name: 'John2',
emails: [
{ label: 'work', email: 'john2@x.com' },
{ label: 'home', email: 'john2@y.com' },
],
age: 35,
}, function(err, customer2) {
Customer.find({ where: { 'emails.email': 'john@x.com' }}, function(err, customers) {
g.log('{{Customers}} matched by {{emails.email}} %s', customers);
});
Customer.find({ where: { 'emails.0.label': 'work' }}, function(err, customers) {
g.log('{{Customers}} matched by {{emails.0.label}} %s', customers);
});
/*
customer1.updateAttributes({name: 'John'}, function(err, result) {
console.log(err, result);
});
customer1.delete(function(err, result) {
customer1.updateAttributes({name: 'JohnX'}, function(err, result) {
console.log(err, result);
});
});
*/
Customer.findById(customer1.seq, function(err, customer1) {
console.log(customer1.toObject());
customer1.name = 'John';
customer1.save(function(err, customer1) {
console.log(customer1.toObject());
ds.disconnect();
});
});
});
});
});
|
Tuxity/loopback-connector-mongodb
|
example/model.js
|
JavaScript
|
mit
| 2,094 |
package com.github.highcharts4gwt.model.array.api;
public interface ArrayNumber
{
double get(int index);
int length();
void push(double value);
/**
* Replacement for native set method
*
* @param index
* @param value
*/
void setValue(int index, double value);
void setLength(int newLength);
}
|
hcharts/highcharts4gwt
|
src/main/java/com/github/highcharts4gwt/model/array/api/ArrayNumber.java
|
Java
|
mit
| 357 |
import src.dot.dotentity
class DotHeart(src.dot.dotentity.DotEntity):
def __init__(self):
res = [
"assets/img/red-brick.png",
"assets/img/black-brick.png"
]
grid = [
[0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
]
src.dot.dotentity.DotEntity.__init__(self, grid, res)
def setSmall(self):
self.setDotScale(0.5)
def setMedium(self):
self.setDotScale(0.75)
def setLarge(self):
self.setDotScale(1)
|
m4nolo/steering-all
|
src/dot/entities/dotheart.py
|
Python
|
mit
| 817 |
class Photo < ActiveRecord::Base
belongs_to :imageable, polymorphic: true
has_many :comments, as: :commentable
has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "default.jpg"
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
end
|
illiteratelinds/OurTinerary1
|
app/models/photo.rb
|
Ruby
|
mit
| 314 |
module.exports = {
entry: './main.js',
output: {
path: './',
filename: 'index.js',
},
devServer: {
inline: true,
port: 3333,
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['es2015', 'react']
}
}
]
}
}
|
claycarpenter/node-sandbox
|
rx-sandbox/creating-apps-with-observables/webpack.config.js
|
JavaScript
|
mit
| 355 |
<?php
namespace ManaPHP\Cli;
interface RunnerInterface
{
public function run();
}
|
manaphp/manaphp
|
ManaPHP/Cli/RunnerInterface.php
|
PHP
|
mit
| 87 |
# The Rukuli::Searchable module is the heart of Sikuli. It defines the
# wrapper around Sikuli's on screen image searching and matching capability
# It is implemented by the Region class.
#
module Rukuli
module Searchable
# Public: search for an image within a Region
#
# filename - A String representation of the filename to match against
# similarity - A Float between 0 and 1 representing the threshold for
# matching an image. Passing 1 corresponds to a 100% pixel for pixel
# match. Defaults to 0.9 (90% match)
#
# Examples
#
# region.find('needle.png')
# region.find('needle.png', 0.5)
#
# Returns an instance of Region representing the best match
#
# Throws Rukuli::FileNotFound if the file could not be found on the system
# Throws Rukuli::ImageNotMatched if no matches are found within the region
def find(filename, similarity = 0.9)
begin
pattern = build_pattern(filename, similarity)
match = Region.new(@java_obj.find(pattern))
match.highlight if Rukuli::Config.highlight_on_find
match
rescue NativeException => e
raise_exception e, filename
end
end
# Public: search for an image within a region (does not raise ImageNotFound exceptions)
#
# filename - A String representation of the filename to match against
# similarity - A Float between 0 and 1 representing the threshold for
# matching an image. Passing 1 corresponds to a 100% pixel for pixel
# match. Defaults to 0.9 (90% match)
#
# Examples
#
# region.find!('needle.png')
# region.find!('needle.png', 0.5)
#
# Returns the match or nil if no match is found
def find!(filename, similarity = 0.9)
begin
find(filename, similarity)
rescue Rukuli::ImageNotFound => e
nil
end
end
# Public: search for an image within a Region and return all matches
#
# TODO: Sort return results so they are always returned in the same order
# (top left to bottom right)
#
# filename - A String representation of the filename to match against
# similarity - A Float between 0 and 1 representing the threshold for
# matching an image. Passing 1 corresponds to a 100% pixel for pixel
# match. Defaults to 0.9 (90% match)
#
# Examples
#
# region.find_all('needle.png')
# region.find_all('needle.png', 0.5)
#
# Returns an array of Region objects that match the given file and
# threshold
#
# Throws Rukuli::FileNotFound if the file could not be found on the system
# Throws Rukuli::ImageNotMatched if no matches are found within the region
def find_all(filename, similarity = 0.9)
begin
pattern = build_pattern(filename, similarity)
matches = @java_obj.findAll(pattern)
regions = matches.collect do |r|
match = Region.new(r)
match.highlight if Rukuli::Config.highlight_on_find
match
end
regions
rescue NativeException => e
raise_exception e, filename
end
end
# Public: wait for a match to appear within a region
#
# filename - A String representation of the filename to match against
# time - A Fixnum representing the amount of time to wait defaults
# to 2 seconds
# similarity - A Float between 0 and 1 representing the threshold for
# matching an image. Passing 1 corresponds to a 100% pixel for pixel
# match. Defaults to 0.9 (90% match)
#
# Examples
#
# region.wait('needle.png') # wait for needle.png to appear for up to 1 second
# region.wait('needle.png', 10) # wait for needle.png to appear for 10 seconds
#
# Returns nothing
#
# Throws Rukuli::FileNotFound if the file could not be found on the system
# Throws Rukuli::ImageNotMatched if no matches are found within the region
def wait(filename, time = 2, similarity = 0.9)
begin
pattern = build_pattern(filename, similarity)
match = Region.new(@java_obj.wait(pattern, time))
match.highlight if Rukuli::Config.highlight_on_find
match
rescue NativeException => e
raise_exception e, filename
end
end
private
# Private: builds a java Pattern to check
#
# filename - A String representation of the filename to match against
# similarity - A Float between 0 and 1 representing the threshold for
# matching an image. Passing 1 corresponds to a 100% pixel for pixel
# match. Defaults to 0.9 (90% match)
#
# Returns a org.sikuli.script::Pattern object to match against
def build_pattern(filename, similarity)
org.sikuli.script::Pattern.new(filename).similar(similarity)
end
end
end
|
ndrluis/Rukuli
|
lib/rukuli/searchable.rb
|
Ruby
|
mit
| 4,815 |
package vm
import (
"fmt"
"io/ioutil"
"net/http"
"strings"
"github.com/goby-lang/goby/vm/classes"
"github.com/goby-lang/goby/vm/errors"
)
// Instance methods --------------------------------------------------------
func builtinHTTPClientInstanceMethods() []*BuiltinMethodObject {
//TODO: cookie jar and mutable client
goClient := http.DefaultClient
return []*BuiltinMethodObject{
{
// Sends a GET request to the target and returns a `Net::HTTP::Response` object.
Name: "get",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 1 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, errors.WrongNumberOfArgument, 1, len(args))
}
typeErr := t.vm.checkArgTypes(args, sourceLine, classes.StringClass)
if typeErr != nil {
return typeErr
}
resp, err := goClient.Get(args[0].Value().(string))
if err != nil {
return t.vm.InitErrorObject(errors.HTTPError, sourceLine, couldNotCompleteRequest, err)
}
gobyResp, err := responseGoToGoby(t, resp)
if err != nil {
return t.vm.InitErrorObject(errors.InternalError, sourceLine, err.Error())
}
return gobyResp
},
}, {
// Sends a POST request to the target and returns a `Net::HTTP::Response` object.
Name: "post",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 3 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, errors.WrongNumberOfArgument, 3, len(args))
}
typeErr := t.vm.checkArgTypes(args, sourceLine, classes.StringClass, classes.StringClass, classes.StringClass)
if typeErr != nil {
return typeErr
}
bodyR := strings.NewReader(args[2].Value().(string))
resp, err := goClient.Post(args[0].Value().(string), args[1].Value().(string), bodyR)
if err != nil {
return t.vm.InitErrorObject(errors.HTTPError, sourceLine, "Could not complete request, %s", err)
}
gobyResp, err := responseGoToGoby(t, resp)
if err != nil {
return t.vm.InitErrorObject(errors.InternalError, sourceLine, err.Error())
}
return gobyResp
},
}, {
// Sends a HEAD request to the target and returns a `Net::HTTP::Response` object.
Name: "head",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 1 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, errors.WrongNumberOfArgument, 1, len(args))
}
typeErr := t.vm.checkArgTypes(args, sourceLine, classes.StringClass)
if typeErr != nil {
return typeErr
}
resp, err := goClient.Head(args[0].Value().(string))
if err != nil {
return t.vm.InitErrorObject(errors.HTTPError, sourceLine, couldNotCompleteRequest, err)
}
gobyResp, err := responseGoToGoby(t, resp)
if err != nil {
return t.vm.InitErrorObject(errors.InternalError, sourceLine, err.Error())
}
return gobyResp
},
}, {
// Returns a blank `Net::HTTP::Request` object to be sent with the`exec` method
Name: "request",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
return httpRequestClass.initializeInstance()
},
}, {
// Sends a passed `Net::HTTP::Request` object and returns a `Net::HTTP::Response` object
Name: "exec",
Fn: func(receiver Object, sourceLine int, t *Thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 1 {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, errors.WrongNumberOfArgument, 1, len(args))
}
typeErr := t.vm.checkArgTypes(args, sourceLine, httpRequestClass.Name)
if typeErr != nil {
return typeErr
}
goReq, err := requestGobyToGo(args[0])
if err != nil {
return t.vm.InitErrorObject(errors.ArgumentError, sourceLine, err.Error())
}
goResp, err := goClient.Do(goReq)
if err != nil {
return t.vm.InitErrorObject(errors.HTTPError, sourceLine, couldNotCompleteRequest, err)
}
gobyResp, err := responseGoToGoby(t, goResp)
if err != nil {
return t.vm.InitErrorObject(errors.InternalError, sourceLine, err.Error())
}
return gobyResp
},
},
}
}
// Internal functions ===================================================
// Functions for initialization -----------------------------------------
func initClientClass(vm *VM, hc *RClass) *RClass {
clientClass := vm.initializeClass("Client")
hc.setClassConstant(clientClass)
clientClass.setBuiltinMethods(builtinHTTPClientInstanceMethods(), false)
httpClientClass = clientClass
return clientClass
}
// Other helper functions -----------------------------------------------
func requestGobyToGo(gobyReq Object) (*http.Request, error) {
//:method, :protocol, :body, :content_length, :transfer_encoding, :host, :path, :url, :params
uObj, ok := gobyReq.InstanceVariableGet("@url")
if !ok {
return nil, fmt.Errorf("could not get url")
}
u := uObj.(*StringObject).value
methodObj, ok := gobyReq.InstanceVariableGet("@method")
if !ok {
return nil, fmt.Errorf("could not get method")
}
method := methodObj.(*StringObject).value
var body string
if !(method == "GET" || method == "HEAD") {
bodyObj, ok := gobyReq.InstanceVariableGet("@body")
if !ok {
return nil, fmt.Errorf("could not get body")
}
body = bodyObj.(*StringObject).value
}
return http.NewRequest(method, u, strings.NewReader(body))
}
func responseGoToGoby(t *Thread, goResp *http.Response) (Object, error) {
gobyResp := httpResponseClass.initializeInstance()
//attr_accessor :body, :status, :status_code, :protocol, :transfer_encoding, :http_version, :request_http_version, :request
//attr_reader :headers
body, err := ioutil.ReadAll(goResp.Body)
if err != nil {
return nil, err
}
gobyResp.InstanceVariableSet("@body", t.vm.InitStringObject(string(body)))
gobyResp.InstanceVariableSet("@status_code", t.vm.InitObjectFromGoType(goResp.StatusCode))
gobyResp.InstanceVariableSet("@status", t.vm.InitObjectFromGoType(goResp.Status))
gobyResp.InstanceVariableSet("@protocol", t.vm.InitObjectFromGoType(goResp.Proto))
gobyResp.InstanceVariableSet("@transfer_encoding", t.vm.InitObjectFromGoType(goResp.TransferEncoding))
underHeaders := map[string]Object{}
for k, v := range goResp.Header {
underHeaders[k] = t.vm.InitObjectFromGoType(v)
}
gobyResp.InstanceVariableSet("@headers", t.vm.InitHashObject(underHeaders))
return gobyResp, nil
}
|
goby-lang/goby
|
vm/http_client.go
|
GO
|
mit
| 6,593 |
{
"name": "espresso.js",
"url": "https://github.com/techlayer/espresso.js.git"
}
|
bower/components
|
packages/espresso.js
|
JavaScript
|
mit
| 85 |
import React from 'react';
const EmptyStateIcon = props => (
<svg {...props.size || { width: '144px', height: '144px' }} {...props} viewBox="0 0 144 144">
{props.title && <title>{props.title}</title>}
<defs>
<path d="M76,8 L20,8 C15.6,8 12,11.6 12,16 L12,72 C12,76.4 15.6,80 20,80 L36,80 L48,92 L60,80 L76,80 C80.4,80 84,76.4 84,72 L84,16 C84,11.6 80.4,8 76,8 Z M55.52,51.52 L48,68 L40.48,51.52 L24,44 L40.48,36.48 L48,20 L55.52,36.48 L72,44 L55.52,51.52 Z" id="path-1"></path>
</defs>
<g id="Task---Insights" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd">
<g id="Insights---Extension-Not-Downloaded" transform="translate(-636.000000, -228.000000)">
<g id="Navigation/Empty-State-Icon" transform="translate(636.000000, 228.000000)">
<circle id="Background" fillOpacity="0.04" fill="#000000" cx="72" cy="72" r="72"></circle>
<g id="Icon/Alert/Error" opacity="0.1" transform="translate(24.000000, 24.000000)">
<polygon id="Spacing" points="0 0 96 0 96 96 0 96"></polygon>
<g id="Icon">
<mask id="mask-2" fill="white">
<use xlinkHref="#path-1"></use>
</mask>
<use id="Shape" fillOpacity="0" fill="#FFFFFF" fillRule="nonzero" xlinkHref="#path-1"></use>
<g id="Color" mask="url(#mask-2)" fill="#000000">
<rect id="Rectangle" x="0" y="0" width="96" height="96"></rect>
</g>
</g>
</g>
</g>
</g>
</g>
</svg>
);
export default EmptyStateIcon;
|
InsideSalesOfficial/insidesales-components
|
src/components/icons/EmptyStateIcon.js
|
JavaScript
|
mit
| 1,707 |
<?php
namespace Qafoo\ChangeTrack\Analyzer\ResultBuilder;
use Qafoo\ChangeTrack\Analyzer\Result\ClassChanges;
class ClassChangesBuilder
{
/**
* @var string
*/
private $className;
/**
* @var \Qafoo\ChangeTrack\Analyzer\ResultBuilder\MethodChangesBuilder[]
*/
private $methodChangesBuilders = array();
/**
* @param string $className
*/
public function __construct($className)
{
$this->className = $className;
}
/**
* @param string $methodName
* @return \Qafoo\ChangeTrack\Analyzer\ResultBuilder\MethodChangesBuilder
*/
public function methodChanges($methodName)
{
if (!isset($this->methodChangesBuilders[$methodName])) {
$this->methodChangesBuilders[$methodName] = new MethodChangesBuilder(
$methodName
);
}
return $this->methodChangesBuilders[$methodName];
}
/**
* @return \Qafoo\ChangeTrack\Analyzer\Result\ClassChanges
*/
public function buildClassChanges()
{
return new ClassChanges(
$this->className,
array_map(
function ($methodChangesBuilder) {
return $methodChangesBuilder->buildMethodChanges();
},
$this->methodChangesBuilders
)
);
}
}
|
Qafoo/changetrack
|
src/main/Qafoo/ChangeTrack/Analyzer/ResultBuilder/ClassChangesBuilder.php
|
PHP
|
mit
| 1,361 |
package v6_test
import (
"errors"
"time"
"code.cloudfoundry.org/bytefmt"
"code.cloudfoundry.org/cli/actor/actionerror"
"code.cloudfoundry.org/cli/actor/v2action"
"code.cloudfoundry.org/cli/actor/v2v3action"
"code.cloudfoundry.org/cli/actor/v3action"
"code.cloudfoundry.org/cli/api/cloudcontroller/ccv2/constant"
"code.cloudfoundry.org/cli/command/commandfakes"
"code.cloudfoundry.org/cli/command/translatableerror"
. "code.cloudfoundry.org/cli/command/v6"
"code.cloudfoundry.org/cli/command/v6/shared/sharedfakes"
"code.cloudfoundry.org/cli/command/v6/v6fakes"
"code.cloudfoundry.org/cli/types"
"code.cloudfoundry.org/cli/util/configv3"
"code.cloudfoundry.org/cli/util/ui"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
. "github.com/onsi/gomega/gbytes"
)
var _ = Describe("Restart Command", func() {
var (
cmd RestartCommand
testUI *ui.UI
fakeConfig *commandfakes.FakeConfig
fakeSharedActor *commandfakes.FakeSharedActor
fakeApplicationSummaryActor *sharedfakes.FakeApplicationSummaryActor
fakeActor *v6fakes.FakeRestartActor
binaryName string
executeErr error
)
BeforeEach(func() {
testUI = ui.NewTestUI(nil, NewBuffer(), NewBuffer())
fakeConfig = new(commandfakes.FakeConfig)
fakeSharedActor = new(commandfakes.FakeSharedActor)
fakeActor = new(v6fakes.FakeRestartActor)
fakeApplicationSummaryActor = new(sharedfakes.FakeApplicationSummaryActor)
cmd = RestartCommand{
UI: testUI,
Config: fakeConfig,
SharedActor: fakeSharedActor,
Actor: fakeActor,
ApplicationSummaryActor: fakeApplicationSummaryActor,
}
cmd.RequiredArgs.AppName = "some-app"
binaryName = "faceman"
fakeConfig.BinaryNameReturns(binaryName)
var err error
testUI.TimezoneLocation, err = time.LoadLocation("America/Los_Angeles")
Expect(err).NotTo(HaveOccurred())
fakeActor.RestartApplicationStub = func(app v2action.Application, client v2action.NOAAClient) (<-chan *v2action.LogMessage, <-chan error, <-chan v2action.ApplicationStateChange, <-chan string, <-chan error) {
messages := make(chan *v2action.LogMessage)
logErrs := make(chan error)
appState := make(chan v2action.ApplicationStateChange)
warnings := make(chan string)
errs := make(chan error)
go func() {
appState <- v2action.ApplicationStateStopping
appState <- v2action.ApplicationStateStaging
appState <- v2action.ApplicationStateStarting
close(messages)
close(logErrs)
close(appState)
close(warnings)
close(errs)
}()
return messages, logErrs, appState, warnings, errs
}
})
JustBeforeEach(func() {
executeErr = cmd.Execute(nil)
})
When("checking target fails", func() {
BeforeEach(func() {
fakeSharedActor.CheckTargetReturns(actionerror.NotLoggedInError{BinaryName: binaryName})
})
It("returns an error if the check fails", func() {
Expect(executeErr).To(MatchError(actionerror.NotLoggedInError{BinaryName: "faceman"}))
Expect(fakeSharedActor.CheckTargetCallCount()).To(Equal(1))
checkTargetedOrg, checkTargetedSpace := fakeSharedActor.CheckTargetArgsForCall(0)
Expect(checkTargetedOrg).To(BeTrue())
Expect(checkTargetedSpace).To(BeTrue())
})
})
When("the user is logged in, and org and space are targeted", func() {
BeforeEach(func() {
fakeConfig.HasTargetedOrganizationReturns(true)
fakeConfig.TargetedOrganizationReturns(configv3.Organization{Name: "some-org"})
fakeConfig.HasTargetedSpaceReturns(true)
fakeConfig.TargetedSpaceReturns(configv3.Space{
GUID: "some-space-guid",
Name: "some-space"})
fakeConfig.CurrentUserReturns(
configv3.User{Name: "some-user"},
nil)
})
When("getting the current user returns an error", func() {
var expectedErr error
BeforeEach(func() {
expectedErr = errors.New("getting current user error")
fakeConfig.CurrentUserReturns(
configv3.User{},
expectedErr)
})
It("returns the error", func() {
Expect(executeErr).To(MatchError(expectedErr))
})
})
It("displays flavor text", func() {
Expect(testUI.Out).To(Say("Restarting app some-app in org some-org / space some-space as some-user..."))
})
When("the app exists", func() {
When("the app is started", func() {
BeforeEach(func() {
fakeActor.GetApplicationByNameAndSpaceReturns(
v2action.Application{State: constant.ApplicationStarted},
v2action.Warnings{"warning-1", "warning-2"},
nil,
)
})
It("stops and starts the app", func() {
Expect(executeErr).ToNot(HaveOccurred())
Expect(testUI.Out).Should(Say("Stopping app..."))
Expect(testUI.Out).Should(Say("Staging app and tracing logs..."))
Expect(testUI.Out).Should(Say("Waiting for app to start..."))
Expect(testUI.Err).To(Say("warning-1"))
Expect(testUI.Err).To(Say("warning-2"))
Expect(fakeActor.RestartApplicationCallCount()).To(Equal(1))
})
})
When("the app is not already started", func() {
BeforeEach(func() {
fakeActor.GetApplicationByNameAndSpaceReturns(
v2action.Application{GUID: "app-guid", State: constant.ApplicationStopped},
v2action.Warnings{"warning-1", "warning-2"},
nil,
)
})
It("starts the app", func() {
Expect(executeErr).ToNot(HaveOccurred())
Expect(testUI.Err).To(Say("warning-1"))
Expect(testUI.Err).To(Say("warning-2"))
Expect(fakeActor.RestartApplicationCallCount()).To(Equal(1))
app, _ := fakeActor.RestartApplicationArgsForCall(0)
Expect(app.GUID).To(Equal("app-guid"))
})
When("passed an appStarting message", func() {
BeforeEach(func() {
fakeActor.RestartApplicationStub = func(app v2action.Application, client v2action.NOAAClient) (<-chan *v2action.LogMessage, <-chan error, <-chan v2action.ApplicationStateChange, <-chan string, <-chan error) {
messages := make(chan *v2action.LogMessage)
logErrs := make(chan error)
appState := make(chan v2action.ApplicationStateChange)
warnings := make(chan string)
errs := make(chan error)
go func() {
messages <- v2action.NewLogMessage("log message 1", 1, time.Unix(0, 0), "STG", "1")
messages <- v2action.NewLogMessage("log message 2", 1, time.Unix(0, 0), "STG", "1")
appState <- v2action.ApplicationStateStopping
appState <- v2action.ApplicationStateStaging
appState <- v2action.ApplicationStateStarting
close(messages)
close(logErrs)
close(appState)
close(warnings)
close(errs)
}()
return messages, logErrs, appState, warnings, errs
}
})
It("displays the log", func() {
Expect(executeErr).ToNot(HaveOccurred())
Expect(testUI.Out).To(Say("log message 1"))
Expect(testUI.Out).To(Say("log message 2"))
Expect(testUI.Out).To(Say("Waiting for app to start..."))
})
})
When("passed a log message", func() {
BeforeEach(func() {
fakeActor.RestartApplicationStub = func(app v2action.Application, client v2action.NOAAClient) (<-chan *v2action.LogMessage, <-chan error, <-chan v2action.ApplicationStateChange, <-chan string, <-chan error) {
messages := make(chan *v2action.LogMessage)
logErrs := make(chan error)
appState := make(chan v2action.ApplicationStateChange)
warnings := make(chan string)
errs := make(chan error)
go func() {
messages <- v2action.NewLogMessage("log message 1", 1, time.Unix(0, 0), "STG", "1")
messages <- v2action.NewLogMessage("log message 2", 1, time.Unix(0, 0), "STG", "1")
messages <- v2action.NewLogMessage("log message 3", 1, time.Unix(0, 0), "Something else", "1")
close(messages)
close(logErrs)
close(appState)
close(warnings)
close(errs)
}()
return messages, logErrs, appState, warnings, errs
}
})
It("displays the log", func() {
Expect(executeErr).ToNot(HaveOccurred())
Expect(testUI.Out).To(Say("log message 1"))
Expect(testUI.Out).To(Say("log message 2"))
Expect(testUI.Out).ToNot(Say("log message 3"))
})
})
When("passed an log err", func() {
Context("NOAA connection times out/closes", func() {
BeforeEach(func() {
fakeActor.RestartApplicationStub = func(app v2action.Application, client v2action.NOAAClient) (<-chan *v2action.LogMessage, <-chan error, <-chan v2action.ApplicationStateChange, <-chan string, <-chan error) {
messages := make(chan *v2action.LogMessage)
logErrs := make(chan error)
appState := make(chan v2action.ApplicationStateChange)
warnings := make(chan string)
errs := make(chan error)
go func() {
messages <- v2action.NewLogMessage("log message 1", 1, time.Unix(0, 0), "STG", "1")
messages <- v2action.NewLogMessage("log message 2", 1, time.Unix(0, 0), "STG", "1")
messages <- v2action.NewLogMessage("log message 3", 1, time.Unix(0, 0), "STG", "1")
logErrs <- actionerror.NOAATimeoutError{}
close(messages)
close(logErrs)
close(appState)
close(warnings)
close(errs)
}()
return messages, logErrs, appState, warnings, errs
}
})
It("displays a warning and continues until app has started", func() {
Expect(executeErr).To(BeNil())
Expect(testUI.Out).To(Say("message 1"))
Expect(testUI.Out).To(Say("message 2"))
Expect(testUI.Out).To(Say("message 3"))
Expect(testUI.Err).To(Say("timeout connecting to log server, no log will be shown"))
})
})
Context("an unexpected error occurs", func() {
var expectedErr error
BeforeEach(func() {
expectedErr = errors.New("err log message")
fakeActor.RestartApplicationStub = func(app v2action.Application, client v2action.NOAAClient) (<-chan *v2action.LogMessage, <-chan error, <-chan v2action.ApplicationStateChange, <-chan string, <-chan error) {
messages := make(chan *v2action.LogMessage)
logErrs := make(chan error)
appState := make(chan v2action.ApplicationStateChange)
warnings := make(chan string)
errs := make(chan error)
go func() {
logErrs <- expectedErr
close(messages)
close(logErrs)
close(appState)
close(warnings)
close(errs)
}()
return messages, logErrs, appState, warnings, errs
}
})
It("displays the error and continues to poll", func() {
Expect(executeErr).NotTo(HaveOccurred())
Expect(testUI.Err).To(Say(expectedErr.Error()))
})
})
})
When("passed a warning", func() {
Context("while NOAA is still logging", func() {
BeforeEach(func() {
fakeActor.RestartApplicationStub = func(app v2action.Application, client v2action.NOAAClient) (<-chan *v2action.LogMessage, <-chan error, <-chan v2action.ApplicationStateChange, <-chan string, <-chan error) {
messages := make(chan *v2action.LogMessage)
logErrs := make(chan error)
appState := make(chan v2action.ApplicationStateChange)
warnings := make(chan string)
errs := make(chan error)
go func() {
warnings <- "warning 1"
warnings <- "warning 2"
close(messages)
close(logErrs)
close(appState)
close(warnings)
close(errs)
}()
return messages, logErrs, appState, warnings, errs
}
})
It("displays the warnings to STDERR", func() {
Expect(executeErr).ToNot(HaveOccurred())
Expect(testUI.Err).To(Say("warning 1"))
Expect(testUI.Err).To(Say("warning 2"))
})
})
Context("while NOAA is no longer logging", func() {
BeforeEach(func() {
fakeActor.RestartApplicationStub = func(app v2action.Application, client v2action.NOAAClient) (<-chan *v2action.LogMessage, <-chan error, <-chan v2action.ApplicationStateChange, <-chan string, <-chan error) {
messages := make(chan *v2action.LogMessage)
logErrs := make(chan error)
appState := make(chan v2action.ApplicationStateChange)
warnings := make(chan string)
errs := make(chan error)
go func() {
warnings <- "warning 1"
warnings <- "warning 2"
logErrs <- actionerror.NOAATimeoutError{}
close(messages)
close(logErrs)
warnings <- "warning 3"
warnings <- "warning 4"
close(appState)
close(warnings)
close(errs)
}()
return messages, logErrs, appState, warnings, errs
}
})
It("displays the warnings to STDERR", func() {
Expect(executeErr).ToNot(HaveOccurred())
Expect(testUI.Err).To(Say("warning 1"))
Expect(testUI.Err).To(Say("warning 2"))
Expect(testUI.Err).To(Say("timeout connecting to log server, no log will be shown"))
Expect(testUI.Err).To(Say("warning 3"))
Expect(testUI.Err).To(Say("warning 4"))
})
})
})
When("passed an API err", func() {
var apiErr error
BeforeEach(func() {
fakeActor.RestartApplicationStub = func(app v2action.Application, client v2action.NOAAClient) (<-chan *v2action.LogMessage, <-chan error, <-chan v2action.ApplicationStateChange, <-chan string, <-chan error) {
messages := make(chan *v2action.LogMessage)
logErrs := make(chan error)
appState := make(chan v2action.ApplicationStateChange)
warnings := make(chan string)
errs := make(chan error)
go func() {
errs <- apiErr
close(messages)
close(logErrs)
close(appState)
close(warnings)
close(errs)
}()
return messages, logErrs, appState, warnings, errs
}
})
Context("an unexpected error", func() {
BeforeEach(func() {
apiErr = errors.New("err log message")
})
It("stops logging and returns the error", func() {
Expect(executeErr).To(MatchError(apiErr))
})
})
Context("staging failed", func() {
BeforeEach(func() {
apiErr = actionerror.StagingFailedError{Reason: "Something, but not nothing"}
})
It("stops logging and returns StagingFailedError", func() {
Expect(executeErr).To(MatchError(translatableerror.StagingFailedError{Message: "Something, but not nothing"}))
})
})
Context("staging timed out", func() {
BeforeEach(func() {
apiErr = actionerror.StagingTimeoutError{AppName: "some-app", Timeout: time.Nanosecond}
})
It("stops logging and returns StagingTimeoutError", func() {
Expect(executeErr).To(MatchError(translatableerror.StagingTimeoutError{AppName: "some-app", Timeout: time.Nanosecond}))
})
})
When("the app instance crashes", func() {
BeforeEach(func() {
apiErr = actionerror.ApplicationInstanceCrashedError{Name: "some-app"}
})
It("stops logging and returns UnsuccessfulStartError", func() {
Expect(executeErr).To(MatchError(translatableerror.UnsuccessfulStartError{AppName: "some-app", BinaryName: "faceman"}))
})
})
When("the app instance flaps", func() {
BeforeEach(func() {
apiErr = actionerror.ApplicationInstanceFlappingError{Name: "some-app"}
})
It("stops logging and returns UnsuccessfulStartError", func() {
Expect(executeErr).To(MatchError(translatableerror.UnsuccessfulStartError{AppName: "some-app", BinaryName: "faceman"}))
})
})
Context("starting timeout", func() {
BeforeEach(func() {
apiErr = actionerror.StartupTimeoutError{Name: "some-app"}
})
It("stops logging and returns StartupTimeoutError", func() {
Expect(executeErr).To(MatchError(translatableerror.StartupTimeoutError{AppName: "some-app", BinaryName: "faceman"}))
})
})
})
When("the app finishes starting", func() {
When("the API is at least 3.27.0", func() {
BeforeEach(func() {
fakeApplicationSummaryActor.CloudControllerV3APIVersionReturns("3.50.0")
fakeApplicationSummaryActor.GetApplicationSummaryByNameAndSpaceReturns(
v2v3action.ApplicationSummary{
ApplicationSummary: v3action.ApplicationSummary{
Application: v3action.Application{
Name: "some-app",
},
ProcessSummaries: v3action.ProcessSummaries{
{
Process: v3action.Process{
Type: "aba",
Command: "some-command-1",
MemoryInMB: types.NullUint64{Value: 32, IsSet: true},
DiskInMB: types.NullUint64{Value: 1024, IsSet: true},
},
},
{
Process: v3action.Process{
Type: "console",
Command: "some-command-2",
MemoryInMB: types.NullUint64{Value: 16, IsSet: true},
DiskInMB: types.NullUint64{Value: 512, IsSet: true},
},
},
},
},
},
v2v3action.Warnings{"combo-summary-warning"},
nil)
})
It("displays process information", func() {
Expect(executeErr).ToNot(HaveOccurred())
Expect(testUI.Out).To(Say(`name:\s+%s`, "some-app"))
Expect(testUI.Out).To(Say(`type:\s+aba`))
Expect(testUI.Out).To(Say(`instances:\s+0/0`))
Expect(testUI.Out).To(Say(`memory usage:\s+32M`))
Expect(testUI.Out).To(Say(`start command:\s+some-command-1`))
Expect(testUI.Out).To(Say(`type:\s+console`))
Expect(testUI.Out).To(Say(`instances:\s+0/0`))
Expect(testUI.Out).To(Say(`memory usage:\s+16M`))
Expect(testUI.Out).To(Say(`start command:\s+some-command-2`))
Expect(testUI.Err).To(Say("combo-summary-warning"))
Expect(fakeApplicationSummaryActor.GetApplicationSummaryByNameAndSpaceCallCount()).To(Equal(1))
passedAppName, spaceGUID, withObfuscatedValues := fakeApplicationSummaryActor.GetApplicationSummaryByNameAndSpaceArgsForCall(0)
Expect(passedAppName).To(Equal("some-app"))
Expect(spaceGUID).To(Equal("some-space-guid"))
Expect(withObfuscatedValues).To(BeTrue())
})
})
When("the API is below 3.27.0", func() {
var (
applicationSummary v2action.ApplicationSummary
warnings []string
)
BeforeEach(func() {
fakeApplicationSummaryActor.CloudControllerV3APIVersionReturns("1.0.0")
applicationSummary = v2action.ApplicationSummary{
Application: v2action.Application{
Name: "some-app",
GUID: "some-app-guid",
Instances: types.NullInt{Value: 3, IsSet: true},
Memory: types.NullByteSizeInMb{IsSet: true, Value: 128},
PackageUpdatedAt: time.Unix(0, 0),
DetectedBuildpack: types.FilteredString{IsSet: true, Value: "some-buildpack"},
State: "STARTED",
DetectedStartCommand: types.FilteredString{IsSet: true, Value: "some start command"},
},
IsolationSegment: "some-isolation-segment",
Stack: v2action.Stack{
Name: "potatos",
},
Routes: []v2action.Route{
{
Host: "banana",
Domain: v2action.Domain{
Name: "fruit.com",
},
Path: "/hi",
},
{
Domain: v2action.Domain{
Name: "foobar.com",
},
Port: types.NullInt{IsSet: true, Value: 13},
},
},
}
warnings = []string{"app-summary-warning"}
applicationSummary.RunningInstances = []v2action.ApplicationInstanceWithStats{
{
ID: 0,
State: v2action.ApplicationInstanceState(constant.ApplicationInstanceRunning),
Since: 1403140717.984577,
CPU: 0.73,
Disk: 50 * bytefmt.MEGABYTE,
DiskQuota: 2048 * bytefmt.MEGABYTE,
Memory: 100 * bytefmt.MEGABYTE,
MemoryQuota: 128 * bytefmt.MEGABYTE,
Details: "info from the backend",
},
}
})
When("the isolation segment is not empty", func() {
BeforeEach(func() {
fakeActor.GetApplicationSummaryByNameAndSpaceReturns(applicationSummary, warnings, nil)
})
It("displays the app summary with isolation segments as well as warnings", func() {
Expect(executeErr).ToNot(HaveOccurred())
Expect(testUI.Out).To(Say(`name:\s+some-app`))
Expect(testUI.Out).To(Say(`requested state:\s+started`))
Expect(testUI.Out).To(Say(`instances:\s+1\/3`))
Expect(testUI.Out).To(Say(`isolation segment:\s+some-isolation-segment`))
Expect(testUI.Out).To(Say(`usage:\s+128M x 3 instances`))
Expect(testUI.Out).To(Say(`routes:\s+banana.fruit.com/hi, foobar.com:13`))
Expect(testUI.Out).To(Say(`last uploaded:\s+\w{3} [0-3]\d \w{3} [0-2]\d:[0-5]\d:[0-5]\d \w+ \d{4}`))
Expect(testUI.Out).To(Say(`stack:\s+potatos`))
Expect(testUI.Out).To(Say(`buildpack:\s+some-buildpack`))
Expect(testUI.Out).To(Say(`start command:\s+some start command`))
Expect(testUI.Err).To(Say("app-summary-warning"))
})
It("should display the instance table", func() {
Expect(executeErr).ToNot(HaveOccurred())
Expect(testUI.Out).To(Say(`state\s+since\s+cpu\s+memory\s+disk`))
Expect(testUI.Out).To(Say(`#0\s+running\s+2014-06-19T01:18:37Z\s+73.0%\s+100M of 128M\s+50M of 2G\s+info from the backend`))
})
})
When("the isolation segment is empty", func() {
BeforeEach(func() {
applicationSummary.IsolationSegment = ""
fakeActor.GetApplicationSummaryByNameAndSpaceReturns(applicationSummary, warnings, nil)
})
It("displays the app summary without isolation segment as well as warnings", func() {
Expect(executeErr).ToNot(HaveOccurred())
Expect(testUI.Out).To(Say(`name:\s+some-app`))
Expect(testUI.Out).To(Say(`requested state:\s+started`))
Expect(testUI.Out).To(Say(`instances:\s+1\/3`))
Expect(testUI.Out).NotTo(Say("isolation segment:"))
Expect(testUI.Out).To(Say(`usage:\s+128M x 3 instances`))
Expect(testUI.Out).To(Say(`routes:\s+banana.fruit.com/hi, foobar.com:13`))
Expect(testUI.Out).To(Say(`last uploaded:\s+\w{3} [0-3]\d \w{3} [0-2]\d:[0-5]\d:[0-5]\d \w+ \d{4}`))
Expect(testUI.Out).To(Say(`stack:\s+potatos`))
Expect(testUI.Out).To(Say(`buildpack:\s+some-buildpack`))
Expect(testUI.Out).To(Say(`start command:\s+some start command`))
Expect(testUI.Err).To(Say("app-summary-warning"))
})
It("should display the instance table", func() {
Expect(executeErr).ToNot(HaveOccurred())
Expect(testUI.Out).To(Say(`state\s+since\s+cpu\s+memory\s+disk`))
Expect(testUI.Out).To(Say(`#0\s+running\s+2014-06-19T01:18:37Z\s+73.0%\s+100M of 128M\s+50M of 2G\s+info from the backend`))
})
})
})
})
})
})
When("the app does *not* exists", func() {
BeforeEach(func() {
fakeActor.GetApplicationByNameAndSpaceReturns(
v2action.Application{},
v2action.Warnings{"warning-1", "warning-2"},
actionerror.ApplicationNotFoundError{Name: "some-app"},
)
})
It("returns back an error", func() {
Expect(executeErr).To(MatchError(actionerror.ApplicationNotFoundError{Name: "some-app"}))
Expect(testUI.Err).To(Say("warning-1"))
Expect(testUI.Err).To(Say("warning-2"))
})
})
})
})
|
odlp/antifreeze
|
vendor/github.com/cloudfoundry/cli/command/v6/restart_command_test.go
|
GO
|
mit
| 23,815 |
package binarytrees;
/**
* Given a binary tree, find its depth.
*
* Signature of expected method:
*
* public static int maxDepth(TreeNode<?> root) {...}
*/
public class TreeDepth {
public static int maxDepth(TreeNode<?> root) {
if (root == null) {
return 0;
}
return Math.max(maxDepth(root.getLeft()), maxDepth(root.getRight())) + 1;
}
}
|
kowshik/big-o
|
java/src/binarytrees/TreeDepth.java
|
Java
|
mit
| 362 |
/*
* Copyright (c) 2017. MIT-license for Jari Van Melckebeke
* Note that there was a lot of educational work in this project,
* this project was (or is) used for an assignment from Realdolmen in Belgium.
* Please just don't abuse my work
*/
//! moment.js locale configuration
//! locale : Albanian (sq)
//! author : Flakërim Ismani : https://github.com/flakerimi
//! author: Menelion Elensúle: https://github.com/Oire (tests)
//! author : Oerd Cukalla : https://github.com/oerd (fixes)
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['moment'], factory) :
factory(global.moment)
}(this, function (moment) { 'use strict';
var sq = moment.defineLocale('sq', {
months : 'Janar_Shkurt_Mars_Prill_Maj_Qershor_Korrik_Gusht_Shtator_Tetor_Nëntor_Dhjetor'.split('_'),
monthsShort : 'Jan_Shk_Mar_Pri_Maj_Qer_Kor_Gus_Sht_Tet_Nën_Dhj'.split('_'),
weekdays : 'E Diel_E Hënë_E Martë_E Mërkurë_E Enjte_E Premte_E Shtunë'.split('_'),
weekdaysShort : 'Die_Hën_Mar_Mër_Enj_Pre_Sht'.split('_'),
weekdaysMin : 'D_H_Ma_Më_E_P_Sh'.split('_'),
weekdaysParseExact : true,
meridiemParse: /PD|MD/,
isPM: function (input) {
return input.charAt(0) === 'M';
},
meridiem : function (hours, minutes, isLower) {
return hours < 12 ? 'PD' : 'MD';
},
longDateFormat : {
LT : 'HH:mm',
LTS : 'HH:mm:ss',
L : 'DD/MM/YYYY',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY HH:mm',
LLLL : 'dddd, D MMMM YYYY HH:mm'
},
calendar : {
sameDay : '[Sot në] LT',
nextDay : '[Nesër në] LT',
nextWeek : 'dddd [në] LT',
lastDay : '[Dje në] LT',
lastWeek : 'dddd [e kaluar në] LT',
sameElse : 'L'
},
relativeTime : {
future : 'në %s',
past : '%s më parë',
s : 'disa sekonda',
m : 'një minutë',
mm : '%d minuta',
h : 'një orë',
hh : '%d orë',
d : 'një ditë',
dd : '%d ditë',
M : 'një muaj',
MM : '%d muaj',
y : 'një vit',
yy : '%d vite'
},
ordinalParse: /\d{1,2}\./,
ordinal : '%d.',
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4th is the first week of the year.
}
});
return sq;
}));
|
N00bface/Real-Dolmen-Stage-Opdrachten
|
stageopdracht/src/main/resources/static/vendors/moment/locale/sq.js
|
JavaScript
|
mit
| 2,726 |
// Dear ImGui: standalone example application for DirectX 10
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
#include "imgui.h"
#include "imgui_impl_win32.h"
#include "imgui_impl_dx10.h"
#include <d3d10_1.h>
#include <d3d10.h>
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
#include <tchar.h>
// Data
static ID3D10Device* g_pd3dDevice = NULL;
static IDXGISwapChain* g_pSwapChain = NULL;
static ID3D10RenderTargetView* g_mainRenderTargetView = NULL;
// Forward declarations of helper functions
bool CreateDeviceD3D(HWND hWnd);
void CleanupDeviceD3D();
void CreateRenderTarget();
void CleanupRenderTarget();
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
// Main code
int main(int, char**)
{
// Create application window
//ImGui_ImplWin32_EnableDpiAwareness();
WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, NULL, NULL, NULL, _T("ImGui Example"), NULL };
::RegisterClassEx(&wc);
HWND hwnd = ::CreateWindow(wc.lpszClassName, _T("Dear ImGui DirectX10 Example"), WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, wc.hInstance, NULL);
// Initialize Direct3D
if (!CreateDeviceD3D(hwnd))
{
CleanupDeviceD3D();
::UnregisterClass(wc.lpszClassName, wc.hInstance);
return 1;
}
// Show the window
::ShowWindow(hwnd, SW_SHOWDEFAULT);
::UpdateWindow(hwnd);
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO(); (void)io;
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
//io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
// Setup Dear ImGui style
ImGui::StyleColorsDark();
//ImGui::StyleColorsClassic();
// Setup Platform/Renderer backends
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX10_Init(g_pd3dDevice);
// Load Fonts
// - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
// - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
// - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
// - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
// - Read 'docs/FONTS.md' for more instructions and details.
// - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
//io.Fonts->AddFontDefault();
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
//io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
//ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
//IM_ASSERT(font != NULL);
// Our state
bool show_demo_window = true;
bool show_another_window = false;
ImVec4 clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
// Main loop
MSG msg;
ZeroMemory(&msg, sizeof(msg));
while (msg.message != WM_QUIT)
{
// Poll and handle messages (inputs, window resize, etc.)
// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
if (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
continue;
}
// Start the Dear ImGui frame
ImGui_ImplDX10_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
// 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
if (show_demo_window)
ImGui::ShowDemoWindow(&show_demo_window);
// 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
{
static float f = 0.0f;
static int counter = 0;
ImGui::Begin("Hello, world!"); // Create a window called "Hello, world!" and append into it.
ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
ImGui::Checkbox("Demo Window", &show_demo_window); // Edit bools storing our window open/close state
ImGui::Checkbox("Another Window", &show_another_window);
ImGui::SliderFloat("float", &f, 0.0f, 1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
ImGui::ColorEdit3("clear color", (float*)&clear_color); // Edit 3 floats representing a color
if (ImGui::Button("Button")) // Buttons return true when clicked (most widgets return true when edited/activated)
counter++;
ImGui::SameLine();
ImGui::Text("counter = %d", counter);
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::End();
}
// 3. Show another simple window.
if (show_another_window)
{
ImGui::Begin("Another Window", &show_another_window); // Pass a pointer to our bool variable (the window will have a closing button that will clear the bool when clicked)
ImGui::Text("Hello from another window!");
if (ImGui::Button("Close Me"))
show_another_window = false;
ImGui::End();
}
// Rendering
ImGui::Render();
g_pd3dDevice->OMSetRenderTargets(1, &g_mainRenderTargetView, NULL);
g_pd3dDevice->ClearRenderTargetView(g_mainRenderTargetView, (float*)&clear_color);
ImGui_ImplDX10_RenderDrawData(ImGui::GetDrawData());
g_pSwapChain->Present(1, 0); // Present with vsync
//g_pSwapChain->Present(0, 0); // Present without vsync
}
ImGui_ImplDX10_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
CleanupDeviceD3D();
::DestroyWindow(hwnd);
::UnregisterClass(wc.lpszClassName, wc.hInstance);
return 0;
}
// Helper functions
bool CreateDeviceD3D(HWND hWnd)
{
// Setup swap chain
DXGI_SWAP_CHAIN_DESC sd;
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 2;
sd.BufferDesc.Width = 0;
sd.BufferDesc.Height = 0;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
UINT createDeviceFlags = 0;
//createDeviceFlags |= D3D10_CREATE_DEVICE_DEBUG;
if (D3D10CreateDeviceAndSwapChain(NULL, D3D10_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags, D3D10_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice) != S_OK)
return false;
CreateRenderTarget();
return true;
}
void CleanupDeviceD3D()
{
CleanupRenderTarget();
if (g_pSwapChain) { g_pSwapChain->Release(); g_pSwapChain = NULL; }
if (g_pd3dDevice) { g_pd3dDevice->Release(); g_pd3dDevice = NULL; }
}
void CreateRenderTarget()
{
ID3D10Texture2D* pBackBuffer;
g_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
g_pd3dDevice->CreateRenderTargetView(pBackBuffer, NULL, &g_mainRenderTargetView);
pBackBuffer->Release();
}
void CleanupRenderTarget()
{
if (g_mainRenderTargetView) { g_mainRenderTargetView->Release(); g_mainRenderTargetView = NULL; }
}
// Forward declare message handler from imgui_impl_win32.cpp
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
// Win32 message handler
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
return true;
switch (msg)
{
case WM_SIZE:
if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED)
{
CleanupRenderTarget();
g_pSwapChain->ResizeBuffers(0, (UINT)LOWORD(lParam), (UINT)HIWORD(lParam), DXGI_FORMAT_UNKNOWN, 0);
CreateRenderTarget();
}
return 0;
case WM_SYSCOMMAND:
if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
return 0;
break;
case WM_DESTROY:
::PostQuitMessage(0);
return 0;
}
return ::DefWindowProc(hWnd, msg, wParam, lParam);
}
|
zq317157782/Narukami
|
external/imgui/examples/example_win32_directx10/main.cpp
|
C++
|
mit
| 9,656 |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddARelationBetweenStudentAndTeam extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('students', function (Blueprint $table) {
$table->integer('team_id')->default(null)->nullable()->after('ce');
$table->boolean('team_accepted')->default(false)->after('team_id');
});
Schema::table('teams', function (Blueprint $table) {
$table->integer('respo_id')->after('img_url');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('students', function (Blueprint $table) {
$table->dropColumn('team_id');
$table->dropColumn('team_accepted');
});
Schema::table('teams', function (Blueprint $table) {
$table->dropColumn('respo_id');
});
}
}
|
ungdev/integration-UTT
|
database/migrations/2016_07_09_171819_add_a_relation_between_student_and_team.php
|
PHP
|
mit
| 1,034 |
// (c) 2012 Guilherme Oenning
var hCharts=[];function setIntervalAndExecute(func,time){func();return(setInterval(func,time));}
Highcharts.Chart.prototype.clearSeries=function(){while(this.series.length>0)
this.series[0].remove(true);};function loadChartAjax(options){var chart=hCharts[options.chartId];var url=options.url;var animation=options.animation;var interval=options.interval;var fn=function(){if("GET"===options.method){$.getJSON(url,function(data){parseAjaxResult(chart,data,animation)});}else{$.post(url,null,function(data){parseAjaxResult(chart,data,animation)},"json");}}
if(typeof(interval)!='undefined')
setIntervalAndExecute(fn,interval);else
fn();}
function parseAjaxResult(chart,data,animation){$.each(data,function(key,value){if(chart.series.length>key){var serie=chart.series[key];for(var i=0;i<serie.data.length;i++){serie.data[i].update(value.Values[i],false,false);}}
else{chart.addSeries({name:value.Name,data:value.Values},false,false);}});chart.redraw(animation);}
|
oenning/highcharts-mvc
|
src/Highcharts.Mvc/highcharts-mvc.min.js
|
JavaScript
|
mit
| 994 |
# frozen_string_literal: true
RSpec.describe RuboCop::Cop::Style::EvenOdd do
subject(:cop) { described_class.new }
it 'converts x % 2 == 0 to #even?' do
expect_offense(<<~RUBY)
x % 2 == 0
^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
x.even?
RUBY
end
it 'converts x % 2 != 0 to #odd?' do
expect_offense(<<~RUBY)
x % 2 != 0
^^^^^^^^^^ Replace with `Integer#odd?`.
RUBY
expect_correction(<<~RUBY)
x.odd?
RUBY
end
it 'converts (x % 2) == 0 to #even?' do
expect_offense(<<~RUBY)
(x % 2) == 0
^^^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
x.even?
RUBY
end
it 'converts (x % 2) != 0 to #odd?' do
expect_offense(<<~RUBY)
(x % 2) != 0
^^^^^^^^^^^^ Replace with `Integer#odd?`.
RUBY
expect_correction(<<~RUBY)
x.odd?
RUBY
end
it 'converts x % 2 == 1 to #odd?' do
expect_offense(<<~RUBY)
x % 2 == 1
^^^^^^^^^^ Replace with `Integer#odd?`.
RUBY
expect_correction(<<~RUBY)
x.odd?
RUBY
end
it 'converts x % 2 != 1 to #even?' do
expect_offense(<<~RUBY)
x % 2 != 1
^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
x.even?
RUBY
end
it 'converts (x % 2) == 1 to #odd?' do
expect_offense(<<~RUBY)
(x % 2) == 1
^^^^^^^^^^^^ Replace with `Integer#odd?`.
RUBY
expect_correction(<<~RUBY)
x.odd?
RUBY
end
it 'converts (y % 2) != 1 to #even?' do
expect_offense(<<~RUBY)
(y % 2) != 1
^^^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
y.even?
RUBY
end
it 'converts (x.y % 2) != 1 to #even?' do
expect_offense(<<~RUBY)
(x.y % 2) != 1
^^^^^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
x.y.even?
RUBY
end
it 'converts (x(y) % 2) != 1 to #even?' do
expect_offense(<<~RUBY)
(x(y) % 2) != 1
^^^^^^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
x(y).even?
RUBY
end
it 'accepts x % 2 == 2' do
expect_no_offenses('x % 2 == 2')
end
it 'accepts x % 3 == 0' do
expect_no_offenses('x % 3 == 0')
end
it 'accepts x % 3 != 0' do
expect_no_offenses('x % 3 != 0')
end
it 'converts (x._(y) % 2) != 1 to even?' do
expect_offense(<<~RUBY)
(x._(y) % 2) != 1
^^^^^^^^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
x._(y).even?
RUBY
end
it 'converts (x._(y)) % 2 != 1 to even?' do
expect_offense(<<~RUBY)
(x._(y)) % 2 != 1
^^^^^^^^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
(x._(y)).even?
RUBY
end
it 'converts x._(y) % 2 != 1 to even?' do
expect_offense(<<~RUBY)
x._(y) % 2 != 1
^^^^^^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
x._(y).even?
RUBY
end
it 'converts 1 % 2 != 1 to even?' do
expect_offense(<<~RUBY)
1 % 2 != 1
^^^^^^^^^^ Replace with `Integer#even?`.
RUBY
expect_correction(<<~RUBY)
1.even?
RUBY
end
it 'converts complex examples' do
expect_offense(<<~RUBY)
if (y % 2) != 1
^^^^^^^^^^^^ Replace with `Integer#even?`.
method == :== ? :even : :odd
elsif x % 2 == 1
^^^^^^^^^^ Replace with `Integer#odd?`.
method == :== ? :odd : :even
end
RUBY
expect_correction(<<~RUBY)
if y.even?
method == :== ? :even : :odd
elsif x.odd?
method == :== ? :odd : :even
end
RUBY
end
end
|
tdeo/rubocop
|
spec/rubocop/cop/style/even_odd_spec.rb
|
Ruby
|
mit
| 3,756 |
export type SpanId = number
export const traceGlobals: Map<any, any> = new Map()
export const setGlobal = (key: any, val: any) => {
traceGlobals.set(key, val)
}
|
zeit/next.js
|
packages/next/trace/shared.ts
|
TypeScript
|
mit
| 164 |
require 'test_helper'
class PageTest < Zena::Unit::TestCase
context 'Creating a page' do
setup do
login(:tiger)
end
should 'work with just a title' do
assert_difference('Node.count', 1) do
secure(Page) { Page.create(:parent_id=>nodes_id(:projects), :title=>'lazy node')}
end
end
should 'allow same title' do
wiki_title = nodes(:wiki).title
assert_difference('Node.count', 1) do
page = secure(Page) { Page.create(:parent_id=>nodes_id(:projects), :title => wiki_title)}
assert_equal page.title, wiki_title
end
end
end # Creating a page
def test_custom_base_path
login(:tiger)
node = secure!(Node) { nodes(:wiki) }
bird = secure!(Node) { nodes(:bird_jpg)}
assert_equal '', node.basepath
assert_equal '', bird.basepath
assert_equal node[:id], bird[:parent_id]
assert node.update_attributes(:custom_base => true)
assert_equal '18/29', node.basepath
bird = secure!(Node) { nodes(:bird_jpg)}
assert_equal '18/29', bird.basepath
end
end
|
BackupTheBerlios/zena
|
test/unit/page_test.rb
|
Ruby
|
mit
| 1,066 |
#pragma once
#include "physics/discrete_trajectory_iterator.hpp"
#include "astronomy/epoch.hpp"
#include "geometry/named_quantities.hpp"
namespace principia {
namespace physics {
namespace internal_discrete_trajectory_iterator {
using geometry::InfiniteFuture;
using geometry::Instant;
template<typename Frame>
FORCE_INLINE(inline) DiscreteTrajectoryIterator<Frame>&
DiscreteTrajectoryIterator<Frame>::operator++() {
CHECK(!is_at_end(point_));
auto& point = iterator(point_);
Instant const previous_time = point->time;
do {
++point;
if (point == segment_->timeline_end()) {
do {
++segment_;
} while (!segment_.is_end() && segment_->timeline_empty());
if (segment_.is_end()) {
point_.reset();
break;
} else {
point = segment_->timeline_begin();
}
}
} while (point->time == previous_time);
return *this;
}
template<typename Frame>
FORCE_INLINE(inline) DiscreteTrajectoryIterator<Frame>&
DiscreteTrajectoryIterator<Frame>::operator--() {
bool const point_is_at_end = is_at_end(point_);
if (point_is_at_end) {
// Move the iterator to the end of the last segment.
segment_ = std::prev(segment_.segments().end());
point_ = segment_->timeline_end();
// Now proceed with the decrement.
}
auto& point = iterator(point_);
Instant const previous_time = point_is_at_end ? InfiniteFuture : point->time;
do {
if (point == segment_->timeline_begin()) {
CHECK(!segment_.is_begin());
--segment_;
point = segment_->timeline_end();
}
--point;
} while (point->time == previous_time);
return *this;
}
template<typename Frame>
DiscreteTrajectoryIterator<Frame>
DiscreteTrajectoryIterator<Frame>::operator++(int) { // NOLINT
auto const initial = *this;
++*this;
return initial;
}
template<typename Frame>
DiscreteTrajectoryIterator<Frame>
DiscreteTrajectoryIterator<Frame>::operator--(int) { // NOLINT
auto const initial = *this;
--*this;
return initial;
}
template<typename Frame>
typename DiscreteTrajectoryIterator<Frame>::reference
DiscreteTrajectoryIterator<Frame>::operator*() const {
CHECK(!is_at_end(point_));
return *iterator(point_);
}
template<typename Frame>
typename DiscreteTrajectoryIterator<Frame>::pointer
DiscreteTrajectoryIterator<Frame>::operator->() const {
CHECK(!is_at_end(point_));
return &*iterator(point_);
}
template<typename Frame>
DiscreteTrajectoryIterator<Frame>&
DiscreteTrajectoryIterator<Frame>::operator+=(difference_type const n) {
if (n < 0) {
return *this -= (-n);
} else {
// This loop attempts to skip entire segments. To do this, it relies on
// how operator++ moves through the trajectory. If this was to change this
// function might become less efficient, but it would not become incorrect
// (it would fall back to vanilla increments).
difference_type m = n;
while (m > 0) {
CHECK(!is_at_end(point_));
auto& point = iterator(point_);
// We know that operator++ never leaves |point_| at |timeline_begin()|.
// Therefore, to detect that we are in a new segment, we must check for
// the second point of the segment.
if (segment_->timeline_size() > 2 &&
segment_->timeline_size() <= m + 2 &&
point == std::next(segment_->timeline_begin())) {
point = std::prev(segment_->timeline_end());
m -= segment_->timeline_size() - 2;
} else {
++*this;
--m;
}
}
return *this;
}
}
template<typename Frame>
DiscreteTrajectoryIterator<Frame>&
DiscreteTrajectoryIterator<Frame>::operator-=(difference_type const n) {
if (n < 0) {
return *this += (-n);
} else {
difference_type m = n;
if (m > 0 && is_at_end(point_)) {
--*this;
--m;
}
// This loop attempts to skip entire segments. To do this, it relies on
// how operator-- moves through the trajectory. If this was to change this
// function might become less efficient, but it would not become incorrect
// (it would fall back to vanilla decrements).
while (m > 0) {
auto& point = iterator(point_);
// We know that operator-- never leaves |point_| at
// |std::prev(timeline_end())|. Therefore, to detect that we are in a new
// segment, we must check for the second-to-last point of the segment.
if (segment_->timeline_size() > 2 &&
segment_->timeline_size() <= m + 2 &&
point == std::prev(std::prev(segment_->timeline_end()))) {
point = segment_->timeline_begin();
m -= segment_->timeline_size() - 2;
} else {
--*this;
--m;
}
}
return *this;
}
}
template<typename Frame>
typename DiscreteTrajectoryIterator<Frame>::reference
DiscreteTrajectoryIterator<Frame>::operator[](difference_type const n) const {
return *(*this + n);
}
template<typename Frame>
DiscreteTrajectoryIterator<Frame> DiscreteTrajectoryIterator<Frame>::operator-(
typename DiscreteTrajectoryIterator<Frame>::difference_type const n) const {
auto mutable_it = *this;
return mutable_it -= n;
}
template<typename Frame>
typename DiscreteTrajectoryIterator<Frame>::difference_type
DiscreteTrajectoryIterator<Frame>::operator-(
DiscreteTrajectoryIterator<Frame> const right) const {
auto const left = *this;
auto it = right;
Instant const left_time =
is_at_end(left.point_) ? InfiniteFuture : left->time;
// This code is similar to operator+=.
difference_type m = 0;
while (it != left) {
CHECK(!is_at_end(it.point_));
auto& point = iterator(it.point_);
auto const& segment = it.segment_;
if (segment->timeline_size() > 2 &&
std::prev(segment->timeline_end())->time <= left_time &&
point == std::next(segment->timeline_begin())) {
point = std::prev(segment->timeline_end());
m += segment->timeline_size() - 2;
} else {
++it;
++m;
}
}
return m;
}
template<typename Frame>
bool DiscreteTrajectoryIterator<Frame>::operator==(
DiscreteTrajectoryIterator const other) const {
if (is_at_end(point_)) {
return segment_ == other.segment_ && is_at_end(other.point_);
} else if (is_at_end(other.point_)) {
return false;
} else {
return iterator(point_)->time == iterator(other.point_)->time;
}
}
template<typename Frame>
bool DiscreteTrajectoryIterator<Frame>::operator!=(
DiscreteTrajectoryIterator const other) const {
return !operator==(other);
}
template<typename Frame>
bool DiscreteTrajectoryIterator<Frame>::operator<(
DiscreteTrajectoryIterator const other) const {
if (is_at_end(point_)) {
return false;
} else if (is_at_end(other.point_)) {
return true;
} else {
return iterator(point_)->time < iterator(other.point_)->time;
}
}
template<typename Frame>
bool DiscreteTrajectoryIterator<Frame>::operator>(
DiscreteTrajectoryIterator const other) const {
if (is_at_end(other.point_)) {
return false;
} else if (is_at_end(point_)) {
return true;
} else {
return iterator(point_)->time > iterator(other.point_)->time;
}
}
template<typename Frame>
bool DiscreteTrajectoryIterator<Frame>::operator<=(
DiscreteTrajectoryIterator const other) const {
return !operator>(other);
}
template<typename Frame>
bool DiscreteTrajectoryIterator<Frame>::operator>=(
DiscreteTrajectoryIterator const other) const {
return !operator<(other);
}
template <typename Frame>
DiscreteTrajectoryIterator<Frame>
DiscreteTrajectoryIterator<Frame>::EndOfLastSegment(
DiscreteTrajectorySegmentIterator<Frame> const segment) {
DCHECK(segment.is_end());
return DiscreteTrajectoryIterator<Frame>(segment, std::nullopt);
}
template<typename Frame>
DiscreteTrajectoryIterator<Frame>::DiscreteTrajectoryIterator(
DiscreteTrajectorySegmentIterator<Frame> const segment,
OptionalTimelineConstIterator const point)
: segment_(segment),
point_(point) {
bool incremented_segment = false;
while (!segment_.is_end() && segment_->timeline_empty()) {
++segment_;
incremented_segment = true;
}
if (segment_.is_end()) {
point_.reset();
} else if (incremented_segment) {
point_ = segment_->timeline_begin();
}
}
template<typename Frame>
bool DiscreteTrajectoryIterator<Frame>::is_at_end(
OptionalTimelineConstIterator const point) {
return !point.has_value();
}
template<typename Frame>
typename DiscreteTrajectoryIterator<Frame>::Timeline::const_iterator&
DiscreteTrajectoryIterator<Frame>::iterator(
OptionalTimelineConstIterator& point) {
DCHECK(point.has_value());
return point.value();
}
template<typename Frame>
typename DiscreteTrajectoryIterator<Frame>::Timeline::const_iterator const&
DiscreteTrajectoryIterator<Frame>::iterator(
OptionalTimelineConstIterator const& point) {
DCHECK(point.has_value());
return point.value();
}
template<typename Frame>
DiscreteTrajectoryIterator<Frame> operator+(
DiscreteTrajectoryIterator<Frame> const it,
typename DiscreteTrajectoryIterator<Frame>::difference_type const n) {
auto mutable_it = it;
return mutable_it += n;
}
template<typename Frame>
DiscreteTrajectoryIterator<Frame> operator+(
typename DiscreteTrajectoryIterator<Frame>::difference_type const n,
DiscreteTrajectoryIterator<Frame> const it) {
auto mutable_it = it;
return mutable_it += n;
}
} // namespace internal_discrete_trajectory_iterator
} // namespace physics
} // namespace principia
|
mockingbirdnest/Principia
|
physics/discrete_trajectory_iterator_body.hpp
|
C++
|
mit
| 9,469 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CAD.Core;
namespace CAD.Web
{
public class Tenant : ITenant
{
public string Name { get; set; }
private Lazy<List<TenantPlugin>> _plugins = new Lazy<List<TenantPlugin>>(() => new List<TenantPlugin>());
public List<TenantPlugin> Plugins
{
get
{
return this._plugins.Value;
}
}
public TenantPlugin GetPlugin(string name)
{
return this.Plugins.Where(p => p.Name == name).FirstOrDefault();
}
public void AddPlugin(TenantPlugin tenant)
{
var plugin = this.GetPlugin(tenant.Name);
if(plugin != null)
{
this._plugins.Value.Remove(plugin);
}
this._plugins.Value.Add(tenant);
}
public void SortPriority()
{
this._plugins.Value.Sort((p1,p2) => p1.Priority.CompareTo(p2.Priority));
}
}
}
|
markglibres/cad.web
|
src/Configuration/Tenant.cs
|
C#
|
mit
| 1,119 |
<?php
/**
* Redirect
*
* HTTP redirection commands.
*
* @package core
* @author stefano.azzolini@caffeinalab.com
* @copyright Caffeina srl - 2015 - http://caffeina.it
*/
class Redirect {
use Module;
public static function to($url, $status=302){
if ($link = Filter::with('core.redirect',$url)) {
Response::clean();
Response::status($status);
Response::header('Location', $link);
Response::send();
exit;
}
}
public static function back(){
if ($link = Filter::with('core.redirect', (empty($_SERVER['HTTP_REFERER']) ? Request::get('redirect_uri',false) : $_SERVER['HTTP_REFERER']) )){
Response::clean();
Response::header('Location', $link);
Response::send();
exit;
}
}
public static function viaJavaScript($url, $parent=false){
if ($link = Filter::with('core.redirect', $url)){
Response::type('text/html');
Response::add('<script>'.($parent?'parent.':'').'location.href="'.addslashes($link).'"</script>');
Response::send();
exit;
}
}
}
|
caffeina-core/core
|
classes/Redirect.php
|
PHP
|
mit
| 1,140 |
##
# This code was generated by
# \ / _ _ _| _ _
# | (_)\/(_)(_|\/| |(/_ v1.0.0
# / /
#
# frozen_string_literal: true
module Twilio
module REST
class Conversations < Domain
class V1 < Version
class ServiceContext < InstanceContext
class ConfigurationContext < InstanceContext
class NotificationList < ListResource
##
# Initialize the NotificationList
# @param [Version] version Version that contains the resource
# @param [String] chat_service_sid The unique string that we created to identify
# the Service configuration resource.
# @return [NotificationList] NotificationList
def initialize(version, chat_service_sid: nil)
super(version)
# Path Solution
@solution = {chat_service_sid: chat_service_sid}
end
##
# Provide a user friendly representation
def to_s
'#<Twilio.Conversations.V1.NotificationList>'
end
end
class NotificationPage < Page
##
# Initialize the NotificationPage
# @param [Version] version Version that contains the resource
# @param [Response] response Response from the API
# @param [Hash] solution Path solution for the resource
# @return [NotificationPage] NotificationPage
def initialize(version, response, solution)
super(version, response)
# Path Solution
@solution = solution
end
##
# Build an instance of NotificationInstance
# @param [Hash] payload Payload response from the API
# @return [NotificationInstance] NotificationInstance
def get_instance(payload)
NotificationInstance.new(@version, payload, chat_service_sid: @solution[:chat_service_sid], )
end
##
# Provide a user friendly representation
def to_s
'<Twilio.Conversations.V1.NotificationPage>'
end
end
class NotificationContext < InstanceContext
##
# Initialize the NotificationContext
# @param [Version] version Version that contains the resource
# @param [String] chat_service_sid The SID of the {Conversation
# Service}[https://www.twilio.com/docs/conversations/api/service-resource] the
# Configuration applies to.
# @return [NotificationContext] NotificationContext
def initialize(version, chat_service_sid)
super(version)
# Path Solution
@solution = {chat_service_sid: chat_service_sid, }
@uri = "/Services/#{@solution[:chat_service_sid]}/Configuration/Notifications"
end
##
# Update the NotificationInstance
# @param [Boolean] log_enabled Weather the notification logging is enabled.
# @param [Boolean] new_message_enabled Whether to send a notification when a new
# message is added to a conversation. The default is `false`.
# @param [String] new_message_template The template to use to create the
# notification text displayed when a new message is added to a conversation and
# `new_message.enabled` is `true`.
# @param [String] new_message_sound The name of the sound to play when a new
# message is added to a conversation and `new_message.enabled` is `true`.
# @param [Boolean] new_message_badge_count_enabled Whether the new message badge
# is enabled. The default is `false`.
# @param [Boolean] added_to_conversation_enabled Whether to send a notification
# when a participant is added to a conversation. The default is `false`.
# @param [String] added_to_conversation_template The template to use to create the
# notification text displayed when a participant is added to a conversation and
# `added_to_conversation.enabled` is `true`.
# @param [String] added_to_conversation_sound The name of the sound to play when a
# participant is added to a conversation and `added_to_conversation.enabled` is
# `true`.
# @param [Boolean] removed_from_conversation_enabled Whether to send a
# notification to a user when they are removed from a conversation. The default is
# `false`.
# @param [String] removed_from_conversation_template The template to use to create
# the notification text displayed to a user when they are removed from a
# conversation and `removed_from_conversation.enabled` is `true`.
# @param [String] removed_from_conversation_sound The name of the sound to play to
# a user when they are removed from a conversation and
# `removed_from_conversation.enabled` is `true`.
# @param [Boolean] new_message_with_media_enabled Whether to send a notification
# when a new message with media/file attachments is added to a conversation. The
# default is `false`.
# @param [String] new_message_with_media_template The template to use to create
# the notification text displayed when a new message with media/file attachments
# is added to a conversation and `new_message.attachments.enabled` is `true`.
# @return [NotificationInstance] Updated NotificationInstance
def update(log_enabled: :unset, new_message_enabled: :unset, new_message_template: :unset, new_message_sound: :unset, new_message_badge_count_enabled: :unset, added_to_conversation_enabled: :unset, added_to_conversation_template: :unset, added_to_conversation_sound: :unset, removed_from_conversation_enabled: :unset, removed_from_conversation_template: :unset, removed_from_conversation_sound: :unset, new_message_with_media_enabled: :unset, new_message_with_media_template: :unset)
data = Twilio::Values.of({
'LogEnabled' => log_enabled,
'NewMessage.Enabled' => new_message_enabled,
'NewMessage.Template' => new_message_template,
'NewMessage.Sound' => new_message_sound,
'NewMessage.BadgeCountEnabled' => new_message_badge_count_enabled,
'AddedToConversation.Enabled' => added_to_conversation_enabled,
'AddedToConversation.Template' => added_to_conversation_template,
'AddedToConversation.Sound' => added_to_conversation_sound,
'RemovedFromConversation.Enabled' => removed_from_conversation_enabled,
'RemovedFromConversation.Template' => removed_from_conversation_template,
'RemovedFromConversation.Sound' => removed_from_conversation_sound,
'NewMessage.WithMedia.Enabled' => new_message_with_media_enabled,
'NewMessage.WithMedia.Template' => new_message_with_media_template,
})
payload = @version.update('POST', @uri, data: data)
NotificationInstance.new(@version, payload, chat_service_sid: @solution[:chat_service_sid], )
end
##
# Fetch the NotificationInstance
# @return [NotificationInstance] Fetched NotificationInstance
def fetch
payload = @version.fetch('GET', @uri)
NotificationInstance.new(@version, payload, chat_service_sid: @solution[:chat_service_sid], )
end
##
# Provide a user friendly representation
def to_s
context = @solution.map {|k, v| "#{k}: #{v}"}.join(',')
"#<Twilio.Conversations.V1.NotificationContext #{context}>"
end
##
# Provide a detailed, user friendly representation
def inspect
context = @solution.map {|k, v| "#{k}: #{v}"}.join(',')
"#<Twilio.Conversations.V1.NotificationContext #{context}>"
end
end
class NotificationInstance < InstanceResource
##
# Initialize the NotificationInstance
# @param [Version] version Version that contains the resource
# @param [Hash] payload payload that contains response from Twilio
# @param [String] chat_service_sid The unique string that we created to identify
# the Service configuration resource.
# @return [NotificationInstance] NotificationInstance
def initialize(version, payload, chat_service_sid: nil)
super(version)
# Marshaled Properties
@properties = {
'account_sid' => payload['account_sid'],
'chat_service_sid' => payload['chat_service_sid'],
'new_message' => payload['new_message'],
'added_to_conversation' => payload['added_to_conversation'],
'removed_from_conversation' => payload['removed_from_conversation'],
'log_enabled' => payload['log_enabled'],
'url' => payload['url'],
}
# Context
@instance_context = nil
@params = {'chat_service_sid' => chat_service_sid, }
end
##
# Generate an instance context for the instance, the context is capable of
# performing various actions. All instance actions are proxied to the context
# @return [NotificationContext] NotificationContext for this NotificationInstance
def context
unless @instance_context
@instance_context = NotificationContext.new(@version, @params['chat_service_sid'], )
end
@instance_context
end
##
# @return [String] The unique ID of the Account responsible for this configuration.
def account_sid
@properties['account_sid']
end
##
# @return [String] The SID of the Conversation Service that the Configuration applies to.
def chat_service_sid
@properties['chat_service_sid']
end
##
# @return [Hash] The Push Notification configuration for New Messages.
def new_message
@properties['new_message']
end
##
# @return [Hash] The Push Notification configuration for being added to a Conversation.
def added_to_conversation
@properties['added_to_conversation']
end
##
# @return [Hash] The Push Notification configuration for being removed from a Conversation.
def removed_from_conversation
@properties['removed_from_conversation']
end
##
# @return [Boolean] Weather the notification logging is enabled.
def log_enabled
@properties['log_enabled']
end
##
# @return [String] An absolute URL for this configuration.
def url
@properties['url']
end
##
# Update the NotificationInstance
# @param [Boolean] log_enabled Weather the notification logging is enabled.
# @param [Boolean] new_message_enabled Whether to send a notification when a new
# message is added to a conversation. The default is `false`.
# @param [String] new_message_template The template to use to create the
# notification text displayed when a new message is added to a conversation and
# `new_message.enabled` is `true`.
# @param [String] new_message_sound The name of the sound to play when a new
# message is added to a conversation and `new_message.enabled` is `true`.
# @param [Boolean] new_message_badge_count_enabled Whether the new message badge
# is enabled. The default is `false`.
# @param [Boolean] added_to_conversation_enabled Whether to send a notification
# when a participant is added to a conversation. The default is `false`.
# @param [String] added_to_conversation_template The template to use to create the
# notification text displayed when a participant is added to a conversation and
# `added_to_conversation.enabled` is `true`.
# @param [String] added_to_conversation_sound The name of the sound to play when a
# participant is added to a conversation and `added_to_conversation.enabled` is
# `true`.
# @param [Boolean] removed_from_conversation_enabled Whether to send a
# notification to a user when they are removed from a conversation. The default is
# `false`.
# @param [String] removed_from_conversation_template The template to use to create
# the notification text displayed to a user when they are removed from a
# conversation and `removed_from_conversation.enabled` is `true`.
# @param [String] removed_from_conversation_sound The name of the sound to play to
# a user when they are removed from a conversation and
# `removed_from_conversation.enabled` is `true`.
# @param [Boolean] new_message_with_media_enabled Whether to send a notification
# when a new message with media/file attachments is added to a conversation. The
# default is `false`.
# @param [String] new_message_with_media_template The template to use to create
# the notification text displayed when a new message with media/file attachments
# is added to a conversation and `new_message.attachments.enabled` is `true`.
# @return [NotificationInstance] Updated NotificationInstance
def update(log_enabled: :unset, new_message_enabled: :unset, new_message_template: :unset, new_message_sound: :unset, new_message_badge_count_enabled: :unset, added_to_conversation_enabled: :unset, added_to_conversation_template: :unset, added_to_conversation_sound: :unset, removed_from_conversation_enabled: :unset, removed_from_conversation_template: :unset, removed_from_conversation_sound: :unset, new_message_with_media_enabled: :unset, new_message_with_media_template: :unset)
context.update(
log_enabled: log_enabled,
new_message_enabled: new_message_enabled,
new_message_template: new_message_template,
new_message_sound: new_message_sound,
new_message_badge_count_enabled: new_message_badge_count_enabled,
added_to_conversation_enabled: added_to_conversation_enabled,
added_to_conversation_template: added_to_conversation_template,
added_to_conversation_sound: added_to_conversation_sound,
removed_from_conversation_enabled: removed_from_conversation_enabled,
removed_from_conversation_template: removed_from_conversation_template,
removed_from_conversation_sound: removed_from_conversation_sound,
new_message_with_media_enabled: new_message_with_media_enabled,
new_message_with_media_template: new_message_with_media_template,
)
end
##
# Fetch the NotificationInstance
# @return [NotificationInstance] Fetched NotificationInstance
def fetch
context.fetch
end
##
# Provide a user friendly representation
def to_s
values = @params.map{|k, v| "#{k}: #{v}"}.join(" ")
"<Twilio.Conversations.V1.NotificationInstance #{values}>"
end
##
# Provide a detailed, user friendly representation
def inspect
values = @properties.map{|k, v| "#{k}: #{v}"}.join(" ")
"<Twilio.Conversations.V1.NotificationInstance #{values}>"
end
end
end
end
end
end
end
end
|
philnash/twilio-ruby
|
lib/twilio-ruby/rest/conversations/v1/service/configuration/notification.rb
|
Ruby
|
mit
| 17,122 |
<?php
namespace REBELinBLUE\Deployer\Presenters;
use Illuminate\Support\Facades\Lang;
use REBELinBLUE\Deployer\Command;
use Robbo\Presenter\Presenter;
/**
* The view presenter for a command class.
*/
class CommandPresenter extends Presenter
{
/**
* Gets the readable list of before clone commands.
*
* @return string
* @see self::commandNames()
*/
public function presentBeforeClone()
{
return $this->commandNames(Command::BEFORE_CLONE);
}
/**
* Gets the readable list of after clone commands.
*
* @return string
* @see self::commandNames()
*/
public function presentAfterClone()
{
return $this->commandNames(Command::AFTER_CLONE);
}
/**
* Gets the readable list of before install commands.
*
* @return string
* @see self::commandNames()
*/
public function presentBeforeInstall()
{
return $this->commandNames(Command::BEFORE_INSTALL);
}
/**
* Gets the readable list of after install commands.
*
* @return string
* @see self::commandNames()
*/
public function presentAfterInstall()
{
return $this->commandNames(Command::AFTER_INSTALL);
}
/**
* Gets the readable list of before activate commands.
*
* @return string
* @see self::commandNames()
*/
public function presentBeforeActivate()
{
return $this->commandNames(Command::BEFORE_ACTIVATE);
}
/**
* Gets the readable list of after activate commands.
*
* @return string
* @see self::commandNames()
*/
public function presentAfterActivate()
{
return $this->commandNames(Command::AFTER_ACTIVATE);
}
/**
* Gets the readable list of before purge commands.
*
* @return string
* @see self::commandNames()
*/
public function presentBeforePurge()
{
return $this->commandNames(Command::BEFORE_PURGE);
}
/**
* Gets the readable list of after purge commands.
*
* @return string
* @see self::commandNames()
*/
public function presentAfterPurge()
{
return $this->commandNames(Command::AFTER_PURGE);
}
/**
* Gets the readable list of commands.
*
* @param int $stage
* @return string
*/
private function commandNames($stage)
{
$commands = [];
foreach ($this->object->commands as $command) {
if ($command->step === $stage) {
$commands[] = $command->name;
}
}
if (count($commands)) {
return implode(', ', $commands);
}
return Lang::get('app.none');
}
}
|
iflamed/deployer
|
app/Presenters/CommandPresenter.php
|
PHP
|
mit
| 2,738 |