code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_29) on Wed May 02 09:32:45 CEST 2012 --> <TITLE> Uses of Class zisko.multicastor.program.controller.ViewController.MessageTyp </TITLE> <META NAME="date" CONTENT="2012-05-02"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class zisko.multicastor.program.controller.ViewController.MessageTyp"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?zisko/multicastor/program/controller//class-useViewController.MessageTyp.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ViewController.MessageTyp.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>zisko.multicastor.program.controller.ViewController.MessageTyp</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#zisko.multicastor.program.controller"><B>zisko.multicastor.program.controller</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="zisko.multicastor.program.controller"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A> in <A HREF="../../../../../zisko/multicastor/program/controller/package-summary.html">zisko.multicastor.program.controller</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../zisko/multicastor/program/controller/package-summary.html">zisko.multicastor.program.controller</A> that return <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A></CODE></FONT></TD> <TD><CODE><B>ViewController.MessageTyp.</B><B><A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html#valueOf(java.lang.String)">valueOf</A></B>(java.lang.String&nbsp;name)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns the enum constant of this type with the specified name.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A>[]</CODE></FONT></TD> <TD><CODE><B>ViewController.MessageTyp.</B><B><A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html#values()">values</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Returns an array containing the constants of this enum type, in the order they are declared.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../zisko/multicastor/program/controller/package-summary.html">zisko.multicastor.program.controller</A> with parameters of type <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;void</CODE></FONT></TD> <TD><CODE><B>ViewController.</B><B><A HREF="../../../../../zisko/multicastor/program/controller/ViewController.html#showMessage(zisko.multicastor.program.controller.ViewController.MessageTyp, java.lang.String)">showMessage</A></B>(<A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller">ViewController.MessageTyp</A>&nbsp;typ, java.lang.String&nbsp;message)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Funktion welche ermueglich Nachrichten in der GUI anzuzeigen.</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../zisko/multicastor/program/controller/ViewController.MessageTyp.html" title="enum in zisko.multicastor.program.controller"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html?zisko/multicastor/program/controller//class-useViewController.MessageTyp.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ViewController.MessageTyp.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
autarchprinceps/MultiCastor
Vorgängerversionen/V2.0/doc/zisko/multicastor/program/controller/class-use/ViewController.MessageTyp.html
HTML
gpl-3.0
10,365
import {Injectable} from '@angular/core'; import {SnackBarService} from './snack-bar.service'; import {LangChangeEvent, TranslateService} from '@ngx-translate/core'; @Injectable({ providedIn: 'root' }) export class TranslatableSnackBarService { /** * @param snackBarService * @param translateService */ constructor(private snackBarService: SnackBarService, private translateService: TranslateService) { this.translateService.onLangChange.subscribe((event: LangChangeEvent) => { this.translateService.get('snackbarMessages.dismiss').subscribe((res: string) => { this.snackBarService.setDefaultAction(res); }); }); } /** * Emit snackbar with given duration * @param {string} key * @param {Object} interpolateParams * @param {number} duration */ open(key: string, interpolateParams: Object = {}, duration: number = SnackBarService.defaultDuration): void { this.translateService.get(key, interpolateParams).subscribe((message: string) => { this.snackBarService.open(message, duration); }); } /** * Emit snackbar with duration short * @param {string} key * @param {Object} interpolateParams */ openShort(key: string, interpolateParams: Object = {}): void { this.open(key, interpolateParams, SnackBarService.durationShort); } /** * Emit snackbar with duration long * @param {string} key * @param {Object} interpolateParams */ openLong(key: string, interpolateParams: Object = {}): void { this.open(key, interpolateParams, SnackBarService.durationLong); } }
h-da/geli
app/webFrontend/src/app/shared/services/translatable-snack-bar.service.ts
TypeScript
gpl-3.0
1,580
import { AccessToken, Project, User, UserFeatureFlag, UserRole } from '@dev/translatr-model'; import { map } from 'rxjs/operators'; // General export const isAdmin = (user?: User): boolean => user !== undefined && user.role === UserRole.Admin; // Users export const hasCreateUserPermission = () => map(isAdmin); export const hasUserPermissionToDeleteUser = (me: User, user: User) => me !== undefined && me.id !== user.id && isAdmin(me); export const hasEditUserPermission = (user: User) => map((me?: User) => (me !== undefined && me.id === user.id) || isAdmin(me)); export const hasDeleteUserPermission = (user: User) => map((me?: User) => hasUserPermissionToDeleteUser(me, user)); export const hasDeleteAllUsersPermission = (users: User[]) => map((me?: User) => users .map((user: User) => hasUserPermissionToDeleteUser(me, user)) .reduce((acc: boolean, next: boolean) => acc && next, true) ); // Projects export const hasUserPermissionToDeleteProject = (me: User, project: Project) => (me !== undefined && me.id === project.ownerId) || isAdmin(me); export const hasEditProjectPermission = (project: Project) => map((me?: User) => (me !== undefined && me.id === project.ownerId) || isAdmin(me)); export const hasDeleteProjectPermission = (project: Project) => map((me?: User) => hasUserPermissionToDeleteProject(me, project)); export const hasDeleteAllProjectsPermission = (projects: Project[]) => map((me?: User) => projects .map((project: Project) => hasUserPermissionToDeleteProject(me, project)) .reduce((acc: boolean, next: boolean) => acc && next, true) ); // Access Tokens export const hasUserPermissionToEditAccessToken = (me: User, accessToken: AccessToken) => (me !== undefined && me.id === accessToken.userId) || isAdmin(me); export const hasUserPermissionToDeleteAccessToken = (me: User, accessToken: AccessToken) => (me !== undefined && me.id === accessToken.userId) || isAdmin(me); export const hasEditAccessTokenPermission = (accessToken: AccessToken) => map((me?: User) => hasUserPermissionToEditAccessToken(me, accessToken)); export const hasDeleteAccessTokenPermission = (accessToken: AccessToken) => map((me?: User) => hasUserPermissionToDeleteAccessToken(me, accessToken)); export const hasDeleteAllAccessTokensPermission = (accessTokens: AccessToken[]) => map((me?: User) => accessTokens .map((accessToken: AccessToken) => hasUserPermissionToDeleteAccessToken(me, accessToken)) .reduce((acc: boolean, next: boolean) => acc && next, true) ); // Feature Flags export const hasUserPermissionToEditFeatureFlag = (me: User, featureFlag: UserFeatureFlag) => (me !== undefined && me.id === featureFlag.userId) || isAdmin(me); export const hasUserPermissionToDeleteFeatureFlag = (me: User, featureFlag: UserFeatureFlag) => (me !== undefined && me.id === featureFlag.userId) || isAdmin(me); export const hasEditFeatureFlagPermission = (featureFlag: UserFeatureFlag) => map((me?: User) => hasUserPermissionToEditFeatureFlag(me, featureFlag)); export const hasDeleteFeatureFlagPermission = (featureFlag: UserFeatureFlag) => map((me?: User) => hasUserPermissionToDeleteFeatureFlag(me, featureFlag)); export const hasDeleteAllFeatureFlagsPermission = (featureFlags: UserFeatureFlag[]) => map((me?: User) => featureFlags .map((featureFlag: UserFeatureFlag) => hasUserPermissionToDeleteFeatureFlag(me, featureFlag)) .reduce((acc: boolean, next: boolean) => acc && next, true) );
resamsel/translatr
ui/libs/translatr-sdk/src/lib/shared/permissions.ts
TypeScript
gpl-3.0
3,518
package Ashafix::I18N::eu; use utf8; use Mojo::Base 'Ashafix::I18N'; our %Lexicon = ( YES => 'BAI', NO => 'EZ', edit => 'aldatu', del => 'ezabatu', exit => 'Exit', cancel => 'Cancel', save => 'Save', confirm => 'Ziur al zaude ezabatu nahi duzula?\n', confirm_domain => 'Ziur al zaude domeinu honetako erregistro guztiak ezbatu nahi dituzula? Hau ezin izango da desegin!\n', check_update => 'Check for update', invalid_parameter => 'Invalid parameter!', pFooter_logged_as => 'Logged as %s', pLogin_welcome => 'Kudeatzailearen logina domeinuak kudeatzeko.', pLogin_username => 'Erabiltzailea (e-mail)', pLogin_password => 'Pasahitza', pLogin_button => 'Erabiltzailea', pLogin_failed => 'Your email address or password are not correct.', pLogin_login_users => 'Erabiltzaileen gunera joateko logina.', pMenu_main => 'Main', pMenu_overview => 'Laburpena', pMenu_create_alias => 'Aliasa gehitu', pMenu_create_alias_domain => 'Add Alias Domain', pMenu_create_mailbox => 'Postontzia gehitu', pMenu_fetchmail => 'Fetch Email', pMenu_sendmail => 'e-maila bidali', pMenu_password => 'Pasahitza', pMenu_viewlog => 'Logak ikusi', pMenu_logout => 'Irten', pMain_welcome => 'Ongietorri Postfix Adminera!', pMain_overview => 'Alias eta postontzien zerrenda. Hemendik aldatu / ezabatu ditzakezu.', pMain_create_alias => 'Zure domeinuarentzako alias berri baten sorkuntza.', pMain_create_mailbox => 'Zure domeinuarentzako postontzi berri baten sorkuntza.', pMain_sendmail => 'Duela gutxi sorturiko postontziren batera e-mail bat bidali.', pMain_password => 'Kudeatzaile konturako pasahitza aldatu.', pMain_viewlog => 'Logak ikusi.', pMain_logout => 'Irten.', pOverview_disabled => 'Disabled', pOverview_unlimited => 'Unlimited', pOverview_title => ':: Defined Domains', pOverview_up_arrow => 'Go Top', pOverview_right_arrow => 'Next Page', pOverview_left_arrow => 'Previous Page', pOverview_alias_domain_title => ':: Domain Aliases', pOverview_alias_title => ':: Alias', pOverview_mailbox_title => ':: Mailboxes', pOverview_button => 'Joan', pOverview_welcome => 'Laburpena ', pOverview_alias_domain_aliases => 'Alias Domains', pOverview_alias_domain_target => '%s is an Alias Domain for:', pOverview_alias_alias_count => 'Aliasa', pOverview_alias_mailbox_count => 'Postontziak', pOverview_alias_address => 'Igorlea', pOverview_alias_goto => 'Norakoa', pOverview_alias_modified => 'Azken aldaketa', pOverview_alias_domain_modified => 'Last Modified', pOverview_alias_active => 'Active', pOverview_alias_domain_active => 'Active', pOverview_alias_edit => 'Alias', and_x_more => '[and %s more...]', pOverview_mailbox_username => 'E-mail', pOverview_mailbox_name => 'Izena', pOverview_mailbox_quota => 'Kuota (MB)', pOverview_mailbox_modified => 'Azken aldaketa', pOverview_mailbox_active => 'Aktibatua', pOverview_vacation_edit => 'VACATION IS ON', pOverview_vacation_option => 'Set Vacation', pOverview_get_domain => 'Domeinua', pOverview_get_aliases => 'Aliasa', pOverview_get_alias_domains => 'Domain Aliases', pOverview_get_mailboxes => 'Postontziak', pOverview_get_quota => 'Postontzi kuota (MB)', pOverview_get_modified => 'Azken aldaketa', pDelete_delete_error => 'Ezinezkoa sarrera ezabatzea ', pDelete_delete_success => '%s deleted.', pDelete_postdelete_error => 'Unable to remove mailbox ', pDelete_domain_error => 'Ez zara domeinu honen jabe', pDelete_domain_alias_error => 'This domain is not yours ', pDelete_alias_error => 'Unable to delete alias ', pCreate_alias_domain_welcome => 'Mirror addresses of one of your domains to another.', pCreate_alias_domain_alias => 'Alias Domain', pCreate_alias_domain_alias_text => 'The domain that mails come in for.', pCreate_alias_domain_target => 'Target Domain', pCreate_alias_domain_target_text => 'The domain where mails should go to.', pCreate_alias_domain_active => 'Active', pCreate_alias_domain_button => 'Add Alias Domain', pCreate_alias_domain_error1 => 'You are not allowed to create the chosen configuration.', pCreate_alias_domain_error2 => 'The chosen configuration is invalid, please choose a different one!', pCreate_alias_domain_error3 => 'Database insert failed.', pCreate_alias_domain_error4 => 'All domains are already aliased.', pCreate_alias_domain_success => 'The domain alias has been added to the alias domain table!', pCreate_alias_welcome => 'Domeinuarentzat alias berri bat sortu.', pCreate_alias_address => 'Aliasa', pCreate_alias_address_text_error1 => 'ALIASa okerra da!', pCreate_alias_address_text_error2 => 'Helbide hau existitzen da, ezberdin bat aukera ezazu mesedez!', pCreate_alias_address_text_error3 => 'Alias sortze mugara heldu zara!', pCreate_alias_goto => 'Norakoa', pCreate_alias_active => 'Active', pCreate_alias_button => 'Aliasa gehitu', pCreate_alias_goto_text => 'Nora bidali behar den e-maila.', pCreate_alias_goto_text_error => 'NORAKO okerra!', pCreate_alias_result_error => 'Ezinezkoa aliasa alias taulan sartzea!', pCreate_alias_result_success => 'Aliasa alias taulan gehituta!', pCreate_alias_catchall_text => 'Alias orokor bat sortzeko "*" erabil ezazu alias gisa. Domeinuz domeinurako birbideraketa baterako Norako gisa "*@domain.tld" erabil ezazu.', pEdit_alias_welcome => 'Domeinuarentzat aliasa aldatu. Lerroko sarrera bat.', pEdit_alias_address => 'Aliasa', pEdit_alias_address_error => 'Ezinezkoa aliasa aurkitzea!', pEdit_alias_goto => 'Norakoa', pEdit_alias_active => 'Active', pEdit_alias_goto_text_error1 => 'Norakoan ez duzu ezer jarri', pEdit_alias_goto_text_error2 => 'Sartutako e-mail helbidea baliiogabekoa da: ', pEdit_alias_domain_error => 'Ez zara domeinu honen jabe: ', pEdit_alias_domain_result_error => 'Unable to modify the alias domain!', pEdit_alias_forward_and_store => 'Deliver to the local mailbox.', pEdit_alias_forward_only => 'Forward to given email addresses only.', pEdit_alias_button => 'Aliasa aldatu', pEdit_alias_result_error => 'Ezinezkoa aliasa aldatzea!', pCreate_mailbox_welcome => 'Postontzi berri bat sortu domeinuarentzat.', pCreate_mailbox_username => 'Erabiltzailea', pCreate_mailbox_username_text_error1 => 'E-maila baliogabekoa da!', pCreate_mailbox_username_text_error2 => 'E-mail hau existitzen da. Ezberdin bat aukera ezazu, mesedez!', pCreate_mailbox_username_text_error3 => 'Postontzi sorkuntza mugara iritsi zara!', pCreate_mailbox_password => 'Pasahitza', pCreate_mailbox_password2 => 'Pasahitza (errepikatu)', pCreate_mailbox_password_text => 'POP3/IMAP-entzat pasahitza', pCreate_mailbox_password_text_error => 'Sartutako pasahitzak ez datoz bat edo zuriz daude!', pCreate_mailbox_name => 'Izena', pCreate_mailbox_name_text => 'Izen osoa', pCreate_mailbox_quota => 'Kuota', pCreate_mailbox_quota_text => 'MB', pCreate_mailbox_quota_text_error => 'Zehazturiko kuota altuegia da!', pCreate_mailbox_active => 'Aktibatua', pCreate_mailbox_mail => 'Postontzia sortu', pCreate_mailbox_button => 'Postontzia gehitu', pCreate_mailbox_result_error => 'Ezinezkoa postontzi taulara postontzia gehitzea!', pCreate_mailbox_result_success => 'Postontzia postontzi taulara sartu da!', pCreate_mailbox_result_succes_nosubfolders => 'The mailbox has been added to the mailbox table, but none (or only some) of the predefined sub-folders could be created', pEdit_mailbox_welcome => 'Domeinuarentzat postontzi bat aldatu.', pEdit_mailbox_username => 'Erabiltzailea', pEdit_mailbox_username_error => 'Ezinezkoa postontzia aurkitzea!', pEdit_mailbox_password => 'Pasahitz berria', pEdit_mailbox_password2 => 'Pasahitz berria (errepikatu)', pEdit_mailbox_password_text_error => 'Sartutako pasahitzak ez datoz bat!', pEdit_mailbox_name => 'Izena', pEdit_mailbox_name_text => 'Full name', pEdit_mailbox_quota => 'Kuota', pEdit_mailbox_quota_text => 'MB', pEdit_mailbox_quota_text_error => 'Zehazturiko kuota altuegia da!', pEdit_mailbox_domain_error => 'Ez zara domeinu honen jabe: ', pEdit_mailbox_button => 'Postontzia aldatu', pEdit_mailbox_result_error => 'Ezinezkoa pasahitza aldatzea!', pPassword_welcome => 'Login pasahitza aldatu.', pPassword_admin => 'Login', pPassword_admin_text_error => 'Emandako LOGINa ez dator inolako postontziekin bat!', pPassword_password_current => 'Egungo pasahitza', pPassword_password_current_text_error => 'Ez duzu egungo pasahitzik sartu!', pPassword_password => 'Pasahitz berria', pPassword_password2 => 'Pasahitz berria (errepikatu)', pPassword_password_text_error => 'Sarturiko pasahitzak ez datoz bat edo zuriz daude!', pPassword_button => 'Pasahitza aldatu', pPassword_result_error => 'Ezinezkoa pasahitza aldatzea!', pPassword_result_success => 'Pasahitza aldatuta!', pEdit_vacation_set => 'Change / Set away message', pEdit_vacation_remove => 'Remove away message', pVacation_result_error => 'Unable to update auto response settings!', pVacation_result_removed => 'Auto response has been removed!', pVacation_result_added => 'Auto response has been enabled!', pViewlog_welcome => 'Honen azken 10 ekintzak ikusi ', pViewlog_timestamp => 'Data/ordua', pViewlog_username => 'Kudeatzailea', pViewlog_domain => 'Domeinua', pViewlog_action => 'Ekintza', pViewlog_data => 'Datuak', pViewlog_action_create_mailbox => 'create mailbox', pViewlog_action_delete_mailbox => 'delete mailbox', pViewlog_action_edit_mailbox => 'edit mailbox', pViewlog_action_edit_mailbox_state => 'edit mailbox active', pViewlog_action_create_alias => 'create alias', pViewlog_action_create_alias_domain => 'create alias domain', pViewlog_action_delete_alias => 'delete alias', pViewlog_action_delete_alias_domain => 'delete alias domain', pViewlog_action_edit_alias => 'edit alias', pViewlog_action_edit_alias_state => 'edit alias active', pViewlog_action_edit_alias_domain_state => 'edit alias domain active', pViewlog_action_edit_password => 'change password', pViewlog_button => 'Joan', pViewlog_result_error => 'Ezinezkoa logak aurkitzea!', pSendmail_welcome => 'e-mail bat bidali.', pSendmail_admin => 'Igorlea', pSendmail_to => 'Norakoa', pSendmail_to_text_error => 'Norako helbidea hutsa dago edo okerra da!', pSendmail_subject => 'Gaia', pSendmail_subject_text => 'Ongi etorri', pSendmail_body => 'Gorputza', pSendmail_button => 'Mezua bidali', pSendmail_result_error => 'Ezinezkoa postontzia sortzea!', pSendmail_result_success => 'Postontzia sortuta!', pAdminMenu_list_admin => 'Kudeatzaile zerrenda', pAdminMenu_list_domain => 'Domeinu zerrenda', pAdminMenu_list_virtual => 'Helbide birtualen zerrenda', pAdminMenu_viewlog => 'Logak ikusi', pAdminMenu_backup => 'Segurtasun kopia', pAdminMenu_create_domain_admins => 'Domeinu kudeatzaileak', pAdminMenu_create_admin => 'Kudeatzaile berria', pAdminMenu_create_domain => 'Domeinu berria', pAdminMenu_create_alias => 'Aliasa gehitu', pAdminMenu_create_mailbox => 'Postontzia gehitu', pAdminList_admin_domain => 'Domeinua', pAdminList_admin_username => 'Kudeatzailea', pAdminList_admin_count => 'Domeinuak', pAdminList_admin_modified => 'Azken aldaketa', pAdminList_admin_active => 'Aktibatua', pAdminList_domain_domain => 'Domeinua', pAdminList_domain_description => 'Deskripzioa', pAdminList_domain_aliases => 'Aliasa', pAdminList_domain_mailboxes => 'Postontziak', pAdminList_domain_maxquota => 'Gehienezko kuota (MB)', pAdminList_domain_transport => 'Transport', pAdminList_domain_backupmx => 'Backup MX', pAdminList_domain_modified => 'Azken aldaketa', pAdminList_domain_active => 'Aktibatua', pAdminList_virtual_button => 'Joan', pAdminList_virtual_welcome => 'Laburpena ', pAdminList_virtual_alias_alias_count => 'Aliasa', pAdminList_virtual_alias_mailbox_count => 'Postontziak', pAdminList_virtual_alias_address => 'Igorlea', pAdminList_virtual_alias_goto => 'Norakoa', pAdminList_virtual_alias_modified => 'Azken aldaketa', pAdminList_virtual_mailbox_username => 'E-mail', pAdminList_virtual_mailbox_name => 'Izena', pAdminList_virtual_mailbox_quota => 'Kuota (MB)', pAdminList_virtual_mailbox_modified => 'Azken aldaketa', pAdminList_virtual_mailbox_active => 'Aktibatua', pAdminCreate_domain_welcome => 'Domeinu berria gehitu', pAdminCreate_domain_domain => 'Domeinua', pAdminCreate_domain_domain_text_error => 'Domeinua existitzen da!', pAdminCreate_domain_domain_text_error2 => 'The domain is invalid!', pAdminCreate_domain_description => 'Deskripzioa', pAdminCreate_domain_aliases => 'Aliasa', pAdminCreate_domain_aliases_text => '-1 = desegokitu | 0 = mugagabea', pAdminCreate_domain_mailboxes => 'Postontziak', pAdminCreate_domain_mailboxes_text => '-1 = desegokitu | 0 = mugagabea', pAdminCreate_domain_maxquota => 'Gehienezko kuota', pAdminCreate_domain_maxquota_text => 'MB -1 = desegokitu | 0 = mugagabea', pAdminCreate_domain_transport => 'Transport', pAdminCreate_domain_transport_text => 'Define transport', pAdminCreate_domain_defaultaliases => 'Aurremugatutako aliasa gehitu', pAdminCreate_domain_defaultaliases_text => '', pAdminCreate_domain_backupmx => 'Mail server is backup MX', pAdminCreate_domain_button => 'Domeinua gehitu', pAdminCreate_domain_result_error => 'Ezinezkoa domeinua gehitzea!', pAdminCreate_domain_result_success => 'Domeinua gehituta!', pAdminDelete_domain_error => 'Unable to remove domain!', pAdminDelete_alias_domain_error => 'Unable to remove domain alias!', pAdminEdit_domain_welcome => 'Domeinu bat aldatu', pAdminEdit_domain_domain => 'Domeinua', pAdminEdit_domain_description => 'Deskripzioa', pAdminEdit_domain_aliases => 'Aliasa', pAdminEdit_domain_aliases_text => '-1 = desegokitu | 0 = mugagabea', pAdminEdit_domain_mailboxes => 'Postontziak', pAdminEdit_domain_mailboxes_text => '-1 = desegokitu | 0 = mugagabea', pAdminEdit_domain_maxquota => 'Gehienezko kuota', pAdminEdit_domain_maxquota_text => 'MB -1 = desegokitu | 0 = mugagabea', pAdminEdit_domain_transport => 'Transport', pAdminEdit_domain_transport_text => 'Define transport', pAdminEdit_domain_backupmx => 'Mail server is backup MX', pAdminEdit_domain_active => 'Aktibatua', pAdminEdit_domain_button => 'Domeinua aldatu', pAdminEdit_domain_result_error => 'Ezinezkoa domeinua aldatzea!', pAdminCreate_admin_welcome => 'Domeinu kudeatzaile berri bat gehitu', pAdminCreate_admin_username => 'Kudeatzailea', pAdminCreate_admin_username_text => 'E-mail helbidea', pAdminCreate_admin_username_text_error1 => 'Kudeatzaile e-mailak ez du balio!', pAdminCreate_admin_username_text_error2 => 'Kudeatzailea existitzen da edo ez du balio!', pAdminCreate_admin_password => 'Pasahitza', pAdminCreate_admin_password2 => 'Pasahitza (errepikatu)', pAdminCreate_admin_password_text_error => 'Sartutako pasahitzak ez datoz bat edo zuriz daude!', pAdminCreate_admin_button => 'Kudeatzailea gehitu', pAdminCreate_admin_result_error => 'Ezinezkoa kudeatzailea gehitzea!', pAdminCreate_admin_result_success => 'Kudeatzailea gehituta1', pAdminCreate_admin_address => 'Domeinua', pAdminEdit_admin_welcome => 'Domeinu kudeatzaile bat aldatu', pAdminEdit_admin_username => 'Kudeatzailea', pAdminEdit_admin_password => 'Pasahitza', pAdminEdit_admin_password2 => 'Pasahitza (errepikatu)', pAdminEdit_admin_password_text_error => 'Sartutako pasahitzak ez datoz bat edo zuriz daude!', pAdminEdit_admin_active => 'Aktibatua', pAdminEdit_admin_super_admin => 'Super admin', pAdminEdit_admin_button => 'Kudeatzailea aldatu', pAdminEdit_admin_result_error => 'Ezinezkoa kudeatzailea aldatzea!', pAdminEdit_admin_result_success => 'Kudeatzailea aldatu da!', pUsersLogin_welcome => 'Erabiltzaileen logina pasahitz eta aliasa aldatzeko.', pUsersLogin_username => 'Login (e-mail)', pUsersLogin_password => 'Pasahitza', pUsersLogin_button => 'Login', pUsersLogin_username_incorrect => 'Login okerra. Ziurta zaitez posta helbidea login gisa sartu duzula!', pUsersLogin_password_incorrect => 'Pasahitz okerra!', pUsersMenu_vacation => 'Erantzun automatikoa', pUsersMenu_edit_alias => 'Berbiderapen helbidea aldatu', pUsersMenu_password => 'Pasahitza aldatu', pUsersMain_vacation => 'Konfigura ezazu "lanetik kanpo" motako mezu bat edo erantzun automatikoa zure postarentzat.', pUsersMain_edit_alias => 'Alda ezazu posta helbidea.', pUsersMain_password => 'Alda ezazu pasahitza.', pUsersVacation_welcome => 'Erantzun automatikoa.', pUsersVacation_welcome_text => 'Erantzun automatiko bat konfiguratuta duzu!', pUsersVacation_subject => 'Gaia', pUsersVacation_subject_text => 'Lanetik kanpo', pUsersVacation_body => 'Gorputza', pUsersVacation_body_text => '<date>-tik <date> arte kanpoan egongo naiz. Larrialdiko gaientzat, hemen <contact person> kontakta dezakezu nirekin. ', pUsersVacation_button_away => 'Aldeginda', pUsersVacation_button_back => 'Itzulita', pUsersVacation_result_error => 'Ezinezkoa zure erantzun atomatikoaren konfigurazioa eguneratzea!', pUsersVacation_result_success => 'Zure erantzun automatikoa borratu da!', pUsersVacation_activefrom => 'Active from', pUsersVacation_activeuntil => 'Active until', pCreate_dbLog_createmailbox => 'create mailbox', pCreate_dbLog_createalias => 'create alias', pDelete_dbLog_deletealias => 'delete alias', pDelete_dbLog_deletemailbox => 'delete mailbox', pEdit_dbLog_editactive => 'change active state', pEdit_dbLog_editalias => 'edit alias', pEdit_dbLog_editmailbox => 'edit mailbox', pSearch => 'search', pSearch_welcome => 'Searching for: ', pReturn_to => 'Return to', pBroadcast_title => 'Send broadcast message', pBroadcast_from => 'From', pBroadcast_name => 'Your name', pBroadcast_subject => 'Subject', pBroadcast_message => 'Message', pBroadcast_send => 'Send message', pBroadcast_success => 'Your broadcast message was sent.', pAdminMenu_broadcast_message => 'Broadcast message', pBroadcast_error_empty => 'The fields Name, Subject and Message should\'t be empty !', pStatus_undeliverable => 'maybe UNDELIVERABLE ', pStatus_custom => 'Delivers to ', pStatus_popimap => 'POP/IMAP ', pPasswordTooShort => 'Password is too short - requires %s characters', pInvalidDomainRegex => 'Invalid domain name %s, fails regexp check', pInvalidDomainDNS => 'Invalid domain %s, and/or not discoverable in DNS', pInvalidMailRegex => 'Invalid email address, fails regexp check', pFetchmail_welcome => 'Fetch mail for:', pFetchmail_new_entry => 'New entry', pFetchmail_database_save_error => 'Could not save this entry in the database!', pFetchmail_database_save_success => 'Entry saved in database.', pFetchmail_error_invalid_id => 'No entry with ID %s found!', pFetchmail_invalid_mailbox => 'Invalid mailbox!', pFetchmail_server_missing => 'Please enter the remote server name!', pFetchmail_user_missing => 'Please enter the remote username!', pFetchmail_password_missing => 'Please enter the remote password!', pFetchmail_field_id => 'ID', pFetchmail_field_mailbox => 'Mailbox', pFetchmail_field_src_server => 'Server', pFetchmail_field_src_auth => 'Auth Type', pFetchmail_field_src_user => 'User', pFetchmail_field_src_password => 'Password', pFetchmail_field_src_folder => 'Folder', pFetchmail_field_poll_time => 'Poll', pFetchmail_field_fetchall => 'Fetch All', pFetchmail_field_keep => 'Keep', pFetchmail_field_protocol => 'Protocol', pFetchmail_field_usessl => 'SSL active', pFetchmail_field_extra_options => 'Extra Options', pFetchmail_field_mda => 'MDA', pFetchmail_field_date => 'Date', pFetchmail_field_returned_text => 'Returned Text', pFetchmail_desc_id => 'Record ID', pFetchmail_desc_mailbox => 'Local mailbox', pFetchmail_desc_src_server => 'Remote Server', pFetchmail_desc_src_auth => 'Mostly \'password\'', pFetchmail_desc_src_user => 'Remote User', pFetchmail_desc_src_password => 'Remote Password', pFetchmail_desc_src_folder => 'Remote Folder', pFetchmail_desc_poll_time => 'Poll every ... minutes', pFetchmail_desc_fetchall => 'Retrieve both old (seen) and new messages', pFetchmail_desc_keep => 'Keep retrieved messages on the remote mailserver', pFetchmail_desc_protocol => 'Protocol to use', pFetchmail_desc_usessl => 'SSL encryption', pFetchmail_desc_extra_options => 'Extra fetchmail Options', pFetchmail_desc_mda => 'Mail Delivery Agent', pFetchmail_desc_date => 'Date of last polling/configuration change', pFetchmail_desc_returned_text => 'Text message from last polling', );
mbethke/Ashafix
lib/Ashafix/I18N/eu.pm
Perl
gpl-3.0
19,933
package com.bytezone.diskbrowser.nufx; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import com.bytezone.diskbrowser.prodos.write.DiskFullException; import com.bytezone.diskbrowser.prodos.write.FileAlreadyExistsException; import com.bytezone.diskbrowser.prodos.write.ProdosDisk; import com.bytezone.diskbrowser.prodos.write.VolumeCatalogFullException; // -----------------------------------------------------------------------------------// public class Binary2 // -----------------------------------------------------------------------------------// { private static final String UNDERLINE = "------------------------------------------------------" + "-----------------------"; Binary2Header binary2Header; byte[] buffer; List<Binary2Header> headers = new ArrayList<> (); int totalBlocks; String fileName; // ---------------------------------------------------------------------------------// public Binary2 (Path path) throws IOException // ---------------------------------------------------------------------------------// { fileName = path.toFile ().getName (); buffer = Files.readAllBytes (path); read (buffer); } // ---------------------------------------------------------------------------------// private void read (byte[] buffer) // ---------------------------------------------------------------------------------// { int ptr = 0; do { binary2Header = new Binary2Header (buffer, ptr); System.out.println (binary2Header); headers.add (binary2Header); totalBlocks += binary2Header.totalBlocks; ptr += ((binary2Header.eof - 1) / 128 + 1) * 128 + 128; } while (binary2Header.filesToFollow > 0); } // ---------------------------------------------------------------------------------// public byte[] getDiskBuffer () throws DiskFullException, VolumeCatalogFullException, FileAlreadyExistsException, IOException // ---------------------------------------------------------------------------------// { ProdosDisk disk = new ProdosDisk (800, "DiskBrowser"); for (Binary2Header header : headers) { byte[] dataBuffer = new byte[header.eof]; // this sux System.arraycopy (buffer, header.ptr + 128, dataBuffer, 0, dataBuffer.length); disk.addFile (header.fileName, header.fileType, header.auxType, header.created, header.modified, dataBuffer, header.eof); } disk.close (); return disk.getBuffer (); } // ---------------------------------------------------------------------------------// @Override public String toString () // ---------------------------------------------------------------------------------// { StringBuilder text = new StringBuilder (); text.append (String.format ( " %-15.15s Files:%5d%n%n", fileName, headers.size ())); text.append (" Name Type Auxtyp Modified" + " Fmat Length\n"); text.append (String.format ("%s%n", UNDERLINE)); for (Binary2Header header : headers) text.append (String.format ("%s%n", header.getLine ())); text.append (String.format ("%s%n", UNDERLINE)); return text.toString (); } }
dmolony/DiskBrowser
src/com/bytezone/diskbrowser/nufx/Binary2.java
Java
gpl-3.0
3,371
package componentes; import javax.swing.JTextField; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; public class JTextFieldPrazo extends PlainDocument { /** * */ private static final long serialVersionUID = -8020852662258513751L; private int iMaxLength; private JTextField txt; private long num; public JTextFieldPrazo(int pMaxLen, JTextField pText) { super(); iMaxLength = pMaxLen; txt = pText; } public void insertString(int pOffSet, String pString, AttributeSet pAttributSet) throws BadLocationException { if (pString == null) return; if (iMaxLength <= 0) {// aceitara qualquer no. de caracteres super.insertString(pOffSet, pString, pAttributSet); return; } long ilen = (getLength() + pString.length()); try { if(pString.length()==1 && !pString.equals("-")) setNum(Long.parseLong(pString)); if(pString.equals("0") && txt.getText().length() == 0){ /**return;*/ } if (ilen <= iMaxLength) // se o comprimento final for menor... super.insertString(pOffSet, pString, pAttributSet); // ...aceita str else if (getLength() == iMaxLength) return; // nada a fazer else { String newStr = pString.substring(0, (iMaxLength - getLength())); super.insertString(pOffSet, newStr, pAttributSet); } } catch(Exception e) {} } public long getNum() { return num; } public void setNum(long num) { this.num = num; } }
DiegoEveling/RHFacil
src/componentes/JTextFieldPrazo.java
Java
gpl-3.0
1,557
 CREATE OR REPLACE VIEW clin_measurements.vwsystolicdiastolic AS SELECT vwmeasurements.fk_patient, vwpatients.wholename, vwpatients.fk_person, vwpatients.surname, vwpatients.firstname, vwpatients.title, vwpatients.sex, vwpatients.age_numeric, vwpatients.fk_lu_active_status, vwpatients.deceased, vwmeasurements.pk_measurement, vwmeasurements.consult_date, vwmeasurements.measurement, round(vwmeasurements.measurement / 1000::numeric) AS systolic, vwmeasurements.measurement % 1000::numeric AS diastolic FROM clin_measurements.vwmeasurements JOIN contacts.vwpatients ON vwpatients.fk_patient = vwmeasurements.fk_patient WHERE vwmeasurements.deleted = false AND vwmeasurements.fk_type = 1 AND vwpatients.deceased = false AND vwpatients.fk_lu_active_status = 1 ORDER BY vwmeasurements.fk_patient, vwmeasurements.consult_date DESC; ALTER TABLE clin_measurements.vwsystolicdiastolic OWNER TO easygp; GRANT ALL ON TABLE clin_measurements.vwsystolicdiastolic TO staff; CREATE OR REPLACE VIEW clin_measurements.vwaveragebp AS SELECT vwsystolicdiastolic.fk_patient, vwsystolicdiastolic.fk_patient AS pk, vwsystolicdiastolic.fk_person, vwsystolicdiastolic.surname, vwsystolicdiastolic.firstname, vwsystolicdiastolic.title, vwsystolicdiastolic.sex, vwsystolicdiastolic.age_numeric, round(avg(vwsystolicdiastolic.systolic)) AS average_systolic, round(avg(vwsystolicdiastolic.diastolic)) AS average_diastolic FROM clin_measurements.vwsystolicdiastolic GROUP BY vwsystolicdiastolic.fk_patient, vwsystolicdiastolic.fk_person, vwsystolicdiastolic.surname, vwsystolicdiastolic.firstname, vwsystolicdiastolic.title, vwsystolicdiastolic.sex, vwsystolicdiastolic.age_numeric ORDER BY vwsystolicdiastolic.surname; ALTER TABLE clin_measurements.vwaveragebp OWNER TO easygp; GRANT ALL ON TABLE clin_measurements.vwaveragebp TO staff; CREATE OR REPLACE VIEW research.vwpatientswithcodedhypertension AS SELECT DISTINCT ON (vwpatients.surname, vwhealthissues.fk_patient) vwhealthissues.fk_patient AS pk_patient, vwpatients.fk_person, vwpatients.firstname, vwpatients.surname, vwpatients.sex, vwpatients.title, vwpatients.age_numeric, vwpatients.fk_lu_active_status, vwpatients.person_deleted, vwpatients.deceased FROM clin_history.vwhealthissues JOIN contacts.vwpatients ON vwpatients.fk_patient = vwhealthissues.fk_patient WHERE vwhealthissues.fk_code = 'K86005'::text OR vwhealthissues.fk_code = 'K85004'::text ORDER BY vwpatients.surname; ALTER TABLE research.vwpatientswithcodedhypertension OWNER TO easygp; GRANT ALL ON TABLE research.vwpatientswithcodedhypertension TO staff; update db.lu_version set lu_minor = 488;
ihaywood3/easygp
db/updates/0.488_hypertension_research_queries.sql
SQL
gpl-3.0
2,777
using System; using System.IO; using System.Linq; namespace FocalLengthAnalyzer { public class Program { public void Main(string[] args) { if (args.Count()<1) { Console.WriteLine("Please pass the path to the directory with jpeg files as the first argument."); return; } if (!Directory.Exists(args[0])) { Console.WriteLine($"Error: directory {args[0]} does not exits."); return; } var analyzer = new Analyzer(); analyzer.AnalyzeDirectoryContent(args[0]); } } }
mkorz/FocalLengthAnalyzer
src/FocalLengthAnalyzer/Program.cs
C#
gpl-3.0
641
explain what are they and common ones, and how important are they?
tikael1011/common_interview_question
[S]/CD_CI.md
Markdown
gpl-3.0
67
#include <stdio.h> #include <stdlib.h> //#include <elf.h> #define ELF_MAGIC 16 //#define MEM_ALLOC_H(ptr) ptr = (FILE *) malloc (sizeof(myElf32_Ehdr)); //#define MEM_ALLOC_S(ptr) ptr = (FILE *) malloc (sizeof(myElf32_Shdr)); #define VALIDATE(ptr) if (!(ptr)) {\ fprintf(stdout, "%s", "Returned NULL\n");\ exit(1);\ } typedef unsigned short int myElf32_Half; typedef unsigned int myElf32_Word; typedef struct { unsigned char magic_num[ELF_MAGIC]; myElf32_Half elfh_type; myElf32_Half elfh_machine; myElf32_Word elfh_version; myElf32_Word elfh_entry; myElf32_Word elfh_phoff; myElf32_Word elfh_shoff; myElf32_Word elfh_flags; myElf32_Half elfh_ehsize; myElf32_Half elfh_phentsize; myElf32_Half elfh_phnum; myElf32_Half elfh_shentsize; myElf32_Half elfh_shnum; myElf32_Half elfh_shstrndx; } myElf32_Ehdr; typedef struct { myElf32_Word sech_name; myElf32_Word sech_type; myElf32_Word sech_flags; myElf32_Word sech_addr; myElf32_Word sech_offset; myElf32_Word sech_size; myElf32_Word sech_link; myElf32_Word sech_info; myElf32_Word sech_addralign; myElf32_Word sech_entsize; } myElf32_Shdr;
avinash-n/work-1
assignments/toolchain/read_elf/header/myelf.h
C
gpl-3.0
1,126
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import argparse import pprint import proteindf_bridge as bridge import logging import logging.config def get_rest_of_frame_molecule(frame_molecule, selected_molecule): # calc the rest selector = bridge.Select_AtomGroup(selected_molecule) selected = frame_molecule.select(selector) rest_molecule = frame_molecule ^ selected return rest_molecule def assign_rest_molecule(rest_molecule, output_atom_group, model_id="model_1", chain_id="Z", res_name="UNK"): chain = bridge.AtomGroup() res = bridge.AtomGroup() res.name = res_name atom_id = 1 for atom in rest_molecule.get_atom_list(): res.set_atom(atom_id, atom) atom_id += 1 chain.set_group(1, res) output_atom_group[model_id].set_group(chain_id, chain) def main(): parser = argparse.ArgumentParser( description='restructure brd file by reference file') parser.add_argument('target_brd_path', nargs=1, help='target brd file') parser.add_argument('ref_brd_path', nargs=1, help='reference brd file') parser.add_argument('-o', '--output_path', nargs=1, default=["output.brd"]) parser.add_argument('-r', '--range', nargs=1, default=[1.0E-5]) parser.add_argument('-v', '--verbose', action='store_true', default=False) args = parser.parse_args() # print(args) target_brd_path = args.target_brd_path[0] ref_brd_path = args.ref_brd_path[0] output_path = args.output_path[0] range = float(args.range[0]) verbose = args.verbose if verbose: print("target: {}".format(target_brd_path)) print("reference: {}".format(ref_brd_path)) # load target_ag = bridge.load_atomgroup(target_brd_path) ref_ag = bridge.load_atomgroup(ref_brd_path) # matching #target_selector = bridge.Select_AtomGroup(target_ag) #restructured = ref_ag.select(target_selector) # calc the rest #rest_of_target = get_rest_of_frame_molecule(target_ag, restructured) #assign_rest_molecule(rest_of_target, restructured) restructured = target_ag.restructure(ref_ag, range) if output_path: if verbose: print("output brd file: {}".format(output_path)) bridge.save_atomgroup(restructured, output_path) if __name__ == '__main__': #import cProfile #pr = cProfile.Profile() # pr.enable() main() # pr.disable() # pr.dump_stats('program.profile')
ProteinDF/ProteinDF_bridge
scripts/brd-restructure.py
Python
gpl-3.0
2,717
package se.vidstige.jadb; import se.vidstige.jadb.managers.Bash; import java.io.*; import java.util.ArrayList; import java.util.List; public class JadbDevice { public enum State { Unknown, Offline, Device, Recovery, BootLoader }; private final String serial; private final ITransportFactory transportFactory; JadbDevice(String serial, String type, ITransportFactory tFactory) { this.serial = serial; this.transportFactory = tFactory; } static JadbDevice createAny(JadbConnection connection) { return new JadbDevice(connection); } private JadbDevice(ITransportFactory tFactory) { serial = null; this.transportFactory = tFactory; } private State convertState(String type) { switch (type) { case "device": return State.Device; case "offline": return State.Offline; case "bootloader": return State.BootLoader; case "recovery": return State.Recovery; default: return State.Unknown; } } private Transport getTransport() throws IOException, JadbException { Transport transport = transportFactory.createTransport(); if (serial == null) { transport.send("host:transport-any"); transport.verifyResponse(); } else { transport.send("host:transport:" + serial); transport.verifyResponse(); } return transport; } public String getSerial() { return serial; } public State getState() throws IOException, JadbException { Transport transport = transportFactory.createTransport(); if (serial == null) { transport.send("host:get-state"); transport.verifyResponse(); } else { transport.send("host-serial:" + serial + ":get-state"); transport.verifyResponse(); } State state = convertState(transport.readString()); transport.close(); return state; } /** <p>Execute a shell command.</p> * * <p>For Lollipop and later see: {@link #execute(String, String...)}</p> * * @param command main command to run. E.g. "ls" * @param args arguments to the command. * @return combined stdout/stderr stream. * @throws IOException * @throws JadbException */ public InputStream executeShell(String command, String... args) throws IOException, JadbException { Transport transport = getTransport(); StringBuilder shellLine = buildCmdLine(command, args); send(transport, "shell:" + shellLine.toString()); return new AdbFilterInputStream(new BufferedInputStream(transport.getInputStream())); } /** * * @deprecated Use InputStream executeShell(String command, String... args) method instead. Together with * Stream.copy(in, out), it is possible to achieve the same effect. */ @Deprecated public void executeShell(OutputStream output, String command, String... args) throws IOException, JadbException { Transport transport = getTransport(); StringBuilder shellLine = buildCmdLine(command, args); send(transport, "shell:" + shellLine.toString()); if (output != null) { AdbFilterOutputStream out = new AdbFilterOutputStream(output); try { transport.readResponseTo(out); } finally { out.close(); } } } /** <p>Execute a command with raw binary output.</p> * * <p>Support for this command was added in Lollipop (Android 5.0), and is the recommended way to transmit binary * data with that version or later. For earlier versions of Android, use * {@link #executeShell(String, String...)}.</p> * * @param command main command to run, e.g. "screencap" * @param args arguments to the command, e.g. "-p". * @return combined stdout/stderr stream. * @throws IOException * @throws JadbException */ public InputStream execute(String command, String... args) throws IOException, JadbException { Transport transport = getTransport(); StringBuilder shellLine = buildCmdLine(command, args); send(transport, "exec:" + shellLine.toString()); return new BufferedInputStream(transport.getInputStream()); } /** * Builds a command line string from the command and its arguments. * * @param command the command. * @param args the list of arguments. * @return the command line. */ private StringBuilder buildCmdLine(String command, String... args) { StringBuilder shellLine = new StringBuilder(command); for (String arg : args) { shellLine.append(" "); shellLine.append(Bash.quote(arg)); } return shellLine; } public List<RemoteFile> list(String remotePath) throws IOException, JadbException { Transport transport = getTransport(); SyncTransport sync = transport.startSync(); sync.send("LIST", remotePath); List<RemoteFile> result = new ArrayList<RemoteFile>(); for (RemoteFileRecord dent = sync.readDirectoryEntry(); dent != RemoteFileRecord.DONE; dent = sync.readDirectoryEntry()) { result.add(dent); } return result; } private int getMode(File file) { //noinspection OctalInteger return 0664; } public void push(InputStream source, long lastModified, int mode, RemoteFile remote) throws IOException, JadbException { Transport transport = getTransport(); SyncTransport sync = transport.startSync(); sync.send("SEND", remote.getPath() + "," + Integer.toString(mode)); sync.sendStream(source); sync.sendStatus("DONE", (int) lastModified); sync.verifyStatus(); } public void push(File local, RemoteFile remote) throws IOException, JadbException { FileInputStream fileStream = new FileInputStream(local); push(fileStream, local.lastModified(), getMode(local), remote); fileStream.close(); } public void pull(RemoteFile remote, OutputStream destination) throws IOException, JadbException { Transport transport = getTransport(); SyncTransport sync = transport.startSync(); sync.send("RECV", remote.getPath()); sync.readChunksTo(destination); } public void pull(RemoteFile remote, File local) throws IOException, JadbException { FileOutputStream fileStream = new FileOutputStream(local); pull(remote, fileStream); fileStream.close(); } private void send(Transport transport, String command) throws IOException, JadbException { transport.send(command); transport.verifyResponse(); } @Override public String toString() { return "Device: " + serial; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((serial == null) ? 0 : serial.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JadbDevice other = (JadbDevice) obj; if (serial == null) { if (other.serial != null) return false; } else if (!serial.equals(other.serial)) return false; return true; } }
Echtzeitsysteme/mindroid
impl/serverApp/src/main/java/se/vidstige/jadb/JadbDevice.java
Java
gpl-3.0
7,644
import RPi.GPIO as GPIO KnockPin = 11 LedPin = 12 Led_status = 1 def setup(): GPIO.setmode(GPIO.BOARD) # Numbers GPIOs by physical location GPIO.setup(LedPin, GPIO.OUT) # Set LedPin's mode is output GPIO.setup(KnockPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.output(LedPin, GPIO.HIGH) # Set LedPin high(+3.3V) to off led def swLed(ev=None): global Led_status Led_status = not Led_status GPIO.output(LedPin, Led_status) # switch led status(on-->off; off-->on) print "LED: " + ("on" if Led_status else "off") def loop(): GPIO.add_event_detect(KnockPin, GPIO.FALLING, callback=swLed, bouncetime=200) # wait for falling while True: pass # Don't do anything def destroy(): GPIO.output(LedPin, GPIO.LOW) # led off GPIO.cleanup() # Release resource if __name__ == '__main__': # Program start from here setup() try: loop() except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed. destroy()
bicard/raspberrypi
quad-store-sensors/37in1/knock-rgb-led-smd.py
Python
gpl-3.0
1,005
/* * Copyright (c) 2016 The Ontario Institute for Cancer Research. All rights reserved. * * This program and the accompanying materials are made available under the terms of the GNU Public License v3.0. * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.icgc.dcc.submission.server.repository; import static org.icgc.dcc.submission.core.model.QUser.user; import java.util.List; import org.icgc.dcc.submission.core.model.QUser; import org.icgc.dcc.submission.core.model.User; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.Morphia; import org.springframework.beans.factory.annotation.Autowired; import lombok.NonNull; public class UserRepository extends AbstractRepository<User, QUser> { @Autowired public UserRepository(@NonNull Morphia morphia, @NonNull Datastore datastore) { super(morphia, datastore, user); } public List<User> findUsers() { return list(); } public User findUserByUsername(@NonNull String username) { return uniqueResult(entity.username.eq(username)); } public User saveUser(@NonNull User user) { save(user); return user; } public User updateUser(@NonNull User user) { return findAndModify( createQuery() .filter("username", user.getUsername()), createUpdateOperations() .set("failedAttempts", user.getFailedAttempts()), false, false); } }
icgc-dcc/dcc-submission
dcc-submission-server/src/main/java/org/icgc/dcc/submission/server/repository/UserRepository.java
Java
gpl-3.0
2,841
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright (C) 2018 David Arroyo Menéndez # Author: David Arroyo Menéndez <[email protected]> # Maintainer: David Arroyo Menéndez <[email protected]> # This file is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # This file is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with GNU Emacs; see the file COPYING. If not, write to # the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, # Boston, MA 02110-1301 USA, # Python program to check if the input year is a leap year or not year = 2000 # To get year (integer input) from the user # year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year))
davidam/python-examples
basics/leap.py
Python
gpl-3.0
1,385
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package Code.Domain; /** * * @author Andres Orduz Grimaldo */ public class Jornada { private int id; private String nombre; private TipoJornada tipoJornada; private Anio anio; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public TipoJornada getTipoJornada() { return tipoJornada; } public void setTipoJornada(TipoJornada tipoJornada) { this.tipoJornada = tipoJornada; } public Anio getAnio() { return anio; } public void setAnio(Anio anio) { this.anio = anio; } }
LayneGranados/Colegios
GestionColegios/Codigo/GestionColegiosCliente/src/Code/Domain/Jornada.java
Java
gpl-3.0
950
<?php /* * Copyright (c) 2013 Algolia * http://www.algolia.com/ * * 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. * * */ namespace WC_Order_Search_Admin\AlgoliaSearch; use Exception; class ClientContext { /** * @var string */ public $applicationID; /** * @var string */ public $apiKey; /** * @var array */ public $readHostsArray; /** * @var array */ public $writeHostsArray; /** * @var resource */ public $curlMHandle; /** * @var string */ public $adminAPIKey; /** * @var string */ public $endUserIP; /** * @var string */ public $algoliaUserToken; /** * @var int */ public $connectTimeout; /** * @var FailingHostsCache */ private $failingHostsCache; /** * @param string|null $applicationID * @param string|null $apiKey * @param array|null $hostsArray * @param bool $placesEnabled * @param FailingHostsCache|null $failingHostsCache * * @throws Exception */ public function __construct($applicationID = null, $apiKey = null, $hostsArray = null, $placesEnabled = false, \WC_Order_Search_Admin\AlgoliaSearch\FailingHostsCache $failingHostsCache = null) { // connect timeout of 1s by default $this->connectTimeout = 1; // global timeout of 30s by default $this->readTimeout = 30; // search timeout of 5s by default $this->searchTimeout = 5; $this->applicationID = $applicationID; $this->apiKey = $apiKey; $this->readHostsArray = $hostsArray; $this->writeHostsArray = $hostsArray; if ($this->readHostsArray == null || count($this->readHostsArray) == 0) { $this->readHostsArray = $this->getDefaultReadHosts($placesEnabled); $this->writeHostsArray = $this->getDefaultWriteHosts(); } if (($this->applicationID == null || mb_strlen($this->applicationID) == 0) && $placesEnabled === false) { throw new \Exception('AlgoliaSearch requires an applicationID.'); } if (($this->apiKey == null || mb_strlen($this->apiKey) == 0) && $placesEnabled === false) { throw new \Exception('AlgoliaSearch requires an apiKey.'); } $this->curlMHandle = null; $this->adminAPIKey = null; $this->endUserIP = null; $this->algoliaUserToken = null; $this->rateLimitAPIKey = null; $this->headers = array(); if ($failingHostsCache === null) { $this->failingHostsCache = new \WC_Order_Search_Admin\AlgoliaSearch\InMemoryFailingHostsCache(); } else { $this->failingHostsCache = $failingHostsCache; } $this->rotateHosts(); } /** * @param bool $placesEnabled * * @return array */ private function getDefaultReadHosts($placesEnabled) { if ($placesEnabled) { $hosts = array('places-1.algolianet.com', 'places-2.algolianet.com', 'places-3.algolianet.com'); shuffle($hosts); array_unshift($hosts, 'places-dsn.algolia.net'); return $hosts; } $hosts = array($this->applicationID . '-1.algolianet.com', $this->applicationID . '-2.algolianet.com', $this->applicationID . '-3.algolianet.com'); shuffle($hosts); array_unshift($hosts, $this->applicationID . '-dsn.algolia.net'); return $hosts; } /** * @return array */ private function getDefaultWriteHosts() { $hosts = array($this->applicationID . '-1.algolianet.com', $this->applicationID . '-2.algolianet.com', $this->applicationID . '-3.algolianet.com'); shuffle($hosts); array_unshift($hosts, $this->applicationID . '.algolia.net'); return $hosts; } /** * Closes eventually opened curl handles. */ public function __destruct() { if (is_resource($this->curlMHandle)) { curl_multi_close($this->curlMHandle); } } /** * @param $curlHandle * * @return resource */ public function getMHandle($curlHandle) { if (!is_resource($this->curlMHandle)) { $this->curlMHandle = curl_multi_init(); } curl_multi_add_handle($this->curlMHandle, $curlHandle); return $this->curlMHandle; } /** * @param $curlHandle */ public function releaseMHandle($curlHandle) { curl_multi_remove_handle($this->curlMHandle, $curlHandle); } /** * @param string $ip */ public function setForwardedFor($ip) { $this->endUserIP = $ip; } /** * @param string $token */ public function setAlgoliaUserToken($token) { $this->algoliaUserToken = $token; } /** * @param string $adminAPIKey * @param string $endUserIP * @param string $rateLimitAPIKey */ public function setRateLimit($adminAPIKey, $endUserIP, $rateLimitAPIKey) { $this->adminAPIKey = $adminAPIKey; $this->endUserIP = $endUserIP; $this->rateLimitAPIKey = $rateLimitAPIKey; } /** * Disables the rate limit. */ public function disableRateLimit() { $this->adminAPIKey = null; $this->endUserIP = null; $this->rateLimitAPIKey = null; } /** * @param string $key * @param string $value */ public function setExtraHeader($key, $value) { $this->headers[$key] = $value; } /** * @param string $host */ public function addFailingHost($host) { $this->failingHostsCache->addFailingHost($host); } /** * @return FailingHostsCache */ public function getFailingHostsCache() { return $this->failingHostsCache; } /** * This method is called to pass on failing hosts. * If the host is first either in the failingHosts array, we * rotate the array to ensure the next API call will be directly made with a working * host. This mainly ensures we don't add the equivalent of the connection timeout value to each * request to the API. */ public function rotateHosts() { $failingHosts = $this->failingHostsCache->getFailingHosts(); $i = 0; while ($i <= count($this->readHostsArray) && in_array($this->readHostsArray[0], $failingHosts)) { $i++; $this->readHostsArray[] = array_shift($this->readHostsArray); } $i = 0; while ($i <= count($this->writeHostsArray) && in_array($this->writeHostsArray[0], $failingHosts)) { $i++; $this->writeHostsArray[] = array_shift($this->writeHostsArray); } } }
rayrutjes/wc-order-search-admin
libs/vendor/algolia/algoliasearch-client-php/src/AlgoliaSearch/ClientContext.php
PHP
gpl-3.0
7,874
MyTestRepo ========== j A Test Repo
spooling/MyTestRepo
README.md
Markdown
gpl-3.0
36
<?php /* @var $this yii\web\View */ use yii\data\ActiveDataProvider; use yii\widgets\ListView; /* @var $books array */ /* @var $book \app\models\Books */ /* @var $booksPhotos \app\models\BooksPhotos */ /* @var $booksDataProvider ActiveDataProvider */ /* @var $popularBooksDataProvider ActiveDataProvider */ $this->title = Yii::t('seo','{appName} - Coding books | Programming Library', ['appName' => \Yii::$app->name]); $this->registerMetaTag([ 'name' => 'description', 'content' => Yii::t('seo', 'CoBooks is an online library consisting of books about programming, management of IT projects and other areas related to IT. Site for free online reading and downloading books in different formats.') ]); ?> <div class="row clearfix text-center"> <h2 class="title-one"> <?= Yii::t('seo', 'Free IT e-library') ?> </h2> <div id="books-categories" class="portfolio-filter"> <ul class="nav nav-pills text-center"> <li class="active"> <a data-toggle="pill" href="#popular-books"> <?= Yii::t('books', 'Popular Books') ?> </a> </li> <li> <a data-toggle="pill" href="#last-books"> <?= Yii::t('categories', 'Novelties') ?> </a> </li> </ul> </div> <div class="tab-content"> <div id="popular-books" class="tab-pane fade in active"> <div class="books-box"> <?= ListView::widget([ 'dataProvider' => $popularBooksDataProvider, 'summary' => false, 'layout' => '{items}', 'itemView' => '/parts/book', ]); ?> <a class="btn btn-default" href="<?= \yii\helpers\Url::to(['/book/popular']) ?>"> <?= Yii::t('app', 'View all') ?> </a> </div> </div> <div id="last-books" class="tab-pane fade"> <div class="books-box"> <?= ListView::widget([ 'dataProvider' => $booksDataProvider, 'summary' => false, 'layout' => '{items}', 'itemView' => '/parts/book', ]); ?> <a class="btn btn-default" href="<?= \yii\helpers\Url::to(['/book/last']) ?>"> <?= Yii::t('app', 'View all') ?> </a> </div> </div> </div> </div>
coding-books/website
views/site/index.php
PHP
gpl-3.0
2,499
function drawChart(len){ var box = document.createElement('div'); box.setAttribute('style','width:500px;height:500px;border:1px solid black;display:flex;flex-direction:column'); for(var i=0; i<len; i++){ var row = document.createElement('div'); if(i<len-1){ row.setAttribute('style','border-bottom:1px solid black;display:flex;box-sizing: border-box; flex: 1;'); } else{ row.setAttribute('style','display:flex;box-sizing: border-box; flex: 1;'); } for(var j=0; j<len; j++){ var col = document.createElement('div'); if(i%2===0){ if(j%2===0){ col.setAttribute('style','background-color:white; flex: 1;'); } else{ col.setAttribute('style','background-color:black; flex: 1;'); } }else{ if(j%2===0){ col.setAttribute('style','background-color:black; flex: 1;'); } else{ col.setAttribute('style','background-color:white; flex: 1;'); } } row.appendChild(col); } box.appendChild(row); } document.body.appendChild(box); } drawChart(5);
shashankKeshava/effective-enigma
jobCrunch/chess.js
JavaScript
gpl-3.0
1,186
package com.tage.rpgutil.client.gui; import net.minecraftforge.client.event.RenderGameOverlayEvent; import cpw.mods.fml.common.eventhandler.Cancelable; import cpw.mods.fml.common.eventhandler.Event; import cpw.mods.fml.common.eventhandler.EventPriority; @Cancelable public class GuiHealth extends Event { public static enum ElementType { ARMOR, HEALTH, } }
T4ge/RPGUtils
src/main/java/com/tage/rpgutil/client/gui/GuiHealth.java
Java
gpl-3.0
386
using System; using System.Linq; using System.Collections.Generic; using System.Reflection; using System.Xml; using log4net; using System.ComponentModel; using System.Xml.Serialization; using System.Text; using System.IO; using common; using jm726.lib.wrapper; using jm726.lib.wrapper.logger; namespace jm726.lib.wrapper.logger { /// <summary> /// Class which uses the ISpy interface to record all method calls to a given object. These are recorded to Xml. /// Can also play back recordings /// /// ONLY PUBLIC PROPERTIES WITH GETTERS _AND_ SETTERS WILL BE LOGGED CORRECTLY /// </summary> /// <typeparam name="TToLog">The interface which is being logged.</typeparam> public class XmlLogWriter<TToLog> : Wrapper<TToLog>, IXmlLogWriter<TToLog> where TToLog : class { #region Private Fields /// <summary> /// The log4net logger object used to log information to the console or log events. /// </summary> private readonly ILog _logger; /// <summary> /// The name of this logger. This is the name of the type being logged with '_Logger' added onto the end. /// </summary> private readonly string _name; /// <summary> /// The XML document which stores the event logging document as it is being built. /// </summary> private XmlDocument _doc; /// <summary> /// The root XML node to which all events are to be appended as children. /// </summary> private XmlNode _root; /// <summary> /// The XML document being built up to log all the events happening to the wrapped instance of TToLog. /// </summary> private DateTime _lastEvent; /// <summary> /// Wether or not events are to be logged currently. /// </summary> private bool _logging; /// <summary> /// Whether or not to serialize the return value of the method. /// </summary> private bool _recordForPlayback; #endregion #region XmlLogWriter Properties /// <inheritdoc /> public XmlDocument Log { get { return _doc; } } #endregion #region Constructor /// <summary> /// Constructor which creates a generic logger. Instantiates a series of helper fields and stores the TToLog instance which is to be wrapped by this logger. /// </summary> /// <param name="spy">The instance of TToLog which this logger will log calls to.</param> public XmlLogWriter(TToLog instance, bool recordForPlayback = false, bool recursive = true) : base(instance, "XmlLogWriter", recursive) { _lastEvent = default(DateTime); _recordForPlayback = recordForPlayback; _name = typeof(TToLog).FullName + "_Logger"; _logger = LogManager.GetLogger(_name); _doc = new XmlDocument(); XmlNode declaration = _doc.CreateXmlDeclaration("1.0", "utf-8", "yes"); _doc.AppendChild(declaration); } #endregion #region Override Abstract Methods from Wrapper public override void ReportMethodCallVoid(string methodName, object[] parameters) { if (!_logging) { CallMethod(methodName, parameters); return; } MethodCall m = new MethodCall(GetMethod(methodName, parameters), WrappedInstance, parameters); if (_recordForPlayback && !m.Type.Equals("Method") && !m.Type.Equals("PropertySet")) return; XmlNode callNode = m.Serialize(_doc, SwitchArgument); callNode.Attributes.Append(GetTimeAttr()); _root.AppendChild(callNode); } public override object ReportMethodCallReturn(string methodName, object[] parameters) { if (!_logging) return CallMethod(methodName, parameters); MethodCall m = new MethodCall(GetMethod(methodName, parameters), WrappedInstance, parameters); if (_recordForPlayback && !m.Type.Equals("Method") && !m.Type.Equals("PropertySet")) return m.Return; XmlNode callNode = m.Serialize(_doc, SwitchArgument, _recordForPlayback); callNode.Attributes.Append(GetTimeAttr()); _root.AppendChild(callNode); return m.Return; } public override void ReportEventTriggered(string eventName, object[] parameters) { //Do Nothing } /// <summary> /// Log the time at which a method call was made. /// </summary> private XmlAttribute GetTimeAttr() { XmlAttribute time = _doc.CreateAttribute("Time"); if (_lastEvent.Equals(default(DateTime))) time.Value = "0"; else time.Value = DateTime.Now.Subtract(_lastEvent).TotalMilliseconds + ""; _lastEvent = DateTime.Now; return time; } #endregion #region XmlLogWriter Methods /// <inheritdoc /> public void StartRecording() { if (_root != null) _doc.RemoveChild(_root); XmlNode root = _doc.CreateElement("Events"); _doc.AppendChild(root); StartRecording(_doc); } public void StartRecording(XmlDocument doc) { XmlNodeList roots = doc.GetElementsByTagName("Events"); if (roots.Count == 0) throw new ArgumentException("Unable to append events to supplied XML document. Document is not in the correct format"); _doc = doc; _doc.NodeInserted += (source, args) => { if (args.NewParent.Name.Equals("Events")) _lastEvent = DateTime.Now; }; _root = roots[0]; _lastEvent = default(DateTime); _logging = true; } /// <inheritdoc /> public void StopRecording() { _logging = false; } /// <inheritdoc /> public void PauseRecording() { _lastEvent = DateTime.Now; _logging = false; } /// <inheritdoc /> public void RestartRecording() { _logging = false; } #endregion #region Util /// <summary> /// Used for extensibility. /// /// Override this and check the type of the argument to define special behaviour for special types. /// Original defined so that instance specific IDs can be swapped to general but less unique names in the XML /// which can then be resolved back to new specific IDs when the sequence is played back. /// </summary> /// <param name="arg">The argument to swap for a different type.</param> /// <returns>The type to swap the argument to.</returns> protected virtual XmlNode SwitchArgument(ParameterInfo param, object arg) { return null; } #endregion } }
JohnMcCaffery/RoutingIsland
Source/Diagrams/jm726.lib/Wrapper/Logger/XmlLogWriter.cs
C#
gpl-3.0
7,090
/*! \file \author Igor Mironchik (igor.mironchik at gmail dot com). Copyright (c) 2017 Igor Mironchik This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef TREE__CAMERA_CONTROLLER_HPP__INCLUDED #define TREE__CAMERA_CONTROLLER_HPP__INCLUDED // Qt include. #include <Qt3DCore/QEntity> // C++ include. #include <memory> QT_BEGIN_NAMESPACE namespace Qt3DRender { class QCamera; } QT_END_NAMESPACE // // CameraController // class CameraControllerPrivate; class CameraController Q_DECL_FINAL : public Qt3DCore::QEntity { Q_OBJECT public: CameraController( Qt3DRender::QCamera * camera, Qt3DCore::QEntity * parent ); ~CameraController(); private slots: void _q_onTriggered( float ); private: friend class CameraControllerPrivate; Q_DISABLE_COPY( CameraController ) std::unique_ptr< CameraControllerPrivate > d; }; // class CameraController #endif // TREE__CAMERA_CONTROLLER_HPP__INCLUDED
igormironchik/3Dtree
3Dtree/camera_controller.hpp
C++
gpl-3.0
1,494
.ui-multiselect { padding:4px 2px 4px 4px; text-align:left } .ui-multiselect span.ui-icon { float:right } .ui-multiselect-single .ui-multiselect-checkboxes input { left:-9999px; position:absolute !important; top: auto !important; } .ui-multiselect-single .ui-multiselect-checkboxes label { padding:5px !important } .ui-multiselect-header { margin-bottom:3px; padding:3px 0 3px 4px; } .ui-multiselect-header ul { font-size:0.9em } .ui-multiselect-header ul li { float:left; padding:0 10px 0 0; } .ui-multiselect-header a { text-decoration:none; } .ui-multiselect-header a:hover { text-decoration:underline; } .ui-multiselect-header span.ui-icon { float:left; } .ui-multiselect-header .ui-multiselect-close { float:right; padding-right:0; text-align:right; } .ui-multiselect-menu { display:none; padding:3px; position:absolute; text-align: left; } .ui-multiselect-checkboxes { overflow-y:auto; position:relative; } .ui-multiselect-checkboxes label { border:1px solid transparent; cursor:default; display:block; padding:3px 1px; } .ui-multiselect-checkboxes label input { position:relative; top:1px } .ui-multiselect-checkboxes label img { height: 30px; vertical-align: middle; padding-right: 3px;} .ui-multiselect-checkboxes li { clear:both; font-size:0.9em; list-style: none; padding-right:3px; } .ui-multiselect-checkboxes .ui-multiselect-optgroup { padding: 3px; } .ui-multiselect-columns { display: inline-block; vertical-align: top; } .ui-multiselect-checkboxes .ui-multiselect-optgroup a { border-bottom:1px solid; cursor: pointer; display:block; font-weight:bold; margin:1px 0; padding:3px; text-align:center; text-decoration:none; } @media print{ .ui-multiselect-menu {display: none;} }
nordneige/ndui
ndui/ndui/lib/jquery-ui-1.12.1.custom/jquery.multiselect.css
CSS
gpl-3.0
1,700
# Copyright 2015 Allen Institute for Brain Science # This file is part of Allen SDK. # # Allen SDK is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # Allen SDK is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Allen SDK. If not, see <http://www.gnu.org/licenses/>. from allensdk.api.api import Api import os, json from collections import OrderedDict class BiophysicalPerisomaticApi(Api): _NWB_file_type = 'NWB' _SWC_file_type = '3DNeuronReconstruction' _MOD_file_type = 'BiophysicalModelDescription' _FIT_file_type = 'NeuronalModelParameters' def __init__(self, base_uri=None): super(BiophysicalPerisomaticApi, self).__init__(base_uri) self.cache_stimulus = True self.ids = {} self.sweeps = [] self.manifest = {} def build_rma(self, neuronal_model_id, fmt='json'): '''Construct a query to find all files related to a neuronal model. Parameters ---------- neuronal_model_id : integer or string representation key of experiment to retrieve. fmt : string, optional json (default) or xml Returns ------- string RMA query url. ''' include_associations = ''.join([ 'neuronal_model_template(well_known_files(well_known_file_type)),', 'specimen', '(ephys_result(well_known_files(well_known_file_type)),' 'neuron_reconstructions(well_known_files(well_known_file_type)),', 'ephys_sweeps),', 'well_known_files(well_known_file_type)']) criteria_associations = ''.join([ ("[id$eq%d]," % (neuronal_model_id)), include_associations]) return ''.join([self.rma_endpoint, '/query.', fmt, '?q=', 'model::NeuronalModel,', 'rma::criteria,', criteria_associations, ',rma::include,', include_associations]) def read_json(self, json_parsed_data): '''Get the list of well_known_file ids from a response body containing nested sample,microarray_slides,well_known_files. Parameters ---------- json_parsed_data : dict Response from the Allen Institute Api RMA. Returns ------- list of strings Well known file ids. ''' self.ids = { 'stimulus': {}, 'morphology': {}, 'modfiles': {}, 'fit': {} } self.sweeps = [] if 'msg' in json_parsed_data: for neuronal_model in json_parsed_data['msg']: if 'well_known_files' in neuronal_model: for well_known_file in neuronal_model['well_known_files']: if ('id' in well_known_file and 'path' in well_known_file and self.is_well_known_file_type(well_known_file, BiophysicalPerisomaticApi._FIT_file_type)): self.ids['fit'][str(well_known_file['id'])] = \ os.path.split(well_known_file['path'])[1] if 'neuronal_model_template' in neuronal_model: neuronal_model_template = neuronal_model['neuronal_model_template'] if 'well_known_files' in neuronal_model_template: for well_known_file in neuronal_model_template['well_known_files']: if ('id' in well_known_file and 'path' in well_known_file and self.is_well_known_file_type(well_known_file, BiophysicalPerisomaticApi._MOD_file_type)): self.ids['modfiles'][str(well_known_file['id'])] = \ os.path.join('modfiles', os.path.split(well_known_file['path'])[1]) if 'specimen' in neuronal_model: specimen = neuronal_model['specimen'] if 'neuron_reconstructions' in specimen: for neuron_reconstruction in specimen['neuron_reconstructions']: if 'well_known_files' in neuron_reconstruction: for well_known_file in neuron_reconstruction['well_known_files']: if ('id' in well_known_file and 'path' in well_known_file and self.is_well_known_file_type(well_known_file, BiophysicalPerisomaticApi._SWC_file_type)): self.ids['morphology'][str(well_known_file['id'])] = \ os.path.split(well_known_file['path'])[1] if 'ephys_result' in specimen: ephys_result = specimen['ephys_result'] if 'well_known_files' in ephys_result: for well_known_file in ephys_result['well_known_files']: if ('id' in well_known_file and 'path' in well_known_file and self.is_well_known_file_type(well_known_file, BiophysicalPerisomaticApi._NWB_file_type)): self.ids['stimulus'][str(well_known_file['id'])] = \ "%d.nwb" % (ephys_result['id']) self.sweeps = [sweep['sweep_number'] for sweep in specimen['ephys_sweeps'] if sweep['stimulus_name'] != 'Test'] return self.ids def is_well_known_file_type(self, wkf, name): '''Check if a structure has the expected name. Parameters ---------- wkf : dict A well-known-file structure with nested type information. name : string The expected type name See Also -------- read_json: where this helper function is used. ''' try: return wkf['well_known_file_type']['name'] == name except: return False def get_well_known_file_ids(self, neuronal_model_id): '''Query the current RMA endpoint with a neuronal_model id to get the corresponding well known file ids. Returns ------- list A list of well known file id strings. ''' rma_builder_fn = self.build_rma json_traversal_fn = self.read_json return self.do_query(rma_builder_fn, json_traversal_fn, neuronal_model_id) def create_manifest(self, fit_path='', stimulus_filename='', swc_morphology_path='', sweeps=[]): '''Generate a json configuration file with parameters for a a biophysical experiment. Parameters ---------- fit_path : string filename of a json configuration file with cell parameters. stimulus_filename : string path to an NWB file with input currents. swc_morphology_path : string file in SWC format. sweeps : array of integers which sweeps in the stimulus file are to be used. ''' self.manifest = OrderedDict() self.manifest['biophys'] = [{ 'model_file': [ 'manifest.json', fit_path ] }] self.manifest['runs'] = [{ 'sweeps': sweeps }] self.manifest['neuron'] = [{ 'hoc': [ 'stdgui.hoc', 'import3d.hoc' ] }] self.manifest['manifest'] = [ { 'type': 'dir', 'spec': '.', 'key': 'BASEDIR' }, { 'type': 'dir', 'spec': 'work', 'key': 'WORKDIR', 'parent': 'BASEDIR' }, { 'type': 'file', 'spec': swc_morphology_path, 'key': 'MORPHOLOGY' }, { 'type': 'dir', 'spec': 'modfiles', 'key': 'MODFILE_DIR' }, { 'type': 'file', 'format': 'NWB', 'spec': stimulus_filename, 'key': 'stimulus_path' }, { 'parent_key': 'WORKDIR', 'type': 'file', 'format': 'NWB', 'spec': stimulus_filename, 'key': 'output' } ] def cache_data(self, neuronal_model_id, working_directory=None): '''Take a an experiment id, query the Api RMA to get well-known-files download the files, and store them in the working directory. Parameters ---------- neuronal_model_id : int or string representation found in the neuronal_model table in the api working_directory : string Absolute path name where the downloaded well-known files will be stored. ''' if working_directory is None: working_directory = self.default_working_directory try: os.stat(working_directory) except: os.mkdir(working_directory) work_dir = os.path.join(working_directory, 'work') try: os.stat(work_dir) except: os.mkdir(work_dir) modfile_dir = os.path.join(working_directory, 'modfiles') try: os.stat(modfile_dir) except: os.mkdir(modfile_dir) well_known_file_id_dict = self.get_well_known_file_ids(neuronal_model_id) for key, id_dict in well_known_file_id_dict.items(): if (not self.cache_stimulus) and (key == 'stimulus'): continue for well_known_id, filename in id_dict.items(): well_known_file_url = self.construct_well_known_file_download_url(well_known_id) cached_file_path = os.path.join(working_directory, filename) self.retrieve_file_over_http(well_known_file_url, cached_file_path) fit_path = self.ids['fit'].values()[0] stimulus_filename = self.ids['stimulus'].values()[0] swc_morphology_path = self.ids['morphology'].values()[0] sweeps = sorted(self.sweeps) self.create_manifest(fit_path, stimulus_filename, swc_morphology_path, sweeps) manifest_path = os.path.join(working_directory, 'manifest.json') with open(manifest_path, 'wb') as f: f.write(json.dumps(self.manifest, indent=2))
wvangeit/AllenSDK
allensdk/api/queries/biophysical_perisomatic_api.py
Python
gpl-3.0
12,180
/* eslint-disable no-self-assign */ import Game from '../../../../gui/html/js/game'; import { Plugin } from '../../../../gui/html/js/plugin'; import Translator from '../../../../gui/html/js/translator'; jest.mock('../../../../gui/html/js/dom'); jest.mock('../../../../gui/html/js/filters'); describe('Game', () => { const l10n = new Translator(); const defaultDerivedPluginMetadata = { name: 'test', isActive: false, isDirty: false, isEmpty: false, isMaster: false, isLightPlugin: false, loadsArchive: false, messages: [], suggestedTags: [], currentTags: [] }; const gameData = { folder: 'test', generalMessages: [ { type: 'say', text: 'test', language: 'en', condition: '' } ], masterlist: { revision: '0', date: '' }, groups: { masterlist: [], userlist: [] }, plugins: [defaultDerivedPluginMetadata], bashTags: [] }; describe('#constructor()', () => { test("should set folder to the object's value", () => { const game = new Game(gameData, l10n); expect(game.folder).toBe('test'); }); test("should set generalMessages to the object's value", () => { const game = new Game(gameData, l10n); expect(game.generalMessages).toEqual([ { type: 'say', text: 'test', language: 'en', condition: '' } ]); }); test("should set masterlist to the object's value", () => { const game = new Game(gameData, l10n); expect(game.masterlist).toEqual({ revision: '0', date: '' }); }); test("should construct plugins from the object's plugins value", () => { const game = new Game(gameData, l10n); expect(game.plugins.length).toBe(1); expect(game.plugins[0]).toHaveProperty('update'); expect(game.plugins[0].name).toBe('test'); expect(game.plugins[0].cardZIndex).toBe(1); }); test("should set oldLoadOrder to an empty array even if the object's value if defined", () => { const game = new Game(gameData, l10n); expect(game.oldLoadOrder).toEqual([]); }); }); describe('#folder', () => { let game: Game; // It's not worth the hassle of defining and checking the event type in test // code. // eslint-disable-next-line @typescript-eslint/no-explicit-any let handleEvent: (evt: any) => void; beforeEach(() => { game = new Game(gameData, l10n); }); afterEach(() => { document.removeEventListener('loot-game-folder-change', handleEvent); }); test('setting value should not dispatch an event if the new value is equal to the old one', done => { handleEvent = () => { done(new Error('Should not have fired an event')); }; document.addEventListener('loot-game-folder-change', handleEvent); game.folder = game.folder; setTimeout(done, 100); }); test('setting value should dispatch an event if the new value differs from the old one', done => { handleEvent = evt => { expect(evt.detail.folder).toBe('other test'); done(); }; document.addEventListener('loot-game-folder-change', handleEvent); game.folder = 'other test'; }); }); describe('#generalMessages', () => { let game: Game; // It's not worth the hassle of defining and checking the event type in test // code. // eslint-disable-next-line @typescript-eslint/no-explicit-any let handleEvent: (evt: any) => void; beforeEach(() => { game = new Game(gameData, l10n); }); afterEach(() => { document.removeEventListener( 'loot-game-global-messages-change', handleEvent ); }); test('setting value should not dispatch an event if the new value is equal to the old one', done => { handleEvent = () => { done(new Error('Should not have fired an event')); }; document.addEventListener( 'loot-game-global-messages-change', handleEvent ); game.generalMessages = game.generalMessages; setTimeout(done, 100); }); test('setting value should dispatch an event if the new and old message strings differ', done => { const newMessages = [ { type: 'say', text: 'bar', language: 'en', condition: '' } ]; handleEvent = evt => { expect(evt.detail.messages).toEqual(newMessages); expect(evt.detail.totalDiff).toBe(0); expect(evt.detail.errorDiff).toBe(0); expect(evt.detail.warningDiff).toBe(0); done(); }; document.addEventListener( 'loot-game-global-messages-change', handleEvent ); game.generalMessages = newMessages; }); test('setting value should dispatch an event if the new and old message type counts differ', done => { const newMessages = [ { type: 'warn', text: 'foo', language: 'en', condition: '' }, { type: 'error', text: 'bar', language: 'en', condition: '' } ]; game.generalMessages = []; handleEvent = evt => { expect(evt.detail.messages).toEqual(newMessages); expect(evt.detail.totalDiff).toBe(2); expect(evt.detail.errorDiff).toBe(1); expect(evt.detail.warningDiff).toBe(1); done(); }; document.addEventListener( 'loot-game-global-messages-change', handleEvent ); game.generalMessages = newMessages; }); }); describe('#masterlist', () => { let game: Game; // It's not worth the hassle of defining and checking the event type in test // code. // eslint-disable-next-line @typescript-eslint/no-explicit-any let handleEvent: (evt: any) => void; beforeEach(() => { game = new Game(gameData, l10n); }); afterEach(() => { document.removeEventListener('loot-game-masterlist-change', handleEvent); }); test('setting value should not dispatch an event if the new value is equal to the old one', done => { handleEvent = () => { done(new Error('Should not have fired an event')); }; document.addEventListener('loot-game-masterlist-change', handleEvent); game.masterlist = game.masterlist; setTimeout(done, 100); }); test('setting value should dispatch an event if the new value differs from the old one', done => { const newMasterlist = { revision: 'foo', date: 'bar' }; handleEvent = evt => { expect(evt.detail).toEqual(newMasterlist); done(); }; document.addEventListener('loot-game-masterlist-change', handleEvent); game.masterlist = newMasterlist; }); }); describe('#plugins', () => { let game: Game; // It's not worth the hassle of defining and checking the event type in test // code. // eslint-disable-next-line @typescript-eslint/no-explicit-any let handleEvent: (evt: any) => void; beforeEach(() => { game = new Game(gameData, l10n); }); afterEach(() => { document.removeEventListener('loot-game-plugins-change', handleEvent); }); test('setting value should dispatch an event if the new value is equal to the old one', done => { handleEvent = () => { done(); }; document.addEventListener('loot-game-plugins-change', handleEvent); game.plugins = game.plugins; }); test('setting value should dispatch an event if the new value differs from the old one', done => { const newMessages = [ { type: 'warn', text: 'foo', language: 'en', condition: '' }, { type: 'error', text: 'bar', language: 'en', condition: '' } ]; const newPlugins = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'a', isActive: true, messages: [newMessages[0]] }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'b', isDirty: true, messages: [{ ...newMessages[0], type: 'say' }] }) ]; handleEvent = evt => { expect(evt.detail.valuesAreTotals).toBe(true); expect(evt.detail.totalMessageNo).toBe(4); expect(evt.detail.warnMessageNo).toBe(2); expect(evt.detail.errorMessageNo).toBe(1); expect(evt.detail.totalPluginNo).toBe(2); expect(evt.detail.activePluginNo).toBe(1); expect(evt.detail.dirtyPluginNo).toBe(1); done(); }; document.addEventListener('loot-game-plugins-change', handleEvent); game.generalMessages = newMessages; game.plugins = newPlugins; }); }); describe('groups', () => { test("get should return the game's groups", () => { const groups = { masterlist: [{ name: 'a', after: [] }], userlist: [{ name: 'b', after: [] }] }; const game = new Game({ ...gameData, groups }, l10n); expect(game.groups).toStrictEqual([ { name: 'a', after: [], isUserAdded: false }, { name: 'b', after: [], isUserAdded: true } ]); }); }); describe('#setGroups()', () => { // It's not worth the hassle of defining and checking the event type in test // code. // eslint-disable-next-line @typescript-eslint/no-explicit-any let handleEvent: (evt: any) => void; afterEach(() => { document.removeEventListener('loot-game-groups-change', handleEvent); }); test('should merge the given masterlist and userlist groups arrays', () => { const game = new Game(gameData, l10n); const groups = { masterlist: [{ name: 'a', after: [] }], userlist: [{ name: 'b', after: [] }] }; game.setGroups(groups); expect(game.groups).toStrictEqual([ { name: 'a', after: [], isUserAdded: false }, { name: 'b', after: [], isUserAdded: true } ]); }); test('should dispatch an event', done => { handleEvent = () => { done(); }; document.addEventListener('loot-game-groups-change', handleEvent); const game = new Game(gameData, l10n); const groups = { masterlist: [{ name: 'a', after: [] }], userlist: [{ name: 'b', after: [] }] }; game.setGroups(groups); }); }); describe('#getContent()', () => { let game: Game; beforeEach(() => { game = new Game(gameData, l10n); }); test('should return an object of two empty arrays if there is no game data', () => { game.plugins = []; game.generalMessages = []; expect(game.getContent()).toEqual({ messages: [], plugins: [] }); }); test('should return a structure containing converted plugin and message structures', () => { game.generalMessages = [ { type: 'say', condition: 'file("foo.esp")', language: 'fr', text: 'Bonjour le monde' } ]; game.plugins = [ new Plugin({ name: 'foo', crc: 0xdeadbeef, version: '1.0', isActive: true, isEmpty: true, isMaster: false, isLightPlugin: false, loadsArchive: true, group: 'group1', messages: [ { type: 'warn', condition: 'file("bar.esp")', language: 'en', text: 'Hello world' } ], currentTags: [ { name: 'Relev', isAddition: true, condition: '' } ], suggestedTags: [ { name: 'Delev', isAddition: true, condition: '' } ], isDirty: true }) ]; expect(game.getContent()).toEqual({ messages: game.generalMessages, plugins: [ { name: game.plugins[0].name, crc: game.plugins[0].crc, version: game.plugins[0].version, isActive: game.plugins[0].isActive, isEmpty: game.plugins[0].isEmpty, loadsArchive: game.plugins[0].loadsArchive, group: game.plugins[0].group, messages: game.plugins[0].messages, currentTags: game.plugins[0].currentTags, suggestedTags: game.plugins[0].suggestedTags, isDirty: game.plugins[0].isDirty } ] }); }); }); describe('#getPluginNames()', () => { let game: Game; beforeEach(() => { game = new Game(gameData, l10n); }); test('should return an empty array if there are no plugins', () => { game.plugins = []; expect(game.getPluginNames().length).toBe(0); }); test('should return an array of plugin filenames if there are plugins', () => { game.plugins = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo', isActive: true, messages: [{ type: 'warn', text: '', language: 'en', condition: '' }] }) ]; expect(game.getPluginNames()).toEqual(['foo']); }); }); describe('#getGroupPluginNames()', () => { let game: Game; beforeEach(() => { const plugins = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo', group: 'test group' }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'bar', group: 'other group' }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'foobar', group: 'test group' }) ]; game = new Game({ ...gameData, plugins }, l10n); }); test('should return an empty array if there are no plugins in the given group', () => { expect(game.getGroupPluginNames('empty group').length).toBe(0); }); test('should return an array of filenames of plugins in the given group', () => { expect(game.getGroupPluginNames('test group')).toEqual(['foo', 'foobar']); }); }); describe('#setSortedPlugins', () => { let game: Game; // It's not worth the hassle of defining and checking the event type in test // code. // eslint-disable-next-line @typescript-eslint/no-explicit-any let handleEvent: (evt: any) => void; beforeEach(() => { game = new Game(gameData, l10n); }); afterEach(() => { document.removeEventListener('loot-game-plugins-change', handleEvent); }); test('should append new plugins to the plugins array', () => { game.setSortedPlugins([ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo' }) ]); expect(game.plugins[0].name).toBe('foo'); }); test('should update existing plugins with new data', () => { game.plugins = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo', isActive: true, messages: [{ type: 'warn', text: '', language: 'en', condition: '' }] }) ]; game.setSortedPlugins([ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo', crc: 0xdeadbeef }) ]); expect(game.plugins[0].crc).toBe(0xdeadbeef); expect(game.plugins[0].isActive).toBe(false); }); test('should reorder plugins to given order', () => { game.plugins = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo' }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'bar' }) ]; game.setSortedPlugins([ new Plugin({ ...defaultDerivedPluginMetadata, name: 'bar' }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo' }) ]); expect(game.plugins[0].name).toBe('bar'); expect(game.plugins[1].name).toBe('foo'); }); test('should store old load order', () => { game.plugins = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo' }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'bar' }) ]; game.setSortedPlugins([ new Plugin({ ...defaultDerivedPluginMetadata, name: 'bar' }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo' }) ]); expect(game.oldLoadOrder[0].name).toBe('foo'); expect(game.oldLoadOrder[1].name).toBe('bar'); }); test('should dispatch an event', done => { handleEvent = () => { done(); }; document.addEventListener('loot-game-plugins-change', handleEvent); game.setSortedPlugins([ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo' }) ]); }); }); describe('#applySort', () => { let game: Game; beforeEach(() => { game = new Game(gameData, l10n); }); test('should delete the stored old load order', () => { game.oldLoadOrder = gameData.plugins.map(p => new Plugin(p)); game.applySort(); expect(game.oldLoadOrder).toEqual([]); }); }); describe('#cancelSort', () => { let game: Game; beforeEach(() => { game = new Game(gameData, l10n); }); test('should set the current load order to the given plugins', () => { const oldLoadOrder = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo' }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'bar' }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'baz' }) ]; game.oldLoadOrder = oldLoadOrder; game.plugins = [oldLoadOrder[2], oldLoadOrder[1], oldLoadOrder[0]]; game.cancelSort( [{ name: 'baz', loadOrderIndex: 0 }, { name: 'foo' }], [] ); expect(game.plugins).toEqual([oldLoadOrder[2], oldLoadOrder[0]]); }); test('should delete the stored old load order', () => { game.oldLoadOrder = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo' }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'bar' }) ]; game.cancelSort([], []); expect(game.oldLoadOrder).toEqual([]); }); test('should set plugin load order indices using the array passed as the first parameter', () => { game.oldLoadOrder = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo', loadOrderIndex: 1 }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'bar', loadOrderIndex: 0 }) ]; game.cancelSort( [ { name: 'bar', loadOrderIndex: 0 }, { name: 'foo', loadOrderIndex: 2 } ], [] ); expect(game.plugins[0].name).toBe('bar'); expect(game.plugins[0].loadOrderIndex).toBe(0); expect(game.plugins[1].name).toBe('foo'); expect(game.plugins[1].loadOrderIndex).toBe(2); }); test('should set the general messages to the second passed parameter', () => { game.oldLoadOrder = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo', loadOrderIndex: 1 }), new Plugin({ ...defaultDerivedPluginMetadata, name: 'bar', loadOrderIndex: 0 }) ]; const messages = [ { type: 'say', text: 'foo', language: 'en', condition: '' } ]; game.cancelSort([], messages); expect(game.generalMessages).toEqual(messages); }); }); describe('#clearMetadata', () => { let game: Game; beforeEach(() => { game = new Game(gameData, l10n); }); test('should delete stored userlist data for existing plugins', () => { game.plugins = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo', userlist: { name: '', after: [], req: [], inc: [], msg: [], tag: [], dirty: [], clean: [], url: [] } }) ]; game.clearMetadata([ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo' }) ]); expect(game.plugins[0].userlist).toBe(undefined); }); test('should update existing plugin data', () => { game.plugins = [ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo', isActive: true }) ]; game.clearMetadata([ new Plugin({ ...defaultDerivedPluginMetadata, name: 'foo', crc: 0xdeadbeef }) ]); expect(game.plugins[0].crc).toBe(0xdeadbeef); expect(game.plugins[0].isActive).toBe(false); }); }); });
silentdark/loot
src/tests/gui/html/js/test_game.ts
TypeScript
gpl-3.0
21,385
# == Schema Information # # Table name: causes # # id :integer not null, primary key # name :string not null # description :string # image_id :integer # created_at :datetime not null # updated_at :datetime not null # require 'rails_helper' RSpec.describe Cause, type: :model do pending "add some examples to (or delete) #{__FILE__}" end
LuizEdgar/SerVoluntarioAPI
spec/models/cause_spec.rb
Ruby
gpl-3.0
403
<?php /** * The template part for displaying single archive from hospital posts * * @package Twenty-Sixteen-Child * * */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header class="entry-header"> <?php the_title( sprintf( '<h2 class="entry-title-hospital"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h2>' );?> </header><!-- .entry-header --> <div class="entry-content-hospital"> <?php $review_description = get_post_meta($post->ID); if(!empty($review_description['reviewer_name'][0])){ $reviewer_name = $review_description['reviewer_name'][0]; echo '<h3>'.$reviewer_name.'</h3>'; } the_post_thumbnail('thumbnail'); the_content(); echo '</br>'; echo get_the_tag_list( '<br>Tags: ', ', ','<br>' ); echo '</br>'; edit_post_link( ); ?> </div><!-- .entry-content-hospital --> </article><!-- #post-## -->
umeshramya/Twenty-Sixteen-Hospital
template-parts/content-reviews-archive.php
PHP
gpl-3.0
906
// simplewall // Copyright (c) 2016-2021 Henry++ #pragma once #include "routine.h" #include <winsock2.h> #include <ws2ipdef.h> #include <ws2tcpip.h> #include <windns.h> #include <mstcpip.h> #include <iphlpapi.h> #include <aclapi.h> #include <dbt.h> #include <fwpmu.h> #include <mmsystem.h> #include <netfw.h> #include <shlguid.h> #include <shobjidl.h> #include <softpub.h> #include <subauth.h> #include <mscat.h> #include "app.h" #include "rapp.h" #include "main.h" #include "resource.h" DECLSPEC_SELECTANY STATIC_DATA config = {0}; DECLSPEC_SELECTANY PROFILE_DATA profile_info = {0}; DECLSPEC_SELECTANY PR_HASHTABLE apps_table = NULL; DECLSPEC_SELECTANY PR_LIST rules_list = NULL; DECLSPEC_SELECTANY PR_HASHTABLE rules_config = NULL; DECLSPEC_SELECTANY PR_HASHTABLE log_table = NULL; DECLSPEC_SELECTANY PR_HASHTABLE cache_information = NULL; DECLSPEC_SELECTANY PR_HASHTABLE cache_resolution = NULL; DECLSPEC_SELECTANY PR_HASHTABLE colors_table = NULL; DECLSPEC_SELECTANY PR_ARRAY filter_ids = NULL; DECLSPEC_SELECTANY R_QUEUED_LOCK lock_apps = PR_QUEUED_LOCK_INIT; DECLSPEC_SELECTANY R_QUEUED_LOCK lock_apply = PR_QUEUED_LOCK_INIT; DECLSPEC_SELECTANY R_QUEUED_LOCK lock_rules = PR_QUEUED_LOCK_INIT; DECLSPEC_SELECTANY R_QUEUED_LOCK lock_rules_config = PR_QUEUED_LOCK_INIT; DECLSPEC_SELECTANY R_QUEUED_LOCK lock_loglist = PR_QUEUED_LOCK_INIT; DECLSPEC_SELECTANY R_QUEUED_LOCK lock_profile = PR_QUEUED_LOCK_INIT; DECLSPEC_SELECTANY R_QUEUED_LOCK lock_transaction = PR_QUEUED_LOCK_INIT; DECLSPEC_SELECTANY R_QUEUED_LOCK lock_cache_information = PR_QUEUED_LOCK_INIT; DECLSPEC_SELECTANY R_QUEUED_LOCK lock_cache_resolution = PR_QUEUED_LOCK_INIT; DECLSPEC_SELECTANY R_WORKQUEUE file_queue = {0}; DECLSPEC_SELECTANY R_WORKQUEUE log_queue = {0}; DECLSPEC_SELECTANY R_WORKQUEUE resolver_queue = {0}; DECLSPEC_SELECTANY R_WORKQUEUE resolve_notify_queue = {0}; DECLSPEC_SELECTANY R_WORKQUEUE wfp_queue = {0}; DECLSPEC_SELECTANY R_FREE_LIST context_free_list = {0}; DECLSPEC_SELECTANY R_FREE_LIST listview_free_list = {0}; // timers array DECLSPEC_SELECTANY const LONG64 timer_array[] = { 2 * 60, 5 * 60, 10 * 60, 30 * 60, 1 * 3600, 2 * 3600, 4 * 3600, 6 * 3600 }; // dropped events callback subscription (win7+) #ifndef FWP_DIRECTION_IN #define FWP_DIRECTION_IN 0x00003900L #endif #ifndef FWP_DIRECTION_OUT #define FWP_DIRECTION_OUT 0x00003901L #endif #include "controls.h" #include "db.h" #include "editor.h" #include "helper.h" #include "icons.h" #include "listview.h" #include "log.h" #include "messages.h" #include "network.h" #include "notifications.h" #include "packages.h" #include "profile.h" #include "search.h" #include "security.h" #include "timer.h" #include "wfp.h"
henrypp/simplewall
src/global.h
C
gpl-3.0
2,798
\section{\-Getopt \-Class \-Reference} \label{interface_getopt}\index{\-Getopt@{\-Getopt}} {\ttfamily \#import $<$\-Getopt.\-h$>$} \subsection*{\-Public \-Member \-Functions} \begin{DoxyCompactItemize} \item (void) -\/ {\bf init\-Getopt\-:} \item (\-B\-O\-O\-L) -\/ {\bf response\-Is\-Valid} \item (\-N\-S\-String $\ast$) -\/ {\bf get\-Message} \item (\-N\-S\-String $\ast$) -\/ {\bf get\-Response\-Status} \item (int) -\/ {\bf get\-Response\-Code} \item (\-N\-S\-Mutable\-Array $\ast$) -\/ {\bf get\-Campaigns\-Id\-List} \item (\-N\-S\-Mutable\-Array $\ast$) -\/ {\bf get\-Campaign\-Status\-List} \item (\-N\-S\-Mutable\-Array $\ast$) -\/ {\bf get\-Campaign\-Status\-Code\-List} \item (int) -\/ {\bf get\-Campaign\-Status\-Code\-:} \item (\-N\-S\-String $\ast$) -\/ {\bf get\-Campaign\-Status\-:} \end{DoxyCompactItemize} \subsection{\-Detailed \-Description} \doxyref{\-Getopt.\-h}{p.}{_getopt_8h_source} \-Mercury\-\_\-i\-O\-S \-Created by \-Julien \-Salvi on 9/12/11. \-Copyright 2011 \-Mogreet \-Inc. \-All rights reserved. \-This file is part of \doxyref{\-Mercury}{p.}{interface_mercury}. \doxyref{\-Mercury}{p.}{interface_mercury} is free software\-: you can redistribute it and/or modify it under the terms of the \-G\-N\-U \-General \-Public \-License as published by the \-Free \-Software \-Foundation, either version 3 of the \-License, or (at your option) any later version. \doxyref{\-Mercury}{p.}{interface_mercury} is distributed in the hope that it will be useful, but \-W\-I\-T\-H\-O\-U\-T \-A\-N\-Y \-W\-A\-R\-R\-A\-N\-T\-Y; without even the implied warranty of \-M\-E\-R\-C\-H\-A\-N\-T\-A\-B\-I\-L\-I\-T\-Y or \-F\-I\-T\-N\-E\-S\-S \-F\-O\-R \-A \-P\-A\-R\-T\-I\-C\-U\-L\-A\-R \-P\-U\-R\-P\-O\-S\-E. \-See the \-G\-N\-U \-General \-Public \-License for more details. \-You should have received a copy of the \-G\-N\-U \-General \-Public \-License along with \doxyref{\-Mercury}{p.}{interface_mercury}. \-If not, see $<${\tt http\-://www.\-gnu.\-org/licenses/}$>$. \-The \doxyref{\-Getopt}{p.}{interface_getopt} object contains the response from a \doxyref{\-Mercury\#getopt}{p.}{} request to the \-Mo\-M\-S \-A\-P\-I. \-Getopt.\-m \-Mercury\-\_\-i\-O\-S \-Created by \-Julien \-Salvi on 9/12/11. \-Copyright 2011 \-Mogreet \-Inc. \-All rights reserved. \-This file is part of \doxyref{\-Mercury}{p.}{interface_mercury}. \doxyref{\-Mercury}{p.}{interface_mercury} is free software\-: you can redistribute it and/or modify it under the terms of the \-G\-N\-U \-General \-Public \-License as published by the \-Free \-Software \-Foundation, either version 3 of the \-License, or (at your option) any later version. \doxyref{\-Mercury}{p.}{interface_mercury} is distributed in the hope that it will be useful, but \-W\-I\-T\-H\-O\-U\-T \-A\-N\-Y \-W\-A\-R\-R\-A\-N\-T\-Y; without even the implied warranty of \-M\-E\-R\-C\-H\-A\-N\-T\-A\-B\-I\-L\-I\-T\-Y or \-F\-I\-T\-N\-E\-S\-S \-F\-O\-R \-A \-P\-A\-R\-T\-I\-C\-U\-L\-A\-R \-P\-U\-R\-P\-O\-S\-E. \-See the \-G\-N\-U \-General \-Public \-License for more details. \-You should have received a copy of the \-G\-N\-U \-General \-Public \-License along with \doxyref{\-Mercury}{p.}{interface_mercury}. \-If not, see $<${\tt http\-://www.\-gnu.\-org/licenses/}$>$. \subsection{\-Member \-Function \-Documentation} \index{\-Getopt@{\-Getopt}!get\-Campaigns\-Id\-List@{get\-Campaigns\-Id\-List}} \index{get\-Campaigns\-Id\-List@{get\-Campaigns\-Id\-List}!Getopt@{\-Getopt}} \subsubsection[{get\-Campaigns\-Id\-List}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-N\-S\-Mutable\-Array $\ast$) get\-Campaigns\-Id\-List \begin{DoxyParamCaption} {} \end{DoxyParamCaption} }\label{interface_getopt_ae67bd34f9a6eefb6991c0d1ba4f1ab5e} \-Gets the campaign \-I\-Ds. \begin{DoxyReturn}{\-Returns} \-An \-N\-S\-Mutable\-Array that contains all the campaigns \-I\-D. \end{DoxyReturn} \index{\-Getopt@{\-Getopt}!get\-Campaign\-Status\-:@{get\-Campaign\-Status\-:}} \index{get\-Campaign\-Status\-:@{get\-Campaign\-Status\-:}!Getopt@{\-Getopt}} \subsubsection[{get\-Campaign\-Status\-:}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-N\-S\-String $\ast$) get\-Campaign\-Status\-: \begin{DoxyParamCaption} \item[{dummy(\-N\-S\-String$\ast$)}]{campaign\-Id} \end{DoxyParamCaption} }\label{interface_getopt_ae462b8840809c38907beeb65600207c3} \-Gets a campaign status. \begin{DoxyParams}{\-Parameters} {\em campaign\-Id} & \-The campaign \-I\-D. \\ \hline \end{DoxyParams} \begin{DoxyReturn}{\-Returns} \-The campaign status of the specified campaign. \end{DoxyReturn} \index{\-Getopt@{\-Getopt}!get\-Campaign\-Status\-Code\-:@{get\-Campaign\-Status\-Code\-:}} \index{get\-Campaign\-Status\-Code\-:@{get\-Campaign\-Status\-Code\-:}!Getopt@{\-Getopt}} \subsubsection[{get\-Campaign\-Status\-Code\-:}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (int) get\-Campaign\-Status\-Code\-: \begin{DoxyParamCaption} \item[{dummy(\-N\-S\-String$\ast$)}]{campaign\-Id} \end{DoxyParamCaption} }\label{interface_getopt_a3c5d5461767b0b60b87640e9bed50fa0} \-Gets a campaign status code. \begin{DoxyParams}{\-Parameters} {\em campaign\-Id} & \-The campaign \-I\-D. \\ \hline \end{DoxyParams} \begin{DoxyReturn}{\-Returns} \-The campaign status code of the specified campaign. \end{DoxyReturn} \index{\-Getopt@{\-Getopt}!get\-Campaign\-Status\-Code\-List@{get\-Campaign\-Status\-Code\-List}} \index{get\-Campaign\-Status\-Code\-List@{get\-Campaign\-Status\-Code\-List}!Getopt@{\-Getopt}} \subsubsection[{get\-Campaign\-Status\-Code\-List}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-N\-S\-Mutable\-Array $\ast$) get\-Campaign\-Status\-Code\-List \begin{DoxyParamCaption} {} \end{DoxyParamCaption} }\label{interface_getopt_a9f7cb55ae8322091c2ed5d6b3778cf96} \-Gets the campaign status codes. \begin{DoxyReturn}{\-Returns} \-An \-N\-S\-Mutable\-Array that contains all the campaign status codes. \end{DoxyReturn} \index{\-Getopt@{\-Getopt}!get\-Campaign\-Status\-List@{get\-Campaign\-Status\-List}} \index{get\-Campaign\-Status\-List@{get\-Campaign\-Status\-List}!Getopt@{\-Getopt}} \subsubsection[{get\-Campaign\-Status\-List}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-N\-S\-Mutable\-Array $\ast$) get\-Campaign\-Status\-List \begin{DoxyParamCaption} {} \end{DoxyParamCaption} }\label{interface_getopt_ab734e471e2498b2e174e13888e1f47d1} \-Gets the campaign status. \begin{DoxyReturn}{\-Returns} \-An \-N\-S\-Mutable\-Array that contains all the campaigns status. \end{DoxyReturn} \index{\-Getopt@{\-Getopt}!get\-Message@{get\-Message}} \index{get\-Message@{get\-Message}!Getopt@{\-Getopt}} \subsubsection[{get\-Message}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-N\-S\-String $\ast$) get\-Message \begin{DoxyParamCaption} {} \end{DoxyParamCaption} }\label{interface_getopt_acd07f968bb1f707190fcbed50f4ffd5b} \begin{DoxyReturn}{\-Returns} \-The \-Message. \end{DoxyReturn} \index{\-Getopt@{\-Getopt}!get\-Response\-Code@{get\-Response\-Code}} \index{get\-Response\-Code@{get\-Response\-Code}!Getopt@{\-Getopt}} \subsubsection[{get\-Response\-Code}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (int) get\-Response\-Code \begin{DoxyParamCaption} {} \end{DoxyParamCaption} }\label{interface_getopt_a13d89e7b1be7fd70ca00d4dc8fd4bf76} \begin{DoxyReturn}{\-Returns} \-The response \-Code. \end{DoxyReturn} \index{\-Getopt@{\-Getopt}!get\-Response\-Status@{get\-Response\-Status}} \index{get\-Response\-Status@{get\-Response\-Status}!Getopt@{\-Getopt}} \subsubsection[{get\-Response\-Status}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-N\-S\-String $\ast$) get\-Response\-Status \begin{DoxyParamCaption} {} \end{DoxyParamCaption} }\label{interface_getopt_a37a6fb2220efa93c9dbe42888df9607b} \begin{DoxyReturn}{\-Returns} \-The response \-Status. \end{DoxyReturn} \index{\-Getopt@{\-Getopt}!init\-Getopt\-:@{init\-Getopt\-:}} \index{init\-Getopt\-:@{init\-Getopt\-:}!Getopt@{\-Getopt}} \subsubsection[{init\-Getopt\-:}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (void) init\-Getopt\-: \begin{DoxyParamCaption} \item[{dummy(\-N\-S\-String$\ast$)}]{url\-Getopt} \end{DoxyParamCaption} }\label{interface_getopt_a30a685ebe3d4b445be6a116147f0a524} \-Initializes a new \doxyref{\-Getopt}{p.}{interface_getopt} response object. \begin{DoxyParams}{\-Parameters} {\em url\-Getopt} & \-U\-R\-L for calling requests from \-Mogreet \-A\-P\-I. \\ \hline \end{DoxyParams} \index{\-Getopt@{\-Getopt}!response\-Is\-Valid@{response\-Is\-Valid}} \index{response\-Is\-Valid@{response\-Is\-Valid}!Getopt@{\-Getopt}} \subsubsection[{response\-Is\-Valid}]{\setlength{\rightskip}{0pt plus 5cm}-\/ (\-B\-O\-O\-L) response\-Is\-Valid \begin{DoxyParamCaption} {} \end{DoxyParamCaption} }\label{interface_getopt_a9ec6a1ac7941b10d44326c16d88e6332} \-Checks if the response code is 1. \begin{DoxyReturn}{\-Returns} \-Y\-E\-S if the response code is 1, \-N\-O if it is not \end{DoxyReturn} \-The documentation for this class was generated from the following files\-:\begin{DoxyCompactItemize} \item \-Mercury\-\_\-i\-O\-S/\-Classes/\-Getopt.\-h\item \-Mercury\-\_\-i\-O\-S/\-Classes/\-Getopt.\-m\end{DoxyCompactItemize}
mogreet/iosSDK
Doc/latex/interface_getopt.tex
TeX
gpl-3.0
9,044
#!/usr/bin/env python # # This file is protected by Copyright. Please refer to the COPYRIGHT file # distributed with this source distribution. # # This file is part of GNUHAWK. # # GNUHAWK is free software: you can redistribute it and/or modify is under the # terms of the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) any later # version. # # GNUHAWK is distributed in the hope that it will be useful, but WITHOUT ANY # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. See the GNU General Public License for more details. # You should have received a copy of the GNU General Public License along with # this program. If not, see http://www.gnu.org/licenses/. # import unittest import ossie.utils.testing import os from omniORB import any class ComponentTests(ossie.utils.testing.ScaComponentTestCase): """Test for all component implementations in sig_source_i""" def testScaBasicBehavior(self): ####################################################################### # Launch the component with the default execparams execparams = self.getPropertySet(kinds=("execparam",), modes=("readwrite", "writeonly"), includeNil=False) execparams = dict([(x.id, any.from_any(x.value)) for x in execparams]) self.launch(execparams) ####################################################################### # Verify the basic state of the component self.assertNotEqual(self.comp, None) self.assertEqual(self.comp.ref._non_existent(), False) self.assertEqual(self.comp.ref._is_a("IDL:CF/Resource:1.0"), True) self.assertEqual(self.spd.get_id(), self.comp.ref._get_identifier()) ####################################################################### # Simulate regular component startup # Verify that initialize nor configure throw errors self.comp.initialize() configureProps = self.getPropertySet(kinds=("configure",), modes=("readwrite", "writeonly"), includeNil=False) self.comp.configure(configureProps) ####################################################################### # Validate that query returns all expected parameters # Query of '[]' should return the following set of properties expectedProps = [] expectedProps.extend(self.getPropertySet(kinds=("configure", "execparam"), modes=("readwrite", "readonly"), includeNil=True)) expectedProps.extend(self.getPropertySet(kinds=("allocate",), action="external", includeNil=True)) props = self.comp.query([]) props = dict((x.id, any.from_any(x.value)) for x in props) # Query may return more than expected, but not less for expectedProp in expectedProps: self.assertEquals(props.has_key(expectedProp.id), True) ####################################################################### # Verify that all expected ports are available for port in self.scd.get_componentfeatures().get_ports().get_uses(): port_obj = self.comp.getPort(str(port.get_usesname())) self.assertNotEqual(port_obj, None) self.assertEqual(port_obj._non_existent(), False) self.assertEqual(port_obj._is_a("IDL:CF/Port:1.0"), True) for port in self.scd.get_componentfeatures().get_ports().get_provides(): port_obj = self.comp.getPort(str(port.get_providesname())) self.assertNotEqual(port_obj, None) self.assertEqual(port_obj._non_existent(), False) self.assertEqual(port_obj._is_a(port.get_repid()), True) ####################################################################### # Make sure start and stop can be called without throwing exceptions self.comp.start() self.comp.stop() ####################################################################### # Simulate regular component shutdown self.comp.releaseObject() # TODO Add additional tests here # # See: # ossie.utils.bulkio.bulkio_helpers, # ossie.utils.bluefile.bluefile_helpers # for modules that will assist with testing components with BULKIO ports if __name__ == "__main__": ossie.utils.testing.main("../sig_source_i.spd.xml") # By default tests all implementations
RedhawkSDR/integration-gnuhawk
components/sig_source_i/tests/test_sig_source_i.py
Python
gpl-3.0
4,531
/******************************************************************************** ** Form generated from reading UI file 'addECGDialog.ui' ** ** Created by: Qt User Interface Compiler version 5.7.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_ADDECGDIALOG_H #define UI_ADDECGDIALOG_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QCheckBox> #include <QtWidgets/QComboBox> #include <QtWidgets/QDialog> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> #include <QtWidgets/QPushButton> #include <QtWidgets/QSpacerItem> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_Dialog { public: QWidget *layoutWidget; QHBoxLayout *hboxLayout; QSpacerItem *horizontalSpacer_2; QPushButton *okButton; QSpacerItem *horizontalSpacer; QPushButton *cancelButton; QSpacerItem *horizontalSpacer_3; QLabel *headLabel; QLabel *nameLabel; QCheckBox *checkBox; QLabel *ECGlabel; QComboBox *ECGBox; QLineEdit *nameEdit; void setupUi(QDialog *Dialog) { if (Dialog->objectName().isEmpty()) Dialog->setObjectName(QStringLiteral("Dialog")); Dialog->resize(393, 233); layoutWidget = new QWidget(Dialog); layoutWidget->setObjectName(QStringLiteral("layoutWidget")); layoutWidget->setGeometry(QRect(20, 180, 351, 33)); hboxLayout = new QHBoxLayout(layoutWidget); hboxLayout->setSpacing(6); hboxLayout->setObjectName(QStringLiteral("hboxLayout")); hboxLayout->setContentsMargins(0, 0, 0, 0); horizontalSpacer_2 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); hboxLayout->addItem(horizontalSpacer_2); okButton = new QPushButton(layoutWidget); okButton->setObjectName(QStringLiteral("okButton")); hboxLayout->addWidget(okButton); horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); hboxLayout->addItem(horizontalSpacer); cancelButton = new QPushButton(layoutWidget); cancelButton->setObjectName(QStringLiteral("cancelButton")); hboxLayout->addWidget(cancelButton); horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); hboxLayout->addItem(horizontalSpacer_3); headLabel = new QLabel(Dialog); headLabel->setObjectName(QStringLiteral("headLabel")); headLabel->setGeometry(QRect(20, 20, 331, 16)); QFont font; font.setPointSize(10); font.setBold(true); font.setWeight(75); headLabel->setFont(font); nameLabel = new QLabel(Dialog); nameLabel->setObjectName(QStringLiteral("nameLabel")); nameLabel->setGeometry(QRect(20, 70, 47, 13)); QFont font1; font1.setBold(true); font1.setWeight(75); nameLabel->setFont(font1); checkBox = new QCheckBox(Dialog); checkBox->setObjectName(QStringLiteral("checkBox")); checkBox->setGeometry(QRect(20, 110, 231, 17)); checkBox->setFont(font1); ECGlabel = new QLabel(Dialog); ECGlabel->setObjectName(QStringLiteral("ECGlabel")); ECGlabel->setGeometry(QRect(20, 140, 81, 16)); ECGlabel->setFont(font1); ECGBox = new QComboBox(Dialog); ECGBox->setObjectName(QStringLiteral("ECGBox")); ECGBox->setGeometry(QRect(100, 140, 271, 22)); ECGBox->setInsertPolicy(QComboBox::InsertAlphabetically); nameEdit = new QLineEdit(Dialog); nameEdit->setObjectName(QStringLiteral("nameEdit")); nameEdit->setGeometry(QRect(100, 70, 271, 20)); headLabel->raise(); nameLabel->raise(); checkBox->raise(); ECGlabel->raise(); ECGBox->raise(); nameEdit->raise(); layoutWidget->raise(); retranslateUi(Dialog); QObject::connect(okButton, SIGNAL(clicked()), Dialog, SLOT(accept())); QObject::connect(cancelButton, SIGNAL(clicked()), Dialog, SLOT(reject())); QMetaObject::connectSlotsByName(Dialog); } // setupUi void retranslateUi(QDialog *Dialog) { Dialog->setWindowTitle(QApplication::translate("Dialog", "Add ECG Rhythm", 0)); okButton->setText(QApplication::translate("Dialog", "OK", 0)); cancelButton->setText(QApplication::translate("Dialog", "Cancel", 0)); headLabel->setText(QApplication::translate("Dialog", "Create a New ECG Rhythm", 0)); #ifndef QT_NO_TOOLTIP nameLabel->setToolTip(QApplication::translate("Dialog", "The Name of the new ECG Rhythm", 0)); #endif // QT_NO_TOOLTIP nameLabel->setText(QApplication::translate("Dialog", "Name", 0)); checkBox->setText(QApplication::translate("Dialog", "Copy parameters?", 0)); #ifndef QT_NO_TOOLTIP ECGlabel->setToolTip(QApplication::translate("Dialog", "The set of predeefined rhythms", 0)); #endif // QT_NO_TOOLTIP ECGlabel->setText(QApplication::translate("Dialog", "ECG Rythms", 0)); } // retranslateUi }; namespace Ui { class Dialog: public Ui_Dialog {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_ADDECGDIALOG_H
tushagarwal/SimECG
ui_addECGDialog.h
C
gpl-3.0
5,439
#include "trayicon.h" #include <QApplication> #include <QMenu> #include <QTimer> #include <conf/addressgroup.h> #include <conf/appgroup.h> #include <conf/confmanager.h> #include <conf/firewallconf.h> #include <form/controls/mainwindow.h> #include <fortsettings.h> #include <manager/hotkeymanager.h> #include <manager/windowmanager.h> #include <user/iniuser.h> #include <util/guiutil.h> #include <util/iconcache.h> #include "traycontroller.h" namespace { const char *const eventSingleClick = "singleClick"; const char *const eventDoubleClick = "doubleClick"; const char *const eventMiddleClick = "middleClick"; const char *const actionShowPrograms = "Programs"; const char *const actionShowOptions = "Options"; const char *const actionShowStatistics = "Statistics"; const char *const actionShowTrafficGraph = "TrafficGraph"; const char *const actionSwitchFilterEnabled = "FilterEnabled"; const char *const actionSwitchStopTraffic = "StopTraffic"; const char *const actionSwitchStopInetTraffic = "StopInetTraffic"; const char *const actionSwitchAutoAllowPrograms = "AutoAllowPrograms"; QString clickNameByType(TrayIcon::ClickType clickType) { switch (clickType) { case TrayIcon::SingleClick: return eventSingleClick; case TrayIcon::DoubleClick: return eventDoubleClick; case TrayIcon::MiddleClick: return eventMiddleClick; default: return QString(); } } QString actionNameByType(TrayIcon::ActionType actionType) { switch (actionType) { case TrayIcon::ActionShowPrograms: return actionShowPrograms; case TrayIcon::ActionShowOptions: return actionShowOptions; case TrayIcon::ActionShowStatistics: return actionShowStatistics; case TrayIcon::ActionShowTrafficGraph: return actionShowTrafficGraph; case TrayIcon::ActionSwitchFilterEnabled: return actionSwitchFilterEnabled; case TrayIcon::ActionSwitchStopTraffic: return actionSwitchStopTraffic; case TrayIcon::ActionSwitchStopInetTraffic: return actionSwitchStopInetTraffic; case TrayIcon::ActionSwitchAutoAllowPrograms: return actionSwitchAutoAllowPrograms; default: return QString(); } } TrayIcon::ActionType actionTypeByName(const QString &name) { if (name.isEmpty()) return TrayIcon::ActionNone; if (name == actionShowPrograms) return TrayIcon::ActionShowPrograms; if (name == actionShowOptions) return TrayIcon::ActionShowOptions; if (name == actionShowStatistics) return TrayIcon::ActionShowStatistics; if (name == actionShowTrafficGraph) return TrayIcon::ActionShowTrafficGraph; if (name == actionSwitchFilterEnabled) return TrayIcon::ActionSwitchFilterEnabled; if (name == actionSwitchStopTraffic) return TrayIcon::ActionSwitchStopTraffic; if (name == actionSwitchStopInetTraffic) return TrayIcon::ActionSwitchStopInetTraffic; if (name == actionSwitchAutoAllowPrograms) return TrayIcon::ActionSwitchAutoAllowPrograms; return TrayIcon::ActionNone; } TrayIcon::ActionType defaultActionTypeByClick(TrayIcon::ClickType clickType) { switch (clickType) { case TrayIcon::SingleClick: return TrayIcon::ActionShowPrograms; case TrayIcon::DoubleClick: return TrayIcon::ActionShowOptions; case TrayIcon::MiddleClick: return TrayIcon::ActionShowStatistics; default: return TrayIcon::ActionNone; } } void setActionCheckable(QAction *action, bool checked = false, const QObject *receiver = nullptr, const char *member = nullptr) { action->setCheckable(true); action->setChecked(checked); if (receiver) { QObject::connect(action, SIGNAL(toggled(bool)), receiver, member); } } QAction *addAction(QWidget *widget, const QIcon &icon, const QString &text, const QObject *receiver = nullptr, const char *member = nullptr, bool checkable = false, bool checked = false) { auto action = new QAction(icon, text, widget); if (receiver) { QObject::connect(action, SIGNAL(triggered(bool)), receiver, member); } if (checkable) { setActionCheckable(action, checked); } widget->addAction(action); return action; } } TrayIcon::TrayIcon(QObject *parent) : QSystemTrayIcon(parent), m_trayTriggered(false), m_ctrl(new TrayController(this)) { setupUi(); setupController(); connect(this, &QSystemTrayIcon::activated, this, &TrayIcon::onTrayActivated); } TrayIcon::~TrayIcon() { delete m_menu; } FortSettings *TrayIcon::settings() const { return ctrl()->settings(); } ConfManager *TrayIcon::confManager() const { return ctrl()->confManager(); } FirewallConf *TrayIcon::conf() const { return ctrl()->conf(); } IniOptions *TrayIcon::ini() const { return ctrl()->ini(); } IniUser *TrayIcon::iniUser() const { return ctrl()->iniUser(); } HotKeyManager *TrayIcon::hotKeyManager() const { return ctrl()->hotKeyManager(); } WindowManager *TrayIcon::windowManager() const { return ctrl()->windowManager(); } void TrayIcon::onMouseClicked(TrayIcon::ClickType clickType) { QAction *action = m_clickActions[clickType]; if (action) { action->trigger(); } } void TrayIcon::onTrayActivated(QSystemTrayIcon::ActivationReason reason) { switch (reason) { case QSystemTrayIcon::Trigger: m_trayTriggered = true; QTimer::singleShot(QApplication::doubleClickInterval(), this, [&] { if (m_trayTriggered) { m_trayTriggered = false; onMouseClicked(SingleClick); } }); break; case QSystemTrayIcon::DoubleClick: if (m_trayTriggered) { m_trayTriggered = false; onMouseClicked(DoubleClick); } break; case QSystemTrayIcon::MiddleClick: m_trayTriggered = false; onMouseClicked(MiddleClick); break; case QSystemTrayIcon::Context: m_trayTriggered = false; showTrayMenu(QCursor::pos()); break; default: break; } } void TrayIcon::updateTrayIcon(bool alerted) { const auto icon = alerted ? GuiUtil::overlayIcon(":/icons/sheild-96.png", ":/icons/error.png") : IconCache::icon(":/icons/sheild-96.png"); this->setIcon(icon); } void TrayIcon::showTrayMenu(const QPoint &pos) { m_menu->popup(pos); } void TrayIcon::updateTrayMenu(bool onlyFlags) { if (!onlyFlags) { updateAppGroupActions(); } updateTrayMenuFlags(); updateHotKeys(); } void TrayIcon::setupController() { connect(windowManager(), &WindowManager::optWindowChanged, this, &TrayIcon::updateTrayMenuFlags); connect(windowManager(), &WindowManager::graphWindowChanged, m_graphAction, &QAction::setChecked); connect(settings(), &FortSettings::passwordCheckedChanged, this, &TrayIcon::updateTrayMenuFlags); connect(ctrl(), &TrayController::retranslateUi, this, &TrayIcon::retranslateUi); retranslateUi(); } void TrayIcon::retranslateUi() { m_programsAction->setText(tr("Programs")); m_optionsAction->setText(tr("Options")); m_statisticsAction->setText(tr("Statistics")); m_zonesAction->setText(tr("Zones")); m_graphAction->setText(tr("Traffic Graph")); m_filterEnabledAction->setText(tr("Filter Enabled")); m_stopTrafficAction->setText(tr("Stop Traffic")); m_stopInetTrafficAction->setText(tr("Stop Internet Traffic")); m_autoAllowProgsAction->setText(tr("Auto-Allow New Programs")); m_quitAction->setText(tr("Quit")); } void TrayIcon::setupUi() { this->setToolTip(QApplication::applicationDisplayName()); setupTrayMenu(); updateTrayMenu(); updateTrayIcon(); updateClickActions(); } void TrayIcon::setupTrayMenu() { m_menu = new QMenu(); m_programsAction = addAction(m_menu, IconCache::icon(":/icons/application.png"), QString(), windowManager(), SLOT(showProgramsWindow())); addHotKey(m_programsAction, iniUser()->hotKeyPrograms()); m_optionsAction = addAction(m_menu, IconCache::icon(":/icons/cog.png"), QString(), windowManager(), SLOT(showOptionsWindow())); addHotKey(m_optionsAction, iniUser()->hotKeyOptions()); m_statisticsAction = addAction(m_menu, IconCache::icon(":/icons/chart_bar.png"), QString(), windowManager(), SLOT(showStatisticsWindow())); addHotKey(m_statisticsAction, iniUser()->hotKeyStatistics()); m_graphAction = addAction(m_menu, IconCache::icon(":/icons/action_log.png"), QString(), windowManager(), SLOT(switchGraphWindow()), true, !!windowManager()->graphWindow()); addHotKey(m_graphAction, iniUser()->hotKeyGraph()); m_zonesAction = addAction(m_menu, IconCache::icon(":/icons/ip_class.png"), QString(), windowManager(), SLOT(showZonesWindow())); addHotKey(m_zonesAction, iniUser()->hotKeyZones()); m_menu->addSeparator(); m_filterEnabledAction = addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true); addHotKey(m_filterEnabledAction, iniUser()->hotKeyFilter()); m_stopTrafficAction = addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true); addHotKey(m_stopTrafficAction, iniUser()->hotKeyStopTraffic()); m_stopInetTrafficAction = addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true); addHotKey(m_stopInetTrafficAction, iniUser()->hotKeyStopInetTraffic()); m_autoAllowProgsAction = addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true); addHotKey(m_autoAllowProgsAction, iniUser()->hotKeyAllowAllNew()); m_menu->addSeparator(); for (int i = 0; i < MAX_APP_GROUP_COUNT; ++i) { QAction *a = addAction(m_menu, QIcon(), QString(), this, SLOT(switchTrayFlag(bool)), true); if (i < 12) { const QString shortcutText = iniUser()->hotKeyAppGroupModifiers() + "+F" + QString::number(i + 1); addHotKey(a, shortcutText); } m_appGroupActions.append(a); } m_menu->addSeparator(); m_quitAction = addAction(m_menu, QIcon(), tr("Quit"), this, SLOT(quitProgram())); addHotKey(m_quitAction, iniUser()->hotKeyQuit()); } void TrayIcon::updateTrayMenuFlags() { const bool editEnabled = (!settings()->isPasswordRequired() && !windowManager()->optWindow()); m_filterEnabledAction->setEnabled(editEnabled); m_stopTrafficAction->setEnabled(editEnabled); m_stopInetTrafficAction->setEnabled(editEnabled); m_autoAllowProgsAction->setEnabled(editEnabled); m_filterEnabledAction->setChecked(conf()->filterEnabled()); m_stopTrafficAction->setChecked(conf()->stopTraffic()); m_stopInetTrafficAction->setChecked(conf()->stopInetTraffic()); m_autoAllowProgsAction->setChecked(conf()->allowAllNew()); int appGroupIndex = 0; for (QAction *action : qAsConst(m_appGroupActions)) { if (!action->isVisible()) break; const bool appGroupEnabled = conf()->appGroupEnabled(appGroupIndex++); action->setEnabled(editEnabled); action->setChecked(appGroupEnabled); } } void TrayIcon::updateAppGroupActions() { const int appGroupsCount = conf()->appGroups().count(); for (int i = 0; i < MAX_APP_GROUP_COUNT; ++i) { QAction *action = m_appGroupActions.at(i); QString menuLabel; bool visible = false; if (i < appGroupsCount) { const AppGroup *appGroup = conf()->appGroups().at(i); menuLabel = appGroup->menuLabel(); visible = true; } action->setText(menuLabel); action->setVisible(visible); action->setEnabled(visible); } } void TrayIcon::saveTrayFlags() { conf()->setFilterEnabled(m_filterEnabledAction->isChecked()); conf()->setStopTraffic(m_stopTrafficAction->isChecked()); conf()->setStopInetTraffic(m_stopInetTrafficAction->isChecked()); conf()->setAllowAllNew(m_autoAllowProgsAction->isChecked()); int i = 0; for (AppGroup *appGroup : conf()->appGroups()) { const QAction *action = m_appGroupActions.at(i++); appGroup->setEnabled(action->isChecked()); } confManager()->saveFlags(); } void TrayIcon::switchTrayFlag(bool checked) { if (iniUser()->confirmTrayFlags()) { const auto action = qobject_cast<QAction *>(sender()); Q_ASSERT(action); if (!windowManager()->showQuestionBox( tr("Are you sure to switch the \"%1\"?").arg(action->text()))) { action->setChecked(!checked); return; } } saveTrayFlags(); } void TrayIcon::quitProgram() { if (iniUser()->confirmQuit()) { if (!windowManager()->showQuestionBox(tr("Are you sure you want to quit the program?"))) return; } windowManager()->quitByCheckPassword(); } void TrayIcon::addHotKey(QAction *action, const QString &shortcutText) { if (shortcutText.isEmpty()) return; const QKeySequence shortcut = QKeySequence::fromString(shortcutText); hotKeyManager()->addAction(action, shortcut); } void TrayIcon::updateHotKeys() { hotKeyManager()->setEnabled(iniUser()->hotKeyEnabled()); } void TrayIcon::removeHotKeys() { hotKeyManager()->removeActions(); } TrayIcon::ActionType TrayIcon::clickEventActionType(ClickType clickType) const { const QString eventName = clickNameByType(clickType); const QString actionName = iniUser()->trayAction(eventName); const ActionType actionType = actionTypeByName(actionName); return (actionType != ActionNone) ? actionType : defaultActionTypeByClick(clickType); } void TrayIcon::setClickEventActionType(ClickType clickType, ActionType actionType) { const QString eventName = clickNameByType(clickType); const QString actionName = actionNameByType(actionType); iniUser()->setTrayAction(eventName, actionName); updateClickActions(); } void TrayIcon::updateClickActions() { m_clickActions[SingleClick] = clickActionFromIni(SingleClick); m_clickActions[DoubleClick] = clickActionFromIni(DoubleClick); m_clickActions[MiddleClick] = clickActionFromIni(MiddleClick); } QAction *TrayIcon::clickActionFromIni(ClickType clickType) const { const ActionType actionType = clickEventActionType(clickType); return clickActionByType(actionType); } QAction *TrayIcon::clickActionByType(ActionType actionType) const { switch (actionType) { case TrayIcon::ActionShowPrograms: return m_programsAction; case TrayIcon::ActionShowOptions: return m_optionsAction; case TrayIcon::ActionShowStatistics: return m_statisticsAction; case TrayIcon::ActionShowTrafficGraph: return m_graphAction; case TrayIcon::ActionSwitchFilterEnabled: return m_filterEnabledAction; case TrayIcon::ActionSwitchStopTraffic: return m_stopTrafficAction; case TrayIcon::ActionSwitchStopInetTraffic: return m_stopInetTrafficAction; case TrayIcon::ActionSwitchAutoAllowPrograms: return m_autoAllowProgsAction; } return nullptr; }
tnodir/fort
src/ui/form/tray/trayicon.cpp
C++
gpl-3.0
15,320
package at.ltd.tools.fw.peer2peerFirewall.backend.entities.comparator; @FunctionalInterface public interface ComparatorLambda<T> { int comp(T t1, T t2); }
a-frankdank/peer2peerFirewall
peer2peerFirewall-pom/peer2peerFirewall-backend-poc/src/main/java/at/ltd/tools/fw/peer2peerFirewall/backend/entities/comparator/ComparatorLambda.java
Java
gpl-3.0
163
// Obdi - a REST interface and GUI for deploying software // Copyright (C) 2014 Mark Clarkson // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package main import ( "encoding/json" "fmt" "net" "net/rpc" "os" ) type PostedData struct { Hostname string } // *************************************************************************** // GO RPC PLUGIN // *************************************************************************** func (t *Plugin) GetRequest(args *Args, response *[]byte) error { // List all keys if len(args.QueryString["env_id"]) == 0 { ReturnError("'env_id' must be set", response) return nil } sa := ScriptArgs{ ScriptName: "saltkey-showkeys.sh", CmdArgs: "", EnvVars: "", EnvCapDesc: "SALT_WORKER", Type: 2, } var jobid int64 var err error if jobid, err = t.RunScript(args, sa, response); err != nil { // RunScript wrote the error return nil } reply := Reply{jobid, "", SUCCESS, ""} jsondata, err := json.Marshal(reply) if err != nil { ReturnError("Marshal error: "+err.Error(), response) return nil } *response = jsondata return nil } func (t *Plugin) PostRequest(args *Args, response *[]byte) error { // Check for required query string entries if len(args.QueryString["hostname"]) == 0 { ReturnError("'type' must be set", response) return nil } if len(args.QueryString["type"]) == 0 { ReturnError("'type' must be set", response) return nil } if len(args.QueryString["env_id"]) == 0 { ReturnError("'env_id' must be set", response) return nil } // Get the ScriptId from the scripts table for: scriptName := "" if args.QueryString["type"][0] == "accept" { scriptName = "saltkey-acceptkeys.sh" } else { scriptName = "saltkey-rejectkeys.sh" } var jobid int64 sa := ScriptArgs{ ScriptName: scriptName, CmdArgs: args.QueryString["hostname"][0], EnvVars: "", EnvCapDesc: "SALT_WORKER", Type: 2, } var err error if jobid, err = t.RunScript(args, sa, response); err != nil { // RunScript wrote the error return nil } reply := Reply{jobid, "", SUCCESS, ""} jsondata, err := json.Marshal(reply) if err != nil { ReturnError("Marshal error: "+err.Error(), response) return nil } *response = jsondata return nil } func (t *Plugin) DeleteRequest(args *Args, response *[]byte) error { // Check for required query string entries if len(args.QueryString["env_id"]) == 0 { ReturnError("'env_id' must be set", response) return nil } var jobid int64 sa := ScriptArgs{ ScriptName: "saltkey-deletekeys.sh", CmdArgs: args.PathParams["id"], EnvVars: "", EnvCapDesc: "SALT_WORKER", Type: 2, } var err error if jobid, err = t.RunScript(args, sa, response); err != nil { // RunScript wrote the error return nil } reply := Reply{jobid, "", SUCCESS, ""} jsondata, err := json.Marshal(reply) if err != nil { ReturnError("Marshal error: "+err.Error(), response) return nil } *response = jsondata return nil } func (t *Plugin) HandleRequest(args *Args, response *[]byte) error { // All plugins must have this. if len(args.QueryType) > 0 { switch args.QueryType { case "GET": t.GetRequest(args, response) return nil case "POST": t.PostRequest(args, response) return nil case "DELETE": t.DeleteRequest(args, response) return nil } ReturnError("Internal error: Invalid HTTP request type for this plugin "+ args.QueryType, response) return nil } else { ReturnError("Internal error: HTTP request type was not set", response) return nil } } func main() { //logit("Plugin starting") plugin := new(Plugin) rpc.Register(plugin) listener, err := net.Listen("tcp", ":"+os.Args[1]) if err != nil { txt := fmt.Sprintf("Listen error. ", err) logit(txt) } //logit("Plugin listening on port " + os.Args[1]) if conn, err := listener.Accept(); err != nil { txt := fmt.Sprintf("Accept error. ", err) logit(txt) } else { //logit("New connection established") rpc.ServeConn(conn) } }
mclarkson/obdi-saltkeymanager
go/saltkeys.go
GO
gpl-3.0
4,629
package com.shumz.think.ex004; public class ExFour03 { public ExFour03() { System.out.println("An instance of ExFour03 was created..."); } public static void main(String[] args) { new ExFour03(); } }
Izek/think_in_java_4
MeCodez/src/com/shumz/think/ex004/ExFour03.java
Java
gpl-3.0
210
/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo * This benchmark is part of SWSC */ #include <assert.h> #include <stdint.h> #include <stdatomic.h> #include <pthread.h> atomic_int vars[5]; atomic_int atom_1_r1_1; void *t0(void *arg){ label_1:; atomic_store_explicit(&vars[0], 2, memory_order_seq_cst); atomic_store_explicit(&vars[1], 1, memory_order_seq_cst); return NULL; } void *t1(void *arg){ label_2:; int v2_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst); int v3_r3 = v2_r1 ^ v2_r1; int v6_r4 = atomic_load_explicit(&vars[2+v3_r3], memory_order_seq_cst); int v7_r6 = v6_r4 ^ v6_r4; atomic_store_explicit(&vars[3+v7_r6], 1, memory_order_seq_cst); int v9_r9 = atomic_load_explicit(&vars[3], memory_order_seq_cst); int v10_r10 = v9_r9 ^ v9_r9; atomic_store_explicit(&vars[4+v10_r10], 1, memory_order_seq_cst); int v12_r13 = atomic_load_explicit(&vars[4], memory_order_seq_cst); int v13_cmpeq = (v12_r13 == v12_r13); if (v13_cmpeq) goto lbl_LC00; else goto lbl_LC00; lbl_LC00:; atomic_store_explicit(&vars[0], 1, memory_order_seq_cst); int v18 = (v2_r1 == 1); atomic_store_explicit(&atom_1_r1_1, v18, memory_order_seq_cst); return NULL; } int main(int argc, char *argv[]){ pthread_t thr0; pthread_t thr1; atomic_init(&vars[3], 0); atomic_init(&vars[1], 0); atomic_init(&vars[0], 0); atomic_init(&vars[2], 0); atomic_init(&vars[4], 0); atomic_init(&atom_1_r1_1, 0); pthread_create(&thr0, NULL, t0, NULL); pthread_create(&thr1, NULL, t1, NULL); pthread_join(thr0, NULL); pthread_join(thr1, NULL); int v14 = atomic_load_explicit(&vars[0], memory_order_seq_cst); int v15 = (v14 == 2); int v16 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); int v17_conj = v15 & v16; if (v17_conj == 1) assert(0); return 0; }
nidhugg/nidhugg
tests/litmus/C-tests/S+PPO645.c
C
gpl-3.0
1,822
package TFC.Handlers.Client; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.renderer.Tessellator; import net.minecraft.entity.player.EntityPlayer; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType; import net.minecraftforge.event.ForgeSubscribe; import org.lwjgl.opengl.GL11; import TFC.Core.TFC_Climate; import TFC.Core.TFC_Settings; import TFC.Core.Player.PlayerManagerTFC; import TFC.Core.Player.TFC_PlayerClient; import TFC.Food.FoodStatsTFC; import TFC.Items.Tools.ItemChisel; import TFC.Items.Tools.ItemCustomHoe; public class RenderOverlayHandler { @ForgeSubscribe public void render(RenderGameOverlayEvent.Pre event) { if(event.type == ElementType.HEALTH || event.type == ElementType.FOOD) { event.setCanceled(true); } } @ForgeSubscribe public void render(RenderGameOverlayEvent.Post event) { if(event.type == ElementType.HEALTH || event.type == ElementType.FOOD) { event.setCanceled(true); } ScaledResolution sr = event.resolution; int healthRowHeight = sr.getScaledHeight() - 39; int armorRowHeight = healthRowHeight - 10; TFC_PlayerClient playerclient = ((TFC.Core.Player.TFC_PlayerClient)Minecraft.getMinecraft().thePlayer.getPlayerBase("TFC Player Client")); if(playerclient != null) { //Draw Health GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); //GL11.glBindTexture(GL11.GL_TEXTURE_2D, Minecraft.getMinecraft().renderEngine.getTexture("/bioxx/icons.png")); Minecraft.getMinecraft().renderEngine.bindTexture("/bioxx/icons.png"); this.drawTexturedModalRect(sr.getScaledWidth() / 2-91, healthRowHeight, 0, 0, 90, 10); float maxHealth = playerclient.getMaxHealth(); float percentHealth = Minecraft.getMinecraft().thePlayer.getHealth()/maxHealth; this.drawTexturedModalRect(sr.getScaledWidth() / 2-91, healthRowHeight, 0, 9, (int) (90*percentHealth), 9); //Draw Food and Water FoodStatsTFC foodstats = playerclient.getFoodStatsTFC(); int foodLevel = foodstats.getFoodLevel(); int preFoodLevel = foodstats.getPrevFoodLevel(); float waterLevel = foodstats.waterLevel; float percentFood = foodLevel/100f; float percentWater = waterLevel/foodstats.getMaxWater(Minecraft.getMinecraft().thePlayer); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); //GL11.glBindTexture(GL11.GL_TEXTURE_2D, Minecraft.getMinecraft().renderEngine.getTexture("/bioxx/icons.png")); this.drawTexturedModalRect(sr.getScaledWidth() / 2, healthRowHeight, 0, 18, 90, 5); if(playerclient.guishowFoodRestoreAmount) { float percentFood2 = Math.min(percentFood + playerclient.guiFoodRestoreAmount/100f, 1); GL11.glColor4f(0.0F, 0.6F, 0.0F, 0.3F); //GL11.glBindTexture(GL11.GL_TEXTURE_2D, Minecraft.getMinecraft().renderEngine.getTexture("/bioxx/icons.png")); this.drawTexturedModalRect(sr.getScaledWidth() / 2, healthRowHeight, 0, 23, (int) (90*(percentFood2)), 5); } GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); //GL11.glBindTexture(GL11.GL_TEXTURE_2D, Minecraft.getMinecraft().renderEngine.getTexture("/bioxx/icons.png")); this.drawTexturedModalRect(sr.getScaledWidth() / 2, healthRowHeight, 0, 23, (int) (90*percentFood), 5); this.drawTexturedModalRect(sr.getScaledWidth() / 2, healthRowHeight+5, 0, 28, 90, 5); this.drawTexturedModalRect(sr.getScaledWidth() / 2, healthRowHeight+5, 0, 33, (int) (90*percentWater), 5); //Render Tool Mode if(Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem() != null && Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem().getItem() instanceof ItemCustomHoe) { int mode = PlayerManagerTFC.getInstance().getClientPlayer().hoeMode; this.drawTexturedModalRect(sr.getScaledWidth() / 2 + 95, sr.getScaledHeight() - 21, 0+(20*mode), 38, 20, 20); } else if(Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem() != null && Minecraft.getMinecraft().thePlayer.inventory.getCurrentItem().getItem() instanceof ItemChisel) { int mode = PlayerManagerTFC.getInstance().getClientPlayer().ChiselMode; this.drawTexturedModalRect(sr.getScaledWidth() / 2 + 95, sr.getScaledHeight() - 21, 0+(20*mode), 58, 20, 20); } } Minecraft.getMinecraft().renderEngine.resetBoundTexture(); } @ForgeSubscribe public void renderText(RenderGameOverlayEvent.Text event) { if(Minecraft.getMinecraft().gameSettings.showDebugInfo || TFC_Settings.enableDebugMode) { EntityPlayer player = Minecraft.getMinecraft().thePlayer; int xCoord = (int)player.posX; int yCoord = (int)player.posY; int zCoord = (int)player.posZ; event.left.add(String.format("rain: %.0f, temp: %.2f, evt: %.3f", new Object[] { TFC_Climate.getRainfall(xCoord, yCoord, zCoord), TFC_Climate.getHeightAdjustedTemp(xCoord, yCoord, zCoord), TFC_Climate.manager.getEVTLayerAt(xCoord, zCoord).floatdata1})); event.left.add("Health: " + player.getHealth()); } } public void drawTexturedModalRect(int par1, int par2, int par3, int par4, int par5, int par6) { float f = 0.00390625F; float f1 = 0.00390625F; Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); tessellator.addVertexWithUV(par1 + 0, par2 + par6, 0.0, (par3 + 0) * f, (par4 + par6) * f1); tessellator.addVertexWithUV(par1 + par5, par2 + par6, 0.0, (par3 + par5) * f, (par4 + par6) * f1); tessellator.addVertexWithUV(par1 + par5, par2 + 0, 0.0, (par3 + par5) * f, (par4 + 0) * f1); tessellator.addVertexWithUV(par1 + 0, par2 + 0, 0.0, (par3 + 0) * f, (par4 + 0) * f1); tessellator.draw(); } }
Timeslice42/TFCraft
TFC_Shared/src/TFC/Handlers/Client/RenderOverlayHandler.java
Java
gpl-3.0
5,784
namespace ContaLibre.Areas.HelpPage.ModelDescriptions { public class EnumValueDescription { public string Documentation { get; set; } public string Name { get; set; } public string Value { get; set; } } }
seranfuen/contalibre
ContaLibre/Areas/HelpPage/ModelDescriptions/EnumValueDescription.cs
C#
gpl-3.0
242
var path = require('path') module.exports = { // Webpack aliases aliases: { quasar: path.resolve(__dirname, '../node_modules/quasar-framework/'), src: path.resolve(__dirname, '../src'), assets: path.resolve(__dirname, '../src/assets'), components: path.resolve(__dirname, '../src/components') }, // Progress Bar Webpack plugin format // https://github.com/clessg/progress-bar-webpack-plugin#options progressFormat: ' [:bar] ' + ':percent'.bold + ' (:msg)', // Default theme to build with ('ios' or 'mat') defaultTheme: 'mat', build: { env: require('./prod.env'), index: path.resolve(__dirname, '../dist/index.html'), publicPath: '', productionSourceMap: false, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'] }, dev: { env: require('./dev.env'), cssSourceMap: true, // auto open browser or not openBrowser: true, publicPath: '/', port: 8081, // If for example you are using Quasar Play // to generate a QR code then on each dev (re)compilation // you need to avoid clearing out the console, so set this // to "false", otherwise you can set it to "true" to always // have only the messages regarding your last (re)compilation. clearConsoleOnRebuild: false, // Proxy your API if using any. // Also see /build/script.dev.js and search for "proxy api requests" // https://github.com/chimurai/http-proxy-middleware proxyTable: {} } } /* * proxyTable example: * proxyTable: { // proxy all requests starting with /api '/api': { target: 'https://some.address.com/api', changeOrigin: true, pathRewrite: { '^/api': '' } } } */
agustincl/AclBoilerplate
config/index.js
JavaScript
gpl-3.0
1,969
// // This file is part of the aMule Project. // // Copyright (c) 2003-2011 aMule Team ( [email protected] / http://www.amule.org ) // Copyright (c) 2002-2011 Merkur ( [email protected] / http://www.emule-project.net ) // // Any parts of this program derived from the xMule, lMule or eMule project, // or contributed by third-party developers are copyrighted by their // respective authors. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA // #include <wx/wx.h> #include <wx/mstream.h> #include <wx/tokenzr.h> #include "updownclient.h" // Needed for CUpDownClient #include "SharedFileList.h" // Needed for CSharedFileList #include <protocol/Protocols.h> #include <protocol/ed2k/Client2Client/TCP.h> #include <protocol/ed2k/ClientSoftware.h> #include <protocol/kad/Client2Client/UDP.h> #include <protocol/kad2/Constants.h> #include <protocol/kad2/Client2Client/TCP.h> #include <protocol/kad2/Client2Client/UDP.h> #include <common/ClientVersion.h> #include <tags/ClientTags.h> #include <zlib.h> // Needed for inflateEnd #include <common/Format.h> // Needed for CFormat #include "SearchList.h" // Needed for CSearchList #include "DownloadQueue.h" // Needed for CDownloadQueue #include "UploadQueue.h" // Needed for CUploadQueue #include "IPFilter.h" // Needed for CIPFilter #include "ServerConnect.h" // Needed for CServerConnect #include "ClientCredits.h" // Needed for CClientCredits #include "ClientCreditsList.h" // Needed for CClientCreditsList #include "Server.h" // Needed for CServer #include "Preferences.h" // Needed for CPreferences #include "MemFile.h" // Needed for CMemFile #include "Packet.h" // Needed for CPacket #include "Friend.h" // Needed for CFriend #include "ClientList.h" // Needed for CClientList #ifndef AMULE_DAEMON #include "amuleDlg.h" // Needed for CamuleDlg #include "CaptchaDialog.h" // Needed for CCaptchaDialog #include "CaptchaGenerator.h" #include "ChatWnd.h" // Needed for CChatWnd #endif #include "amule.h" // Needed for theApp #include "PartFile.h" // Needed for CPartFile #include "ClientTCPSocket.h" // Needed for CClientTCPSocket #include "ListenSocket.h" // Needed for CListenSocket #include "FriendList.h" // Needed for CFriendList #include "Statistics.h" // Needed for theStats #include "ClientUDPSocket.h" #include "Logger.h" #include "DataToText.h" // Needed for GetSoftName() #include "GuiEvents.h" // Needed for Notify_ #include "ServerList.h" // For CServerList #include "kademlia/kademlia/Kademlia.h" #include "kademlia/kademlia/Prefs.h" #include "kademlia/kademlia/Search.h" #include "kademlia/kademlia/UDPFirewallTester.h" #include "kademlia/routing/RoutingZone.h" //#define __PACKET_DEBUG__ // some client testing variables static wxString crash_name = wxT("[Invalid User Name]"); static wxString empty_name = wxT("[Empty User Name]"); // members of CUpDownClient // which are used by down and uploading functions CUpDownClient::CUpDownClient(CClientTCPSocket* sender) { #ifdef __DEBUG__ m_socket = NULL; SetSocket(sender); #else m_socket = sender; #endif Init(); } CUpDownClient::CUpDownClient(uint16 in_port, uint32 in_userid, uint32 in_serverip, uint16 in_serverport, CPartFile* in_reqfile, bool ed2kID, bool checkfriend) { m_socket = NULL; Init(); m_nUserPort = in_port; if(ed2kID && !IsLowID(in_userid)) { SetUserIDHybrid( wxUINT32_SWAP_ALWAYS(in_userid) ); } else { SetUserIDHybrid( in_userid); } //If highID and ED2K source, incoming ID and IP are equal.. //If highID and Kad source, incoming IP needs swap for the IP if (!HasLowID()) { if (ed2kID) { m_nConnectIP = in_userid; } else { m_nConnectIP = wxUINT32_SWAP_ALWAYS(in_userid); } // Will be on right endianess now m_FullUserIP = m_nConnectIP; } m_dwServerIP = in_serverip; m_nServerPort = in_serverport; SetRequestFile( in_reqfile ); ReGetClientSoft(); if (checkfriend) { if ((m_Friend = theApp->friendlist->FindFriend(CMD4Hash(), m_dwUserIP, m_nUserPort)) != NULL){ m_Friend->LinkClient(CCLIENTREF(this, wxT("CUpDownClient::CUpDownClient m_Friend->LinkClient"))); } else{ // avoid that an unwanted client instance keeps a friend slot m_bFriendSlot = false; } } } void CUpDownClient::Init() { m_linked = 0; #ifdef DEBUG_ZOMBIE_CLIENTS m_linkedDebug = false; #endif m_bAddNextConnect = false; credits = NULL; m_byChatstate = MS_NONE; m_nKadState = KS_NONE; m_nChatCaptchaState = CA_NONE; m_cShowDR = 0; m_reqfile = NULL; // No file required yet m_nTransferredUp = 0; m_cSendblock = 0; m_cAsked = 0; msReceivedPrev = 0; kBpsDown = 0.0; bytesReceivedCycle = 0; m_nServerPort = 0; m_iFileListRequested = 0; m_dwLastUpRequest = 0; m_bEmuleProtocol = false; m_bCompleteSource = false; m_bFriendSlot = false; m_bCommentDirty = false; m_bReaskPending = false; m_bUDPPending = false; m_nUserPort = 0; m_nPartCount = 0; m_dwLastAskedTime = 0; m_nDownloadState = DS_NONE; m_dwUploadTime = 0; m_nTransferredDown = 0; m_nUploadState = US_NONE; m_dwLastBlockReceived = 0; m_bUnicodeSupport = false; m_fSentOutOfPartReqs = 0; m_nCurQueueSessionPayloadUp = 0; m_addedPayloadQueueSession = 0; m_nUpDatarate = 0; m_nSumForAvgUpDataRate = 0; m_nRemoteQueueRank = 0; m_nOldRemoteQueueRank = 0; m_dwLastSourceRequest = 0; m_dwLastSourceAnswer = 0; m_dwLastAskedForSources = 0; m_SecureIdentState = IS_UNAVAILABLE; m_dwLastSignatureIP = 0; m_byInfopacketsReceived = IP_NONE; m_bIsHybrid = false; m_bIsML = false; m_Friend = NULL; m_iRating = 0; m_nCurSessionUp = 0; m_clientSoft=SO_UNKNOWN; m_bRemoteQueueFull = false; m_HasValidHash = false; SetWaitStartTime(); m_fHashsetRequesting = 0; m_fSharedDirectories = 0; m_lastPartAsked = 0xffff; m_nUpCompleteSourcesCount= 0; m_waitingPosition = 0; m_score = 0; m_lastRefreshedDLDisplay = 0; m_bHelloAnswerPending = false; m_fSentCancelTransfer = 0; m_Aggressiveness = 0; m_LastFileRequest = 0; m_clientState = CS_NEW; ClearHelloProperties(); m_pReqFileAICHHash = NULL; m_fSupportsAICH = 0; m_fAICHRequested = 0; m_fSupportsLargeFiles = 0; m_fExtMultiPacket = 0; m_fIsSpammer = 0; m_dwUserIP = 0; m_nConnectIP = 0; m_dwServerIP = 0; m_fNeedOurPublicIP = false; m_bHashsetRequested = false; m_lastDownloadingPart = 0; m_uploadingfile = NULL; m_OSInfo_sent = false; /* Kad stuff */ SetBuddyID(NULL); m_nBuddyIP = 0; m_nBuddyPort = 0; m_nUserIDHybrid = 0; m_nSourceFrom = SF_NONE; if (m_socket) { SetIP(m_socket->GetPeerInt()); } else { SetIP(0); } /* Statistics */ m_lastClientSoft = (uint32)(-1); m_lastClientVersion = 0; /* Creation time (for buddies timeout) */ m_nCreationTime = ::GetTickCount(); m_MaxBlockRequests = STANDARD_BLOCKS_REQUEST; // Safe starting amount m_last_block_start = 0; m_lastaverage = 0; SetLastBuddyPingPongTime(); m_fRequestsCryptLayer = 0; m_fSupportsCryptLayer = 0; m_fRequiresCryptLayer = 0; m_fSupportsSourceEx2 = 0; m_fSupportsCaptcha = 0; m_fDirectUDPCallback = 0; m_dwDirectCallbackTimeout = 0; m_hasbeenobfuscatinglately = false; m_cCaptchasSent = 0; m_cMessagesReceived = 0; m_cMessagesSent = 0; } CUpDownClient::~CUpDownClient() { #ifdef __DEBUG__ if (!connection_reason.IsEmpty()) { AddDebugLogLineN(logClient, wxT("Client to check for ") + connection_reason + wxT(" was deleted without connection.")); } #endif if (m_lastClientSoft == SO_UNKNOWN) { theStats::RemoveUnknownClient(); } else if (m_lastClientSoft != (uint32)(-1)) { theStats::RemoveKnownClient(m_lastClientSoft, m_lastClientVersion, m_lastOSInfo); } // Indicate that we are not anymore on stats m_lastClientSoft = (uint32)(-1); // The socket should have been removed in Safe_Delete, but it // doesn't hurt to have an extra check. if (m_socket) { m_socket->Safe_Delete(); // Paranoia SetSocket(NULL); } ClearUploadBlockRequests(); ClearDownloadBlockRequests(); DeleteContents(m_WaitingPackets_list); // Allow detection of deleted clients that didn't go through Safe_Delete m_clientState = CS_DYING; } void CUpDownClient::ClearHelloProperties() { m_nUDPPort = 0; m_byUDPVer = 0; m_byDataCompVer = 0; m_byEmuleVersion = 0; m_bySourceExchange1Ver = 0; m_byAcceptCommentVer = 0; m_byExtendedRequestsVer = 0; m_byCompatibleClient = 0; m_nKadPort = 0; m_bySupportSecIdent = 0; m_bSupportsPreview = 0; m_nClientVersion = 0; m_fSharedDirectories = 0; m_bMultiPacket = 0; m_fOsInfoSupport = 0; m_fValueBasedTypeTags = 0; SecIdentSupRec = 0; m_byKadVersion = 0; m_fRequestsCryptLayer = 0; m_fSupportsCryptLayer = 0; m_fRequiresCryptLayer = 0; m_fSupportsSourceEx2 = 0; m_fSupportsCaptcha = 0; m_fDirectUDPCallback = 0; m_bIsHybrid = false; m_bIsML = false; m_fNoViewSharedFiles = true; // that's a sensible default to assume until we get the real value m_bUnicodeSupport = false; } bool CUpDownClient::ProcessHelloPacket(const byte* pachPacket, uint32 nSize) { const CMemFile data(pachPacket,nSize); uint8 hashsize = data.ReadUInt8(); if ( 16 != hashsize ) { /* * Hint: We can not accept other sizes here because: * - the magic number is spread all over the source * - the answer packet lacks the size field */ throw wxString(wxT("Invalid Hello packet: Other userhash sizes than 16 are not implemented")); } // eMule 0.42: reset all client properties; a client may not send a particular emule tag any longer ClearHelloProperties(); return ProcessHelloTypePacket(data); } void CUpDownClient::Safe_Delete() { // Because we are delaying the deletion, we might end up trying to delete // it twice, however, this is normal and shouldn't trigger any failures if ( m_clientState == CS_DYING ) { return; } // If called from background, post an event to process it in main thread if (!wxThread::IsMain()) { CoreNotify_Client_Delete(CCLIENTREF(this, wxT("CUpDownClient::Safe_Delete CoreNotify_Client_Delete"))); return; } m_clientState = CS_DYING; // Make sure client doesn't get deleted until this method is finished CClientRef ref(CCLIENTREF(this, wxT("CUpDownClient::Safe_Delete reflocker"))); // Close the socket to avoid any more connections and related events if ( m_socket ) { m_socket->Safe_Delete(); // Paranoia SetSocket(NULL); } // Remove the client from the clientlist if we still have it if ( theApp->clientlist ) { theApp->clientlist->RemoveClient( this ); } // Doing what RemoveClient used to do. Just to be sure... if (theApp->uploadqueue) { theApp->uploadqueue->RemoveFromUploadQueue(this); theApp->uploadqueue->RemoveFromWaitingQueue(this); } if (theApp->downloadqueue) { theApp->downloadqueue->RemoveSource(this); } // For security, remove it from the lists unconditionally. Notify_SharedCtrlRemoveClient(ECID(), (CKnownFile*)NULL); Notify_SourceCtrlRemoveSource(ECID(), (CPartFile*)NULL); if (IsAICHReqPending()){ m_fAICHRequested = FALSE; CAICHHashSet::ClientAICHRequestFailed(this); } if (m_Friend) { m_Friend->UnLinkClient(); // this notifies m_Friend = NULL; } if (m_iRating>0 || !m_strComment.IsEmpty()) { m_iRating = 0; m_strComment.Clear(); if (m_reqfile) { m_reqfile->UpdateFileRatingCommentAvail(); } } // Ensure that source-counts gets updated in case // of a source not on the download-queue SetRequestFile( NULL ); SetUploadFileID(NULL); delete m_pReqFileAICHHash; m_pReqFileAICHHash = NULL; #ifdef DEBUG_ZOMBIE_CLIENTS if (m_linked > 1) { AddLogLineC(CFormat(wxT("Client %d still linked in %d places: %s")) % ECID() % (m_linked - 1) % GetLinkedFrom()); m_linkedDebug = true; } #endif } bool CUpDownClient::ProcessHelloAnswer(const byte* pachPacket, uint32 nSize) { const CMemFile data(pachPacket,nSize); bool bIsMule = ProcessHelloTypePacket(data); m_bHelloAnswerPending = false; return bIsMule; } bool CUpDownClient::ProcessHelloTypePacket(const CMemFile& data) { uint32 dwEmuleTags = 0; CMD4Hash hash = data.ReadHash(); SetUserHash( hash ); SetUserIDHybrid( data.ReadUInt32() ); uint16 nUserPort = data.ReadUInt16(); // hmm clientport is sent twice - why? uint32 tagcount = data.ReadUInt32(); for (uint32 i = 0;i < tagcount; i++){ CTag temptag(data, true); switch(temptag.GetNameID()){ case CT_NAME: m_Username = temptag.GetStr(); break; case CT_VERSION: m_nClientVersion = temptag.GetInt(); break; case ET_MOD_VERSION: if (temptag.IsStr()) { m_strModVersion = temptag.GetStr(); } else if (temptag.IsInt()) { m_strModVersion = CFormat(wxT("ModID=%u")) % temptag.GetInt(); } else { m_strModVersion = wxT("ModID=<Unknown>"); } break; case CT_PORT: nUserPort = temptag.GetInt(); break; case CT_EMULE_UDPPORTS: // 16 KAD Port // 16 UDP Port SetKadPort((temptag.GetInt() >> 16) & 0xFFFF); m_nUDPPort = temptag.GetInt() & 0xFFFF; dwEmuleTags |= 1; #ifdef __PACKET_DEBUG__ AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule ports UDP=%i KAD=%i")) % m_nUDPPort % m_nKadPort); #endif break; case CT_EMULE_BUDDYIP: // 32 BUDDY IP m_nBuddyIP = temptag.GetInt(); #ifdef __PACKET_DEBUG__ AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule BuddyIP=%u (%s)")) % m_nBuddyIP % Uint32toStringIP(m_nBuddyIP)); #endif break; case CT_EMULE_BUDDYUDP: // 16 --Reserved for future use-- // 16 BUDDY Port m_nBuddyPort = (uint16)temptag.GetInt(); #ifdef __PACKET_DEBUG__ AddLogLineNS(CFormat(wxT("Hello type packet processing with eMule BuddyPort=%u")) % m_nBuddyPort); #endif break; case CT_EMULE_MISCOPTIONS1: { // 3 AICH Version (0 = not supported) // 1 Unicode // 4 UDP version // 4 Data compression version // 4 Secure Ident // 4 Source Exchange // 4 Ext. Requests // 4 Comments // 1 PeerCache supported // 1 No 'View Shared Files' supported // 1 MultiPacket // 1 Preview uint32 flags = temptag.GetInt(); m_fSupportsAICH = (flags >> (4*7+1)) & 0x07; m_bUnicodeSupport = (flags >> 4*7) & 0x01; m_byUDPVer = (flags >> 4*6) & 0x0f; m_byDataCompVer = (flags >> 4*5) & 0x0f; m_bySupportSecIdent = (flags >> 4*4) & 0x0f; m_bySourceExchange1Ver = (flags >> 4*3) & 0x0f; m_byExtendedRequestsVer = (flags >> 4*2) & 0x0f; m_byAcceptCommentVer = (flags >> 4*1) & 0x0f; m_fNoViewSharedFiles = (flags >> 1*2) & 0x01; m_bMultiPacket = (flags >> 1*1) & 0x01; m_fSupportsPreview = (flags >> 1*0) & 0x01; dwEmuleTags |= 2; #ifdef __PACKET_DEBUG__ AddLogLineNS(wxT("Hello type packet processing with eMule Misc Options:")); AddLogLineNS(CFormat(wxT("m_byUDPVer = %i")) % m_byUDPVer); AddLogLineNS(CFormat(wxT("m_byDataCompVer = %i")) % m_byDataCompVer); AddLogLineNS(CFormat(wxT("m_bySupportSecIdent = %i")) % m_bySupportSecIdent); AddLogLineNS(CFormat(wxT("m_bySourceExchangeVer = %i")) % m_bySourceExchange1Ver); AddLogLineNS(CFormat(wxT("m_byExtendedRequestsVer = %i")) % m_byExtendedRequestsVer); AddLogLineNS(CFormat(wxT("m_byAcceptCommentVer = %i")) % m_byAcceptCommentVer); AddLogLineNS(CFormat(wxT("m_fNoViewSharedFiles = %i")) % m_fNoViewSharedFiles); AddLogLineNS(CFormat(wxT("m_bMultiPacket = %i")) % m_bMultiPacket); AddLogLineNS(CFormat(wxT("m_fSupportsPreview = %i")) % m_fSharedDirectories); AddLogLineNS(wxT("That's all.")); #endif SecIdentSupRec += 1; break; } case CT_EMULE_MISCOPTIONS2: // 19 Reserved // 1 Direct UDP Callback supported and available // 1 Supports ChatCaptchas // 1 Supports SourceExachnge2 Packets, ignores SX1 Packet Version // 1 Requires CryptLayer // 1 Requests CryptLayer // 1 Supports CryptLayer // 1 Reserved (ModBit) // 1 Ext Multipacket (Hash+Size instead of Hash) // 1 Large Files (includes support for 64bit tags) // 4 Kad Version - will go up to version 15 only (may need to add another field at some point in the future) m_fDirectUDPCallback = (temptag.GetInt() >> 12) & 0x01; m_fSupportsCaptcha = (temptag.GetInt() >> 11) & 0x01; m_fSupportsSourceEx2 = (temptag.GetInt() >> 10) & 0x01; m_fRequiresCryptLayer = (temptag.GetInt() >> 9) & 0x01; m_fRequestsCryptLayer = (temptag.GetInt() >> 8) & 0x01; m_fSupportsCryptLayer = (temptag.GetInt() >> 7) & 0x01; // reserved 1 m_fExtMultiPacket = (temptag.GetInt() >> 5) & 0x01; m_fSupportsLargeFiles = (temptag.GetInt() >> 4) & 0x01; m_byKadVersion = (temptag.GetInt() >> 0) & 0x0f; dwEmuleTags |= 8; m_fRequestsCryptLayer &= m_fSupportsCryptLayer; m_fRequiresCryptLayer &= m_fRequestsCryptLayer; #ifdef __PACKET_DEBUG__ AddLogLineNS(wxT("Hello type packet processing with eMule Misc Options 2:")); AddLogLineNS(CFormat(wxT(" m_fDirectUDPCallback = %i")) % m_fDirectUDPCallback); AddLogLineNS(CFormat(wxT(" m_fSupportsCaptcha = %i")) % m_fSupportsCaptcha); AddLogLineNS(CFormat(wxT(" m_fSupportsSourceEx2 = %i")) % m_fSupportsSourceEx2); AddLogLineNS(CFormat(wxT(" m_fRequiresCryptLayer = %i")) % m_fRequiresCryptLayer); AddLogLineNS(CFormat(wxT(" m_fRequestsCryptLayer = %i")) % m_fRequestsCryptLayer); AddLogLineNS(CFormat(wxT(" m_fSupportsCryptLayer = %i")) % m_fSupportsCryptLayer); AddLogLineNS(CFormat(wxT(" m_fExtMultiPacket = %i")) % m_fExtMultiPacket); AddLogLineNS(CFormat(wxT(" m_fSupportsLargeFiles = %i")) % m_fSupportsLargeFiles); AddLogLineNS(CFormat(wxT(" KadVersion = %u")) % m_byKadVersion); AddLogLineNS(wxT("That's all.")); #endif break; // Special tag for Compat. Clients Misc options. case CT_EMULECOMPAT_OPTIONS: // 1 Operative System Info // 1 Value-based-type int tags (experimental!) m_fValueBasedTypeTags = (temptag.GetInt() >> 1*1) & 0x01; m_fOsInfoSupport = (temptag.GetInt() >> 1*0) & 0x01; break; case CT_EMULE_VERSION: // 8 Compatible Client ID // 7 Mjr Version (Doesn't really matter..) // 7 Min Version (Only need 0-99) // 3 Upd Version (Only need 0-5) // 7 Bld Version (Only need 0-99) m_byCompatibleClient = (temptag.GetInt() >> 24); m_nClientVersion = temptag.GetInt() & 0x00ffffff; m_byEmuleVersion = 0x99; m_fSharedDirectories = 1; dwEmuleTags |= 4; break; } } m_nUserPort = nUserPort; m_dwServerIP = data.ReadUInt32(); m_nServerPort = data.ReadUInt16(); // Hybrid now has an extra uint32.. What is it for? // Also, many clients seem to send an extra 6? These are not eDonkeys or Hybrids.. if ( data.GetLength() - data.GetPosition() == sizeof(uint32) ) { uint32 test = data.ReadUInt32(); /*if (test == 'KDLM') below kdlm is converted to ascii values. This fixes a warning with gcc 3.4. K=4b D=44 L=4c M=4d */ if (test == 0x4b444c4d) { //if it's == "KDLM" m_bIsML=true; } else{ m_bIsHybrid = true; m_fSharedDirectories = 1; } } if (m_socket) { SetIP(m_socket->GetPeerInt()); } else { throw wxString(wxT("Huh, socket failure. Avoided crash this time.")); } if (thePrefs::AddServersFromClient()) { CServer* addsrv = new CServer(m_nServerPort, Uint32toStringIP(m_dwServerIP)); addsrv->SetListName(addsrv->GetAddress()); if (!theApp->AddServer(addsrv)) { delete addsrv; } } //(a)If this is a highID user, store the ID in the Hybrid format. //(b)Some older clients will not send a ID, these client are HighID users that are not connected to a server. //(c)Kad users with a *.*.*.0 IPs will look like a lowID user they are actually a highID user.. They can be detected easily //because they will send a ID that is the same as their IP.. if(!HasLowID() || m_nUserIDHybrid == 0 || m_nUserIDHybrid == m_dwUserIP ) { SetUserIDHybrid(wxUINT32_SWAP_ALWAYS(m_dwUserIP)); } // get client credits CClientCredits* pFoundCredits = theApp->clientcredits->GetCredit(m_UserHash); if (credits == NULL){ credits = pFoundCredits; if (!theApp->clientlist->ComparePriorUserhash(m_dwUserIP, m_nUserPort, pFoundCredits)){ AddDebugLogLineN( logClient, CFormat( wxT("Client: %s (%s) Banreason: Userhash changed (Found in TrackedClientsList)") ) % GetUserName() % GetFullIP() ); Ban(); } } else if (credits != pFoundCredits){ // userhash change ok, however two hours "waittime" before it can be used credits = pFoundCredits; AddDebugLogLineN( logClient, CFormat( wxT("Client: %s (%s) Banreason: Userhash changed") ) % GetUserName() % GetFullIP() ); Ban(); } if ((m_Friend = theApp->friendlist->FindFriend(m_UserHash, m_dwUserIP, m_nUserPort)) != NULL){ m_Friend->LinkClient(CCLIENTREF(this, wxT("CUpDownClient::ProcessHelloTypePacket m_Friend->LinkClient"))); } else{ // avoid that an unwanted client instance keeps a friend slot SetFriendSlot(false); } ReGetClientSoft(); m_byInfopacketsReceived |= IP_EDONKEYPROTPACK; // check if at least CT_EMULEVERSION was received, all other tags are optional bool bIsMule = (dwEmuleTags & 0x04) == 0x04; if (bIsMule) { m_bEmuleProtocol = true; m_byInfopacketsReceived |= IP_EMULEPROTPACK; } if (GetKadPort() && GetKadVersion() > 1) { Kademlia::CKademlia::Bootstrap(wxUINT32_SWAP_ALWAYS(GetIP()), GetKadPort()); } return bIsMule; } bool CUpDownClient::SendHelloPacket() { if (m_socket == NULL) { wxFAIL; return true; } // if IP is filtered, don't greet him but disconnect... if (theApp->ipfilter->IsFiltered(m_socket->GetPeerInt())) { if (Disconnected(wxT("IPFilter"))) { Safe_Delete(); return false; } return true; } CMemFile data(128); data.WriteUInt8(16); // size of userhash SendHelloTypePacket(&data); CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_HELLO); theStats::AddUpOverheadOther(packet->GetPacketSize()); SendPacket(packet,true); m_bHelloAnswerPending = true; AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_HELLO to ") + GetFullIP() ); return true; } void CUpDownClient::SendMuleInfoPacket(bool bAnswer, bool OSInfo) { if (m_socket == NULL){ wxFAIL; return; } CPacket* packet = NULL; CMemFile data; data.WriteUInt8(CURRENT_VERSION_SHORT); if (OSInfo) { // Special MuleInfo packet for clients supporting it. // This means aMule >= 2.0.0 and Hydranode // Violently mark it as special Mule Info packet // Sending this makes non-supporting-osinfo clients to refuse to read this // packet. Anyway, this packet should NEVER get to non-supporting clients. data.WriteUInt8(/*EMULE_PROTOCOL*/ 0xFF); data.WriteUInt32(1); // One Tag (OS_INFO) CTagString tag1(ET_OS_INFO,theApp->GetOSType()); tag1.WriteTagToFile(&data); m_OSInfo_sent = true; // So we don't send it again } else { // Normal MuleInfo packet // Kry - There's no point on upgrading to VBT tags here // as no client supporting it uses mule info packet. data.WriteUInt8(EMULE_PROTOCOL); // Tag number data.WriteUInt32(9); CTagInt32 tag1(ET_COMPRESSION,1); tag1.WriteTagToFile(&data); CTagInt32 tag2(ET_UDPVER,4); tag2.WriteTagToFile(&data); CTagInt32 tag3(ET_UDPPORT, thePrefs::GetEffectiveUDPPort()); tag3.WriteTagToFile(&data); CTagInt32 tag4(ET_SOURCEEXCHANGE,3); tag4.WriteTagToFile(&data); CTagInt32 tag5(ET_COMMENTS,1); tag5.WriteTagToFile(&data); CTagInt32 tag6(ET_EXTENDEDREQUEST,2); tag6.WriteTagToFile(&data); uint32 dwTagValue = (theApp->CryptoAvailable() ? 3 : 0); // Kry - Needs the preview code from eMule /* // set 'Preview supported' only if 'View Shared Files' allowed if (thePrefs::CanSeeShares() != vsfaNobody) { dwTagValue |= 128; } */ CTagInt32 tag7(ET_FEATURES, dwTagValue); tag7.WriteTagToFile(&data); CTagInt32 tag8(ET_COMPATIBLECLIENT,SO_AMULE); tag8.WriteTagToFile(&data); // Support for tag ET_MOD_VERSION wxString mod_name(MOD_VERSION_LONG); CTagString tag9(ET_MOD_VERSION, mod_name); tag9.WriteTagToFile(&data); // Maella end } packet = new CPacket(data, OP_EMULEPROT, (bAnswer ? OP_EMULEINFOANSWER : OP_EMULEINFO)); if (m_socket) { theStats::AddUpOverheadOther(packet->GetPacketSize()); SendPacket(packet,true,true); #ifdef __DEBUG__ if (!bAnswer) { if (!OSInfo) { AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_EMULEINFO to ") + GetFullIP() ); } else { AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_EMULEINFO/OS_INFO to ") + GetFullIP() ); } } else { AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_EMULEINFOANSWER to ") + GetFullIP() ); } #endif } } bool CUpDownClient::ProcessMuleInfoPacket(const byte* pachPacket, uint32 nSize) { uint8 protocol_version; const CMemFile data(pachPacket,nSize); // The version number part of this packet will soon be useless since // it is only able to go to v.99. Why the version is a uint8 and why // it was not done as a tag like the eDonkey hello packet is not known. // Therefore, sooner or later, we are going to have to switch over to // using the eDonkey hello packet to set the version. No sense making // a third value sent for versions. uint8 mule_version = data.ReadUInt8(); protocol_version = data.ReadUInt8(); uint32 tagcount = data.ReadUInt32(); if (protocol_version == 0xFF) { // OS Info supporting clients sending a recycled Mule info packet for (uint32 i = 0;i < tagcount; i++){ CTag temptag(data, true); switch(temptag.GetNameID()){ case ET_OS_INFO: // Special tag, only supporting clients (aMule/Hydranode) // It was recycled from a mod's tag, so if the other side // is not supporting OS Info, we're seriously fucked up :) m_sClientOSInfo = temptag.GetStr(); // If we didn't send our OSInfo to this client, just send it if (!m_OSInfo_sent) { SendMuleInfoPacket(false,true); } UpdateStats(); break; // Your ad... er... I mean TAG, here default: break; } } } else { // Old eMule sending tags m_byCompatibleClient = 0; m_byEmuleVersion = mule_version; if( m_byEmuleVersion == 0x2B ) { m_byEmuleVersion = 0x22; } if (!(m_bEmuleProtocol = (protocol_version == EMULE_PROTOCOL))) { return false; } for (uint32 i = 0;i < tagcount; i++){ CTag temptag(data, false); switch(temptag.GetNameID()){ case ET_COMPRESSION: // Bits 31- 8: 0 - reserved // Bits 7- 0: data compression version m_byDataCompVer = temptag.GetInt(); break; case ET_UDPPORT: // Bits 31-16: 0 - reserved // Bits 15- 0: UDP port m_nUDPPort = temptag.GetInt(); break; case ET_UDPVER: // Bits 31- 8: 0 - reserved // Bits 7- 0: UDP protocol version m_byUDPVer = temptag.GetInt(); break; case ET_SOURCEEXCHANGE: // Bits 31- 8: 0 - reserved // Bits 7- 0: source exchange protocol version m_bySourceExchange1Ver = temptag.GetInt(); break; case ET_COMMENTS: // Bits 31- 8: 0 - reserved // Bits 7- 0: comments version m_byAcceptCommentVer = temptag.GetInt(); break; case ET_EXTENDEDREQUEST: // Bits 31- 8: 0 - reserved // Bits 7- 0: extended requests version m_byExtendedRequestsVer = temptag.GetInt(); break; case ET_COMPATIBLECLIENT: // Bits 31- 8: 0 - reserved // Bits 7- 0: compatible client ID m_byCompatibleClient = temptag.GetInt(); break; case ET_FEATURES: // Bits 31- 8: 0 - reserved // Bit 7: Preview // Bit 6- 0: secure identification m_bySupportSecIdent = temptag.GetInt() & 3; m_bSupportsPreview = (temptag.GetInt() & 128) > 0; SecIdentSupRec += 2; break; case ET_MOD_VERSION: if (temptag.IsStr()) { m_strModVersion = temptag.GetStr(); } else if (temptag.IsInt()) { m_strModVersion = CFormat(wxT("ModID=%u")) % temptag.GetInt(); } else { m_strModVersion = wxT("ModID=<Unknown>"); } break; default: AddDebugLogLineN( logPacketErrors, CFormat( wxT("Unknown Mule tag (%s) from client: %s") ) % temptag.GetFullInfo() % GetClientFullInfo() ); break; } } if( m_byDataCompVer == 0 ){ m_bySourceExchange1Ver = 0; m_byExtendedRequestsVer = 0; m_byAcceptCommentVer = 0; m_nUDPPort = 0; } //implicitly supported options by older clients //in the future do not use version to guess about new features if(m_byEmuleVersion < 0x25 && m_byEmuleVersion > 0x22) { m_byUDPVer = 1; } if(m_byEmuleVersion < 0x25 && m_byEmuleVersion > 0x21) { m_bySourceExchange1Ver = 1; } if(m_byEmuleVersion == 0x24) { m_byAcceptCommentVer = 1; } // Shared directories are requested from eMule 0.28+ because eMule 0.27 has a bug in // the OP_ASKSHAREDFILESDIR handler, which does not return the shared files for a // directory which has a trailing backslash. if(m_byEmuleVersion >= 0x28 && !m_bIsML) {// MLdonkey currently does not support shared directories m_fSharedDirectories = 1; } ReGetClientSoft(); m_byInfopacketsReceived |= IP_EMULEPROTPACK; } return (protocol_version == 0xFF); // This was a OS_Info? } void CUpDownClient::SendHelloAnswer() { if (m_socket == NULL){ wxFAIL; return; } CMemFile data(128); SendHelloTypePacket(&data); CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_HELLOANSWER); theStats::AddUpOverheadOther(packet->GetPacketSize()); AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_HELLOANSWER to ") + GetFullIP() ); SendPacket(packet,true); } void CUpDownClient::SendHelloTypePacket(CMemFile* data) { data->WriteHash(thePrefs::GetUserHash()); data->WriteUInt32(theApp->GetID()); data->WriteUInt16(thePrefs::GetPort()); uint32 tagcount = 6; if( theApp->clientlist->GetBuddy() && theApp->IsFirewalled() ) { tagcount += 2; } tagcount ++; // eMule misc flags 2 (kad version) #ifdef __SVN__ // Kry - This is the tagcount!!! Be sure to update it!! // Last update: CT_EMULECOMPAT_OPTIONS included data->WriteUInt32(tagcount + 1); #else data->WriteUInt32(tagcount); // NO MOD_VERSION #endif CTagString tagname(CT_NAME,thePrefs::GetUserNick()); tagname.WriteTagToFile(data, utf8strRaw); CTagVarInt tagversion(CT_VERSION, EDONKEYVERSION, GetVBTTags() ? 0 : 32); tagversion.WriteTagToFile(data); // eMule UDP Ports uint32 kadUDPPort = 0; if(Kademlia::CKademlia::IsConnected()) { if (Kademlia::CKademlia::GetPrefs()->GetExternalKadPort() != 0 && Kademlia::CKademlia::GetPrefs()->GetUseExternKadPort() && Kademlia::CUDPFirewallTester::IsVerified()) { kadUDPPort = Kademlia::CKademlia::GetPrefs()->GetExternalKadPort(); } else { kadUDPPort = Kademlia::CKademlia::GetPrefs()->GetInternKadPort(); } } CTagVarInt tagUdpPorts(CT_EMULE_UDPPORTS, (kadUDPPort << 16) | ((uint32)thePrefs::GetEffectiveUDPPort()), GetVBTTags() ? 0 : 32); tagUdpPorts.WriteTagToFile(data); if( theApp->clientlist->GetBuddy() && theApp->IsFirewalled() ) { CTagVarInt tagBuddyIP(CT_EMULE_BUDDYIP, theApp->clientlist->GetBuddy()->GetIP(), GetVBTTags() ? 0 : 32); tagBuddyIP.WriteTagToFile(data); CTagVarInt tagBuddyPort(CT_EMULE_BUDDYUDP, // ( RESERVED ) ((uint32)theApp->clientlist->GetBuddy()->GetUDPPort() ) , GetVBTTags() ? 0 : 32); tagBuddyPort.WriteTagToFile(data); } // aMule Version CTagVarInt tagMuleVersion(CT_EMULE_VERSION, (SO_AMULE << 24) | make_full_ed2k_version(VERSION_MJR, VERSION_MIN, VERSION_UPDATE) // | (RESERVED ) , GetVBTTags() ? 0 : 32); tagMuleVersion.WriteTagToFile(data); // eMule Misc. Options #1 const uint32 uUdpVer = 4; const uint32 uDataCompVer = 1; const uint32 uSupportSecIdent = theApp->CryptoAvailable() ? 3 : 0; const uint32 uSourceExchangeVer = 3; const uint32 uExtendedRequestsVer = 2; const uint32 uAcceptCommentVer = 1; const uint32 uNoViewSharedFiles = (thePrefs::CanSeeShares() == vsfaNobody) ? 1 : 0; // for backward compatibility this has to be a 'negative' flag const uint32 uMultiPacket = 1; const uint32 uSupportPreview = 0; // No network preview at all. const uint32 uPeerCache = 0; // No peercache for aMule, baby const uint32 uUnicodeSupport = 1; const uint32 nAICHVer = 1; // AICH is ENABLED right now. CTagVarInt tagMisOptions(CT_EMULE_MISCOPTIONS1, (nAICHVer << ((4*7)+1)) | (uUnicodeSupport << 4*7) | (uUdpVer << 4*6) | (uDataCompVer << 4*5) | (uSupportSecIdent << 4*4) | (uSourceExchangeVer << 4*3) | (uExtendedRequestsVer << 4*2) | (uAcceptCommentVer << 4*1) | (uPeerCache << 1*3) | (uNoViewSharedFiles << 1*2) | (uMultiPacket << 1*1) | (uSupportPreview << 1*0) , GetVBTTags() ? 0 : 32); tagMisOptions.WriteTagToFile(data); // eMule Misc. Options #2 const uint32 uKadVersion = KADEMLIA_VERSION; const uint32 uSupportLargeFiles = 1; const uint32 uExtMultiPacket = 1; const uint32 uReserved = 0; // mod bit const uint32 uSupportsCryptLayer = thePrefs::IsClientCryptLayerSupported() ? 1 : 0; const uint32 uRequestsCryptLayer = thePrefs::IsClientCryptLayerRequested() ? 1 : 0; const uint32 uRequiresCryptLayer = thePrefs::IsClientCryptLayerRequired() ? 1 : 0; const uint32 uSupportsSourceEx2 = 1; #ifdef AMULE_DAEMON // captcha for daemon/remotegui not supported for now const uint32 uSupportsCaptcha = 0; #else const uint32 uSupportsCaptcha = 1; #endif // direct callback is only possible if connected to kad, tcp firewalled and verified UDP open (for example on a full cone NAT) const uint32 uDirectUDPCallback = (Kademlia::CKademlia::IsRunning() && Kademlia::CKademlia::IsFirewalled() && !Kademlia::CUDPFirewallTester::IsFirewalledUDP(true) && Kademlia::CUDPFirewallTester::IsVerified()) ? 1 : 0; CTagVarInt tagMisOptions2(CT_EMULE_MISCOPTIONS2, // (RESERVED ) (uDirectUDPCallback << 12) | (uSupportsCaptcha << 11) | (uSupportsSourceEx2 << 10) | (uRequiresCryptLayer << 9) | (uRequestsCryptLayer << 8) | (uSupportsCryptLayer << 7) | (uReserved << 6) | (uExtMultiPacket << 5) | (uSupportLargeFiles << 4) | (uKadVersion << 0) , GetVBTTags() ? 0 : 32 ); tagMisOptions2.WriteTagToFile(data); const uint32 nOSInfoSupport = 1; // We support OS_INFO const uint32 nValueBasedTypeTags = 0; // Experimental, disabled CTagVarInt tagMisCompatOptions(CT_EMULECOMPAT_OPTIONS, (nValueBasedTypeTags << 1*1) | (nOSInfoSupport << 1*0) , GetVBTTags() ? 0 : 32); tagMisCompatOptions.WriteTagToFile(data); #ifdef __SVN__ wxString mod_name(MOD_VERSION_LONG); CTagString tagModName(ET_MOD_VERSION, mod_name); tagModName.WriteTagToFile(data); #endif uint32 dwIP = 0; uint16 nPort = 0; if (theApp->IsConnectedED2K()) { dwIP = theApp->serverconnect->GetCurrentServer()->GetIP(); nPort = theApp->serverconnect->GetCurrentServer()->GetPort(); } data->WriteUInt32(dwIP); data->WriteUInt16(nPort); } void CUpDownClient::ProcessMuleCommentPacket(const byte* pachPacket, uint32 nSize) { if (!m_reqfile) { throw CInvalidPacket(wxT("Comment packet for unknown file")); } if (!m_reqfile->IsPartFile()) { throw CInvalidPacket(wxT("Comment packet for completed file")); } const CMemFile data(pachPacket, nSize); uint8 rating = data.ReadUInt8(); if (rating > 5) { AddDebugLogLineN( logClient, wxString(wxT("Invalid Rating for file '")) << m_clientFilename << wxT("' received: ") << rating); m_iRating = 0; } else { m_iRating = rating; AddDebugLogLineN( logClient, wxString(wxT("Rating for file '")) << m_clientFilename << wxT("' received: ") << m_iRating); } // The comment is unicoded, with a uin32 len and safe read // (won't break if string size is < than advertised len) // Truncated to MAXFILECOMMENTLEN size m_strComment = data.ReadString((GetUnicodeSupport() != utf8strNone), 4 /* bytes (it's a uint32)*/, true).Left(MAXFILECOMMENTLEN); AddDebugLogLineN( logClient, wxString(wxT("Description for file '")) << m_clientFilename << wxT("' received: ") << m_strComment); // Update file rating m_reqfile->UpdateFileRatingCommentAvail(); } void CUpDownClient::ClearDownloadBlockRequests() { { std::list<Requested_Block_Struct*>::iterator it = m_DownloadBlocks_list.begin(); for (; it != m_DownloadBlocks_list.end(); ++it) { Requested_Block_Struct* cur_block = *it; if (m_reqfile){ m_reqfile->RemoveBlockFromList(cur_block->StartOffset, cur_block->EndOffset); } delete cur_block; } m_DownloadBlocks_list.clear(); } { std::list<Pending_Block_Struct*>::iterator it = m_PendingBlocks_list.begin(); for (; it != m_PendingBlocks_list.end(); ++it) { Pending_Block_Struct* pending = *it; if (m_reqfile) { m_reqfile->RemoveBlockFromList(pending->block->StartOffset, pending->block->EndOffset); } delete pending->block; // Not always allocated if (pending->zStream){ inflateEnd(pending->zStream); delete pending->zStream; } delete pending; } m_PendingBlocks_list.clear(); } } bool CUpDownClient::Disconnected(const wxString& DEBUG_ONLY(strReason), bool bFromSocket) { //wxASSERT(theApp->clientlist->IsValidClient(this)); if (HasBeenDeleted()) { AddDebugLogLineN(logClient, wxT("Disconnected() called for already deleted client on ip ") + Uint32toStringIP(GetConnectIP())); return false; } // was this a direct callback? if (m_dwDirectCallbackTimeout != 0) { theApp->clientlist->RemoveDirectCallback(this); m_dwDirectCallbackTimeout = 0; theApp->clientlist->AddDeadSource(this); AddDebugLogLineN(logClient, wxT("Direct callback failed to client on ip ") + Uint32toStringIP(GetConnectIP())); } if (GetKadState() == KS_QUEUED_FWCHECK_UDP || GetKadState() == KS_CONNECTING_FWCHECK_UDP) { Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, true, wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0); // inform the tester that this test was cancelled } else if (GetKadState() == KS_FWCHECK_UDP) { Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, false, wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0); // inform the tester that this test has failed } else if (GetKadState() == KS_CONNECTED_BUDDY) { AddDebugLogLineN(logClient, wxT("Buddy client disconnected - ") + strReason); } //If this is a KAD client object, just delete it! SetKadState(KS_NONE); if (GetUploadState() == US_UPLOADING) { // sets US_NONE theApp->uploadqueue->RemoveFromUploadQueue(this); } if (GetDownloadState() == DS_DOWNLOADING) { SetDownloadState(DS_ONQUEUE); } else { // ensure that all possible block requests are removed from the partfile ClearDownloadBlockRequests(); if (GetDownloadState() == DS_CONNECTED) { // successfully connected, but probably didn't respond to our filerequest theApp->clientlist->AddDeadSource(this); theApp->downloadqueue->RemoveSource(this); } } // we had still an AICH request pending, handle it if (IsAICHReqPending()) { m_fAICHRequested = FALSE; CAICHHashSet::ClientAICHRequestFailed(this); } // The remote client does not have to answer with OP_HASHSETANSWER *immediatly* // after we've sent OP_HASHSETREQUEST. It may occure that a (buggy) remote client // is sending use another OP_FILESTATUS which would let us change to DL-state to DS_ONQUEUE. if (((GetDownloadState() == DS_REQHASHSET) || m_fHashsetRequesting) && (m_reqfile)) { m_reqfile->SetHashSetNeeded(true); } SourceItemType source_type = UNAVAILABLE_SOURCE; SourceItemType peer_type = UNAVAILABLE_SOURCE; //check if this client is needed in any way, if not delete it bool bDelete = true; switch (m_nUploadState) { case US_ONUPLOADQUEUE: bDelete = false; peer_type = AVAILABLE_SOURCE; break; }; switch (m_nDownloadState) { case DS_ONQUEUE: source_type = A4AF_SOURCE; // Will be checked. case DS_TOOMANYCONNS: case DS_NONEEDEDPARTS: case DS_LOWTOLOWIP: bDelete = false; break; }; switch (m_nUploadState) { case US_CONNECTING: case US_WAITCALLBACK: case US_ERROR: theApp->clientlist->AddDeadSource(this); bDelete = true; }; switch (m_nDownloadState) { case DS_CONNECTING: case DS_WAITCALLBACK: case DS_ERROR: case DS_BANNED: theApp->clientlist->AddDeadSource(this); bDelete = true; }; // We keep chat partners in any case if (GetChatState() != MS_NONE) { bDelete = false; m_pendingMessage.Clear(); Notify_ChatConnResult(false,GUI_ID(GetIP(),GetUserPort()),wxEmptyString); } // Delete socket if (!bFromSocket && m_socket) { wxASSERT (theApp->listensocket->IsValidSocket(m_socket)); m_socket->Safe_Delete(); } SetSocket(NULL); if (m_iFileListRequested) { AddLogLineC(CFormat(_("Failed to retrieve shared files from user '%s'")) % GetUserName() ); m_iFileListRequested = 0; } if (bDelete) { if (m_Friend) { // Remove the friend linkage m_Friend->UnLinkClient(); // this notifies } } else { Notify_SharedCtrlRefreshClient(ECID(), peer_type); Notify_SourceCtrlUpdateSource(ECID(), source_type); m_fHashsetRequesting = 0; SetSentCancelTransfer(0); m_bHelloAnswerPending = false; m_fSentOutOfPartReqs = 0; } AddDebugLogLineN(logClient, CFormat(wxT("--- %s client D:%d U:%d \"%s\"; Reason was %s")) % (bDelete ? wxT("Deleted") : wxT("Disconnected")) % m_nDownloadState % m_nUploadState % GetClientFullInfo() % strReason ); return bDelete; } //Returned bool is not if the TryToConnect is successful or not.. //false means the client was deleted! //true means the client was not deleted! bool CUpDownClient::TryToConnect(bool bIgnoreMaxCon) { // Kad reviewed if (theApp->listensocket->TooManySockets() && !bIgnoreMaxCon ) { if (!(m_socket && m_socket->IsConnected())) { if(Disconnected(wxT("Too many connections"))) { Safe_Delete(); return false; } return true; } } // Do not try to connect to source which are incompatible with our encryption setting (one requires it, and the other one doesn't supports it) if ( (RequiresCryptLayer() && !thePrefs::IsClientCryptLayerSupported()) || (thePrefs::IsClientCryptLayerRequired() && !SupportsCryptLayer()) ){ if(Disconnected(wxT("CryptLayer-Settings (Obfuscation) incompatible"))){ Safe_Delete(); return false; } else { return true; } } // Ipfilter check uint32 uClientIP = GetIP(); if (uClientIP == 0 && !HasLowID()) { uClientIP = wxUINT32_SWAP_ALWAYS(m_nUserIDHybrid); } if (uClientIP) { // Although we filter all received IPs (server sources, source exchange) and all incomming connection attempts, // we do have to filter outgoing connection attempts here too, because we may have updated the ip filter list if (theApp->ipfilter->IsFiltered(uClientIP)) { AddDebugLogLineN(logIPFilter, CFormat(wxT("Filtered ip %u (%s) on TryToConnect\n")) % uClientIP % Uint32toStringIP(uClientIP)); if (Disconnected(wxT("IPFilter"))) { Safe_Delete(); return false; } return true; } // for safety: check again whether that IP is banned if (theApp->clientlist->IsBannedClient(uClientIP)) { AddDebugLogLineN(logClient, wxT("Refused to connect to banned client ") + Uint32toStringIP(uClientIP)); if (Disconnected(wxT("Banned IP"))) { Safe_Delete(); return false; } return true; } } if (GetKadState() == KS_QUEUED_FWCHECK) { SetKadState(KS_CONNECTING_FWCHECK); } else if (GetKadState() == KS_QUEUED_FWCHECK_UDP) { SetKadState(KS_CONNECTING_FWCHECK_UDP); } if (HasLowID()) { if (!theApp->CanDoCallback(GetServerIP(), GetServerPort())) { //We cannot do a callback! if (GetDownloadState() == DS_CONNECTING) { SetDownloadState(DS_LOWTOLOWIP); } else if (GetDownloadState() == DS_REQHASHSET) { SetDownloadState(DS_ONQUEUE); m_reqfile->SetHashSetNeeded(true); } if (GetUploadState() == US_CONNECTING) { if(Disconnected(wxT("LowID->LowID and US_CONNECTING"))) { Safe_Delete(); return false; } } return true; } //We already know we are not firewalled here as the above condition already detected LowID->LowID and returned. //If ANYTHING changes with the "if(!theApp->CanDoCallback(this))" above that will let you fall through //with the condition that the source is firewalled and we are firewalled, we must //recheck it before the this check.. if (HasValidBuddyID() && !GetBuddyIP() && !GetBuddyPort() && !theApp->serverconnect->IsLocalServer(GetServerIP(), GetServerPort()) && !(SupportsDirectUDPCallback() && thePrefs::GetEffectiveUDPPort() != 0)) { //This is a Kad firewalled source that we want to do a special callback because it has no buddyIP or buddyPort. if( Kademlia::CKademlia::IsConnected() ) { //We are connect to Kad if( Kademlia::CKademlia::GetPrefs()->GetTotalSource() > 0 || Kademlia::CSearchManager::AlreadySearchingFor(Kademlia::CUInt128(GetBuddyID()))) { //There are too many source lookups already or we are already searching this key. SetDownloadState(DS_TOOMANYCONNSKAD); return true; } } } } if (!m_socket || !m_socket->IsConnected()) { if (m_socket) { m_socket->Safe_Delete(); } m_socket = new CClientTCPSocket(this, thePrefs::GetProxyData()); } else { ConnectionEstablished(); return true; } if (HasLowID() && SupportsDirectUDPCallback() && thePrefs::GetEffectiveUDPPort() != 0 && GetConnectIP() != 0) { // LOWID with DirectCallback if (m_dwDirectCallbackTimeout != 0) { AddDebugLogLineN(logClient, wxT("ERROR: Trying Direct UDP Callback while already trying to connect to client on ip ") + Uint32toStringIP(GetConnectIP())); return true; // We're already trying a direct connection to this client } // a direct callback is possible - since no other parties are involved and only one additional packet overhead // is used we basically handle it like a normal connection try, no restrictions apply // we already check above with !theApp->CanDoCallback(this) if any callback is possible at all m_dwDirectCallbackTimeout = ::GetTickCount() + SEC2MS(45); theApp->clientlist->AddDirectCallbackClient(this); AddDebugLogLineN(logClient, CFormat(wxT("Direct Callback on port %u to client on ip %s")) % GetKadPort() % Uint32toStringIP(GetConnectIP())); CMemFile data; data.WriteUInt16(thePrefs::GetPort()); // needs to know our port data.WriteHash(thePrefs::GetUserHash()); // and userhash // our connection settings data.WriteUInt8(Kademlia::CPrefs::GetMyConnectOptions(true, false)); AddDebugLogLineN(logClientUDP, wxT("Sending OP_DIRECTCALLBACKREQ to ") + Uint32_16toStringIP_Port(GetConnectIP(), GetKadPort())); CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_DIRECTCALLBACKREQ); theStats::AddUpOverheadOther(packet->GetPacketSize()); theApp->clientudp->SendPacket(packet, GetConnectIP(), GetKadPort(), ShouldReceiveCryptUDPPackets(), GetUserHash().GetHash(), false, 0); } else if (HasLowID()) { // LOWID if (GetDownloadState() == DS_CONNECTING) { SetDownloadState(DS_WAITCALLBACK); } if (GetUploadState() == US_CONNECTING) { if(Disconnected(wxT("LowID and US_CONNECTING"))) { Safe_Delete(); return false; } return true; } if (theApp->serverconnect->IsLocalServer(m_dwServerIP,m_nServerPort)) { CMemFile data; // AFAICS, this id must be reversed to be sent to clients // But if I reverse it, we do a serve violation ;) data.WriteUInt32(m_nUserIDHybrid); CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_CALLBACKREQUEST); theStats::AddUpOverheadServer(packet->GetPacketSize()); AddDebugLogLineN(logLocalClient, wxT("Local Client: OP_CALLBACKREQUEST to ") + GetFullIP()); theApp->serverconnect->SendPacket(packet); SetDownloadState(DS_WAITCALLBACK); } else { if (GetUploadState() == US_NONE && (!GetRemoteQueueRank() || m_bReaskPending)) { if( !HasValidBuddyID() ) { theApp->downloadqueue->RemoveSource(this); if (Disconnected(wxT("LowID and US_NONE and QR=0"))) { Safe_Delete(); return false; } return true; } if( !Kademlia::CKademlia::IsConnected() ) { //We are not connected to Kad and this is a Kad Firewalled source.. theApp->downloadqueue->RemoveSource(this); if(Disconnected(wxT("Kad Firewalled source but not connected to Kad."))) { Safe_Delete(); return false; } return true; } if( GetDownloadState() == DS_WAITCALLBACK ) { if( GetBuddyIP() && GetBuddyPort()) { CMemFile bio(34); bio.WriteUInt128(Kademlia::CUInt128(GetBuddyID())); bio.WriteUInt128(Kademlia::CUInt128(m_reqfile->GetFileHash().GetHash())); bio.WriteUInt16(thePrefs::GetPort()); CPacket* packet = new CPacket(bio, OP_KADEMLIAHEADER, KADEMLIA_CALLBACK_REQ); // eMule FIXME: We don't know which kadversion the buddy has, so we need to send unencrypted theApp->clientudp->SendPacket(packet, GetBuddyIP(), GetBuddyPort(), false, NULL, true, 0); AddDebugLogLineN(logClientKadUDP, CFormat(wxT("KadCallbackReq (size=%i) to %s")) % packet->GetPacketSize() % Uint32_16toStringIP_Port(GetBuddyIP(), GetBuddyPort())); theStats::AddUpOverheadKad(packet->GetRealPacketSize()); SetDownloadState(DS_WAITCALLBACKKAD); } else { AddLogLineN(_("Searching buddy for lowid connection")); //Create search to find buddy. Kademlia::CSearch *findSource = new Kademlia::CSearch; findSource->SetSearchTypes(Kademlia::CSearch::FINDSOURCE); findSource->SetTargetID(Kademlia::CUInt128(GetBuddyID())); findSource->AddFileID(Kademlia::CUInt128(m_reqfile->GetFileHash().GetHash())); if(Kademlia::CSearchManager::StartSearch(findSource)) { //Started lookup.. SetDownloadState(DS_WAITCALLBACKKAD); } else { //This should never happen.. wxFAIL; } } } } else { if (GetDownloadState() == DS_WAITCALLBACK) { m_bReaskPending = true; SetDownloadState(DS_ONQUEUE); } } } } else { // HIGHID if (!Connect()) { return false; } } return true; } bool CUpDownClient::Connect() { m_hasbeenobfuscatinglately = false; if (!m_socket->IsOk()) { // Enable or disable crypting based on our and the remote clients preference if (HasValidHash() && SupportsCryptLayer() && thePrefs::IsClientCryptLayerSupported() && (RequestsCryptLayer() || thePrefs::IsClientCryptLayerRequested())){ m_socket->SetConnectionEncryption(true, GetUserHash().GetHash(), false); } else { m_socket->SetConnectionEncryption(false, NULL, false); } amuleIPV4Address tmp; tmp.Hostname(GetConnectIP()); tmp.Service(GetUserPort()); AddDebugLogLineN(logClient, wxT("Trying to connect to ") + Uint32_16toStringIP_Port(GetConnectIP(),GetUserPort())); m_socket->Connect(tmp, false); // We should send hello packets AFTER connecting! // so I moved it to OnConnect return true; } else { return false; } } void CUpDownClient::ConnectionEstablished() { /* Kry - First thing, check if this client was just used to retrieve info. That's some debug thing for myself... check connection_reason definition */ m_hasbeenobfuscatinglately = (m_socket && m_socket->IsConnected() && m_socket->IsObfusicating()); #ifdef __DEBUG__ if (!connection_reason.IsEmpty()) { AddLogLineN(CFormat(wxT("Got client info checking for %s: %s\nDisconnecting and deleting.")) % connection_reason % GetClientFullInfo()); connection_reason.Clear(); // So we don't re-print on destructor. Safe_Delete(); return; } #endif // Check if we should use this client to retrieve our public IP // Ignore local ip on GetPublicIP (could be wrong) if (theApp->GetPublicIP(true) == 0 && theApp->IsConnectedED2K()) { SendPublicIPRequest(); } // was this a direct callback? if (m_dwDirectCallbackTimeout != 0){ theApp->clientlist->RemoveDirectCallback(this); m_dwDirectCallbackTimeout = 0; AddDebugLogLineN(logClient, wxT("Direct Callback succeeded, connection established to ") + Uint32toStringIP(GetConnectIP())); } switch (GetKadState()) { case KS_CONNECTING_FWCHECK: SetKadState(KS_CONNECTED_FWCHECK); break; case KS_CONNECTING_BUDDY: case KS_INCOMING_BUDDY: SetKadState(KS_CONNECTED_BUDDY); break; case KS_CONNECTING_FWCHECK_UDP: SetKadState(KS_FWCHECK_UDP); SendFirewallCheckUDPRequest(); break; default: break; } // ok we have a connection, lets see if we want anything from this client if (GetChatState() == MS_CONNECTING) { SetChatState( MS_CHATTING ); } if (GetChatState() == MS_CHATTING) { bool result = true; if (!m_pendingMessage.IsEmpty()) { result = SendChatMessage(m_pendingMessage); } Notify_ChatConnResult(result,GUI_ID(GetIP(),GetUserPort()),m_pendingMessage); m_pendingMessage.Clear(); } switch(GetDownloadState()) { case DS_CONNECTING: case DS_WAITCALLBACK: case DS_WAITCALLBACKKAD: m_bReaskPending = false; SetDownloadState(DS_CONNECTED); SendFileRequest(); } if (m_bReaskPending){ m_bReaskPending = false; if (GetDownloadState() != DS_NONE && GetDownloadState() != DS_DOWNLOADING) { SetDownloadState(DS_CONNECTED); SendFileRequest(); } } switch(GetUploadState()){ case US_CONNECTING: case US_WAITCALLBACK: if (theApp->uploadqueue->IsDownloading(this)) { SetUploadState(US_UPLOADING); CPacket* packet = new CPacket(OP_ACCEPTUPLOADREQ, 0, OP_EDONKEYPROT); theStats::AddUpOverheadFileRequest(packet->GetPacketSize()); SendPacket(packet,true); AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ACCEPTUPLOADREQ to ") + GetFullIP() ); } } if (m_iFileListRequested == 1) { CPacket* packet = new CPacket(m_fSharedDirectories ? OP_ASKSHAREDDIRS : OP_ASKSHAREDFILES, 0, OP_EDONKEYPROT); theStats::AddUpOverheadOther(packet->GetPacketSize()); SendPacket(packet,true,true); #ifdef __DEBUG__ if (m_fSharedDirectories) { AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDDIRS to ") + GetFullIP() ); } else { AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDFILES to ") + GetFullIP() ); } #endif } while (!m_WaitingPackets_list.empty()) { CPacket* packet = m_WaitingPackets_list.front(); m_WaitingPackets_list.pop_front(); SendPacket(packet); } } int CUpDownClient::GetHashType() const { if ( m_UserHash[5] == 13 && m_UserHash[14] == 110 ) { return SO_OLDEMULE; } if ( m_UserHash[5] == 14 && m_UserHash[14] == 111 ) { return SO_EMULE; } if ( m_UserHash[5] == 'M' && m_UserHash[14] == 'L' ) { return SO_MLDONKEY; } return SO_UNKNOWN; } void CUpDownClient::SetSocket(CClientTCPSocket* socket) { #ifdef __DEBUG__ if (m_socket == NULL && socket != NULL) { theStats::SocketAssignedToClient(); } else if (m_socket != NULL && socket == NULL) { theStats::SocketUnassignedFromClient(); } #endif m_socket = socket; } void CUpDownClient::ReGetClientSoft() { if (m_Username.IsEmpty()) { m_clientSoft=SO_UNKNOWN; m_clientVerString = m_clientSoftString = m_clientVersionString = m_fullClientVerString = _("Unknown"); UpdateStats(); return; } int iHashType = GetHashType(); wxString clientModString; if (iHashType == SO_EMULE) { m_clientSoft = m_byCompatibleClient; m_clientSoftString = GetSoftName(m_clientSoft); // Special issues: if(!GetClientModString().IsEmpty() && (m_clientSoft != SO_EMULE)) { m_clientSoftString = GetClientModString(); } // Isn't xMule annoying? if ((m_clientSoft == SO_LXMULE) && (GetMuleVersion() > 0x26) && (GetMuleVersion() != 0x99)) { m_clientSoftString += CFormat(_(" (Fake eMule version %#x)")) % GetMuleVersion(); } if ((m_clientSoft == SO_EMULE) && ( wxString(GetClientModString()).MakeLower().Find(wxT("xmule")) != -1 || GetUserName().Find(wxT("xmule.")) != -1 ) ) { // FAKE eMule -a newer xMule faking is ident. m_clientSoft = SO_LXMULE; if (GetClientModString().IsEmpty() == false) { m_clientSoftString = GetClientModString() + _(" (Fake eMule)"); } else { m_clientSoftString = _("xMule (Fake eMule)"); // don't use GetSoftName, it's not lmule. } } // Now, what if we don't know this SO_ID? if (m_clientSoftString.IsEmpty()) { if(m_bIsML) { m_clientSoft = SO_MLDONKEY; m_clientSoftString = GetSoftName(m_clientSoft); } else if (m_bIsHybrid) { m_clientSoft = SO_EDONKEYHYBRID; m_clientSoftString = GetSoftName(m_clientSoft); } else if (m_byCompatibleClient != 0) { m_clientSoft = SO_COMPAT_UNK; #ifdef __DEBUG__ if ( // Exceptions: (m_byCompatibleClient != 0xf0) // Chinese leech mod && (1==1) // Your ad here ) { AddLogLineNS(CFormat(wxT("Compatible client found with ET_COMPATIBLECLIENT of %x")) % m_byCompatibleClient); } #endif m_clientSoftString = CFormat(wxT("%s(%#x)")) % GetSoftName(m_clientSoft) % m_byCompatibleClient; } else { // If we step here, it might mean 2 things: // a eMule // a Compat Client that has sent no MuleInfo packet yet. m_clientSoft = SO_EMULE; m_clientSoftString = wxT("eMule"); } } if (m_byEmuleVersion == 0) { m_nClientVersion = MAKE_CLIENT_VERSION(0,0,0); } else if (m_byEmuleVersion != 0x99) { uint32 nClientMinVersion = (m_byEmuleVersion >> 4)*10 + (m_byEmuleVersion & 0x0f); m_nClientVersion = MAKE_CLIENT_VERSION(0,nClientMinVersion,0); switch (m_clientSoft) { case SO_AMULE: m_clientVerString = CFormat(_("1.x (based on eMule v0.%u)")) % nClientMinVersion; break; case SO_LPHANT: m_clientVerString = wxT("< v0.05"); break; default: clientModString = GetClientModString(); m_clientVerString = CFormat(wxT("v0.%u")) % nClientMinVersion; break; } } else { uint32 nClientMajVersion = (m_nClientVersion >> 17) & 0x7f; uint32 nClientMinVersion = (m_nClientVersion >> 10) & 0x7f; uint32 nClientUpVersion = (m_nClientVersion >> 7) & 0x07; m_nClientVersion = MAKE_CLIENT_VERSION(nClientMajVersion, nClientMinVersion, nClientUpVersion); switch (m_clientSoft) { case SO_AMULE: case SO_LXMULE: case SO_HYDRANODE: case SO_MLDONKEY: case SO_NEW_MLDONKEY: case SO_NEW2_MLDONKEY: // Kry - xMule started sending correct version tags on 1.9.1b. // It only took them 4 months, and being told by me and the // eMule+ developers, so I think they're slowly getting smarter. // They are based on our implementation, so we use the same format // for the version string. m_clientVerString = CFormat(wxT("v%u.%u.%u")) % nClientMajVersion % nClientMinVersion % nClientUpVersion; break; case SO_LPHANT: m_clientVerString = CFormat(wxT(" v%u.%.2u%c")) % (nClientMajVersion-1) % nClientMinVersion % ('a' + nClientUpVersion); break; case SO_EMULEPLUS: m_clientVerString = CFormat(wxT("v%u")) % nClientMajVersion; if(nClientMinVersion != 0) { m_clientVerString += CFormat(wxT(".%u")) % nClientMinVersion; } if(nClientUpVersion != 0) { m_clientVerString += CFormat(wxT("%c")) % ('a' + nClientUpVersion - 1); } break; default: clientModString = GetClientModString(); m_clientVerString = CFormat(wxT("v%u.%u%c")) % nClientMajVersion % nClientMinVersion % ('a' + nClientUpVersion); break; } } } else if (m_bIsHybrid) { // seen: // 105010 50.10 // 10501 50.1 // 1051 51.0 // 501 50.1 m_clientSoft = SO_EDONKEYHYBRID; m_clientSoftString = GetSoftName(m_clientSoft); uint32 nClientMajVersion; uint32 nClientMinVersion; uint32 nClientUpVersion; if (m_nClientVersion > 100000) { uint32 uMaj = m_nClientVersion/100000; nClientMajVersion = uMaj - 1; nClientMinVersion = (m_nClientVersion - uMaj*100000) / 100; nClientUpVersion = m_nClientVersion % 100; } else if (m_nClientVersion > 10000) { uint32 uMaj = m_nClientVersion/10000; nClientMajVersion = uMaj - 1; nClientMinVersion = (m_nClientVersion - uMaj*10000) / 10; nClientUpVersion = m_nClientVersion % 10; } else if (m_nClientVersion > 1000) { uint32 uMaj = m_nClientVersion/1000; nClientMajVersion = uMaj - 1; nClientMinVersion = m_nClientVersion - uMaj*1000; nClientUpVersion = 0; } else if (m_nClientVersion > 100) { uint32 uMin = m_nClientVersion/10; nClientMajVersion = 0; nClientMinVersion = uMin; nClientUpVersion = m_nClientVersion - uMin*10; } else{ nClientMajVersion = 0; nClientMinVersion = m_nClientVersion; nClientUpVersion = 0; } m_nClientVersion = MAKE_CLIENT_VERSION(nClientMajVersion, nClientMinVersion, nClientUpVersion); if (nClientUpVersion) { m_clientVerString = CFormat(wxT("v%u.%u.%u")) % nClientMajVersion % nClientMinVersion % nClientUpVersion; } else { m_clientVerString = CFormat(wxT("v%u.%u")) % nClientMajVersion % nClientMinVersion; } } else if (m_bIsML || (iHashType == SO_MLDONKEY)) { m_clientSoft = SO_MLDONKEY; m_clientSoftString = GetSoftName(m_clientSoft); uint32 nClientMinVersion = m_nClientVersion; m_nClientVersion = MAKE_CLIENT_VERSION(0, nClientMinVersion, 0); m_clientVerString = CFormat(wxT("v0.%u")) % nClientMinVersion; } else if (iHashType == SO_OLDEMULE) { m_clientSoft = SO_OLDEMULE; m_clientSoftString = GetSoftName(m_clientSoft); uint32 nClientMinVersion = m_nClientVersion; m_nClientVersion = MAKE_CLIENT_VERSION(0, nClientMinVersion, 0); m_clientVerString = CFormat(wxT("v0.%u")) % nClientMinVersion; } else { m_clientSoft = SO_EDONKEY; m_clientSoftString = GetSoftName(m_clientSoft); m_nClientVersion *= 10; m_clientVerString = CFormat(wxT("v%u.%u")) % (m_nClientVersion / 100000) % ((m_nClientVersion / 1000) % 100); } m_clientVersionString = m_clientVerString; if (!clientModString.IsEmpty()) { m_clientVerString += wxT(" - ") + clientModString; } m_fullClientVerString = m_clientSoftString + wxT(" ") + m_clientVerString; UpdateStats(); } void CUpDownClient::RequestSharedFileList() { if (m_iFileListRequested == 0) { AddDebugLogLineN( logClient, wxString( wxT("Requesting shared files from ") ) + GetUserName() ); m_iFileListRequested = 1; TryToConnect(true); } else { AddDebugLogLineN( logClient, CFormat( wxT("Requesting shared files from user %s (%u) is already in progress") ) % GetUserName() % GetUserIDHybrid() ); } } void CUpDownClient::ProcessSharedFileList(const byte* pachPacket, uint32 nSize, wxString& pszDirectory) { if (m_iFileListRequested > 0) { m_iFileListRequested--; theApp->searchlist->ProcessSharedFileList(pachPacket, nSize, this, NULL, pszDirectory); } } void CUpDownClient::ResetFileStatusInfo() { m_nPartCount = 0; if ( m_reqfile ) { m_reqfile->UpdatePartsFrequency( this, false ); } m_downPartStatus.clear(); m_clientFilename.Clear(); m_bCompleteSource = false; m_dwLastAskedTime = 0; m_iRating = 0; m_strComment.Clear(); if (m_pReqFileAICHHash != NULL) { delete m_pReqFileAICHHash; m_pReqFileAICHHash = NULL; } } wxString CUpDownClient::GetUploadFileInfo() { // build info text and display it wxString sRet; sRet = (CFormat(_("NickName: %s ID: %u")) % GetUserName() % GetUserIDHybrid()) + wxT(" "); if (m_reqfile) { sRet += CFormat(_("Requested: %s\n")) % m_reqfile->GetFileName(); sRet += CFormat( wxPLURAL("Filestats for this session: Accepted %d of %d request, %s transferred\n", "Filestats for this session: Accepted %d of %d requests, %s transferred\n", m_reqfile->statistic.GetRequests()) ) % m_reqfile->statistic.GetAccepts() % m_reqfile->statistic.GetRequests() % CastItoXBytes(m_reqfile->statistic.GetTransferred()); sRet += CFormat( wxPLURAL("Filestats for all sessions: Accepted %d of %d request, %s transferred\n", "Filestats for all sessions: Accepted %d of %d requests, %s transferred\n", m_reqfile->statistic.GetAllTimeRequests()) ) % m_reqfile->statistic.GetAllTimeAccepts() % m_reqfile->statistic.GetAllTimeRequests() % CastItoXBytes(m_reqfile->statistic.GetAllTimeTransferred()); } else { sRet += _("Requested unknown file"); } return sRet; } // sends a packet, if needed it will establish a connection before // options used: ignore max connections, control packet, delete packet // !if the functions returns false it is _possible_ that this clientobject was deleted, because the connectiontry fails bool CUpDownClient::SafeSendPacket(CPacket* packet) { if (IsConnected()) { SendPacket(packet, true); return true; } else { m_WaitingPackets_list.push_back(packet); return TryToConnect(true); } } void CUpDownClient::SendPublicKeyPacket(){ // send our public key to the client who requested it if (m_socket == NULL || credits == NULL || m_SecureIdentState != IS_KEYANDSIGNEEDED){ wxFAIL; return; } if (!theApp->CryptoAvailable()) return; CMemFile data; data.WriteUInt8(theApp->clientcredits->GetPubKeyLen()); data.Write(theApp->clientcredits->GetPublicKey(), theApp->clientcredits->GetPubKeyLen()); CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_PUBLICKEY); theStats::AddUpOverheadOther(packet->GetPacketSize()); AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_PUBLICKEY to ") + GetFullIP() ); SendPacket(packet,true,true); m_SecureIdentState = IS_SIGNATURENEEDED; } void CUpDownClient::SendSignaturePacket(){ // signate the public key of this client and send it if (m_socket == NULL || credits == NULL || m_SecureIdentState == 0){ wxFAIL; return; } if (!theApp->CryptoAvailable()) { return; } if (credits->GetSecIDKeyLen() == 0) { return; // We don't have his public key yet, will be back here later } // do we have a challenge value received (actually we should if we are in this function) if (credits->m_dwCryptRndChallengeFrom == 0){ AddDebugLogLineN( logClient, wxString(wxT("Want to send signature but challenge value is invalid - User ")) + GetUserName()); return; } // v2 // we will use v1 as default, except if only v2 is supported bool bUseV2; if ( (m_bySupportSecIdent&1) == 1 ) bUseV2 = false; else bUseV2 = true; uint8 byChaIPKind = 0; uint32 ChallengeIP = 0; if (bUseV2){ if (::IsLowID(theApp->GetED2KID())) { // we cannot do not know for sure our public ip, so use the remote clients one ChallengeIP = GetIP(); byChaIPKind = CRYPT_CIP_REMOTECLIENT; } else { ChallengeIP = theApp->GetED2KID(); byChaIPKind = CRYPT_CIP_LOCALCLIENT; } } //end v2 byte achBuffer[250]; uint8 siglen = theApp->clientcredits->CreateSignature(credits, achBuffer, 250, ChallengeIP, byChaIPKind ); if (siglen == 0){ wxFAIL; return; } CMemFile data; data.WriteUInt8(siglen); data.Write(achBuffer, siglen); if (bUseV2) { data.WriteUInt8(byChaIPKind); } CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_SIGNATURE); theStats::AddUpOverheadOther(packet->GetPacketSize()); AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_SIGNATURE to ") + GetFullIP() ); SendPacket(packet,true,true); m_SecureIdentState = IS_ALLREQUESTSSEND; } void CUpDownClient::ProcessPublicKeyPacket(const byte* pachPacket, uint32 nSize) { theApp->clientlist->AddTrackClient(this); if (m_socket == NULL || credits == NULL || pachPacket[0] != nSize-1 || nSize == 0 || nSize > 250){ wxFAIL; return; } if (!theApp->CryptoAvailable()) return; // the function will handle everything (mulitple key etc) if (credits->SetSecureIdent(pachPacket+1, pachPacket[0])){ // if this client wants a signature, now we can send him one if (m_SecureIdentState == IS_SIGNATURENEEDED){ SendSignaturePacket(); } else if (m_SecureIdentState == IS_KEYANDSIGNEEDED) { // something is wrong AddDebugLogLineN( logClient, wxT("Invalid State error: IS_KEYANDSIGNEEDED in ProcessPublicKeyPacket") ); } } else { AddDebugLogLineN( logClient, wxT("Failed to use new received public key") ); } } void CUpDownClient::ProcessSignaturePacket(const byte* pachPacket, uint32 nSize) { // here we spread the good guys from the bad ones ;) if (m_socket == NULL || credits == NULL || nSize == 0 || nSize > 250){ wxFAIL; return; } uint8 byChaIPKind; if (pachPacket[0] == nSize-1) byChaIPKind = 0; else if (pachPacket[0] == nSize-2 && (m_bySupportSecIdent & 2) > 0) //v2 byChaIPKind = pachPacket[nSize-1]; else{ wxFAIL; return; } if (!theApp->CryptoAvailable()) return; // we accept only one signature per IP, to avoid floods which need a lot cpu time for cryptfunctions if (m_dwLastSignatureIP == GetIP()){ AddDebugLogLineN( logClient, wxT("received multiple signatures from one client") ); return; } // also make sure this client has a public key if (credits->GetSecIDKeyLen() == 0){ AddDebugLogLineN( logClient, wxT("received signature for client without public key") ); return; } // and one more check: did we ask for a signature and sent a challange packet? if (credits->m_dwCryptRndChallengeFor == 0){ AddDebugLogLineN( logClient, wxT("received signature for client with invalid challenge value - User ") + GetUserName() ); return; } // cppcheck-suppress duplicateBranch if (theApp->clientcredits->VerifyIdent(credits, pachPacket+1, pachPacket[0], GetIP(), byChaIPKind ) ) { // result is saved in function above AddDebugLogLineN( logClient, CFormat( wxT("'%s' has passed the secure identification, V2 State: %i") ) % GetUserName() % byChaIPKind ); } else { AddDebugLogLineN( logClient, CFormat( wxT("'%s' has failed the secure identification, V2 State: %i") ) % GetUserName() % byChaIPKind ); } m_dwLastSignatureIP = GetIP(); } void CUpDownClient::SendSecIdentStatePacket(){ // check if we need public key and signature if (credits){ uint8 nValue = 0; if (theApp->CryptoAvailable()){ if (credits->GetSecIDKeyLen() == 0) { nValue = IS_KEYANDSIGNEEDED; } else if (m_dwLastSignatureIP != GetIP()) { nValue = IS_SIGNATURENEEDED; } } if (nValue == 0){ AddDebugLogLineN( logClient, wxT("Not sending SecIdentState Packet, because State is Zero") ); return; } // crypt: send random data to sign uint32 dwRandom = rand()+1; credits->m_dwCryptRndChallengeFor = dwRandom; CMemFile data; data.WriteUInt8(nValue); data.WriteUInt32(dwRandom); CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_SECIDENTSTATE); theStats::AddUpOverheadOther(packet->GetPacketSize()); AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_SECIDENTSTATE to ") + GetFullIP() ); SendPacket(packet,true,true); } else { wxFAIL; } } void CUpDownClient::ProcessSecIdentStatePacket(const byte* pachPacket, uint32 nSize) { if ( nSize != 5 ) { return; } if ( !credits ) { wxASSERT( credits ); return; } CMemFile data(pachPacket,nSize); switch ( data.ReadUInt8() ) { case 0: m_SecureIdentState = IS_UNAVAILABLE; break; case 1: m_SecureIdentState = IS_SIGNATURENEEDED; break; case 2: m_SecureIdentState = IS_KEYANDSIGNEEDED; break; default: return; } credits->m_dwCryptRndChallengeFrom = data.ReadUInt32(); } void CUpDownClient::InfoPacketsReceived() { // indicates that both Information Packets has been received // needed for actions, which process data from both packets wxASSERT ( m_byInfopacketsReceived == IP_BOTH ); m_byInfopacketsReceived = IP_NONE; if (m_bySupportSecIdent){ SendSecIdentStatePacket(); } } bool CUpDownClient::CheckHandshakeFinished() const { if (m_bHelloAnswerPending) { // this triggers way too often.. need more time to look at this -> only create a warning // The reason for this is that 2 clients are connecting to each other at the same time.. AddDebugLogLineN( logClient, wxT("Handshake not finished while processing packet.") ); return false; } return true; } #ifdef __DEBUG__ wxString CUpDownClient::GetClientFullInfo() { if (m_clientVerString.IsEmpty()) { ReGetClientSoft(); } return CFormat( wxT("Client %s on IP:Port %s:%d using %s %s %s") ) % ( m_Username.IsEmpty() ? wxString(_("Unknown")) : m_Username ) % GetFullIP() % GetUserPort() % m_clientSoftString % m_clientVerString % m_strModVersion; } #endif wxString CUpDownClient::GetClientShortInfo() { if (m_clientVerString.IsEmpty()) { ReGetClientSoft(); } return CFormat( wxT("'%s' (%s %s %s)") ) % ( m_Username.IsEmpty() ? wxString(_("Unknown")) : m_Username ) % m_clientSoftString % m_clientVerString % m_strModVersion; } void CUpDownClient::SendPublicIPRequest() { if (IsConnected()){ CPacket* packet = new CPacket(OP_PUBLICIP_REQ,0,OP_EMULEPROT); theStats::AddUpOverheadOther(packet->GetPacketSize()); AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_PUBLICIP_REQ to ") + GetFullIP()); SendPacket(packet,true); m_fNeedOurPublicIP = true; } } void CUpDownClient::ProcessPublicIPAnswer(const byte* pbyData, uint32 uSize) { if (uSize != 4) { throw wxString(wxT("Wrong Packet size on Public IP answer")); } uint32 dwIP = PeekUInt32(pbyData); if (m_fNeedOurPublicIP == true){ // did we? m_fNeedOurPublicIP = false; // Ignore local ip on GetPublicIP (could be wrong) if (theApp->GetPublicIP(true) == 0 && !IsLowID(dwIP) ) { theApp->SetPublicIP(dwIP); } } } bool CUpDownClient::IsConnected() const { return m_socket && m_socket->IsConnected(); } bool CUpDownClient::SendPacket(CPacket* packet, bool delpacket, bool controlpacket) { if ( m_socket ) { m_socket->SendPacket(packet, delpacket, controlpacket ); return true; } else { AddLogLineN(wxT("CAUGHT DEAD SOCKET IN SENDPACKET()")); return false; } } float CUpDownClient::SetDownloadLimit(uint32 reducedownload) { // lfroen: in daemon it actually can happen wxASSERT( m_socket ); float kBpsClient = CalculateKBpsDown(); if ( m_socket ) { if (reducedownload) { // (% to reduce * current speed) / 100 and THEN, / (1000 / CORE_TIMER_PERIOD) // which is how often it is called per second. uint32 limit = (uint32)(reducedownload * kBpsClient * 1024.0 / 100000.0 * CORE_TIMER_PERIOD); if(limit<1024 && reducedownload >= 200) { // If we're going up and this download is < 1kB, // we want it to go up fast. Can be reduced later, // and it'll probably be in a more fair way with // other downloads that are faster. limit +=1024; } else if(limit == 0) { // This download is not transferring yet... make it // 1024 so we don't fill the TCP stack and lose the // connection. limit = 1024; } m_socket->SetDownloadLimit(limit); } else { m_socket->DisableDownloadLimit(); } } else { AddLogLineNS(CFormat(wxT("CAUGHT DEAD SOCKET IN SETDOWNLOADLIMIT() WITH SPEED %f")) % kBpsClient); } return kBpsClient; } void CUpDownClient::SetUserIDHybrid(uint32 nUserID) { theApp->clientlist->UpdateClientID( this, nUserID ); m_nUserIDHybrid = nUserID; } void CUpDownClient::SetIP( uint32 val ) { theApp->clientlist->UpdateClientIP( this, val ); m_dwUserIP = val; m_nConnectIP = val; m_FullUserIP = val; } void CUpDownClient::SetUserHash(const CMD4Hash& userhash) { theApp->clientlist->UpdateClientHash( this, userhash ); m_UserHash = userhash; ValidateHash(); } EUtf8Str CUpDownClient::GetUnicodeSupport() const { return m_bUnicodeSupport ? utf8strRaw : utf8strNone; } void CUpDownClient::SetSpammer(bool bVal) { if (bVal) { Ban(); } else if (IsBanned() && m_fIsSpammer) { UnBan(); } m_fIsSpammer = bVal; } uint8 CUpDownClient::GetSecureIdentState() { if (m_SecureIdentState != IS_UNAVAILABLE) { if (!SecIdentSupRec) { // This can be caused by a 0.30x based client which sends the old // style Hello packet, and the mule info packet, but between them they // send a secure ident state packet (after a hello but before we have // the SUI capabilities). This is a misbehaving client, and somehow I // feel like it should be dropped. But then again, it won't harm to use // this SUI state if they are reporting no SUI (won't be used) and if // they report using SUI on the mule info packet, it's ok to use it. AddDebugLogLineN(logClient, wxT("A client sent secure ident state before telling us the SUI capabilities")); AddDebugLogLineN(logClient, wxT("Client info: ") + GetClientFullInfo()); AddDebugLogLineN(logClient, wxT("This client won't be disconnected, but it should be. :P")); } } return m_SecureIdentState; } bool CUpDownClient::SendChatMessage(const wxString& message) { if (GetChatCaptchaState() == CA_CAPTCHARECV) { m_nChatCaptchaState = CA_SOLUTIONSENT; } else if (GetChatCaptchaState() == CA_SOLUTIONSENT) { wxFAIL; // we responsed to a captcha but didn't heard from the client afterwards - hopefully its just lag and this message will get through } else { m_nChatCaptchaState = CA_ACCEPTING; } SetSpammer(false); IncMessagesSent(); // Already connecting? if (GetChatState() == MS_CONNECTING) { // Queue all messages till we're able to send them (or discard them) if (!m_pendingMessage.IsEmpty()) { m_pendingMessage += wxT("\n"); } else { // There must be a message to send // - except if we got disconnected. No need to assert therefore. } m_pendingMessage += message; return false; } if (IsConnected()) { // If we are already connected when we send the first message, // we have to update the chat status. SetChatState(MS_CHATTING); CMemFile data; data.WriteString(message, GetUnicodeSupport()); CPacket* packet = new CPacket(data, OP_EDONKEYPROT, OP_MESSAGE); theStats::AddUpOverheadOther(packet->GetPacketSize()); AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_MESSAGE to ") + GetFullIP()); SendPacket(packet, true, true); return true; } else { m_pendingMessage = message; SetChatState(MS_CONNECTING); // True to ignore "Too Many Connections" TryToConnect(true); return false; } } /* Kad stuff */ void CUpDownClient::SetBuddyID(const byte* pucBuddyID) { if( pucBuddyID == NULL ){ md4clr(m_achBuddyID); m_bBuddyIDValid = false; return; } m_bBuddyIDValid = true; md4cpy(m_achBuddyID, pucBuddyID); } // Kad added by me bool CUpDownClient::SendBuddyPing() { SetLastBuddyPingPongTime(); CPacket* buddyPing = new CPacket(OP_BUDDYPING, 0, OP_EMULEPROT); theStats::AddUpOverheadKad(buddyPing->GetPacketSize()); AddDebugLogLineN(logLocalClient,wxT("Local Client: OP_BUDDYPING to ") + GetFullIP()); return SafeSendPacket(buddyPing); } /* Statistics */ void CUpDownClient::UpdateStats() { if (m_lastClientSoft != m_clientSoft || m_lastClientVersion != m_nClientVersion || m_lastOSInfo != m_sClientOSInfo) { if (m_lastClientSoft == SO_UNKNOWN) { theStats::RemoveUnknownClient(); } else if (m_lastClientSoft != (uint32)(-1)) { theStats::RemoveKnownClient(m_lastClientSoft, m_lastClientVersion, m_lastOSInfo); } m_lastClientSoft = m_clientSoft; m_lastClientVersion = m_nClientVersion; m_lastOSInfo = m_sClientOSInfo; if (m_clientSoft == SO_UNKNOWN) { theStats::AddUnknownClient(); } else { theStats::AddKnownClient(this); } } } bool CUpDownClient::IsIdentified() const { return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDENTIFIED); } bool CUpDownClient::IsBadGuy() const { return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDBADGUY); } bool CUpDownClient::SUIFailed() const { return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDFAILED); } bool CUpDownClient::SUINeeded() const { return (credits && credits->GetCurrentIdentState(GetIP()) == IS_IDNEEDED); } bool CUpDownClient::SUINotSupported() const { return (credits && credits->GetCurrentIdentState(GetIP()) == IS_NOTAVAILABLE); } uint64 CUpDownClient::GetDownloadedTotal() const { return credits ? credits->GetDownloadedTotal() : 0; } uint64 CUpDownClient::GetUploadedTotal() const { return credits ? credits->GetUploadedTotal() : 0; } double CUpDownClient::GetScoreRatio() const { return credits ? credits->GetScoreRatio(GetIP(), theApp->CryptoAvailable()) : 0; } const wxString CUpDownClient::GetServerName() const { wxString ret; wxString srvaddr = Uint32toStringIP(GetServerIP()); CServer* cserver = theApp->serverlist->GetServerByAddress( srvaddr, GetServerPort()); if (cserver) { ret = cserver->GetListName(); } else { ret = _("Unknown"); } return ret; } bool CUpDownClient::ShouldReceiveCryptUDPPackets() const { return (thePrefs::IsClientCryptLayerSupported() && SupportsCryptLayer() && theApp->GetPublicIP() != 0 && HasValidHash() && (thePrefs::IsClientCryptLayerRequested() || RequestsCryptLayer()) ); } #ifdef AMULE_DAEMON void CUpDownClient::ProcessCaptchaRequest(CMemFile* WXUNUSED(data)) {} void CUpDownClient::ProcessCaptchaReqRes(uint8 WXUNUSED(nStatus)) {} void CUpDownClient::ProcessChatMessage(const wxString WXUNUSED(message)) {} #else void CUpDownClient::ProcessCaptchaRequest(CMemFile* data) { uint64 id = GUI_ID(GetIP(),GetUserPort()); // received a captcha request, check if we actually accept it (only after sending a message ourself to this client) if (GetChatCaptchaState() == CA_ACCEPTING && GetChatState() != MS_NONE && theApp->amuledlg->m_chatwnd->IsIdValid(id)) { // read tags (for future use) uint8 nTagCount = data->ReadUInt8(); if (nTagCount) { AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client (%s) with (%u) tags")) % GetFullIP() % nTagCount); // and ignore them for now for (uint32 i = 0; i < nTagCount; i++) { CTag tag(*data, true); } } // sanitize checks - we want a small captcha not a wallpaper uint32 nSize = (uint32)(data->GetLength() - data->GetPosition()); if ( nSize > 128 && nSize < 4096 ) { uint64 pos = data->GetPosition(); wxMemoryInputStream memstr(data->GetRawBuffer() + pos, nSize); wxImage imgCaptcha(memstr, wxBITMAP_TYPE_BMP); if (imgCaptcha.IsOk() && imgCaptcha.GetHeight() > 10 && imgCaptcha.GetHeight() < 50 && imgCaptcha.GetWidth() > 10 && imgCaptcha.GetWidth() < 150 ) { m_nChatCaptchaState = CA_CAPTCHARECV; CCaptchaDialog * dialog = new CCaptchaDialog(theApp->amuledlg, imgCaptcha, id); dialog->Show(); } else { AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client, processing image failed or invalid pixel size (%s)")) % GetFullIP()); } } else { AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client, size sanitize check failed (%u) (%s)")) % nSize % GetFullIP()); } } else { AddDebugLogLineN(logClient, CFormat(wxT("Received captcha request from client, but don't accepting it at this time (%s)")) % GetFullIP()); } } void CUpDownClient::ProcessCaptchaReqRes(uint8 nStatus) { uint64 id = GUI_ID(GetIP(),GetUserPort()); if (GetChatCaptchaState() == CA_SOLUTIONSENT && GetChatState() != MS_NONE && theApp->amuledlg->m_chatwnd->IsIdValid(id)) { wxASSERT( nStatus < 3 ); m_nChatCaptchaState = CA_NONE; theApp->amuledlg->m_chatwnd->ShowCaptchaResult(id, nStatus == 0); } else { m_nChatCaptchaState = CA_NONE; AddDebugLogLineN(logClient, CFormat(wxT("Received captcha result from client, but not accepting it at this time (%s)")) % GetFullIP()); } } void CUpDownClient::ProcessChatMessage(wxString message) { if (IsMessageFiltered(message)) { AddLogLineC(CFormat(_("Message filtered from '%s' (IP:%s)")) % GetUserName() % GetFullIP()); return; } // advanced spamfilter check if (thePrefs::IsChatCaptchaEnabled() && !IsFriend()) { // captcha checks outrank any further checks - if the captcha has been solved, we assume it's not spam // first check if we need to send a captcha request to this client if (GetMessagesSent() == 0 && GetMessagesReceived() == 0 && GetChatCaptchaState() != CA_CAPTCHASOLVED) { // we have never sent a message to this client, and no message from him has ever passed our filters if (GetChatCaptchaState() != CA_CHALLENGESENT) { // we also aren't currently expecting a captcha response if (m_fSupportsCaptcha) { // and he supports captcha, so send him one and store the message (without showing for now) if (m_cCaptchasSent < 3) { // no more than 3 tries m_strCaptchaPendingMsg = message; wxMemoryOutputStream memstr; memstr.PutC(0); // no tags, for future use CCaptchaGenerator captcha(4); if (captcha.WriteCaptchaImage(memstr)){ m_strCaptchaChallenge = captcha.GetCaptchaText(); m_nChatCaptchaState = CA_CHALLENGESENT; m_cCaptchasSent++; CMemFile fileAnswer((byte*) memstr.GetOutputStreamBuffer()->GetBufferStart(), memstr.GetLength()); CPacket* packet = new CPacket(fileAnswer, OP_EMULEPROT, OP_CHATCAPTCHAREQ); theStats::AddUpOverheadOther(packet->GetPacketSize()); AddLogLineN(CFormat(wxT("sent Captcha %s (%d)")) % m_strCaptchaChallenge % packet->GetPacketSize()); SafeSendPacket(packet); } else { wxFAIL; } } } else { // client doesn't support captchas, but we require them, tell him that it's not going to work out // with an answer message (will not be shown and doesn't count as sent message) if (m_cCaptchasSent < 1) { // don't send this notifier more than once m_cCaptchasSent++; // always sent in english SendChatMessage(wxT("In order to avoid spam messages, this user requires you to solve a captcha before you can send a message to him. However your client does not supports captchas, so you will not be able to chat with this user.")); AddDebugLogLineN(logClient, CFormat(wxT("Received message from client not supporting captchas, filtered and sent notifier (%s)")) % GetClientFullInfo()); } else { AddDebugLogLineN(logClient, CFormat(wxT("Received message from client not supporting captchas, filtered, didn't send notifier (%s)")) % GetClientFullInfo()); } } return; } else { // (GetChatCaptchaState() == CA_CHALLENGESENT) // this message must be the answer to the captcha request we sent him, let's verify wxASSERT( !m_strCaptchaChallenge.IsEmpty() ); if (m_strCaptchaChallenge.CmpNoCase(message.Trim().Right(std::min(message.Length(), m_strCaptchaChallenge.Length()))) == 0) { // allright AddDebugLogLineN(logClient, CFormat(wxT("Captcha solved, showing withheld message (%s)")) % GetClientFullInfo()); m_nChatCaptchaState = CA_CAPTCHASOLVED; // this state isn't persitent, but the messagecounter will be used to determine later if the captcha has been solved // replace captchaanswer with withheld message and show it message = m_strCaptchaPendingMsg; m_cCaptchasSent = 0; m_strCaptchaChallenge.Clear(); CPacket* packet = new CPacket(OP_CHATCAPTCHARES, 1, OP_EMULEPROT, false); byte statusResponse = 0; // status response packet->CopyToDataBuffer(0, &statusResponse, 1); theStats::AddUpOverheadOther(packet->GetPacketSize()); SafeSendPacket(packet); } else { // wrong, cleanup and ignore AddDebugLogLineN(logClient, CFormat(wxT("Captcha answer failed (%s)")) % GetClientFullInfo()); m_nChatCaptchaState = CA_NONE; m_strCaptchaChallenge.Clear(); m_strCaptchaPendingMsg.Clear(); CPacket* packet = new CPacket(OP_CHATCAPTCHARES, 1, OP_EMULEPROT, false); byte statusResponse = (m_cCaptchasSent < 3) ? 1 : 2; // status response packet->CopyToDataBuffer(0, &statusResponse, 1); theStats::AddUpOverheadOther(packet->GetPacketSize()); SafeSendPacket(packet); return; // nothing more todo } } } } if (thePrefs::IsAdvancedSpamfilterEnabled() && !IsFriend()) { // friends are never spammer... (but what if two spammers are friends :P ) bool bIsSpam = false; if (m_fIsSpammer) { bIsSpam = true; } else { // first fixed criteria: If a client sends me an URL in his first message before I respond to him // there is a 99,9% chance that it is some poor guy advising his leech mod, or selling you .. well you know :P if (GetMessagesSent() == 0) { static wxArrayString urlindicators(wxStringTokenize(wxT("http:|www.|.de |.net |.com |.org |.to |.tk |.cc |.fr |ftp:|ed2k:|https:|ftp.|.info|.biz|.uk|.eu|.es|.tv|.cn|.tw|.ws|.nu|.jp"), wxT("|"))); for (size_t pos = urlindicators.GetCount(); pos--;) { if (message.Find(urlindicators[pos]) != wxNOT_FOUND) { bIsSpam = true; break; } } // second fixed criteria: he sent me 4 or more messages and I didn't answer him once if (GetMessagesReceived() > 3) { bIsSpam = true; } } } if (bIsSpam) { AddDebugLogLineN(logClient, CFormat(wxT("'%s' has been marked as spammer")) % GetUserName()); SetSpammer(true); theApp->amuledlg->m_chatwnd->EndSession(GUI_ID(GetIP(),GetUserPort())); return; } } wxString logMsg = CFormat(_("New message from '%s' (IP:%s)")) % GetUserName() % GetFullIP(); if(thePrefs::ShowMessagesInLog()) { logMsg += wxT(": ") + message; } AddLogLineC(logMsg); IncMessagesReceived(); Notify_ChatProcessMsg(GUI_ID(GetIP(), GetUserPort()), GetUserName() + wxT("|") + message); } bool CUpDownClient::IsMessageFiltered(const wxString& message) { bool filtered = false; // If we're chatting to the guy, we don't want to filter! if (GetChatState() != MS_CHATTING) { if (thePrefs::MsgOnlyFriends() && !IsFriend()) { filtered = true; } else if (thePrefs::MsgOnlySecure() && GetUserName().IsEmpty() ) { filtered = true; } else if (thePrefs::MustFilterMessages()) { filtered = thePrefs::IsMessageFiltered(message); } } if (filtered) { SetSpammer(true); } return filtered; } #endif void CUpDownClient::SendSharedDirectories() { // This list will contain all (unique) folders. PathList foldersToSend; // The shared folders const unsigned folderCount = theApp->glob_prefs->shareddir_list.size(); for (unsigned i = 0; i < folderCount; ++i) { foldersToSend.push_back(theApp->glob_prefs->shareddir_list[i]); } // ... the categories folders ... (category 0 -> incoming) for (unsigned i = 0; i < theApp->glob_prefs->GetCatCount(); ++i) { foldersToSend.push_back(theApp->glob_prefs->GetCategory(i)->path); } // Strip duplicates foldersToSend.sort(); foldersToSend.unique(); // Build packet CMemFile tempfile(80); tempfile.WriteUInt32(foldersToSend.size() + 1); // + 1 for the incomplete files PathList::iterator it = foldersToSend.begin(); for (; it != foldersToSend.end(); ++it) { // Note: the public shared name contains the 'raw' path, so we can recognize it again. // the 'raw' path is determined using CPath::GetRaw() tempfile.WriteString( theApp->sharedfiles->GetPublicSharedDirName(*it), GetUnicodeSupport() ); } // ... and the Magic thing from the eDonkey Hybrids... tempfile.WriteString(OP_INCOMPLETE_SHARED_FILES, GetUnicodeSupport()); // Send the packet. CPacket* replypacket = new CPacket(tempfile, OP_EDONKEYPROT, OP_ASKSHAREDDIRSANS); theStats::AddUpOverheadOther(replypacket->GetPacketSize()); AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDDIRSANS to ") + GetFullIP() ); SendPacket(replypacket, true, true); } void CUpDownClient::SendSharedFilesOfDirectory(const wxString& strReqDir) { CKnownFilePtrList list; if (strReqDir == OP_INCOMPLETE_SHARED_FILES) { // get all shared files from download queue int iQueuedFiles = theApp->downloadqueue->GetFileCount(); for (int i = 0; i < iQueuedFiles; i++) { CPartFile* pFile = theApp->downloadqueue->GetFileByIndex(i); if (pFile == NULL || pFile->GetStatus(true) != PS_READY) { continue; } list.push_back(pFile); } } else { // get all shared files for the requested directory const CPath *sharedDir = theApp->sharedfiles->GetDirForPublicSharedDirName(strReqDir); if (sharedDir) { theApp->sharedfiles->GetSharedFilesByDirectory(sharedDir->GetRaw(), list); } else { AddLogLineC(CFormat(_("User %s (%u) requested sharedfiles-list for not existing directory '%s' -> Ignored")) % GetUserName() % GetUserIDHybrid() % strReqDir); } } CMemFile tempfile(80); tempfile.WriteString(strReqDir, GetUnicodeSupport()); tempfile.WriteUInt32(list.size()); while (!list.empty()) { if (!list.front()->IsLargeFile() || SupportsLargeFiles()) { list.front()->CreateOfferedFilePacket(&tempfile, NULL, this); } list.pop_front(); } CPacket* replypacket = new CPacket(tempfile, OP_EDONKEYPROT, OP_ASKSHAREDFILESDIRANS); theStats::AddUpOverheadOther(replypacket->GetPacketSize()); AddDebugLogLineN( logLocalClient, wxT("Local Client: OP_ASKSHAREDFILESDIRANS to ") + GetFullIP() ); SendPacket(replypacket, true, true); } void CUpDownClient::SendFirewallCheckUDPRequest() { wxASSERT(GetKadState() == KS_FWCHECK_UDP); if (!Kademlia::CKademlia::IsRunning()) { SetKadState(KS_NONE); return; } else if (GetUploadState() != US_NONE || GetDownloadState() != DS_NONE || GetChatState() != MS_NONE || GetKadVersion() <= 5 || GetKadPort() == 0) { Kademlia::CUDPFirewallTester::SetUDPFWCheckResult(false, true, wxUINT32_SWAP_ALWAYS(GetIP()), 0); // inform the tester that this test was cancelled SetKadState(KS_NONE); return; } CMemFile data; data.WriteUInt16(Kademlia::CKademlia::GetPrefs()->GetInternKadPort()); data.WriteUInt16(Kademlia::CKademlia::GetPrefs()->GetExternalKadPort()); data.WriteUInt32(Kademlia::CKademlia::GetPrefs()->GetUDPVerifyKey(GetConnectIP())); CPacket* packet = new CPacket(data, OP_EMULEPROT, OP_FWCHECKUDPREQ); theStats::AddUpOverheadKad(packet->GetPacketSize()); SafeSendPacket(packet); } void CUpDownClient::ProcessFirewallCheckUDPRequest(CMemFile* data) { if (!Kademlia::CKademlia::IsRunning() || Kademlia::CKademlia::GetUDPListener() == NULL) { //DebugLogWarning(_T("Ignored Kad Firewallrequest UDP because Kad is not running (%s)"), GetClientFullInfo()); return; } // first search if we know this IP already, if so the result might be biased and we need tell the requester bool errorAlreadyKnown = false; if (GetUploadState() != US_NONE || GetDownloadState() != DS_NONE || GetChatState() != MS_NONE) { errorAlreadyKnown = true; } else if (Kademlia::CKademlia::GetRoutingZone()->GetContact(wxUINT32_SWAP_ALWAYS(GetConnectIP()), 0, false) != NULL) { errorAlreadyKnown = true; } uint16_t remoteInternPort = data->ReadUInt16(); uint16_t remoteExternPort = data->ReadUInt16(); uint32_t senderKey = data->ReadUInt32(); if (remoteInternPort == 0) { //DebugLogError(_T("UDP Firewallcheck requested with Intern Port == 0 (%s)"), GetClientFullInfo()); return; } // if (senderKey == 0) // DebugLogWarning(_T("UDP Firewallcheck requested with SenderKey == 0 (%s)"), GetClientFullInfo()); CMemFile testPacket1; testPacket1.WriteUInt8(errorAlreadyKnown ? 1 : 0); testPacket1.WriteUInt16(remoteInternPort); DebugSend(Kad2FirewallUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteInternPort); Kademlia::CKademlia::GetUDPListener()->SendPacket(testPacket1, KADEMLIA2_FIREWALLUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteInternPort, Kademlia::CKadUDPKey(senderKey, theApp->GetPublicIP(false)), NULL); // if the client has a router with PAT (and therefore a different extern port than intern), test this port too if (remoteExternPort != 0 && remoteExternPort != remoteInternPort) { CMemFile testPacket2; testPacket2.WriteUInt8(errorAlreadyKnown ? 1 : 0); testPacket2.WriteUInt16(remoteExternPort); DebugSend(Kad2FirewalledUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteExternPort); Kademlia::CKademlia::GetUDPListener()->SendPacket(testPacket2, KADEMLIA2_FIREWALLUDP, wxUINT32_SWAP_ALWAYS(GetConnectIP()), remoteExternPort, Kademlia::CKadUDPKey(senderKey, theApp->GetPublicIP(false)), NULL); } //DebugLog(_T("Answered UDP Firewallcheck request (%s)"), GetClientFullInfo()); } void CUpDownClient::SetConnectOptions(uint8_t options, bool encryption, bool callback) { SetCryptLayerSupport((options & 0x01) != 0 && encryption); SetCryptLayerRequest((options & 0x02) != 0 && encryption); SetCryptLayerRequires((options & 0x04) != 0 && encryption); SetDirectUDPCallbackSupport((options & 0x08) != 0 && callback); } #ifdef DEBUG_ZOMBIE_CLIENTS void CUpDownClient::Unlink(const wxString& from) { std::multiset<wxString>::iterator it = m_linkedFrom.find(from); if (it != m_linkedFrom.end()) { m_linkedFrom.erase(it); } m_linked--; if (!m_linked) { if (m_linkedDebug) { AddLogLineN(CFormat(wxT("Last reference to client %d %p unlinked, delete it.")) % ECID() % this); } delete this; } } #else void CUpDownClient::Unlink() { m_linked--; if (!m_linked) { delete this; } } #endif // File_checked_for_headers
hlechner/hl-test
amule/src/BaseClient.cpp
C++
gpl-3.0
96,820
/* * An Abstract communicator interface which implements listeners. */ /* Copywrite 2013 Will Winder This file is part of Universal Gcode Sender (UGS). UGS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. UGS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with UGS. If not, see <http://www.gnu.org/licenses/>. */ package com.willwinder.universalgcodesender; import com.willwinder.universalgcodesender.i18n.Localization; import com.willwinder.universalgcodesender.listeners.SerialCommunicatorListener; import com.willwinder.universalgcodesender.types.GcodeCommand; import java.io.IOException; import java.util.ArrayList; /** * * @author wwinder */ public abstract class AbstractCommunicator { public static String DEFAULT_TERMINATOR = "\r\n"; private String lineTerminator; protected Connection conn; // Callback interfaces ArrayList<SerialCommunicatorListener> commandSentListeners; ArrayList<SerialCommunicatorListener> commandCompleteListeners; ArrayList<SerialCommunicatorListener> commConsoleListeners; ArrayList<SerialCommunicatorListener> commVerboseConsoleListeners; ArrayList<SerialCommunicatorListener> commRawResponseListener; private final ArrayList<Connection> connections; public AbstractCommunicator() { this.lineTerminator = DEFAULT_TERMINATOR; this.commandSentListeners = new ArrayList<SerialCommunicatorListener>(); this.commandCompleteListeners = new ArrayList<SerialCommunicatorListener>(); this.commConsoleListeners = new ArrayList<SerialCommunicatorListener>(); this.commVerboseConsoleListeners = new ArrayList<SerialCommunicatorListener>(); this.commRawResponseListener = new ArrayList<SerialCommunicatorListener>(); //instanciate all known connection drivers //TODO: Scan the classpath for classes extending Connection, // and instantiate them dynamically. this.connections = new ArrayList<Connection>(); this.addConnectionType(new SerialConnection()); } final public void addConnectionType(Connection conn) { this.connections.add(conn); } /*********************/ /* Serial Layer API. */ /*********************/ abstract public void setSingleStepMode(boolean enable); abstract public boolean getSingleStepMode(); abstract public void queueStringForComm(final String input); abstract public void sendByteImmediately(byte b) throws IOException; abstract public boolean areActiveCommands(); abstract public void streamCommands(); abstract public void pauseSend(); abstract public void resumeSend(); abstract public void cancelSend(); abstract public void softReset(); abstract public void responseMessage(String response); //do common operations (related to the connection, that is shared by all communicators) protected boolean openCommPort(String name, int baud) throws Exception { //choose port for(Connection candidate: connections) { if(candidate.supports(name)) { conn = candidate; conn.setCommunicator(this); break; } } if(conn==null) { throw new Exception(Localization.getString("communicator.exception.port") + ": "+name); } //open it conn.openPort(name, baud); return true; } //do common things (related to the connection, that is shared by all communicators) protected void closeCommPort() { conn.closePort(); } /** Getters & Setters. */ void setLineTerminator(String terminator) { if (terminator == null || terminator.length() < 1) { this.lineTerminator = DEFAULT_TERMINATOR; } else { this.lineTerminator = terminator; } } String getLineTerminator() { return this.lineTerminator; } /* ****************** */ /** Listener helpers. */ /* ****************** */ void setListenAll(SerialCommunicatorListener scl) { this.addCommandSentListener(scl); this.addCommandCompleteListener(scl); this.addCommConsoleListener(scl); this.addCommVerboseConsoleListener(scl); this.addCommRawResponseListener(scl); } void addCommandSentListener(SerialCommunicatorListener scl) { this.commandSentListeners.add(scl); } void addCommandCompleteListener(SerialCommunicatorListener scl) { this.commandCompleteListeners.add(scl); } void addCommConsoleListener(SerialCommunicatorListener scl) { this.commConsoleListeners.add(scl); } void addCommVerboseConsoleListener(SerialCommunicatorListener scl) { this.commVerboseConsoleListeners.add(scl); } void addCommRawResponseListener(SerialCommunicatorListener scl) { this.commRawResponseListener.add(scl); } // Helper for the console listener. protected void sendMessageToConsoleListener(String msg) { this.sendMessageToConsoleListener(msg, false); } protected void sendMessageToConsoleListener(String msg, boolean verbose) { // Exit early if there are no listeners. if (this.commConsoleListeners == null) { return; } int verbosity; if (!verbose) { verbosity = CONSOLE_MESSAGE; } else { verbosity = VERBOSE_CONSOLE_MESSAGE; } dispatchListenerEvents(verbosity, this.commConsoleListeners, msg); } // Serial Communicator Listener Events protected static final int COMMAND_SENT = 1; protected static final int COMMAND_COMPLETE = 2; protected static final int RAW_RESPONSE = 3; protected static final int CONSOLE_MESSAGE = 4; protected static final int VERBOSE_CONSOLE_MESSAGE = 5; /** * A bunch of methods to dispatch listener events with various arguments. */ static protected void dispatchListenerEvents(int event, ArrayList<SerialCommunicatorListener> sclList, String message) { if (sclList != null) { for (SerialCommunicatorListener s : sclList) { sendEventToListener(event, s, message, null); } } } static protected void dispatchListenerEvents(int event, ArrayList<SerialCommunicatorListener> sclList, GcodeCommand command) { if (sclList != null) { for (SerialCommunicatorListener s : sclList) { sendEventToListener(event, s, null, command); } } } static protected void sendEventToListener(int event, SerialCommunicatorListener scl, String string, GcodeCommand command) { switch(event) { case COMMAND_SENT: scl.commandSent(string); break; case CONSOLE_MESSAGE: scl.messageForConsole(string); break; case VERBOSE_CONSOLE_MESSAGE: scl.verboseMessageForConsole(string); break; case RAW_RESPONSE: scl.rawResponseListener(string); default: } } }
shapeoko/Universal-G-Code-Sender
src/com/willwinder/universalgcodesender/AbstractCommunicator.java
Java
gpl-3.0
7,779
/* * Copyright (c) "Neo4j" * Neo4j Sweden AB [http://neo4j.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import ManualLink from 'browser-components/ManualLink' const title = 'FOREACH' const subtitle = 'Operate on a collection' const category = 'cypherHelp' const content = ( <> <p> The <code>FOREACH</code> clause is used to update data within a collection whether components of a path, or result of aggregation. </p> <div className="links"> <div className="link"> <p className="title">Reference</p> <p className="content"> <ManualLink chapter="cypher-manual" page="/clauses/foreach/"> FOREACH </ManualLink>{' '} manual page </p> </div> <div className="link"> <p className="title">Related</p> <p className="content"> <a help-topic="create">:help CREATE</a> <a help-topic="delete">:help DELETE</a> <a help-topic="set">:help SET</a> <a help-topic="cypher">:help Cypher</a> </p> </div> </div> <section className="example"> <figure className="runnable"> <pre> {`MATCH p = (ups)<-[DEPENDS_ON]-(device) WHERE ups.id='EPS-7001' FOREACH (n IN nodes(p) | SET n.available = FALSE )`} </pre> <figcaption> Mark all devices plugged into a failed UPS as unavailable. </figcaption> </figure> </section> </> ) export default { title, subtitle, category, content }
neo4j/neo4j-browser
src/browser/documentation/help/foreach.tsx
TypeScript
gpl-3.0
2,176
/* * Unplayer * Copyright (C) 2015-2019 Alexey Rochev <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "queuemodel.h" #include "queue.h" namespace unplayer { QVariant QueueModel::data(const QModelIndex& index, int role) const { if (!mQueue || !index.isValid()) { return QVariant(); } const QueueTrack* track = mQueue->tracks()[static_cast<size_t>(index.row())].get(); switch (role) { case UrlRole: return track->url; case IsLocalFileRole: return track->url.isLocalFile(); case FilePathRole: return track->url.path(); case TitleRole: return track->title; case ArtistRole: return track->artist; case DisplayedArtistRole: return track->artist; case AlbumRole: return track->album; case DisplayedAlbumRole: return track->album; case DurationRole: return track->duration; default: return QVariant(); } } int QueueModel::rowCount(const QModelIndex&) const { return mQueue ? static_cast<int>(mQueue->tracks().size()) : 0; } Queue* QueueModel::queue() const { return mQueue; } void QueueModel::setQueue(Queue* queue) { if (queue == mQueue || !queue) { return; } mQueue = queue; QObject::connect(mQueue, &Queue::tracksAboutToBeAdded, this, [=](int count) { const int first = rowCount(); beginInsertRows(QModelIndex(), first, first + count - 1); }); QObject::connect(mQueue, &Queue::tracksAdded, this, [=]() { endInsertRows(); }); QObject::connect(mQueue, &Queue::trackAboutToBeRemoved, this, [=](int index) { beginRemoveRows(QModelIndex(), index, index); }); QObject::connect(mQueue, &Queue::trackRemoved, this, [=]() { endRemoveRows(); }); QObject::connect(mQueue, &Queue::aboutToBeCleared, this, [=]() { beginRemoveRows(QModelIndex(), 0, rowCount() - 1); }); QObject::connect(mQueue, &Queue::cleared, this, [=]() { endRemoveRows(); }); } QHash<int, QByteArray> QueueModel::roleNames() const { return {{UrlRole, "url"}, {IsLocalFileRole, "isLocalFile"}, {FilePathRole, "filePath"}, {TitleRole, "title"}, {ArtistRole, "artist"}, {DisplayedArtistRole, "displayedArtist"}, {AlbumRole, "album"}, {DisplayedAlbumRole, "displayedAlbum"}, {DurationRole, "duration"}}; } }
equeim/unplayer
src/queuemodel.cpp
C++
gpl-3.0
3,387
#!/usr/bin/env node 'use strict'; /*All Includes needed for the Bot Core*/ var isfile = function(name) { require('fs').exists(name, function(exists) { return exists; }); }; var jsonfile = require('jsonfile'); var configfile = 'config.json'; var Event = require('./modules/Events').eventBus; // One way Events from the Main Core System var DiscordProxy = require('./modules/DiscordProxy'); // Proxy between Core & Plugins var Discord = require('discord.io'); // Required for the Bot to do anything with Discord var Plugins = require('require-all')(__dirname + '/plugins');//Loads all Plugins into the Bot var express = require('express'); var app = express(); var bodyparser = require("body-parser"); var mongoose = require('mongoose'); /*System Related Variables & Checks*/ var SYSTEM = { CURRENT_VERSION: require('./package.json').version, LATEST_VERSION: null, NPM_URL: "https://registry.npmjs.org/devbot", HOMEPAGE_URL: require('./package.json').repository.url, BUGREPORT_URL: require('./package.json').bugs.url, AUTHOR: require('./package.json').author.name + " <" + require('./package.json').author.email + ">", WEB: { IP: "127.0.0.1", PORT: 1337, MONGODB: "mongodb://localhost" } CONFIG: null }; console.log(` ▓█████▄ ▓█████ ██▒ █▓ ▄▄▄▄ ▒█████ ▄▄▄█████▓ ▒██▀ ██▌▓█ ▀▓██░ █▒▓█████▄ ▒██▒ ██▒▓ ██▒ ▓▒ ░██ █▌▒███ ▓██ █▒░▒██▒ ▄██▒██░ ██▒▒ ▓██░ ▒░ ░▓█▄ ▌▒▓█ ▄ ▒██ █░░▒██░█▀ ▒██ ██░░ ▓██▓ ░ ░▒████▓ ░▒████▒ ▒▀█░ ░▓█ ▀█▓░ ████▓▒░ ▒██▒ ░ ▒▒▓ ▒ ░░ ▒░ ░ ░ ▐░ ░▒▓███▀▒░ ▒░▒░▒░ ▒ ░░ ░ ▒ ▒ ░ ░ ░ ░ ░░ ▒░▒ ░ ░ ▒ ▒░ ░ ░ ░ ░ ░ ░░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ `); console.log("Current Version: " + SYSTEM.CURRENT_VERSION); console.log("Created by: " SYSTEM.AUTHOR) require("request").get(SYSTEM.NPM_URL, function (err, res, body) { if (err) { console.log("[ERROR] There was a Error Checking the NPM Registry for Version Information!\nBot Shutting Down....."); process.exit(); } console.log("[UPDATE CHECK] Checking for Update...."); var data = JSON.parse((body)); var NPM_VERSION = data['dist-tags'].latest; if (require("semver").lt(SYSTEM.CURRENT_VERSION, NPM_VERSION)) { console.log("[UPDATE THE BOT]: This BOT is out of date! Your version is (" + SYSTEM.CURRENT_VERSION + ") but the latest version on NPM is (" + NPM_VERSION + ")\nWhen are you going to Update HUH!"); } else { console.log("[UPDATE CHECKED] No Updates Found!"); } if (isfile(configfile) == false) { console.log("[SETUP START] Seems like this is the first time the bot has been Launched. \n[CONFIG CREATION] Creating config.json and filling it up. Please wait a momment......"); var data = { TOKEN: null, TRIGGER: "!", OWNER: null }; jsonfile.writeFile(configfile,data, function(err) { if (err) { console.log("[ERROR] Error in creating the Config file.\n[ERROR] Please check the permissions. Application Terminating....."); process.exit(); } else { console.log("[SETUP COMPLETE] Seems to be all Set. Please edit the " + configfile + " adding the Discord Bot Token information.\nProcess will Close now!"); process.exit(); } }); } else { console.log("[INFORMATION] Config file found! Loading......."); jsonfile.readFile(configfile, function(err, data) { if (err) { console.log("Error in Parsing and Loading the Config file.\nPlease check the permissions.\nApplication Terminating....."); process.exit(); } else { SYSTEM.CONFIG = data; if (SYSTEM.CONFIG.TOKEN == null) { console.log("[SETUP REQUIRED] Please edit the " + configfile + " adding the Discord Bot Token information.\nProcess will Close now!"); process.exit(); } else if (SYSTEM.CONFIG.OWNER == null) { console.log("[SETUP REQUIRED] Please edit the " + configfile + " adding the Discord Bot Owner ID.\nProcess will Close now!"); process.exit(); } else { app.use(bodyparser.urlencoded({ extended: true })); app.use(bodyparser.json()); var Client = new Discord.Client({ token: SYSTEM.CONFIG.TOKEN }); DiscordProxy.addClient(Client); DiscordProxy.registerOwner(SYSTEM.CONFIG.OWNER); Client.on('ready', function(event) { console.log("[DISCORD] Connected!"); Event.emit("status", true); }); Client.on('disconnect', function(errMsg, code) { console.log("[DISCORD] Disconnected!"); Event.emit("status", false); Client.connect(); }); Client.on('message', function(user, userID, channelID, message, event) { if (Client.id == userID) return; Event.emit("message", user, userID, channelID, message, event); var arr = message.split(" "); if (arr[0].charAt(0) == SYSTEM.CONFIG.TRIGGER) { Event.emit("command", arr[0].slice(1), user, userID, channelID, message); } else if (arr[0].indexOf(Client.id.toString()) > 1) { Event.emit("direct_command", arr[1], user, userID, channelID, message); } }); Client.on('presence', function(user, userID, status, game, event) { Event.emit("presence", user, userID, status, game, event); }); app.post("/api/webhook/:webhook/:name", function(req, res) { console.log("[WEBHOOK RECEIVED] Received a webhook from " + req.params.webhook.toLowerCase() + " for " + req.params.name.toLowerCase()); Event.emit("webhook", req.params.webhook.toLowerCase(), req.params.name.toLowerCase(), req.headers, req.body); res.status(200).json({ success: true }); }); app.listen(SYSTEM.WEB.IP, SYSTEM.WEB.PORT, function() { mongoose.connect(SYSTEM.WEB.MONGODB); Client.connect(); console.log("[BOT] API Handling System Online!"); }); } } }); } });
Bioblaze/Devbot
bot.js
JavaScript
gpl-3.0
6,811
<div class="main-title">15, Sunday <span>2016</span> </div> <ul class="stage clearfix"> <a class="calendar-history poster tasklist-green"> <div class="max-constrain"> <div class="first-20"> <div class="cal-from"><strong>20:15 <small>GMT</small></strong></div> <div class="cal-to"><strong>22:00 <small>GMT</small></strong></div> </div> <div class="second-40"> <div class="teams">Aldosivi <br><small>vs</small> <br>Atl. Rafaela</div><em><i class="fa fa-map-marker"></i>Argentina - Primera Division</em></div> <div class="third-40 last-column"> <div class="over-under-hist"> <div class="over-under-icon-hist"> <div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div> <div class="over-under-number-hist">2.5</div> </div> </div> <div class="result-top-win-hist uppercase">WIN</div> </div> </div> </a> <a class="calendar-history poster tasklist-green"> <div class="max-constrain"> <div class="first-20"> <div class="cal-from"><strong>22:30 <small>GMT</small></strong></div> <div class="cal-to"><strong>0:15 <small>GMT</small></strong></div> </div> <div class="second-40"> <div class="teams">Barcelona SC <br><small>vs</small> <br>Emelec</div><em><i class="fa fa-map-marker"></i>Ecuador - Serie A</em></div> <div class="third-40 last-column"> <div class="over-under-hist"> <div class="over-under-icon-hist"> <div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div> <div class="over-under-number-hist">2.5</div> </div> </div> <div class="result-top-win-hist uppercase">WIN</div> </div> </div> </a> <a class="calendar-history poster tasklist-red"> <div class="max-constrain"> <div class="first-20"> <div class="cal-from"><strong>15:00 <small>GMT</small></strong></div> <div class="cal-to"><strong>16:45 <small>GMT</small></strong></div> </div> <div class="second-40"> <div class="teams">Chelsea <br><small>vs</small> <br>Leicester City</div><em><i class="fa fa-map-marker"></i>England - Premier League</em></div> <div class="third-40 last-column"> <div class="over-under-hist"> <div class="over-under-icon-hist"> <div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div> <div class="over-under-number-hist">2.5</div> </div> </div> <div class="result-top-loss-hist uppercase">LOSS</div> </div> </div> </a> <a class="calendar-history poster tasklist-green"> <div class="max-constrain"> <div class="first-20"> <div class="cal-from"><strong>16:00 <small>GMT</small></strong></div> <div class="cal-to"><strong>17:45 <small>GMT</small></strong></div> </div> <div class="second-40"> <div class="teams">Dinamo-Auto <br><small>vs</small> <br>Milsami Orhei</div><em><i class="fa fa-map-marker"></i>Moldova - Divizia Nationala</em></div> <div class="third-40 last-column"> <div class="over-under-hist"> <div class="over-under-icon-hist"> <div class="over-under-number-hist">2.5</div> <div class="over-under-text-under-hist uppercase">Under<i class="fa fa-angle-down"></i></div> </div> </div> <div class="result-top-win-hist uppercase">WIN</div> </div> </div> </a> <a class="calendar-history poster tasklist-green"> <div class="max-constrain"> <div class="first-20"> <div class="cal-from"><strong>15:00 <small>GMT</small></strong></div> <div class="cal-to"><strong>16:45 <small>GMT</small></strong></div> </div> <div class="second-40"> <div class="teams">Everton <br><small>vs</small> <br>Norwich City</div><em><i class="fa fa-map-marker"></i>England - Premier League</em></div> <div class="third-40 last-column"> <div class="over-under-hist"> <div class="over-under-icon-hist"> <div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div> <div class="over-under-number-hist">2.5</div> </div> </div> <div class="result-top-win-hist uppercase">WIN</div> </div> </div> </a> <a class="calendar-history poster tasklist-red"> <div class="max-constrain"> <div class="first-20"> <div class="cal-from"><strong>2:00 <small>GMT</small></strong></div> <div class="cal-to"><strong>3:45 <small>GMT</small></strong></div> </div> <div class="second-40"> <div class="teams">FBC Melgar <br><small>vs</small> <br>UTC Cajamarca</div><em><i class="fa fa-map-marker"></i>Peru - Primera Division</em></div> <div class="third-40 last-column"> <div class="over-under-hist"> <div class="over-under-icon-hist"> <div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div> <div class="over-under-number-hist">2.5</div> </div> </div> <div class="result-top-loss-hist uppercase">LOSS</div> </div> </div> </a> <a class="calendar-history poster tasklist-green"> <div class="max-constrain"> <div class="first-20"> <div class="cal-from"><strong>22:00 <small>GMT</small></strong></div> <div class="cal-to"><strong>23:45 <small>GMT</small></strong></div> </div> <div class="second-40"> <div class="teams">Guaraní PRG <br><small>vs</small> <br>Sol de América</div><em><i class="fa fa-map-marker"></i>Paraguay - Division Profesional</em></div> <div class="third-40 last-column"> <div class="over-under-hist"> <div class="over-under-icon-hist"> <div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div> <div class="over-under-number-hist">2.5</div> </div> </div> <div class="result-top-win-hist uppercase">WIN</div> </div> </div> </a> <a class="calendar-history poster tasklist-red"> <div class="max-constrain"> <div class="first-20"> <div class="cal-from"><strong>13:00 <small>GMT</small></strong></div> <div class="cal-to"><strong>14:45 <small>GMT</small></strong></div> </div> <div class="second-40"> <div class="teams">OB Odense <br><small>vs</small> <br>Hobro IK</div><em><i class="fa fa-map-marker"></i>Denmark - Superligaen</em></div> <div class="third-40 last-column"> <div class="over-under-hist"> <div class="over-under-icon-hist"> <div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div> <div class="over-under-number-hist">2.5</div> </div> </div> <div class="result-top-loss-hist uppercase">LOSS</div> </div> </div> </a> <a class="calendar-history poster tasklist-green"> <div class="max-constrain"> <div class="first-20"> <div class="cal-from"><strong>3:00 <small>GMT</small></strong></div> <div class="cal-to"><strong>4:45 <small>GMT</small></strong></div> </div> <div class="second-40"> <div class="teams">Orange County B <br><small>vs</small> <br>Arizona United</div><em><i class="fa fa-map-marker"></i>USA - USL</em></div> <div class="third-40 last-column"> <div class="over-under-hist"> <div class="over-under-icon-hist"> <div class="over-under-number-hist">2.5</div> <div class="over-under-text-under-hist uppercase">Under<i class="fa fa-angle-down"></i></div> </div> </div> <div class="result-top-win-hist uppercase">WIN</div> </div> </div> </a> <a class="calendar-history poster tasklist-green"> <div class="max-constrain"> <div class="first-20"> <div class="cal-from"><strong>22:00 <small>GMT</small></strong></div> <div class="cal-to"><strong>23:45 <small>GMT</small></strong></div> </div> <div class="second-40"> <div class="teams">Rubio Nu <br><small>vs</small> <br>Olimpia PRG</div><em><i class="fa fa-map-marker"></i>Paraguay - Division Profesional</em></div> <div class="third-40 last-column"> <div class="over-under-hist"> <div class="over-under-icon-hist"> <div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div> <div class="over-under-number-hist">2.5</div> </div> </div> <div class="result-top-win-hist uppercase">WIN</div> </div> </div> </a> <a class="calendar-history poster tasklist-green"> <div class="max-constrain"> <div class="first-20"> <div class="cal-from"><strong>22:00 <small>GMT</small></strong></div> <div class="cal-to"><strong>23:45 <small>GMT</small></strong></div> </div> <div class="second-40"> <div class="teams">Sport. Luqueño <br><small>vs</small> <br>Nacional PRG</div><em><i class="fa fa-map-marker"></i>Paraguay - Division Profesional</em></div> <div class="third-40 last-column"> <div class="over-under-hist"> <div class="over-under-icon-hist"> <div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div> <div class="over-under-number-hist">2.5</div> </div> </div> <div class="result-top-win-hist uppercase">WIN</div> </div> </div> </a> <a class="calendar-history poster tasklist-green"> <div class="max-constrain"> <div class="first-20"> <div class="cal-from"><strong>16:00 <small>GMT</small></strong></div> <div class="cal-to"><strong>17:45 <small>GMT</small></strong></div> </div> <div class="second-40"> <div class="teams">Travnik <br><small>vs</small> <br>Drina Zvornik</div><em><i class="fa fa-map-marker"></i>Bosnia - Premier Liga</em></div> <div class="third-40 last-column"> <div class="over-under-hist"> <div class="over-under-icon-hist"> <div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div> <div class="over-under-number-hist">2.5</div> </div> </div> <div class="result-top-win-hist uppercase">WIN</div> </div> </div> </a> <a class="calendar-history poster tasklist-red"> <div class="max-constrain"> <div class="first-20"> <div class="cal-from"><strong>17:00 <small>GMT</small></strong></div> <div class="cal-to"><strong>18:45 <small>GMT</small></strong></div> </div> <div class="second-40"> <div class="teams">Zenit <br><small>vs</small> <br>Lokomotiv M.</div><em><i class="fa fa-map-marker"></i>Russia - Premier League</em></div> <div class="third-40 last-column"> <div class="over-under-hist"> <div class="over-under-icon-hist"> <div class="over-under-text-over-hist uppercase"><i class="fa fa-angle-up"></i>Over</div> <div class="over-under-number-hist">2.5</div> </div> </div> <div class="result-top-loss-hist uppercase">LOSS</div> </div> </div> </a> </ul>
DavidEmanuelCanilho/winning-tips-master
www/days/may2016/may-15.html
HTML
gpl-3.0
10,697
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.quickstep; import static com.android.launcher3.FastBitmapDrawable.newIcon; import static com.android.launcher3.uioverrides.QuickstepLauncher.GO_LOW_RAM_RECENTS_ENABLED; import static com.android.launcher3.util.Executors.MAIN_EXECUTOR; import android.app.ActivityManager.TaskDescription; import android.content.Context; import android.content.pm.ActivityInfo; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.os.UserHandle; import android.util.SparseArray; import android.view.accessibility.AccessibilityManager; import androidx.annotation.WorkerThread; import com.android.launcher3.FastBitmapDrawable; import com.android.launcher3.R; import com.android.launcher3.Utilities; import com.android.launcher3.icons.BitmapInfo; import com.android.launcher3.icons.IconProvider; import com.android.launcher3.icons.LauncherIcons; import com.android.launcher3.icons.cache.HandlerRunnable; import com.android.launcher3.util.Preconditions; import com.android.quickstep.util.TaskKeyLruCache; import com.android.systemui.shared.recents.model.Task; import com.android.systemui.shared.recents.model.Task.TaskKey; import com.android.systemui.shared.system.ActivityManagerWrapper; import com.android.systemui.shared.system.PackageManagerWrapper; import com.android.systemui.shared.system.TaskDescriptionCompat; import java.util.function.Consumer; /** * Manages the caching of task icons and related data. */ public class TaskIconCache { private final Handler mBackgroundHandler; private final AccessibilityManager mAccessibilityManager; private final Context mContext; private final TaskKeyLruCache<TaskCacheEntry> mIconCache; private final SparseArray<BitmapInfo> mDefaultIcons = new SparseArray<>(); private final IconProvider mIconProvider; public TaskIconCache(Context context, Looper backgroundLooper) { mContext = context; mBackgroundHandler = new Handler(backgroundLooper); mAccessibilityManager = context.getSystemService(AccessibilityManager.class); Resources res = context.getResources(); int cacheSize = res.getInteger(R.integer.recentsIconCacheSize); mIconCache = new TaskKeyLruCache<>(cacheSize); mIconProvider = new IconProvider(context); } /** * Asynchronously fetches the icon and other task data. * * @param task The task to fetch the data for * @param callback The callback to receive the task after its data has been populated. * @return A cancelable handle to the request */ public IconLoadRequest updateIconInBackground(Task task, Consumer<Task> callback) { Preconditions.assertUIThread(); if (task.icon != null) { // Nothing to load, the icon is already loaded callback.accept(task); return null; } IconLoadRequest request = new IconLoadRequest(mBackgroundHandler) { @Override public void run() { TaskCacheEntry entry = getCacheEntry(task); if (isCanceled()) { // We don't call back to the provided callback in this case return; } MAIN_EXECUTOR.execute(() -> { task.icon = entry.icon; task.titleDescription = entry.contentDescription; callback.accept(task); onEnd(); }); } }; Utilities.postAsyncCallback(mBackgroundHandler, request); return request; } public void clear() { mIconCache.evictAll(); } void onTaskRemoved(TaskKey taskKey) { mIconCache.remove(taskKey); } void invalidateCacheEntries(String pkg, UserHandle handle) { Utilities.postAsyncCallback(mBackgroundHandler, () -> mIconCache.removeAll(key -> pkg.equals(key.getPackageName()) && handle.getIdentifier() == key.userId)); } @WorkerThread private TaskCacheEntry getCacheEntry(Task task) { TaskCacheEntry entry = mIconCache.getAndInvalidateIfModified(task.key); if (entry != null) { return entry; } TaskDescription desc = task.taskDescription; TaskKey key = task.key; ActivityInfo activityInfo = null; // Create new cache entry entry = new TaskCacheEntry(); // Load icon // TODO: Load icon resource (b/143363444) Bitmap icon = TaskDescriptionCompat.getIcon(desc, key.userId); if (icon != null) { entry.icon = new FastBitmapDrawable(getBitmapInfo( new BitmapDrawable(mContext.getResources(), icon), key.userId, desc.getPrimaryColor(), false /* isInstantApp */)); } else { activityInfo = PackageManagerWrapper.getInstance().getActivityInfo( key.getComponent(), key.userId); if (activityInfo != null) { BitmapInfo bitmapInfo = getBitmapInfo( mIconProvider.getIcon(activityInfo, UserHandle.of(key.userId)), key.userId, desc.getPrimaryColor(), activityInfo.applicationInfo.isInstantApp()); entry.icon = newIcon(mContext, bitmapInfo); } else { entry.icon = getDefaultIcon(key.userId); } } // Loading content descriptions if accessibility or low RAM recents is enabled. if (GO_LOW_RAM_RECENTS_ENABLED || mAccessibilityManager.isEnabled()) { // Skip loading the content description if the activity no longer exists if (activityInfo == null) { activityInfo = PackageManagerWrapper.getInstance().getActivityInfo( key.getComponent(), key.userId); } if (activityInfo != null) { entry.contentDescription = ActivityManagerWrapper.getInstance() .getBadgedContentDescription(activityInfo, task.key.userId, task.taskDescription); } } mIconCache.put(task.key, entry); return entry; } @WorkerThread private Drawable getDefaultIcon(int userId) { synchronized (mDefaultIcons) { BitmapInfo info = mDefaultIcons.get(userId); if (info == null) { try (LauncherIcons la = LauncherIcons.obtain(mContext)) { info = la.makeDefaultIcon(UserHandle.of(userId)); } mDefaultIcons.put(userId, info); } return new FastBitmapDrawable(info); } } @WorkerThread private BitmapInfo getBitmapInfo(Drawable drawable, int userId, int primaryColor, boolean isInstantApp) { try (LauncherIcons la = LauncherIcons.obtain(mContext)) { la.disableColorExtraction(); la.setWrapperBackgroundColor(primaryColor); // User version code O, so that the icon is always wrapped in an adaptive icon container return la.createBadgedIconBitmap(drawable, UserHandle.of(userId), Build.VERSION_CODES.O, isInstantApp); } } public static abstract class IconLoadRequest extends HandlerRunnable { IconLoadRequest(Handler handler) { super(handler, null); } } private static class TaskCacheEntry { public Drawable icon; public String contentDescription = ""; } }
Deletescape-Media/Lawnchair
quickstep/src/com/android/quickstep/TaskIconCache.java
Java
gpl-3.0
8,440
# -*- coding: utf-8 -*- """ Created on Wed Jul 6 22:58:00 2016 @author: Diogo """ # -*- coding: utf-8 -*- """ Created on Sun Jun 26 19:08:00 2016 @author: Diogo """ def ImportGames(): games = list() user_games = dict() with open('C:\\Users\\Diogo\\Documents\\Monografia FIA\\UserGamesCleansed.txt', 'r', encoding = 'utf-8') as lines: next(lines) # Skiping headers for ln in lines: user, board_game, board_type, list_type, score10 = ln.split('##') if board_game not in games: games.append(board_game.replace('\t',' ').replace(' ', ' ')) if user not in user_games: user_games[user] = dict() if board_game not in user_games[user].keys(): user_games[user][board_game] = 1 return (games, user_games) games, user_games = ImportGames() def BuildMatrix(games, user_games): with open('C:\\Users\\Diogo\\Documents\\Monografia FIA\\UserGamesMatrix.tab', 'a', encoding = 'utf-8') as lines: lines.write('user\t' + '\t'.join(games) + '\n') for user in user_games: user_line = list() for game in games: if game in user_games[user].keys(): user_line.append('1') else: user_line.append('0') with open('C:\\Users\\Diogo\\Documents\\Monografia FIA\\UserGamesMatrix.tab', 'a', encoding = 'utf-8') as lines: lines.write(user + '\t' + '\t'.join(user_line) + '\n') BuildMatrix(games, user_games)
DiogoGoes/TCC
AssociationRule.py
Python
gpl-3.0
1,429
<?php /****************************************************************************** * * Subrion - open source content management system * Copyright (C) 2017 Intelliants, LLC <https://intelliants.com> * * This file is part of Subrion. * * Subrion is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Subrion is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Subrion. If not, see <http://www.gnu.org/licenses/>. * * * @link https://subrion.org/ * ******************************************************************************/ require_once IA_INCLUDES . 'helpers/ia.category.interface.php'; abstract class iaAbstractFrontHelperCategoryFlat extends abstractModuleFront { const ROOT_PARENT_ID = 0; const COL_PARENT_ID = 'parent_id'; const COL_LEVEL = 'level'; protected $_tableFlat; protected $_recountEnabled = true; protected $_recountOptions = []; // this to be extended by ancestor private $_defaultRecountOptions = [ 'listingsTable' => null, 'activeStatus' => iaCore::STATUS_ACTIVE, 'columnCounter' => 'num_listings', 'columnTotalCounter' => 'num_all_listings' ]; private $_root; public function init() { parent::init(); $this->_tableFlat = self::getTable() . '_flat'; } public function getTableFlat($prefix = false) { return ($prefix ? $this->iaDb->prefix : '') . $this->_tableFlat; } public function getRoot() { if (is_null($this->_root)) { $this->_root = $this->getOne(iaDb::convertIds(self::ROOT_PARENT_ID, self::COL_PARENT_ID)); } return $this->_root; } public function getRootId() { return $this->getRoot()['id']; } public function getTopLevel($fields = null) { return $this->getByLevel(1, $fields); } public function getByLevel($level, $fields = null) { $where = '`status` = :status and `level` = :level'; $this->iaDb->bind($where, ['status' => iaCOre::STATUS_ACTIVE, 'level' => $level]); return $this->getAll($where, $fields); } public function getParents($entryId) { $where = sprintf('`id` IN (SELECT `parent_id` FROM `%s` WHERE `child_id` = %d)', $this->getTableFlat(true), $entryId); return $this->getAll($where); } public function getChildren($entryId, $recursive = false) { $where = $recursive ? sprintf('`id` IN (SELECT `child_id` FROM `%s` WHERE `parent_id` = %d)', $this->getTableFlat(true), $entryId) : iaDb::convertIds($entryId, self::COL_PARENT_ID); return $this->getAll($where); } public function getTreeVars($id, $title) { $nodes = []; foreach ($this->getParents($id) as $category) { $nodes[] = $category['id']; } $result = [ 'url' => $this->getInfo('url') . 'add/tree.json', 'id' => $id, 'nodes' => implode(',', $nodes), 'title' => $title ]; return $result; } public function getJsonTree(array $data) { $output = []; $this->iaDb->setTable(self::getTable()); $dynamicLoadMode = ((int)$this->iaDb->one(iaDb::STMT_COUNT_ROWS) > 150); $rootId = $this->getRootId(); $parentId = isset($data['id']) && is_numeric($data['id']) ? (int)$data['id'] : $rootId; $where = $dynamicLoadMode ? iaDb::convertIds($parentId, self::COL_PARENT_ID) : iaDb::convertIds($rootId, 'id', false); $where .= ' ORDER BY `title`'; $fields = '`id`, `title_' . $this->iaCore->language['iso'] . '` `title`, `parent_id`, ' . '(SELECT COUNT(*) FROM `' . $this->getTableFlat(true) . '` f WHERE f.`parent_id` = `id`) `children_count`'; foreach ($this->iaDb->all($fields, $where) as $row) { $entry = ['id' => $row['id'], 'text' => $row['title']]; if ($dynamicLoadMode) { $entry['children'] = $row['children_count'] > 1; } else { $entry['state'] = []; $entry['parent'] = $rootId == $row[self::COL_PARENT_ID] ? '#' : $row[self::COL_PARENT_ID]; } $output[] = $entry; } return $output; } public function recountById($id, $factor = 1) { if (!$this->_recountEnabled) { return; } $options = array_merge($this->_defaultRecountOptions, $this->_recountOptions); $sql = <<<SQL UPDATE `:table_data` SET `:col_counter` = IF(`id` = :id, `:col_counter` + :factor, `:col_counter`), `:col_total_counter` = `:col_total_counter` + :factor WHERE `id` IN (SELECT `parent_id` FROM `:table_flat` WHERE `child_id` = :id) SQL; $sql = iaDb::printf($sql, [ 'table_data' => self::getTable(true), 'table_flat' => self::getTableFlat(true), 'col_counter' => $options['columnCounter'], 'col_total_counter' => $options['columnTotalCounter'], 'id' => (int)$id, 'factor' => (int)$factor ]); $this->iaDb->query($sql); } }
Saltw/webusable
includes/helpers/ia.category.front.flat.php
PHP
gpl-3.0
5,629
<?php /** * \PHPCompatibility\Sniffs\LanguageConstructs\NewEmptyNonVariableSniff. * * PHP version 5.5 * * @category PHP * @package PHPCompatibility * @author Juliette Reinders Folmer <[email protected]> */ namespace PHPCompatibility\Sniffs\LanguageConstructs; use PHPCompatibility\Sniff; use PHP_CodeSniffer_File as File; use PHP_CodeSniffer_Tokens as Tokens; /** * \PHPCompatibility\Sniffs\LanguageConstructs\NewEmptyNonVariableSniff. * * Verify that nothing but variables are passed to empty(). * * PHP version 5.5 * * @category PHP * @package PHPCompatibility * @author Juliette Reinders Folmer <[email protected]> */ class NewEmptyNonVariableSniff extends Sniff { /** * Returns an array of tokens this test wants to listen for. * * @return array */ public function register() { return array(\T_EMPTY); } /** * Processes this test, when one of its tokens is encountered. * * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned. * @param int $stackPtr The position of the current token in the * stack passed in $tokens. * * @return void */ public function process(File $phpcsFile, $stackPtr) { if ($this->supportsBelow('5.4') === false) { return; } $tokens = $phpcsFile->getTokens(); $open = $phpcsFile->findNext(Tokens::$emptyTokens, ($stackPtr + 1), null, true, null, true); if ($open === false || $tokens[$open]['code'] !== \T_OPEN_PARENTHESIS || isset($tokens[$open]['parenthesis_closer']) === false ) { return; } $close = $tokens[$open]['parenthesis_closer']; $nestingLevel = 0; if ($close !== ($open + 1) && isset($tokens[$open + 1]['nested_parenthesis'])) { $nestingLevel = count($tokens[$open + 1]['nested_parenthesis']); } if ($this->isVariable($phpcsFile, ($open + 1), $close, $nestingLevel) === true) { return; } $phpcsFile->addError( 'Only variables can be passed to empty() prior to PHP 5.5.', $stackPtr, 'Found' ); } }
universityofglasgow/moodle
local/codechecker/PHPCompatibility/Sniffs/LanguageConstructs/NewEmptyNonVariableSniff.php
PHP
gpl-3.0
2,308
/* ============================================================================ Name : lcd_scroll_text.c Author : Kiran N <[email protected] > Version : 1.0 Copyright : Your copyright notice Description : This application prints pre-stored strings on a LCD panel with shifting/scrolling effect TODOs for the students 1) Take multiple strings as a command line argumentsinstead of pre-stored. ============================================================================*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <fcntl.h> #include <poll.h> #include<stdint.h> #include <time.h> #include <math.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <net/if.h> #include <arpa/inet.h> #include "lcd_driver.h" #include "gpio_driver.h" #include "lcd_text_scroll.h" /*========================================================================================================= BBB_expansion_heade_P8_pins GPIO number 16x2 LCD pin Purpose =========================================================================================================== P8.7 GPIO_66 4(RS) Register selection (Character vs. Command) P8.8 GPIO_67 5(RW) Read/write P8.9 GPIO_69 6(EN) Enable P8.10 GPIO_68 7(D4) Data line 4 P8.11 GPIO_45 8(D5) Data line 5 P8.12 GPIO_44 9(D6) Data line 6 P8.14 GPIO_26 10(D7) Data line 7 P8.16 GPIO_46 15(BKLTA) Backlight anode P9.15 GPIO_48 16(BKLTK) Backlight cathode ============================================================================================================= */ char* some_strings[]= { "Mahatma Gandhi said,", "First they ignore you,", "then they laugh at you ", "then they fight with you,", "then you win !", }; /* This function initializes all the gpios for this application * TODO : Error handling implementation */ int initialize_all_gpios(void) { /* first lets export all the GPIOs */ gpio_export(GPIO_66_P8_7_RS_4); gpio_export(GPIO_67_P8_8_RW_5); gpio_export(GPIO_69_P8_9_EN_6); gpio_export(GPIO_68_P8_10_D4_11); gpio_export(GPIO_45_P8_11_D5_12); gpio_export(GPIO_44_P8_12_D6_13); gpio_export(GPIO_26_P8_14_D7_14); /*first configure the direction for LCD pins */ gpio_configure_dir(GPIO_66_P8_7_RS_4,GPIO_DIR_OUT); gpio_configure_dir(GPIO_67_P8_8_RW_5,GPIO_DIR_OUT); gpio_configure_dir(GPIO_69_P8_9_EN_6,GPIO_DIR_OUT); gpio_configure_dir(GPIO_68_P8_10_D4_11,GPIO_DIR_OUT); gpio_configure_dir(GPIO_45_P8_11_D5_12,GPIO_DIR_OUT); gpio_configure_dir(GPIO_44_P8_12_D6_13,GPIO_DIR_OUT); gpio_configure_dir(GPIO_26_P8_14_D7_14,GPIO_DIR_OUT); return 0; } /* This function gathers the ip address of the system and prints it on LCD */ int print_ip_address() { int fd; struct ifreq ifr; char iface[] = "usb0"; fd = socket(AF_INET, SOCK_DGRAM, 0); //Type of address to retrieve - IPv4 IP address ifr.ifr_addr.sa_family = AF_INET; //Copy the interface name in the ifreq structure strncpy(ifr.ifr_name , iface , IFNAMSIZ-1); ioctl(fd, SIOCGIFADDR, &ifr); close(fd); //display result lcd_printf("%s - %s\n" , iface , inet_ntoa(( (struct sockaddr_in *)&ifr.ifr_addr )->sin_addr) ); return 0; } /* Some silly graphics :) */ void tansition_graphics(void) { sleep(1); lcd_set_cursor(1,1); lcd_send_command(LCD_CMD_CLEAR_DISPLAY); for (uint8_t n =0 ; n < 2 ; n++) { for(uint8_t i=0;i<16;i++) { lcd_print_char('*'); usleep(75*1000); } lcd_set_cursor(2,16); lcd_send_command(0x04); } lcd_set_cursor(1,1); lcd_send_command(0x06); usleep(450 * 1000); lcd_send_command(LCD_CMD_CLEAR_DISPLAY); } int main(int argc, char *argv[]) { printf("Application to print text in scrollable fashion on LCD\n"); initialize_all_gpios(); gpio_write_value(GPIO_66_P8_7_RS_4,LOW_VALUE); /*The RW pin is always tied to ground in this implementation, meaning that you are only writing to the display and never reading from it.*/ gpio_write_value(GPIO_67_P8_8_RW_5,LOW_VALUE); /*• The EN pin is used to tell the LCD when data is ready*/ gpio_write_value(GPIO_69_P8_9_EN_6,LOW_VALUE); /*Data pins 4~7 are used for actually transmitting data, and data pins 0~3 are left unconnected*/ gpio_write_value(GPIO_68_P8_10_D4_11,LOW_VALUE); gpio_write_value(GPIO_45_P8_11_D5_12,LOW_VALUE); gpio_write_value(GPIO_44_P8_12_D6_13,LOW_VALUE); gpio_write_value(GPIO_26_P8_14_D7_14,LOW_VALUE); /* You can illuminate the backlight by connecting the anode pin to 5V and the cathode pin to ground if you are using an LCD with a built-in resistor for the backlight. If you are not, you must put a current-limiting resistor in-line with the anode or cathode pin. The datasheet for your device will generally tell you if you need to do this. */ uint8_t cmd=0; lcd_init(); //setting function // only single line mode is chosen here , that means all the 80 characters of the DDRAM will be mapped to lcd line 1. cmd= LCD_CMD_FUNCTION_SET | DATA_LEN_4 | DISPLAY_1_LINE | MATRIX_5_X_8; lcd_send_command(cmd); //3.display on/off control , no cursor cmd = LCD_CMD_DISPLAY_CURSOR_ONOFF_CONTROL |DISPLAY_ON |CURSOR_OFF ; lcd_send_command(cmd); lcd_send_command(LCD_CMD_CLEAR_DISPLAY yo); //lets start printing from extreme right end of first row of the lcd. . lcd_set_cursor( 1,17); #if 1 char *ptr = NULL; uint8_t i; while(1) { //we have total five strings. for ( i = 0 ;i < 5 ; i++) { //print till each string meets NULL char ptr= some_strings[i]; while( *ptr != '\0' ) { lcd_print_char((uint8_t)*ptr); //printing one character at a time and then left shifting by sending this command. cmd = LCD_CMD_CURSOR_DISPLAY_SHIFT_CONTROL | DISPLAY_SHIFT | SHIFT_TO_LEFT ; lcd_send_command(cmd); ptr++; usleep(500 * 1000); } } } #endif }
niekiran/EmbeddedLinuxBBB
Project_Src/lcd_scrollable_text/src/lcd_text_scroll.c
C
gpl-3.0
6,531
%include lhs2TeX.fmt \usepackage{ stmaryrd } %format <?> = "~\lightning~"
zouppen/valo
new/header.tex
TeX
gpl-3.0
74
*{ font-family: 'Raleway', sans-serif; } body{ background: #d6d6d6; color: #333; margin: 0; font-family: 'Raleway', sans-serif; } #masterContainer{ width: 100vw; height: 100vh; padding: 0; margin: 0; display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; align-items: center; justify-content: center; } #logindiv{ background: #dfdfdf; padding: 50px 20px; border-radius: 3px; box-shadow: 0 0 3px #888; } #logindiv span { width: 80px; display: inline-block; font-size: 15px; } #logindiv input { width: 220px; height: 30px; padding: 5px; margin: 5px 0px; display: inline-block; font-size: 15px; outline: none; transition: 0.2s; border: 1px solid #aaa; } #logindiv input[type=submit] { display: block; width: 100%; margin: 20px 0 0 0; border: 0; border-radius: 3px; background-color: #29b0d0; color: #fff; height: 35px; } #logindiv input[type=submit]:hover { background: #2990a0; } .logo { background-image: url(./logo.png); background-size: contain; filter: hue-rotate(120); display: block; width: 80px; height: 80px; margin: 0 auto 20px auto; } #about{ width: 100%; text-align: center; bottom: 20px; position: fixed; color: #777; font-weight: 300; text-shadow: 0 0 0px #b1b1b1; } html { height: 100%; } .h1, .h2, .h3, .h4, .h5, .h6, h1, h2, h3, h4, h5, h6 { font-family: inherit; font-weight: 400; line-height: 1.1; color: inherit; } input[type=submit]{ padding: 10px; background-color: #29b0d0; color: #fff; border: 0; border-radius: 3px; font-size: 13px; outline: none; } input[type=text], input[type=password]{ padding: 10px; background-color: #eee; color: #000; border: 1px solid #ccc; font-size: 13px; border-radius: 3px; min-width: 270px; outline: none; transition: 0.2s; } input[type=text]:hover, input[type=password]:hover{ border: 1px solid #aaa; } input[type=text]:focus, input[type=password]:focus{ border: 1px solid #29b0d0; } nav { height: 60px; background: #fff; display: block; padding: 0; -webkit-box-shadow: 0 0px 2px #777; -moz-box-shadow: 0 0px 2px #777; box-shadow: 0 0px 2px #777; z-index: 9999; color: #333; box-shadow: 0 1px 0 rgba(12,13,14,0.1), 0 1px 3px rgba(12,13,14,0.1), 0 4px 20px rgba(12,13,14,0.035), 0 1px 1px rgba(12,13,14,0.025); } #title { width: 80px; background-size: 50px 50px; background-repeat: no-repeat; background-position: center; font-size: 14px; color: #655dff; display: inline-block; margin: 0; height: 59px; min-width: 60px; cursor: pointer; max-width: 200px; } #search{ display: inline-block; width: 250px; height: 40px; margin: 10px 25px; background-color: #29b0d0; position: absolute; border: 0; box-shadow: 0 0 2px #ddd; color: #fff; } #search::placeholder{ color: #ddd; } #headerRight { height: 60px; margin: 0; } .headerButton { margin: 10px 5px; background-color: #29b0d0; color: #fff; min-width: 40px; border: 0; border-radius: 4px; height: 40px; box-shadow: 0 0 3px #cccccc; } .headerButton:hover { background: #f0f0f0; transition: 0.2s; } .headerText { font-weight: 400; font-size: 15px; padding: 0; margin: 9px 12px 9px 2px; display: inline-block; vertical-align: top; text-align: center; } .userPhoto { width: 30px; height: 30px; margin: 5px; display: inline-block; border-radius: 15px; background-size: contain; } .mainContent{ padding-top: 100px; background-color: #f6f6f6; padding-bottom: 40px; box-shadow: 0 0 20px 2px #aaa; min-height: 100%; position: relative; } .post { min-width: 500px; max-width: 800px; min-height: 200px; position: relative; margin: 30px auto; margin-bottom: 60px; background-color: #fff; border-radius: 3px; border: 1px solid #ccc; box-shadow: 0 10px 0px 0px #29b0d0, 0 4px 8px 0 rgba(0,0,0,0.2); display: block; transition: 0.3s; } .post:hover { box-shadow: 0 10px 0px 0px #2292ac, 0 8px 16px 0 rgba(0,0,0,0.2); } .post .row > .col > *{ display: inline-block; vertical-align: middle; } .postText { padding-bottom: 60px; margin: 20px; } .postTitle { padding: 2px 20px 10px 20px; display: block; font-size: 1.5em; color: #333; text-align: center; } .react { width: 100%; left: 0; height: 60px; bottom: 0; left: 15px; position: absolute; background-color: #eee; overflow: hidden; border: 0; padding: 0; border-top: 1px solid #ddd; } .reactButton{ width: 40px; height: 40px; margin: 0; padding: 0; border-radius: 40px; border: 1px solid #ddd; display: inline-block; background: #fff; color: #555; position: relative; bottom: 0; transition: 0.2s; margin: 10px; } .reactButton:focus{ outline: none; } .react > input[type=submit]{ background: #eee; color: #666; } .react > input[type=submit]:hover { background: #e0e0e0; transition: 0.2s; color: #29b0d0; } .reactButton:hover { background-color: #555; color: #fff; border: 0; cursor: pointer; } ._thumbsup:hover { background-color: #29b0d0; } ._heart:hover { background-color: #f03; } ._comments{ } ._comments:hover { background-color: #555; } ._post:hover { background-color: #590; } .comments { left: 0; height: 0px; position: relative; background-color: #f4f4f4; overflow: hidden; border: 0; padding: 0; border-top: 1px solid #ddd; display: block; overflow-y: scroll; max-height: 199px; padding: 10px 10px 10px 0; } .UpostText { display: block; height: 180px; margin: 20px; margin-bottom: 0px; border: 1px solid #ccc; border-radius: 3px; background-color: #fcfcfc; max-height: 160px; outline: 0px; resize: none; padding: 10px; } .UpostText:hover { transition: 0.2s; border: 1px solid #aaa; } .UpostText:focus { transition: 0.2s; border: 1px solid #29b0d0; } hr { border: 0; height: 1px; background-image: -webkit-linear-gradient(left, #f0f0f0, #8c8b8b, #f0f0f0); background-image: -moz-linear-gradient(left, #f0f0f0, #8c8b8b, #f0f0f0); background-image: -ms-linear-gradient(left, #f0f0f0, #8c8b8b, #f0f0f0); background-image: -o-linear-gradient(left, #f0f0f0, #8c8b8b, #f0f0f0); } #register{ width: 380px; margin: 0 auto; margin-top: 100px; height: 550px; background-color: #fff; border-radius: 3px; font-size: 14px; border: 1px solid #ccc; box-shadow: 0 5px 10px -2px #888; font-weight: 300; } #register input{ display: block; margin-top: 15px; width: 270px; } #register form { padding-top: 15px; width: 270px; margin: auto; display: block; } #register h1 { margin: 15px; font-size: 30px; } #register h3 { margin-top: 10px; font-size: 20px; } .comment{ background: white; max-height: 50px; padding: 5px; border-radius: 10px; margin: 15px; box-shadow: 0 0 15px #d8d8d8; display: block; } .commentUserImage{ width: 30px; height: 30px; border-radius: 15px; margin: 5px; } .commentUser{ font-weight: 700; } .commentText{ font-weight: 200; font-family: monospace; } .commentInput{ height: 40px; width: 200px; border-radius: 20px; border: 1px solid #ddd; padding: 10px; margin: 10px; display: inline-block; background: #fff; color: #555; position: relative; bottom: 0; outline: 0; }
thboud/twingram
frontend/required/stylesheet/style.css
CSS
gpl-3.0
7,140
// Copyright (c) 2012-2014 Lotaris SA // // This file is part of ROX Center. // // ROX Center is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ROX Center is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ROX Center. If not, see <http://www.gnu.org/licenses/>. App.autoModule('globalSettings', function() { var Settings = Backbone.Model.extend({ url: LegacyApiPath.builder('settings') }); var SettingsForm = Marionette.ItemView.extend({ template: 'globalSettings', ui: { ticketingSystemUrl: '#settings_ticketing_system_url', reportsCacheSize: '#settings_reports_cache_size', tagCloudSize: '#settings_tag_cloud_size', testOutdatedDays: '#settings_test_outdated_days', testPayloadsLifespan: '#settings_test_payloads_lifespan', testRunsLifespan: '#settings_test_runs_lifespan', fields: 'form :input', saveButton: 'form button', formControls: 'form .form-controls' }, events: { 'submit form': 'save' }, modelEvents: { 'change': 'refresh' }, appEvents: { 'maintenance:changed': 'updateControls' }, model: new Settings(), initialize: function() { App.bindEvents(this); }, onRender: function() { this.$el.button(); this.model.fetch(this.requestOptions()); this.updateControls(); }, setBusy: function(busy) { this.busy = busy; this.updateControls(); }, updateControls: function() { this.ui.saveButton.attr('disabled', this.busy || !!App.maintenance); this.ui.fields.attr('disabled', !!App.maintenance); }, refresh: function() { this.ui.ticketingSystemUrl.val(this.model.get('ticketing_system_url')); this.ui.reportsCacheSize.val(this.model.get('reports_cache_size')); this.ui.tagCloudSize.val(this.model.get('tag_cloud_size')); this.ui.testOutdatedDays.val(this.model.get('test_outdated_days')); this.ui.testPayloadsLifespan.val(this.model.get('test_payloads_lifespan')); this.ui.testRunsLifespan.val(this.model.get('test_runs_lifespan')); }, save: function(e) { e.preventDefault(); this.setNotice(false); this.setBusy(true); var options = this.requestOptions(); options.type = 'PUT'; options.success = _.bind(this.onSaved, this, 'success'); options.error = _.bind(this.onSaved, this, 'error'); this.model.save({ ticketing_system_url: this.ui.ticketingSystemUrl.val(), reports_cache_size: this.ui.reportsCacheSize.val(), tag_cloud_size: this.ui.tagCloudSize.val(), test_outdated_days: this.ui.testOutdatedDays.val(), test_payloads_lifespan: this.ui.testPayloadsLifespan.val(), test_runs_lifespan: this.ui.testRunsLifespan.val() }, options).always(_.bind(this.setBusy, this, false)); }, onSaved: function(result) { this.setNotice(result); if (result == 'success') { this.refresh(); } }, setNotice: function(type) { this.ui.saveButton.next('.text-success,.text-danger').remove(); if (type == 'success') { $('<span class="text-success" />').text(I18n.t('jst.globalSettings.success')).insertAfter(this.ui.saveButton).hide().fadeIn('fast'); } else if (type == 'error') { $('<span class="text-danger" />').text(I18n.t('jst.globalSettings.error')).insertAfter(this.ui.saveButton).hide().fadeIn('fast'); } }, requestOptions: function() { return { dataType: 'json', accepts: { json: 'application/json' } }; } }); this.addAutoInitializer(function(options) { options.region.show(new SettingsForm()); }); });
lotaris/rox-center
app/assets/javascripts/modules/globalSettings.js
JavaScript
gpl-3.0
4,170
@charset "utf-8"; html{ background: FloralWhite; /*background:#40A0DA; Ivory PowderBlue Lavender Azure Honeydew*/ } body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,form,fieldset,input,textarea,p,blockquote,th,td{ margin:0 auto; padding:0; } table{ border-collapse:collapse; border-spacing:0; } a{ text-decoration:none; } a:link{color: #fff;} /* 未访问的链接 */ a:visited {color: #fff;} /* 已访问的链接 */ a:hover{color: #fff;} /* 鼠标在链接上 */ a:active {color: #fff;} /* 点击激活链接——在你点击该链接之后,页面正在转向新地址的时候,链接显示此颜色;当你已经到了要链接的页面,然后再返回,原页面上的此链接仍是此颜色 */ em,strong,b,u,i{ font-style:normal; font-weight:normal; } ul,ol{ list-style:none; } h1,h2,h3{ font-size:100%; font-weight:normal; } input,textarea,select{ font-family:inherit; font-size:inherit; font-weight:inherit; *font-size:100%;/*ie*/ } input,textarea{ border:none; }
For1024/myRepository
project/二期项目/css/CssReset.css
CSS
gpl-3.0
989
package com.glory.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Log { @Id @GeneratedValue private Long id; private Long transactionId; private String message; public Log() { } public Log(Long id, Long transactionId, String message) { super(); this.id = id; this.transactionId = transactionId; this.message = message; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getTransactionId() { return transactionId; } public void setTransactionId(Long transactionId) { this.transactionId = transactionId; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
aliemrahpekesen/4GloryApi
src/main/java/com/glory/model/Log.java
Java
gpl-3.0
851
Imports Microsoft.VisualBasic Imports System ' ' * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. ' * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' * ' Namespace java.lang.invoke ''' <summary> ''' <p>Methods to facilitate the creation of simple "function objects" that ''' implement one or more interfaces by delegation to a provided <seealso cref="MethodHandle"/>, ''' possibly after type adaptation and partial evaluation of arguments. These ''' methods are typically used as <em>bootstrap methods</em> for {@code invokedynamic} ''' call sites, to support the <em>lambda expression</em> and <em>method ''' reference expression</em> features of the Java Programming Language. ''' ''' <p>Indirect access to the behavior specified by the provided {@code MethodHandle} ''' proceeds in order through three phases: ''' <ul> ''' <li><em>Linkage</em> occurs when the methods in this class are invoked. ''' They take as arguments an interface to be implemented (typically a ''' <em>functional interface</em>, one with a single abstract method), a ''' name and signature of a method from that interface to be implemented, a ''' method handle describing the desired implementation behavior ''' for that method, and possibly other additional metadata, and produce a ''' <seealso cref="CallSite"/> whose target can be used to create suitable function ''' objects. Linkage may involve dynamically loading a new class that ''' implements the target interface. The {@code CallSite} can be considered a ''' "factory" for function objects and so these linkage methods are referred ''' to as "metafactories".</li> ''' ''' <li><em>Capture</em> occurs when the {@code CallSite}'s target is ''' invoked, typically through an {@code invokedynamic} call site, ''' producing a function object. This may occur many times for ''' a single factory {@code CallSite}. Capture may involve allocation of a ''' new function object, or may return an existing function object. The ''' behavior {@code MethodHandle} may have additional parameters beyond those ''' of the specified interface method; these are referred to as <em>captured ''' parameters</em>, which must be provided as arguments to the ''' {@code CallSite} target, and which may be early-bound to the behavior ''' {@code MethodHandle}. The number of captured parameters and their types ''' are determined during linkage.</li> ''' ''' <li><em>Invocation</em> occurs when an implemented interface method ''' is invoked on a function object. This may occur many times for a single ''' function object. The method referenced by the behavior {@code MethodHandle} ''' is invoked with the captured arguments and any additional arguments ''' provided on invocation, as if by <seealso cref="MethodHandle#invoke(Object...)"/>.</li> ''' </ul> ''' ''' <p>It is sometimes useful to restrict the set of inputs or results permitted ''' at invocation. For example, when the generic interface {@code Predicate<T>} ''' is parameterized as {@code Predicate<String>}, the input must be a ''' {@code String}, even though the method to implement allows any {@code Object}. ''' At linkage time, an additional <seealso cref="MethodType"/> parameter describes the ''' "instantiated" method type; on invocation, the arguments and eventual result ''' are checked against this {@code MethodType}. ''' ''' <p>This class provides two forms of linkage methods: a standard version ''' (<seealso cref="#metafactory(MethodHandles.Lookup, String, MethodType, MethodType, MethodHandle, MethodType)"/>) ''' using an optimized protocol, and an alternate version ''' <seealso cref="#altMetafactory(MethodHandles.Lookup, String, MethodType, Object...)"/>). ''' The alternate version is a generalization of the standard version, providing ''' additional control over the behavior of the generated function objects via ''' flags and additional arguments. The alternate version adds the ability to ''' manage the following attributes of function objects: ''' ''' <ul> ''' <li><em>Bridging.</em> It is sometimes useful to implement multiple ''' variations of the method signature, involving argument or return type ''' adaptation. This occurs when multiple distinct VM signatures for a method ''' are logically considered to be the same method by the language. The ''' flag {@code FLAG_BRIDGES} indicates that a list of additional ''' {@code MethodType}s will be provided, each of which will be implemented ''' by the resulting function object. These methods will share the same ''' name and instantiated type.</li> ''' ''' <li><em>Multiple interfaces.</em> If needed, more than one interface ''' can be implemented by the function object. (These additional interfaces ''' are typically marker interfaces with no methods.) The flag {@code FLAG_MARKERS} ''' indicates that a list of additional interfaces will be provided, each of ''' which should be implemented by the resulting function object.</li> ''' ''' <li><em>Serializability.</em> The generated function objects do not ''' generally support serialization. If desired, {@code FLAG_SERIALIZABLE} ''' can be used to indicate that the function objects should be serializable. ''' Serializable function objects will use, as their serialized form, ''' instances of the class {@code SerializedLambda}, which requires additional ''' assistance from the capturing class (the class described by the ''' <seealso cref="MethodHandles.Lookup"/> parameter {@code caller}); see ''' <seealso cref="SerializedLambda"/> for details.</li> ''' </ul> ''' ''' <p>Assume the linkage arguments are as follows: ''' <ul> ''' <li>{@code invokedType} (describing the {@code CallSite} signature) has ''' K parameters of types (D1..Dk) and return type Rd;</li> ''' <li>{@code samMethodType} (describing the implemented method type) has N ''' parameters, of types (U1..Un) and return type Ru;</li> ''' <li>{@code implMethod} (the {@code MethodHandle} providing the ''' implementation has M parameters, of types (A1..Am) and return type Ra ''' (if the method describes an instance method, the method type of this ''' method handle already includes an extra first argument corresponding to ''' the receiver);</li> ''' <li>{@code instantiatedMethodType} (allowing restrictions on invocation) ''' has N parameters, of types (T1..Tn) and return type Rt.</li> ''' </ul> ''' ''' <p>Then the following linkage invariants must hold: ''' <ul> ''' <li>Rd is an interface</li> ''' <li>{@code implMethod} is a <em>direct method handle</em></li> ''' <li>{@code samMethodType} and {@code instantiatedMethodType} have the same ''' arity N, and for i=1..N, Ti and Ui are the same type, or Ti and Ui are ''' both reference types and Ti is a subtype of Ui</li> ''' <li>Either Rt and Ru are the same type, or both are reference types and ''' Rt is a subtype of Ru</li> ''' <li>K + N = M</li> ''' <li>For i=1..K, Di = Ai</li> ''' <li>For i=1..N, Ti is adaptable to Aj, where j=i+k</li> ''' <li>The return type Rt is void, or the return type Ra is not Sub and is ''' adaptable to Rt</li> ''' </ul> ''' ''' <p>Further, at capture time, if {@code implMethod} corresponds to an instance ''' method, and there are any capture arguments ({@code K > 0}), then the first ''' capture argument (corresponding to the receiver) must be non-null. ''' ''' <p>A type Q is considered adaptable to S as follows: ''' <table summary="adaptable types"> ''' <tr><th>Q</th><th>S</th><th>Link-time checks</th><th>Invocation-time checks</th></tr> ''' <tr> ''' <td>Primitive</td><td>Primitive</td> ''' <td>Q can be converted to S via a primitive widening conversion</td> ''' <td>None</td> ''' </tr> ''' <tr> ''' <td>Primitive</td><td>Reference</td> ''' <td>S is a supertype of the Wrapper(Q)</td> ''' <td>Cast from Wrapper(Q) to S</td> ''' </tr> ''' <tr> ''' <td>Reference</td><td>Primitive</td> ''' <td>for parameter types: Q is a primitive wrapper and Primitive(Q) ''' can be widened to S ''' <br>for return types: If Q is a primitive wrapper, check that ''' Primitive(Q) can be widened to S</td> ''' <td>If Q is not a primitive wrapper, cast Q to the base Wrapper(S); ''' for example Number for numeric types</td> ''' </tr> ''' <tr> ''' <td>Reference</td><td>Reference</td> ''' <td>for parameter types: S is a supertype of Q ''' <br>for return types: none</td> ''' <td>Cast from Q to S</td> ''' </tr> ''' </table> ''' ''' @apiNote These linkage methods are designed to support the evaluation ''' of <em>lambda expressions</em> and <em>method references</em> in the Java ''' Language. For every lambda expressions or method reference in the source code, ''' there is a target type which is a functional interface. Evaluating a lambda ''' expression produces an object of its target type. The recommended mechanism ''' for evaluating lambda expressions is to desugar the lambda body to a method, ''' invoke an invokedynamic call site whose static argument list describes the ''' sole method of the functional interface and the desugared implementation ''' method, and returns an object (the lambda object) that implements the target ''' type. (For method references, the implementation method is simply the ''' referenced method; no desugaring is needed.) ''' ''' <p>The argument list of the implementation method and the argument list of ''' the interface method(s) may differ in several ways. The implementation ''' methods may have additional arguments to accommodate arguments captured by ''' the lambda expression; there may also be differences resulting from permitted ''' adaptations of arguments, such as casting, boxing, unboxing, and primitive ''' widening. (Varargs adaptations are not handled by the metafactories; these are ''' expected to be handled by the caller.) ''' ''' <p>Invokedynamic call sites have two argument lists: a static argument list ''' and a dynamic argument list. The static argument list is stored in the ''' constant pool; the dynamic argument is pushed on the operand stack at capture ''' time. The bootstrap method has access to the entire static argument list ''' (which in this case, includes information describing the implementation method, ''' the target interface, and the target interface method(s)), as well as a ''' method signature describing the number and static types (but not the values) ''' of the dynamic arguments and the static return type of the invokedynamic site. ''' ''' @implNote The implementation method is described with a method handle. In ''' theory, any method handle could be used. Currently supported are direct method ''' handles representing invocation of virtual, interface, constructor and static ''' methods. ''' </summary> Public Class LambdaMetafactory ''' <summary> ''' Flag for alternate metafactories indicating the lambda object ''' must be serializable ''' </summary> Public Shared ReadOnly FLAG_SERIALIZABLE As Integer = 1 << 0 ''' <summary> ''' Flag for alternate metafactories indicating the lambda object implements ''' other marker interfaces ''' besides Serializable ''' </summary> Public Shared ReadOnly FLAG_MARKERS As Integer = 1 << 1 ''' <summary> ''' Flag for alternate metafactories indicating the lambda object requires ''' additional bridge methods ''' </summary> Public Shared ReadOnly FLAG_BRIDGES As Integer = 1 << 2 Private Shared ReadOnly EMPTY_CLASS_ARRAY As [Class]() = New [Class](){} Private Shared ReadOnly EMPTY_MT_ARRAY As MethodType() = New MethodType(){} ''' <summary> ''' Facilitates the creation of simple "function objects" that implement one ''' or more interfaces by delegation to a provided <seealso cref="MethodHandle"/>, ''' after appropriate type adaptation and partial evaluation of arguments. ''' Typically used as a <em>bootstrap method</em> for {@code invokedynamic} ''' call sites, to support the <em>lambda expression</em> and <em>method ''' reference expression</em> features of the Java Programming Language. ''' ''' <p>This is the standard, streamlined metafactory; additional flexibility ''' is provided by <seealso cref="#altMetafactory(MethodHandles.Lookup, String, MethodType, Object...)"/>. ''' A general description of the behavior of this method is provided ''' <seealso cref="LambdaMetafactory above"/>. ''' ''' <p>When the target of the {@code CallSite} returned from this method is ''' invoked, the resulting function objects are instances of a class which ''' implements the interface named by the return type of {@code invokedType}, ''' declares a method with the name given by {@code invokedName} and the ''' signature given by {@code samMethodType}. It may also override additional ''' methods from {@code Object}. ''' </summary> ''' <param name="caller"> Represents a lookup context with the accessibility ''' privileges of the caller. When used with {@code invokedynamic}, ''' this is stacked automatically by the VM. </param> ''' <param name="invokedName"> The name of the method to implement. When used with ''' {@code invokedynamic}, this is provided by the ''' {@code NameAndType} of the {@code InvokeDynamic} ''' structure and is stacked automatically by the VM. </param> ''' <param name="invokedType"> The expected signature of the {@code CallSite}. The ''' parameter types represent the types of capture variables; ''' the return type is the interface to implement. When ''' used with {@code invokedynamic}, this is provided by ''' the {@code NameAndType} of the {@code InvokeDynamic} ''' structure and is stacked automatically by the VM. ''' In the event that the implementation method is an ''' instance method and this signature has any parameters, ''' the first parameter in the invocation signature must ''' correspond to the receiver. </param> ''' <param name="samMethodType"> Signature and return type of method to be implemented ''' by the function object. </param> ''' <param name="implMethod"> A direct method handle describing the implementation ''' method which should be called (with suitable adaptation ''' of argument types, return types, and with captured ''' arguments prepended to the invocation arguments) at ''' invocation time. </param> ''' <param name="instantiatedMethodType"> The signature and return type that should ''' be enforced dynamically at invocation time. ''' This may be the same as {@code samMethodType}, ''' or may be a specialization of it. </param> ''' <returns> a CallSite whose target can be used to perform capture, generating ''' instances of the interface named by {@code invokedType} </returns> ''' <exception cref="LambdaConversionException"> If any of the linkage invariants ''' described <seealso cref="LambdaMetafactory above"/> ''' are violated </exception> Public Shared Function metafactory( caller As MethodHandles.Lookup, invokedName As String, invokedType As MethodType, samMethodType As MethodType, implMethod As MethodHandle, instantiatedMethodType As MethodType) As CallSite Dim mf As AbstractValidatingLambdaMetafactory mf = New InnerClassLambdaMetafactory(caller, invokedType, invokedName, samMethodType, implMethod, instantiatedMethodType, False, EMPTY_CLASS_ARRAY, EMPTY_MT_ARRAY) mf.validateMetafactoryArgs() Return mf.buildCallSite() End Function ''' <summary> ''' Facilitates the creation of simple "function objects" that implement one ''' or more interfaces by delegation to a provided <seealso cref="MethodHandle"/>, ''' after appropriate type adaptation and partial evaluation of arguments. ''' Typically used as a <em>bootstrap method</em> for {@code invokedynamic} ''' call sites, to support the <em>lambda expression</em> and <em>method ''' reference expression</em> features of the Java Programming Language. ''' ''' <p>This is the general, more flexible metafactory; a streamlined version ''' is provided by {@link #metafactory(java.lang.invoke.MethodHandles.Lookup, ''' String, MethodType, MethodType, MethodHandle, MethodType)}. ''' A general description of the behavior of this method is provided ''' <seealso cref="LambdaMetafactory above"/>. ''' ''' <p>The argument list for this method includes three fixed parameters, ''' corresponding to the parameters automatically stacked by the VM for the ''' bootstrap method in an {@code invokedynamic} invocation, and an {@code Object[]} ''' parameter that contains additional parameters. The declared argument ''' list for this method is: ''' ''' <pre>{@code ''' CallSite altMetafactory(MethodHandles.Lookup caller, ''' String invokedName, ''' MethodType invokedType, ''' Object... args) ''' }</pre> ''' ''' <p>but it behaves as if the argument list is as follows: ''' ''' <pre>{@code ''' CallSite altMetafactory(MethodHandles.Lookup caller, ''' String invokedName, ''' MethodType invokedType, ''' MethodType samMethodType, ''' MethodHandle implMethod, ''' MethodType instantiatedMethodType, ''' int flags, ''' int markerInterfaceCount, // IF flags has MARKERS set ''' Class... markerInterfaces, // IF flags has MARKERS set ''' int bridgeCount, // IF flags has BRIDGES set ''' MethodType... bridges // IF flags has BRIDGES set ''' ) ''' }</pre> ''' ''' <p>Arguments that appear in the argument list for ''' <seealso cref="#metafactory(MethodHandles.Lookup, String, MethodType, MethodType, MethodHandle, MethodType)"/> ''' have the same specification as in that method. The additional arguments ''' are interpreted as follows: ''' <ul> ''' <li>{@code flags} indicates additional options; this is a bitwise ''' OR of desired flags. Defined flags are <seealso cref="#FLAG_BRIDGES"/>, ''' <seealso cref="#FLAG_MARKERS"/>, and <seealso cref="#FLAG_SERIALIZABLE"/>.</li> ''' <li>{@code markerInterfaceCount} is the number of additional interfaces ''' the function object should implement, and is present if and only if the ''' {@code FLAG_MARKERS} flag is set.</li> ''' <li>{@code markerInterfaces} is a variable-length list of additional ''' interfaces to implement, whose length equals {@code markerInterfaceCount}, ''' and is present if and only if the {@code FLAG_MARKERS} flag is set.</li> ''' <li>{@code bridgeCount} is the number of additional method signatures ''' the function object should implement, and is present if and only if ''' the {@code FLAG_BRIDGES} flag is set.</li> ''' <li>{@code bridges} is a variable-length list of additional ''' methods signatures to implement, whose length equals {@code bridgeCount}, ''' and is present if and only if the {@code FLAG_BRIDGES} flag is set.</li> ''' </ul> ''' ''' <p>Each class named by {@code markerInterfaces} is subject to the same ''' restrictions as {@code Rd}, the return type of {@code invokedType}, ''' as described <seealso cref="LambdaMetafactory above"/>. Each {@code MethodType} ''' named by {@code bridges} is subject to the same restrictions as ''' {@code samMethodType}, as described <seealso cref="LambdaMetafactory above"/>. ''' ''' <p>When FLAG_SERIALIZABLE is set in {@code flags}, the function objects ''' will implement {@code Serializable}, and will have a {@code writeReplace} ''' method that returns an appropriate <seealso cref="SerializedLambda"/>. The ''' {@code caller} class must have an appropriate {@code $deserializeLambda$} ''' method, as described in <seealso cref="SerializedLambda"/>. ''' ''' <p>When the target of the {@code CallSite} returned from this method is ''' invoked, the resulting function objects are instances of a class with ''' the following properties: ''' <ul> ''' <li>The class implements the interface named by the return type ''' of {@code invokedType} and any interfaces named by {@code markerInterfaces}</li> ''' <li>The class declares methods with the name given by {@code invokedName}, ''' and the signature given by {@code samMethodType} and additional signatures ''' given by {@code bridges}</li> ''' <li>The class may override methods from {@code Object}, and may ''' implement methods related to serialization.</li> ''' </ul> ''' </summary> ''' <param name="caller"> Represents a lookup context with the accessibility ''' privileges of the caller. When used with {@code invokedynamic}, ''' this is stacked automatically by the VM. </param> ''' <param name="invokedName"> The name of the method to implement. When used with ''' {@code invokedynamic}, this is provided by the ''' {@code NameAndType} of the {@code InvokeDynamic} ''' structure and is stacked automatically by the VM. </param> ''' <param name="invokedType"> The expected signature of the {@code CallSite}. The ''' parameter types represent the types of capture variables; ''' the return type is the interface to implement. When ''' used with {@code invokedynamic}, this is provided by ''' the {@code NameAndType} of the {@code InvokeDynamic} ''' structure and is stacked automatically by the VM. ''' In the event that the implementation method is an ''' instance method and this signature has any parameters, ''' the first parameter in the invocation signature must ''' correspond to the receiver. </param> ''' <param name="args"> An {@code Object[]} array containing the required ''' arguments {@code samMethodType}, {@code implMethod}, ''' {@code instantiatedMethodType}, {@code flags}, and any ''' optional arguments, as described ''' <seealso cref="#altMetafactory(MethodHandles.Lookup, String, MethodType, Object...)"/> above} </param> ''' <returns> a CallSite whose target can be used to perform capture, generating ''' instances of the interface named by {@code invokedType} </returns> ''' <exception cref="LambdaConversionException"> If any of the linkage invariants ''' described <seealso cref="LambdaMetafactory above"/> ''' are violated </exception> Public Shared Function altMetafactory( caller As MethodHandles.Lookup, invokedName As String, invokedType As MethodType, ParamArray args As Object()) As CallSite Dim samMethodType As MethodType = CType(args(0), MethodType) Dim implMethod As MethodHandle = CType(args(1), MethodHandle) Dim instantiatedMethodType As MethodType = CType(args(2), MethodType) Dim flags As Integer = CInt(Fix(args(3))) Dim markerInterfaces As [Class]() Dim bridges As MethodType() Dim argIndex As Integer = 4 If (flags And FLAG_MARKERS) <> 0 Then Dim markerCount As Integer = CInt(Fix(args(argIndex))) argIndex += 1 markerInterfaces = New [Class](markerCount - 1){} Array.Copy(args, argIndex, markerInterfaces, 0, markerCount) argIndex += markerCount Else markerInterfaces = EMPTY_CLASS_ARRAY End If If (flags And FLAG_BRIDGES) <> 0 Then Dim bridgeCount As Integer = CInt(Fix(args(argIndex))) argIndex += 1 bridges = New MethodType(bridgeCount - 1){} Array.Copy(args, argIndex, bridges, 0, bridgeCount) argIndex += bridgeCount Else bridges = EMPTY_MT_ARRAY End If Dim isSerializable As Boolean = ((flags And FLAG_SERIALIZABLE) <> 0) If isSerializable Then Dim foundSerializableSupertype As Boolean = invokedType.returnType().IsSubclassOf(GetType(java.io.Serializable)) For Each c As [Class] In markerInterfaces foundSerializableSupertype = foundSerializableSupertype Or c.IsSubclassOf(GetType(java.io.Serializable)) Next c If Not foundSerializableSupertype Then markerInterfaces = java.util.Arrays.copyOf(markerInterfaces, markerInterfaces.Length + 1) markerInterfaces(markerInterfaces.Length-1) = GetType(java.io.Serializable) End If End If Dim mf As AbstractValidatingLambdaMetafactory = New InnerClassLambdaMetafactory(caller, invokedType, invokedName, samMethodType, implMethod, instantiatedMethodType, isSerializable, markerInterfaces, bridges) mf.validateMetafactoryArgs() Return mf.buildCallSite() End Function End Class End Namespace
amethyst-asuka/java_dotnet
java/lang/invoke/LambdaMetafactory.vb
Visual Basic
gpl-3.0
26,112
::-webkit-scrollbar { width: 8px; height: 8px; } ::-webkit-scrollbar-track { background-color: #222; } ::-webkit-scrollbar-thumb { background-color: #ddd; } .no-select { user-select: none; -webkit-user-select: none; } html, body { height: 100%; margin: 0; overflow: hidden; font-family: var( --gsui-font ); background-color: var( --app-bg ); } a { color: inherit; text-decoration: none; }
GridSound/daw
src/css/reset.css
CSS
gpl-3.0
401
<?php /** * @copyright &copy; 2005-2022 PHPBoost * @license https://www.gnu.org/licenses/gpl-3.0.html GNU/GPL-3.0 * @author Julien BRISWALTER <[email protected]> * @version PHPBoost 6.0 - last update: 2021 12 05 * @since PHPBoost 3.0 - 2013 04 29 * @contributor Arnaud GENET <[email protected]> * @contributor Sebastien LARTIGUE <[email protected]> */ class BugtrackerViews { public static function build_body_view(View $view, $current_page, $bug_id = 0, $bug_type = "") { $lang = LangLoader::get_all_langs('bugtracker'); $config = BugtrackerConfig::load(); $types = $config->get_types(); $body_view = new FileTemplate('bugtracker/BugtrackerBody.tpl'); $body_view->add_lang($lang); $body_view->put_all(array( 'C_ROADMAP_ENABLED' => $config->is_roadmap_displayed(), 'C_STATS_ENABLED' => $config->are_stats_enabled(), 'C_DISPLAY_MENU' => in_array($current_page, array('unsolved', 'solved', 'roadmap', 'stats')), 'C_SYNDICATION' => $current_page == 'unsolved' || $current_page == 'solved', 'C_UNSOLVED' => $current_page == 'unsolved', 'C_SOLVED' => $current_page == 'solved', 'C_ROADMAP' => $current_page == 'roadmap', 'C_STATS' => $current_page == 'stats', 'L_TITLE' => $lang['bugtracker.' . $current_page] . (in_array($current_page, array('change_status', 'history', 'detail', 'edit')) ? " : " . $types[$bug_type] . ' #' .$bug_id : ''), 'TEMPLATE' => $view, 'U_SYNDICATION_UNSOLVED' => SyndicationUrlBuilder::rss('bugtracker', 0)->rel(), 'U_SYNDICATION_SOLVED' => SyndicationUrlBuilder::rss('bugtracker', 1)->rel() )); return $body_view; } public static function build_filters($current_page, $nbr_bugs = 0) { $lang = LangLoader::get_all_langs('bugtracker'); $object = new self(); $request = AppContext::get_request(); $page = $request->get_int('page', 1); $filter = $request->get_value('filter', ''); $filter_id = $request->get_value('filter_id', ''); if (!empty($filter) && empty($filter_id)) { $filter = $filter_id = ''; } $filters_tmp = $filters = !empty($filter) ? explode('-', $filter) : array(); $nb_filters = count($filters); $filters_ids_tmp = $filters_ids = !empty($filter_id) ? explode('-', $filter_id) : array(); $nb_filters_ids = count($filters_ids); if ($nb_filters != $nb_filters_ids) { for ($i = $nb_filters_ids; $i < $nb_filters; $i++) { $filters_ids[] = 0; } } $display_save_button = AppContext::get_current_user()->check_level(User::MEMBER_LEVEL) && count($filters) >= 1; $config = BugtrackerConfig::load(); $types = $config->get_types(); $categories = $config->get_categories(); $severities = $config->get_severities(); $versions = $config->get_versions_detected(); $all_versions = $config->get_versions(); $display_types = count($types); $display_categories = count($categories); $display_severities = count($severities); $display_versions = count($versions); $display_all_versions = count($all_versions); $filters_number = 1; if ($display_types) $filters_number = $filters_number + 1; if ($display_categories) $filters_number = $filters_number + 1; if ($display_severities) $filters_number = $filters_number + 1; if ($display_versions || $display_all_versions) $filters_number = $filters_number + 1; if (!empty($filters)) $filters_number = $filters_number + 1; $filters_view = new FileTemplate('bugtracker/BugtrackerFilter.tpl'); $filters_view->add_lang($lang); $result = PersistenceContext::get_querier()->select("SELECT * FROM " . BugtrackerSetup::$bugtracker_users_filters_table . " WHERE page = :page AND user_id = :user_id", array( 'page' => $current_page, 'user_id' => AppContext::get_current_user()->get_id() ), SelectQueryResult::FETCH_ASSOC ); $saved_filters = false; while ($row = $result->fetch()) { $row_filters_tmp = $row_filters = !empty($row['filters']) ? explode('-', $row['filters']) : array(); $row_filters_ids_tmp = $row_filters_ids = !empty($row['filters_ids']) ? explode('-', $row['filters_ids']) : array(); sort($filters_tmp, SORT_STRING); sort($row_filters_tmp, SORT_STRING); sort($filters_ids_tmp, SORT_STRING); sort($row_filters_ids_tmp, SORT_STRING); if (implode('-', $filters_tmp) == implode('-', $row_filters_tmp) && implode('-', $filters_ids_tmp) == implode('-', $row_filters_ids_tmp)) $display_save_button = false; $filter_not_saved_value = '-------------'; $filter_type_value = in_array('type', $row_filters) && $row_filters_ids[array_search('type', $row_filters)] && isset($types[$row_filters_ids[array_search('type', $row_filters)]]) ? $types[$row_filters_ids[array_search('type', $row_filters)]] : $filter_not_saved_value; $filter_category_value = in_array('category', $row_filters) && $row_filters_ids[array_search('category', $row_filters)] && isset($categories[$row_filters_ids[array_search('category', $row_filters)]]) ? $categories[$row_filters_ids[array_search('category', $row_filters)]] : $filter_not_saved_value; $filter_severity_value = in_array('severity', $row_filters) && $row_filters_ids[array_search('severity', $row_filters)] && isset($severities[$row_filters_ids[array_search('severity', $row_filters)]]) ? $severities[$row_filters_ids[array_search('severity', $row_filters)]]['name'] : $filter_not_saved_value; $filter_status_value = in_array('status', $row_filters) && $row_filters_ids[array_search('status', $row_filters)] && isset($lang['status.' . $row_filters_ids[array_search('status', $row_filters)]]) ? $lang['status.' . $row_filters_ids[array_search('status', $row_filters)]] : $filter_not_saved_value; $filter_version_value = ($current_page == 'unsolved' ? (in_array('detected_in', $row_filters) && $row_filters_ids[array_search('detected_in', $row_filters)] && isset($versions[$row_filters_ids[array_search('detected_in', $row_filters)]]) ? $versions[$row_filters_ids[array_search('detected_in', $row_filters)]]['name'] : $filter_not_saved_value) : (in_array('fixed_in', $row_filters) && $row_filters_ids[array_search('fixed_in', $row_filters)] && isset($all_versions[$row_filters_ids[array_search('fixed_in', $row_filters)]]) ? $all_versions[$row_filters_ids[array_search('fixed_in', $row_filters)]]['name'] : $filter_not_saved_value)); $filters_view->assign_block_vars('filters', array( 'ID' => $row['id'], 'FILTER' => '| ' . $filter_type_value . ' | ' . $filter_category_value . ' | ' . $filter_severity_value . ' | ' . $filter_status_value . ' | ' . $filter_version_value . ' |', 'LINK_FILTER' => ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, $row['filters'], $row['filters_ids'])->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, $row['filters'], $row['filters_ids'])->rel()), )); $saved_filters = true; } $result->dispose(); $filters_view->put_all(array( 'C_SEVERAL_FILTERS' => $filters_number > 1, 'C_DISPLAY_TYPES' => $display_types, 'C_DISPLAY_CATEGORIES' => $display_categories, 'C_DISPLAY_SEVERITIES' => $display_severities, 'C_DISPLAY_VERSIONS' => $current_page == 'solved' ? $display_all_versions : $display_versions, 'C_DISPLAY_SAVE_BUTTON' => $display_save_button, 'C_SAVED_FILTERS' => $saved_filters, 'C_HAS_SELECTED_FILTERS'=> $filters, 'FILTERS_NUMBER' => $filters_number, 'BUGS_NUMBER' => $nbr_bugs, 'LINK_FILTER_SAVE' => BugtrackerUrlBuilder::add_filter($current_page, $filter, $filter_id)->rel(), 'SELECT_TYPE' => $object->build_types_form($current_page,($filter == 'type') ? $filter_id : (in_array('type', $filters) ? $filters_ids[array_search('type', $filters)] : 0), $filters, $filters_ids)->display(), 'SELECT_CATEGORY' => $object->build_categories_form($current_page, ($filter == 'category') ? $filter_id : (in_array('category', $filters) ? $filters_ids[array_search('category', $filters)] : 0), $filters, $filters_ids)->display(), 'SELECT_SEVERITY' => $object->build_severities_form($current_page, ($filter == 'severity') ? $filter_id : (in_array('severity', $filters) ? $filters_ids[array_search('severity', $filters)] : 0), $filters, $filters_ids)->display(), 'SELECT_STATUS' => $object->build_status_form($current_page, ($filter == 'status') ? $filter_id : (in_array('status', $filters) ? $filters_ids[array_search('status', $filters)] : 0), $filters, $filters_ids, $lang)->display(), 'SELECT_VERSION' => $object->build_versions_form($current_page, ($current_page == 'unsolved' ? (($filter == 'detected_in') ? $filter_id : (in_array('detected_in', $filters) ? $filters_ids[array_search('detected_in', $filters)] : 0)) : (($filter == 'fixed_in') ? $filter_id : (in_array('fixed_in', $filters) ? $filters_ids[array_search('fixed_in', $filters)] : 0))), $filters, $filters_ids)->display(), )); return $filters_view; } public static function build_legend($list, $current_page) { $lang = LangLoader::get_all_langs('bugtracker'); $config = BugtrackerConfig::load(); $severities = $config->get_severities(); $legend_view = new FileTemplate('bugtracker/BugtrackerLegend.tpl'); $legend_view->add_lang($lang); $legend_colspan = 0; foreach ($list as $element) { if (($current_page == 'solved') || (!empty($element) && isset($severities[$element]))) { $legend_view->assign_block_vars('legend', array( 'COLOR' => $current_page == 'solved' ? ($element == 'fixed' ? $config->get_fixed_bug_color() : $config->get_rejected_bug_color()) : stripslashes($severities[$element]['color']), 'NAME' => $current_page == 'solved' ? $lang['status.' . $element] : stripslashes($severities[$element]['name']) )); $legend_colspan = $legend_colspan + 3; } } $legend_view->put_all(array( 'LEGEND_COLSPAN' => $legend_colspan )); return ($legend_colspan ? $legend_view : new StringTemplate('')); } private function build_types_form($current_page, $requested_type, $filters, $filters_ids) { if (in_array('type', $filters)) { $key = array_search('type', $filters); unset($filters[$key]); unset($filters_ids[$key]); } $filter = implode('-', $filters); $filter_id = implode('-', $filters_ids); $form = new HTMLForm('type-form', '', false); $fieldset = new FormFieldsetHorizontal('filter-type'); $form->add_fieldset($fieldset); $fieldset->add_field(new FormFieldSimpleSelectChoice('filter_type', '', $requested_type, $this->build_select_types(), array( 'events' => array('change' => ' if (HTMLForms.getField("filter_type").getValue() > 0) { document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'type', (!empty($filter_id) ? $filter_id . '-' : ''))->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'type', (!empty($filter_id) ? $filter_id . '-' : ''))->rel()) .'" + HTMLForms.getField("filter_type").getValue(); } else { document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, $filter, $filter_id)->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, $filter, $filter_id)->rel()) .'"; }' ) ) )); return $form; } private function build_select_types() { $types = BugtrackerConfig::load()->get_types(); $array_types = array(); $array_types[] = new FormFieldSelectChoiceOption('&nbsp;', 0); foreach ($types as $key => $type) { $array_types[] = new FormFieldSelectChoiceOption(stripslashes($type), $key); } return $array_types; } private function build_categories_form($current_page, $requested_category, $filters, $filters_ids) { if (in_array('category', $filters)) { $key = array_search('category', $filters); unset($filters[$key]); unset($filters_ids[$key]); } $filter = implode('-', $filters); $filter_id = implode('-', $filters_ids); $form = new HTMLForm('category-form', '', false); $fieldset = new FormFieldsetHorizontal('filter-category'); $form->add_fieldset($fieldset); $fieldset->add_field(new FormFieldSimpleSelectChoice('filter_category', '', $requested_category, $this->build_select_categories(), array('events' => array('change' => 'if (HTMLForms.getField("filter_category").getValue() > 0) { document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'category', (!empty($filter_id) ? $filter_id . '-' : ''))->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'category', (!empty($filter_id) ? $filter_id . '-' : ''))->rel()) .'" + HTMLForms.getField("filter_category").getValue(); } else { document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, $filter, $filter_id)->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, $filter, $filter_id)->rel()) .'"; }') ))); return $form; } private function build_select_categories() { $categories = BugtrackerConfig::load()->get_categories(); $array_categories = array(); $array_categories[] = new FormFieldSelectChoiceOption('&nbsp;', 0); foreach ($categories as $key => $category) { $array_categories[] = new FormFieldSelectChoiceOption(stripslashes($category), $key); } return $array_categories; } private function build_severities_form($current_page, $requested_severity, $filters, $filters_ids) { if (in_array('severity', $filters)) { $key = array_search('severity', $filters); unset($filters[$key]); unset($filters_ids[$key]); } $filter = implode('-', $filters); $filter_id = implode('-', $filters_ids); $form = new HTMLForm('severity-form', '', false); $fieldset = new FormFieldsetHorizontal('filter-severity'); $form->add_fieldset($fieldset); $fieldset->add_field(new FormFieldSimpleSelectChoice('filter_severity', '', $requested_severity, $this->build_select_severities(), array('events' => array('change' => 'if (HTMLForms.getField("filter_severity").getValue() > 0) { document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'severity', (!empty($filter_id) ? $filter_id . '-' : ''))->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'severity', (!empty($filter_id) ? $filter_id . '-' : ''))->rel()) .'" + HTMLForms.getField("filter_severity").getValue(); } else { document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, $filter, $filter_id)->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, $filter, $filter_id)->rel()) .'"; }') ))); return $form; } private function build_select_severities() { $severities = BugtrackerConfig::load()->get_severities(); $array_categories = array(); $array_severities[] = new FormFieldSelectChoiceOption('&nbsp;', 0); foreach ($severities as $key => $severity) { $array_severities[] = new FormFieldSelectChoiceOption(stripslashes($severity['name']), $key); } return $array_severities; } private function build_status_form($current_page, $requested_status, $filters, $filters_ids, $lang) { if (in_array('status', $filters)) { $key = array_search('status', $filters); unset($filters[$key]); unset($filters_ids[$key]); } $filter = implode('-', $filters); $filter_id = implode('-', $filters_ids); $form = new HTMLForm('status-form', '', false); $fieldset = new FormFieldsetHorizontal('filter-status'); $form->add_fieldset($fieldset); $fieldset->add_field(new FormFieldSimpleSelectChoice('filter_status', '', $requested_status, $this->build_select_status($current_page, $lang), array('events' => array('change' => 'if (HTMLForms.getField("filter_status").getValue()) { document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'status', (!empty($filter_id) ? $filter_id . '-' : ''))->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'status', (!empty($filter_id) ? $filter_id . '-' : ''))->rel()) .'" + HTMLForms.getField("filter_status").getValue(); } else { document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, $filter, $filter_id)->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, $filter, $filter_id)->rel()) .'"; }') ))); return $form; } private function build_select_status($current_page, $lang) { $status_list = BugtrackerConfig::load()->get_status_list(); $array_status = array(); $array_status[] = new FormFieldSelectChoiceOption('&nbsp;', ''); foreach ($status_list as $status => $progress) { if (($current_page == 'unsolved' && !in_array($status, array(BugtrackerItem::FIXED, BugtrackerItem::REJECTED))) || ($current_page == 'solved' && in_array($status, array(BugtrackerItem::FIXED, BugtrackerItem::REJECTED)))) $array_status[] = new FormFieldSelectChoiceOption($lang['status.' . $status], $status); } return $array_status; } private function build_versions_form($current_page, $requested_version, $filters, $filters_ids) { $search_field = ($current_page == 'unsolved' ? 'detected_in' : 'fixed_in'); if (in_array($search_field , $filters)) { $key = array_search($search_field , $filters); unset($filters[$key]); unset($filters_ids[$key]); } $filter = implode('-', $filters); $filter_id = implode('-', $filters_ids); $form = new HTMLForm('version-form', '', false); $fieldset = new FormFieldsetHorizontal('filter-version'); $form->add_fieldset($fieldset); $fieldset->add_field(new FormFieldSimpleSelectChoice('filter_version', '', $requested_version, $this->build_select_versions($current_page), array('events' => array('change' => 'if (HTMLForms.getField("filter_version").getValue() > 0) { document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'detected_in', (!empty($filter_id) ? $filter_id . '-' : ''))->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, (!empty($filter) ? $filter . '-' : '') . 'fixed_in', (!empty($filter_id) ? $filter_id . '-' : ''))->rel()) .'" + HTMLForms.getField("filter_version").getValue(); } else { document.location = "'. ($current_page == 'unsolved' ? BugtrackerUrlBuilder::unsolved('name', 'desc', 1, $filter, $filter_id)->rel() : BugtrackerUrlBuilder::solved('name', 'desc', 1, $filter, $filter_id)->rel()) .'"; }') ))); return $form; } private function build_select_versions($current_page) { $versions = ($current_page == 'unsolved' ? BugtrackerConfig::load()->get_versions_detected() : BugtrackerConfig::load()->get_versions()); $versions = array_reverse($versions, true); $array_versions = array(); $array_versions[] = new FormFieldSelectChoiceOption('&nbsp;', ''); foreach ($versions as $key => $version) { $array_versions[] = new FormFieldSelectChoiceOption(stripslashes($version['name']), $key); } return $array_versions; } } ?>
PHPBoost/PHPBoost
bugtracker/util/BugtrackerViews.class.php
PHP
gpl-3.0
19,662
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Entidades { public class Class1 { } }
romanf77/Metodos-Estaticos
Clase 8 Array/PROG-LAB-II-master/Clase 08/ejemplosArray/Clases/Class1.cs
C#
gpl-3.0
180
package l2s.gameserver.network.l2.s2c; import java.util.ArrayList; import java.util.Collections; import java.util.List; import l2s.commons.lang.ArrayUtils; import l2s.gameserver.model.Player; import l2s.gameserver.model.items.ItemInfo; import l2s.gameserver.model.items.ItemInstance; import l2s.gameserver.model.items.Warehouse.ItemClassComparator; import l2s.gameserver.model.items.Warehouse.WarehouseType; public class WareHouseWithdrawListPacket extends L2GameServerPacket { private long _adena; private List<ItemInfo> _itemList = new ArrayList<ItemInfo>(); private int _type; private int _inventoryUsedSlots; public WareHouseWithdrawListPacket(Player player, WarehouseType type) { _adena = player.getAdena(); _type = type.ordinal(); ItemInstance[] items; switch(type) { case PRIVATE: items = player.getWarehouse().getItems(); break; case FREIGHT: items = player.getFreight().getItems(); break; case CLAN: case CASTLE: items = player.getClan().getWarehouse().getItems(); break; default: _itemList = Collections.emptyList(); return; } _itemList = new ArrayList<ItemInfo>(items.length); ArrayUtils.eqSort(items, ItemClassComparator.getInstance()); for(ItemInstance item : items) _itemList.add(new ItemInfo(item)); _inventoryUsedSlots = player.getInventory().getSize(); } @Override protected final void writeImpl() { writeH(_type); writeQ(_adena); writeH(_itemList.size()); if(_type == 1 || _type == 2) { if(_itemList.size() > 0) { writeH(0x01); writeD(0x1063); // TODO: writeD(_itemList.get(0).getItemId()); первый предмет в списке. } else writeH(0x00); } writeD(_inventoryUsedSlots); //Количество занятых ячеек в инвентаре. for(ItemInfo item : _itemList) { writeItemInfo(item); writeD(item.getObjectId()); writeD(0); writeD(0); } } }
pantelis60/L2Scripts_Underground
gameserver/src/main/java/l2s/gameserver/network/l2/s2c/WareHouseWithdrawListPacket.java
Java
gpl-3.0
1,932
# -*- coding: utf-8 -*- from django.contrib import admin from models import FileMapping # Register your models here. admin.site.register(FileMapping)
tiankangkan/paper_plane
treasure/admin.py
Python
gpl-3.0
155
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Aviso de Privacidad</title> <!-- Bootstrap Core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Cinzel:400,700" rel="stylesheet" type="text/css"> <!-- Theme CSS --> <link href="css/creative.min.css" rel="stylesheet"> <!-- Pagina Inicial CSS --> <link href="css/pagina-inicial.css" rel="stylesheet"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body id="page-top"> <!-- Navegacion inicia --> <nav id="mainNav" class="navbar navbar-default navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i> </button> <a class="navbar-brand page-scroll" href="index.html">La Caja Blanca</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li> <a class="page-scroll" href="index.html#services">¿Cómo funciona?</a> </li> <li> <a class="page-scroll" href="index.html#contact">Contacto</a> </li> <li> <a class="page-scroll" href="#">Aviso de Privacidad</a> </li> <li> <a class="page-scroll" href="terminos-condiciones.html">Términos y Condiciones</a> </li> </ul> </div> </div> </nav> <!-- Navegacion termina --> <!-- Aviso inicia --> <section id="aviso"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 text-center"> <h2 class="section-heading">Aviso de Privacidad</h2> <hr class="primary"> </div> <div class="col-lg-8 aviso-privacidad"> <p>Nemosíntesis SC de RL, mejor conocido como La Caja Blanca, con domicilio en calle Río de la Plata 209, colonia Navarro, ciudad Torreón, municipio o delegación Torreón, C.P. 27010, en la entidad de Coahuila, país México, y portal de internet www.lacajablanca.mx, es el responsable del uso y protección de sus datos personales, y al respecto le informamos lo siguiente:</p> <p>¿Para qué fines utilizaremos sus datos personales?</p> <p>Los datos personales que recabamos de usted, los utilizaremos para las siguientes finalidades que son necesarias para el servicio que solicita:</p> <ul> <li>Para verificar y confirmar su identidad</li> <li>Para entrega de productos a domicilio</li> <li>Para llevar a cabo encuestas de satisfacción</li> <li>Para informarle y/o contactarle con fines mercadológicos</li> <li>Para evaluar la calidad de los productos</li> </ul> <p>De manera adicional, utilizaremos su información personal para las siguientes <b>finalidades secundarias</b> que no son necesarias para el servicio solicitado, pero que nos permiten y facilitan brindarle una mejor atención:</p> <ul> <li>Mercadotecnia o publicidad</li> <li>Prospección comercial</li> </ul> <p>En caso de que no desee que sus datos personales se utilicen para estos <b>fines secundarios</b>, indíquelo por medio de un correo electrónico a [email protected] con el mensaje:</p> <blockquote> No consiento que mis datos personales se utilicen para los fines de Mercadotecnia, publicidad o prospección comercial </blockquote> <p>La negativa para el uso de sus datos personales para estas finalidades no podrá ser un motivo para que le neguemos los servicios y productos que solicita o contrata con nosotros.</p> <p>¿Qué datos personales utilizaremos para estos fines?</p> Para llevar a cabo las finalidades descritas en el presente aviso de privacidad, utilizaremos los siguientes datos personales: <ul> <li>Nombre</li> <li>Nombre de su pareja o cónyuge</li> <li>Estado Civil</li> <li>Fecha de nacimiento</li> <li>Fecha de matrimonio civil</li> <li>Domicilio</li> <li>Teléfono particular</li> <li>Teléfono celular</li> <li> Correo electrónico</li> </ul> <p>¿Con quién compartimos su información personal y para qué fines?</p> <p>Le informamos que sus datos personales son compartidos dentro del país con empresas dedicadas al servicio de paquetería con la finalidad de hacer llegar los productos a su domicilio.</p> <p>¿Cómo puede acceder, rectificar o cancelar sus datos personales, u oponerse a su uso?</p> <p>Usted tiene derecho a conocer qué datos personales tenemos de usted, para qué los utilizamos y las condiciones del uso que les damos (Acceso). Asimismo, es su derecho solicitar la corrección de su información personal en caso de que esté desactualizada, sea inexacta o incompleta (Rectificación); que la eliminemos de nuestros registros o bases de datos cuando considere que la misma no está siendo utilizada adecuadamente (Cancelación); así como oponerse al uso de sus datos personales para fines específicos (Oposición). Estos derechos se conocen como derechos ARCO.</p> <p>Para el ejercicio de cualquiera de los derechos ARCO, usted deberá presentar la solicitud respectiva enviando un correo electrónico a [email protected]</p> <p>Para conocer el procedimiento y requisitos para el ejercicio de los derechos ARCO, ponemos a su disposición el siguiente medio: www.lacajablanca.mx/aviso-privacidad.html</p> <p>Los datos de contacto de la persona o departamento de datos personales, que está a cargo de dar trámite a las solicitudes de derechos ARCO, son los siguientes:</p> <p> a) Nombre de la persona o departamento de datos personales: Atención a Clientes La Caja Blanca<br> b) Domicilio: Calle Río de la Plata 2019, Colonia Navarro, Ciudad Torreón, C.P. 27010<br> c) Correo electrónico: [email protected]<br> d) Número telefónico: 8717179849<br></p> <p>Usted puede revocar el consentimiento que, en su caso, nos haya otorgado para el tratamiento de sus datos personales. Sin embargo, es importante que tenga en cuenta que no en todos los casos podremos atender su solicitud o concluir el uso de forma inmediata, ya que es posible que por alguna obligación legal requiramos seguir tratando sus datos personales. Asimismo, usted deberá considerar que para ciertos fines, la revocación de su consentimiento implicará que no le podamos seguir prestando el servicio que nos solicitó, o la conclusión de su relación con nosotros.</p> <p>Para revocar su consentimiento deberá presentar su solicitud a través del siguiente medio: [email protected]</p> <p>Para conocer el procedimiento y requisitos para la revocación del consentimiento, ponemos a su disposición el siguiente medio: www.lacajablanca.mx/aviso-privacidad.html</p> <p>¿Cómo puede limitar el uso o divulgación de su información personal? <p>Con objeto de que usted pueda limitar el uso y divulgación de su información personal, le ofrecemos los siguientes medios: [email protected]</p> <p>Asimismo, usted se podrá inscribir a los siguientes registros, en caso de que no desee obtener publicidad de nuestra parte:</p> <p>Registro Público para Evitar Publicidad, para mayor información consulte el portal de internet de la <a href="https://www.gob.mx/profeco">PROFECO</a><br> Registro Público de Usuarios, para mayor información consulte el portal de internet de la <a href="https://www.gob.mx/condusef">CONDUSEF</a>.</p> <p>¿Cómo puede conocer los cambios en este aviso de privacidad?</p> <p>El presente aviso de privacidad puede sufrir modificaciones, cambios o actualizaciones derivadas de nuevos requerimientos legals; de nuestras propias necesidades por los productos o servicios que ofrecemos; de nuestras prácticas de privacidad; de cambios en nuestro modelo de negocio, o por otras causas. Nos comprometemos a mantenerlo informado sobre los cambios que pueda sufrir el presente aviso de privacidad, a través de: www.lacajablanca.mx.</p> <p>El procedimiento a través del cual se llevarán a cabo las notificaciones sobre cambios o actualizaciones al presente aviso de privacidad es el siguiente: a través de la página de internet www.lacajablanca.mx</p> <p>Última actualización: 22/08/2017</p> </div> </div> </div> </section> <!-- Aviso termina --> <!-- jQuery --> <script src="vendor/jquery/jquery.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="vendor/bootstrap/js/bootstrap.min.js"></script> <!-- Theme JavaScript --> <script src="js/creative.min.js"></script> </body> </html>
LaCajaBlanca/lacajablanca.github.io
aviso-privacidad.html
HTML
gpl-3.0
10,047
<?php /** * BwPostman Newsletter Component * * BwPostman form field Text templates class. * * @version %%version_number%% * @package BwPostman-Admin * @author Karl Klostermann * @copyright (C) %%copyright_year%% Boldt Webservice <[email protected]> * @support https://www.boldt-webservice.de/en/forum-en/forum/bwpostman.html * @license GNU/GPL, see LICENSE.txt * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ namespace BoldtWebservice\Component\BwPostman\Administrator\Field; defined('JPATH_PLATFORM') or die; use BoldtWebservice\Component\BwPostman\Administrator\Helper\BwPostmanHelper; use Exception; use Joomla\CMS\Factory; use Joomla\CMS\Form\Field\RadioField; use Joomla\CMS\Language\Text; use Joomla\CMS\Uri\Uri; use RuntimeException; /** * Form Field class for the Joomla Platform. * Supports a nested check box field listing user groups. * Multi select is available by default. * * @package BwPostman.Administrator * * @since 1.2.0 */ class TexttemplatesField extends RadioField { /** * The form field type. * * @var string * * @since 1.2.0 */ protected $type = 'Texttemplates'; /** * Method to get the Text template field input markup. * * @return string The field input markup. * * @throws Exception * * @since 1.2.0 */ protected function getInput(): string { $item = Factory::getApplication()->getUserState('com_bwpostman.edit.newsletter.data'); $html = array(); $selected = ''; // Initialize some field attributes. $readonly = $this->readonly; // Get the field options. $options = $this->getOptions(); // Get selected template. if (is_object($item)) { $selected = $item->text_template_id; } // note for old templates if ($selected < 1) { $html[] = Text::_('COM_BWPOSTMAN_NOTE_OLD_TEMPLATE'); } if (count($options) > 0) { // Build the radio field output. foreach ($options as $i => $option) { // Initialize some option attributes. $checked = ((string) $option->value == (string) $selected) ? ' checked="checked"' : ''; $lblclass = ' class="mailinglists form-check-label"'; $inputclass = ' class="mailinglists form-check-input"'; $disabled = !empty($option->disable) || ($readonly && !$checked); $disabled = $disabled ? ' disabled' : ''; // Initialize some JavaScript option attributes. $onclick = !empty($option->onclick) ? ' onclick="' . $option->onclick . '"' : ''; $onchange = !empty($option->onchange) ? ' onchange="' . $option->onchange . '"' : ''; $html[] = '<div class="form-check" aria-describedby="tip-' . $this->id . $i . '">'; $html[] = '<input type="radio" id="' . $this->id . $i . '" name="' . $this->name . '" value="' . htmlspecialchars($option->value, ENT_COMPAT) . '"' . $checked . $inputclass . $onclick . $onchange . $disabled . ' />'; $html[] = '<label for="' . $this->id . $i . '"' . $lblclass . ' >'; $html[] = $option->title . '</label>'; $tooltip = '<strong>' . $option->description . '</strong><br /><br />' . '<div><img src="' . Uri::root() . $option->thumbnail . '" alt="' . $option->title . '"' .'style="max-width:160px; max-height:100px;" /></div>'; $html[] = '<div role="tooltip" id="tip-' . $this->id . $i . '">'.$tooltip.'</div>'; $html[] = '</div>'; } } else { $html[] = Text::_('COM_BWPOSTMAN_NO_DATA'); } // End the radio field output. // $html[] = '</div>'; return implode($html); } /** * Method to get the field options. * * @return array The field option objects. * * @throws Exception * * @since 1.2.0 */ public function getOptions(): array { $app = Factory::getApplication(); // Initialize variables. $item = $app->getUserState('com_bwpostman.edit.newsletter.data'); $options = array(); // prepare query $db = BwPostmanHelper::getDbo(); // Build the select list for the templates $query = $db->getQuery(true); $query->select($db->quoteName('id') . ' AS ' . $db->quoteName('value')); $query->select($db->quoteName('title') . ' AS ' . $db->quoteName('title')); $query->select($db->quoteName('description') . ' AS ' . $db->quoteName('description')); $query->select($db->quoteName('thumbnail') . ' AS ' . $db->quoteName('thumbnail')); $query->from($db->quoteName('#__bwpostman_templates')); // special for old newsletters with template_id < 1 if (is_object($item)) { if ($item->text_template_id < 1 && !is_null($item->text_template_id)) { $query->where($db->quoteName('id') . ' >= ' . $db->quote('-2')); } else { $query->where($db->quoteName('id') . ' > ' . $db->quote('0')); } } $query->where($db->quoteName('archive_flag') . ' = ' . $db->quote('0')); $query->where($db->quoteName('published') . ' = ' . $db->quote('1')); $query->where($db->quoteName('tpl_id') . ' > ' . $db->quote('997')); $query->order($db->quoteName('title') . ' ASC'); try { $db->setQuery($query); $options = $db->loadObjectList(); } catch (RuntimeException $e) { Factory::getApplication()->enqueueMessage($e->getMessage(), 'error'); } // Merge any additional options in the XML definition. return array_merge(parent::getOptions(), $options); } }
RomanaBW/BwPostman
src/administrator/components/com_bwpostman/src/Field/TexttemplatesField.php
PHP
gpl-3.0
5,859
#ifndef __BACKTRACE_H__ #define __BACKTRACE_H__ #include <stdint.h> void __backtrace(uintptr_t rbp, uintptr_t stack_begin, uintptr_t stack_end); uintptr_t stack_begin(void); uintptr_t stack_end(void); void backtrace(void); #endif /*__BACKTRACE_H__*/
ItsLastDay/academic_university_2016-2018
subjects/OperatingSystems/task4/inc/backtrace.h
C
gpl-3.0
253
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="ro"> <head> <!-- Generated by javadoc (version 1.7.0_80) on Mon Jun 20 18:37:10 EEST 2016 --> <title>SimplePrintPart (JasperReports 6.3.0 API)</title> <meta name="date" content="2016-06-20"> <link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="SimplePrintPart (JasperReports 6.3.0 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/SimplePrintPart.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../net/sf/jasperreports/engine/SimplePrintPageFormat.html" title="class in net.sf.jasperreports.engine"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../net/sf/jasperreports/engine/SimpleReportContext.html" title="class in net.sf.jasperreports.engine"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?net/sf/jasperreports/engine/SimplePrintPart.html" target="_top">Frames</a></li> <li><a href="SimplePrintPart.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">net.sf.jasperreports.engine</div> <h2 title="Class SimplePrintPart" class="title">Class SimplePrintPart</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>net.sf.jasperreports.engine.SimplePrintPart</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.io.Serializable, <a href="../../../../net/sf/jasperreports/engine/PrintPart.html" title="interface in net.sf.jasperreports.engine">PrintPart</a></dd> </dl> <hr> <br> <pre>public class <span class="strong">SimplePrintPart</span> extends java.lang.Object implements <a href="../../../../net/sf/jasperreports/engine/PrintPart.html" title="interface in net.sf.jasperreports.engine">PrintPart</a>, java.io.Serializable</pre> <dl><dt><span class="strong">Author:</span></dt> <dd>Teodor Danciu ([email protected])</dd> <dt><span class="strong">See Also:</span></dt><dd><a href="../../../../serialized-form.html#net.sf.jasperreports.engine.SimplePrintPart">Serialized Form</a></dd></dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><strong><a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html#SimplePrintPart()">SimplePrintPart</a></strong>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method_summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span>Methods</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html" title="class in net.sf.jasperreports.engine">SimplePrintPart</a></code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html#fromJasperPrint(net.sf.jasperreports.engine.JasperPrint,%20java.lang.String)">fromJasperPrint</a></strong>(<a href="../../../../net/sf/jasperreports/engine/JasperPrint.html" title="class in net.sf.jasperreports.engine">JasperPrint</a>&nbsp;partJasperPrint, java.lang.String&nbsp;partName)</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html#getName()">getName</a></strong>()</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../net/sf/jasperreports/engine/PrintPageFormat.html" title="interface in net.sf.jasperreports.engine">PrintPageFormat</a></code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html#getPageFormat()">getPageFormat</a></strong>()</code>&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html#setName(java.lang.String)">setName</a></strong>(java.lang.String&nbsp;name)</code>&nbsp;</td> </tr> <tr class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><strong><a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html#setPageFormat(net.sf.jasperreports.engine.PrintPageFormat)">setPageFormat</a></strong>(<a href="../../../../net/sf/jasperreports/engine/PrintPageFormat.html" title="interface in net.sf.jasperreports.engine">PrintPageFormat</a>&nbsp;pageFormat)</code>&nbsp;</td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods_inherited_from_class_java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor_detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="SimplePrintPart()"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>SimplePrintPart</h4> <pre>public&nbsp;SimplePrintPart()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method_detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="fromJasperPrint(net.sf.jasperreports.engine.JasperPrint, java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>fromJasperPrint</h4> <pre>public static&nbsp;<a href="../../../../net/sf/jasperreports/engine/SimplePrintPart.html" title="class in net.sf.jasperreports.engine">SimplePrintPart</a>&nbsp;fromJasperPrint(<a href="../../../../net/sf/jasperreports/engine/JasperPrint.html" title="class in net.sf.jasperreports.engine">JasperPrint</a>&nbsp;partJasperPrint, java.lang.String&nbsp;partName)</pre> </li> </ul> <a name="getName()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getName</h4> <pre>public&nbsp;java.lang.String&nbsp;getName()</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../net/sf/jasperreports/engine/PrintPart.html#getName()">getName</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../net/sf/jasperreports/engine/PrintPart.html" title="interface in net.sf.jasperreports.engine">PrintPart</a></code></dd> </dl> </li> </ul> <a name="setName(java.lang.String)"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setName</h4> <pre>public&nbsp;void&nbsp;setName(java.lang.String&nbsp;name)</pre> </li> </ul> <a name="getPageFormat()"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getPageFormat</h4> <pre>public&nbsp;<a href="../../../../net/sf/jasperreports/engine/PrintPageFormat.html" title="interface in net.sf.jasperreports.engine">PrintPageFormat</a>&nbsp;getPageFormat()</pre> <dl> <dt><strong>Specified by:</strong></dt> <dd><code><a href="../../../../net/sf/jasperreports/engine/PrintPart.html#getPageFormat()">getPageFormat</a></code>&nbsp;in interface&nbsp;<code><a href="../../../../net/sf/jasperreports/engine/PrintPart.html" title="interface in net.sf.jasperreports.engine">PrintPart</a></code></dd> </dl> </li> </ul> <a name="setPageFormat(net.sf.jasperreports.engine.PrintPageFormat)"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>setPageFormat</h4> <pre>public&nbsp;void&nbsp;setPageFormat(<a href="../../../../net/sf/jasperreports/engine/PrintPageFormat.html" title="interface in net.sf.jasperreports.engine">PrintPageFormat</a>&nbsp;pageFormat)</pre> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="class-use/SimplePrintPart.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../index-all.html">Index</a></li> <li><a href="../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../net/sf/jasperreports/engine/SimplePrintPageFormat.html" title="class in net.sf.jasperreports.engine"><span class="strong">Prev Class</span></a></li> <li><a href="../../../../net/sf/jasperreports/engine/SimpleReportContext.html" title="class in net.sf.jasperreports.engine"><span class="strong">Next Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../index.html?net/sf/jasperreports/engine/SimplePrintPart.html" target="_top">Frames</a></li> <li><a href="SimplePrintPart.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor_detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method_detail">Method</a></li> </ul> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <span style="font-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:8pt;font-style:normal;color:#000000;">&copy; 2001 - 2016 TIBCO Software Inc. <a href="http://www.jaspersoft.com" target="_blank" style="color:#000000;">www.jaspersoft.com</a></span> </small></p> </body> </html>
MHTaleb/Encologim
lib/JasperReport/docs/api/net/sf/jasperreports/engine/SimplePrintPart.html
HTML
gpl-3.0
13,195
/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo * This benchmark is part of SWSC */ #include <assert.h> #include <stdint.h> #include <stdatomic.h> #include <pthread.h> atomic_int vars[3]; atomic_int atom_0_r3_2; atomic_int atom_1_r1_1; void *t0(void *arg){ label_1:; atomic_store_explicit(&vars[0], 2, memory_order_seq_cst); int v2_r3 = atomic_load_explicit(&vars[0], memory_order_seq_cst); int v3_r4 = v2_r3 ^ v2_r3; atomic_store_explicit(&vars[1+v3_r4], 1, memory_order_seq_cst); atomic_store_explicit(&vars[2], 1, memory_order_seq_cst); int v14 = (v2_r3 == 2); atomic_store_explicit(&atom_0_r3_2, v14, memory_order_seq_cst); return NULL; } void *t1(void *arg){ label_2:; int v5_r1 = atomic_load_explicit(&vars[2], memory_order_seq_cst); int v6_r3 = v5_r1 ^ v5_r1; int v7_r3 = v6_r3 + 1; atomic_store_explicit(&vars[0], v7_r3, memory_order_seq_cst); int v15 = (v5_r1 == 1); atomic_store_explicit(&atom_1_r1_1, v15, memory_order_seq_cst); return NULL; } int main(int argc, char *argv[]){ pthread_t thr0; pthread_t thr1; atomic_init(&vars[0], 0); atomic_init(&vars[2], 0); atomic_init(&vars[1], 0); atomic_init(&atom_0_r3_2, 0); atomic_init(&atom_1_r1_1, 0); pthread_create(&thr0, NULL, t0, NULL); pthread_create(&thr1, NULL, t1, NULL); pthread_join(thr0, NULL); pthread_join(thr1, NULL); int v8 = atomic_load_explicit(&atom_0_r3_2, memory_order_seq_cst); int v9 = atomic_load_explicit(&vars[0], memory_order_seq_cst); int v10 = (v9 == 2); int v11 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); int v12_conj = v10 & v11; int v13_conj = v8 & v12_conj; if (v13_conj == 1) assert(0); return 0; }
nidhugg/nidhugg
tests/litmus/C-tests/DETOUR0477.c
C
gpl-3.0
1,695
<?php namespace App\Model\Table; use App\Model\Entity\Guest; use Cake\ORM\Query; use Cake\ORM\RulesChecker; use Cake\ORM\Table; use Cake\Validation\Validator; /** * Guests Model * * @property \Cake\ORM\Association\BelongsTo $Matchteams * @property \Cake\ORM\Association\BelongsToMany $Hosts */ class GuestsTable extends Table { /** * Initialize method * * @param array $config The configuration for the Table. * @return void */ public function initialize(array $config) { parent::initialize($config); $this->table('guests'); $this->displayField('name'); $this->primaryKey('id'); $this->belongsTo('Matchteams', [ 'foreignKey' => 'matchteam_id' ]); $this->belongsToMany('Hosts', [ 'foreignKey' => 'guest_id', 'targetForeignKey' => 'host_id', 'joinTable' => 'hosts_guests' ]); } /** * Default validation rules. * * @param \Cake\Validation\Validator $validator Validator instance. * @return \Cake\Validation\Validator */ public function validationDefault(Validator $validator) { $validator ->add('id', 'valid', ['rule' => 'numeric']) ->allowEmpty('id', 'create'); $validator ->add('primary_squad', 'valid', ['rule' => 'boolean']) ->allowEmpty('primary_squad'); $validator ->allowEmpty('name'); $validator ->allowEmpty('yellow'); $validator ->allowEmpty('red'); $validator ->allowEmpty('substitution'); $validator ->allowEmpty('goals'); $validator ->allowEmpty('rating'); $validator ->allowEmpty('assist'); $validator ->allowEmpty('injuries'); return $validator; } /** * Returns a rules checker object that will be used for validating * application integrity. * * @param \Cake\ORM\RulesChecker $rules The rules object to be modified. * @return \Cake\ORM\RulesChecker */ public function buildRules(RulesChecker $rules) { $rules->add($rules->existsIn(['matchteam_id'], 'Matchteams')); return $rules; } }
pacior/testimonials
src/Model/Table/GuestsTable.php
PHP
gpl-3.0
2,307
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. require_once('../../config.php'); require_once($CFG->dirroot.'/mod/scorm/locallib.php'); $id = optional_param('id', '', PARAM_INT); // Course Module ID, or $a = optional_param('a', '', PARAM_INT); // scorm ID $scoid = required_param('scoid', PARAM_INT); // sco ID $attempt = required_param('attempt', PARAM_INT); // attempt number if (!empty($id)) { if (! $cm = get_coursemodule_from_id('scorm', $id)) { print_error('invalidcoursemodule'); } if (! $course = $DB->get_record("course", array("id"=>$cm->course))) { print_error('coursemisconf'); } if (! $scorm = $DB->get_record("scorm", array("id"=>$cm->instance))) { print_error('invalidcoursemodule'); } } else if (!empty($a)) { if (! $scorm = $DB->get_record("scorm", array("id"=>$a))) { print_error('invalidcoursemodule'); } if (! $course = $DB->get_record("course", array("id"=>$scorm->course))) { print_error('coursemisconf'); } if (! $cm = get_coursemodule_from_instance("scorm", $scorm->id, $course->id)) { print_error('invalidcoursemodule'); } } else { print_error('missingparameter'); } $PAGE->set_url('/mod/scorm/datamodel.php', array('scoid'=>$scoid, 'attempt'=>$attempt, 'id'=>$cm->id)); require_login($course, false, $cm); if (confirm_sesskey() && (!empty($scoid))) { $result = true; $request = null; if (has_capability('mod/scorm:savetrack', context_module::instance($cm->id))) { foreach (data_submitted() as $element => $value) { $element = str_replace('__', '.', $element); if (substr($element, 0, 3) == 'cmi') { $netelement = preg_replace('/\.N(\d+)\./', "\.\$1\.", $element); $result = scorm_insert_track($USER->id, $scorm->id, $scoid, $attempt, $element, $value, $scorm->forcecompleted) && $result; } if (substr($element, 0, 15) == 'adl.nav.request') { // SCORM 2004 Sequencing Request require_once($CFG->dirroot.'/mod/scorm/datamodels/scorm_13lib.php'); $search = array('@continue@', '@previous@', '@\{target=(\S+)\}choice@', '@exit@', '@exitAll@', '@abandon@', '@abandonAll@'); $replace = array('continue_', 'previous_', '\1', 'exit_', 'exitall_', 'abandon_', 'abandonall'); $action = preg_replace($search, $replace, $value); if ($action != $value) { // Evaluating navigation request $valid = scorm_seq_overall ($scoid, $USER->id, $action, $attempt); $valid = 'true'; // Set valid request $search = array('@continue@', '@previous@', '@\{target=(\S+)\}choice@'); $replace = array('true', 'true', 'true'); $matched = preg_replace($search, $replace, $value); if ($matched == 'true') { $request = 'adl.nav.request_valid["'.$action.'"] = "'.$valid.'";'; } } } } } if ($result) { echo "true\n0"; } else { echo "false\n101"; } if ($request != null) { echo "\n".$request; } }
ouyangyu/fdmoodle
mod/scorm/datamodel.php
PHP
gpl-3.0
4,031
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Richard Benson In Memory</title> <link rel="stylesheet" href="build/benson.css"> <script type="text/javascript" src="../../node_modules/jquery/dist/jquery.js"></script> <script type="text/javascript" src="../../node_modules/materialize-css/dist/js/materialize.js"></script> </head> <body> <div id="all"> <nav> <a href="../Home/"> <div id="brand"> <img src="../Logo.png" alt="Yale School of Art" id="logo"> <h1>Yale School of Art</h1> </div> </a> <div class="menu-list"> <div class="menu-item"> <div class="sub-items-trigger">Academic</div> <ul class="sub-items"> <li><a href="../Calendar">Calendar</a></li> <li><a href="http://art.yale.edu/Courses">Courses</a></li> <li><a href="http://art.yale.edu/StudyAreas">Study Area</a></li> <li><a href="http://art.yale.edu/SummerPrograms">Summer Programs</a></li> <li><a href="http://art.yale.edu/gallery">Gallery</a></li> </ul> </div> <div class="menu-item"> <div class="sub-items-trigger">Admission</div> <ul class="sub-items"> <li><a href="http://art.yale.edu/Admissions">General</a></li> <li><a href="http://art.yale.edu/FinancialAid">Financial Aid</a></li> <li><a href="http://art.yale.edu/Visiting">Visiting</a></li> </ul> </div> <div class="menu-item"> <div class="sub-items-trigger">Events</div> <ul class="sub-items"> <li><a href="../Events/112days.html">112 Days in New Heaven</a></li> <li><a href="../Events/1971life.html">Life of Color</a></li> <li><a href="../Events/benson.html">Richard Benson</a></li> </ul> </div> <div class="menu-item"> <div class="sub-items-trigger">People</div> <ul class="sub-items"> <li><a href="http://art.yale.edu/Alums">Alums</a></li> <li><a href="http://art.yale.edu/CurrentStudents">Current Students</a></li> <li><a href="http://art.yale.edu/FacultyAndStaff">Faculty</a></li> <li><a href="http://art.yale.edu/undergraduate">Undergrads</a></li> </ul> </div> <div class="menu-item"> <div class="sub-items-trigger">About</div> <ul class="sub-items"> <li><a href="http://art.yale.edu/AboutThisSite">This Site</a></li> <li><a href="http://art.yale.edu/RecentChanges">Recent Changes</a></li> <li><a href="../Contact">Contact</a></li> </ul> </div> </div> </nav> <div class="section" id="content"> <div class="header"> <img src="memory.png" alt="good looking professor" id="prof-photo"> <h1>Richard Benson In Memory 1943 - 2017</h1> </div> <div class="articles"> <div class="article"> <h2>A Letter from Dean Marta Kuzma</h2> <p>Dear Members of the Yale School of Art Community,</p> <p>It is with sincere regret that I must inform you of the death of Richard Benson—a renowned authority on the history of photographic printing, an American photographer, an author, a former Yale University professor, and Dean of the Yale School of Art from 1996 to 2006. I hadn’t the opportunity to get to know my predecessor, although one does not need to look far to understand his immense contribution to the field of photography. Some years ago, The Guardian’s literary editor Liz Jobey aptly wrote:</p> <p>“A long time ago I read a New Yorker profile of a master photographic printer called Richard Benson. It was titled, with that deliberate matter-of-factness that New Yorker titles invariably have, ‘A single person making a single thing’. This man was a unique craftsman, who great photographers and great institutions turned to when they wanted their pictures printed better than ever before. He had printed photographs by Alfred Stieglitz, Paul Strand and Lee Friedlander, as well as three volumes of the works of great French photographer Eugène Atget for the Museum of Modern Art. He had made an unsurpassed volume of prints for the collector Howard Gilman, whose collection is now part of the Metropolitan Museum of Art in New York. And in 1986 Benson had been awarded a MacArthur Foundation grant worth nearly quarter of a million dollars to carry on doing what he did so well.”</p> <p>As a testimony to the series of lectures he had given at the Yale School of Art over a period of three decades, Richard Benson, more commonly known among friends as “Chip” co-curated with Peter Galassi an exhibition at New York’s MoMA in 2008 called “The Printed Picture.” The exhibition and accompanying book reflected Benson’s perspective on the evolution of the printed still image and traced the changing technology of making and distributing pictures from the Renaissance to the present. He was the recipient of numerous honors including two publication grants from the National Endowment of the Arts; two Guggenheim fellowships; the Rhode Island Governor’s Medal for the Arts; and a MacArthur Foundation fellowship. His work—located within the permanent collections of the Metropolitan Museum; New York’s MoMA; the Nelson-Atkins Museum of Art in Kansas City, Missouri; and the Yale University Art Gallery in New Haven; among others.</p> <p>Upon his retirement from Yale, the acclaimed photographer and Yale School of Art Professor Emeritus Tod Papageorge noted in his Tribute to Richard Benson, “He’s a special kind, the sort that reminds us that the words genius and genial share a common root. For who here doesn’t understand that Benson’s great good nature is at the core of his ability to accomplish so much in so many different ways?” Tod has written another tribute in memory of Chip, which you can read on the School of Art website by clicking here .</p> <p>I expect there are so many who would wish to express their sincere condolences and also to reflect upon Chip Benson as a friend, teacher, and dean. We ask that you kindly send your thoughts to the School of Art so that we may gather these respects in celebration of Richard Benson and share them with our community in the coming weeks.</p> With respectful wishes,<br> Marta Kuzma Dean Yale School of Art New Haven </div> <div class="article"> <h2>RICHARD BENSON: IN MEMORIAM</h2> <p>Richard Benson was born and raised in the seacoast town of Newport, Rhode Island, the third and youngest son of a Quaker mother and an ardent Catholic father. As a boy, he was so happy in his skin that his mother called him her “little ray of sunshine”; later on, befitting a child whose father was a stonecutter, she and nearly everyone else came to call him “Chip.”</p> <p>His father, John Howard Benson, considered the greatest calligrapher and stone-letterer of his time, died when Chip was twelve. The year before, W. K. Wimsatt, a chess partner of Benson’s and a legendary English professor at Yale, successfully championed his dying friend for an honorary degree at the university, joining, for the first time, the Benson name and the school. This, however, had no observable effect on Chip, who, left with only a few sharp memories of his father, and thereby insulated from having to measure his life against that of an extraordinary man, gave up his education after one semester at Brown, explaining to Brown’s president—another friend of John Howard Benson’s—that he was leaving the school so that he could work with his hands. (It’s worth adding that Richard was directed from the president’s office to the dean of students for his send-off, which, in its entirety, consisted of the dean reading to him the first chapter of Moby Dick.)</p> <p>From Providence, he took a crooked course for himself, moving on from the Navy to a minimum-wage job in a Connecticut printing plant and then an unparalleled career back in Newport as a photographer, master printer, and inventor of radical new techniques of photographic reproduction. Only after all of that did he himself cross paths with Yale, first as a great teacher in the Department of Photography and, fifteen years later, as an admired dean of the School of Art, before retiring in 2011 to pursue whatever interests attracted the sharp edge of his curiosity.</p> <p>In 1986, Richard was awarded a grant from the MacArthur Foundation, an achievement characterized in the popular press as the “genius” award. In his case, the description was appropriate, as anyone who was exposed to the range and depth of his understanding about any number of things, including, of course, photography—or sailing ships or electricity or hydraulics—would testify. But, to my mind, Richard more nearly demonstrated through his life and actions that “genius” shares a common root with the word “genial,” the subject I feel myself pressed to write about here. For his great, good nature was at the core of his ability to accomplish so much in so many different ways, and to earn effortlessly the admiration and love of so many people. After all, who can resist loving the person who, out of hand, has just offered to help by giving over his time and knowledge in response to an earnest, or even casual, request? And, moreover, a person who, it turns out, will give more greatly the more he’s asked to, as if, like the sun, he trusts his own energy will grow as its excess burns away serving others.</p> <p>We’ve recently learned that, put crudely, the more a person gives, the happier, or better, he or she will feel, a truth that’s now been traced in the workings of the brain. Richard Benson demonstrated that bit of science in how he lived, although, in his case, it appeared that feeling good, his natural state, directed his doing good, rather than the other way around. And, perhaps because of this difference, his mode and range of doing good, at least to me, seemed virtually Olympian, by being so outsized and barely earthbound (although, like the sailor he was, the man himself cantered his way bow-legged through the world). For as his students and friends all recognized, there was something large and unprecedented in his willingness to shower his energy and brilliance on everyone around him, more and yet more, today and forever. Until now.</p> <p>Perhaps, rather than invoking the sun and the Olympians, it would have been enough for me to say about Richard that whenever I worked through the logic of imagining a possible model of an achieved human being for my son, I invariably ended up with him, a man who straddled with natural ease—I’d guess because of his happy marriage to Barbara—what artists often find to be the intractable contradiction between loving and art that Yeats described as “the perfection of the life or of the work.” But this isn’t the time, immediately after his death, for teasing contradictions into sense. And so I’ve been led, at least at this moment, to invoke a star, and the Greek gods, to counter sense. For Richard Benson was so unrelentingly generous, and good, and spirited in the manner that only the very best of us have been, that a nod to the heavens—or more, as each of us is inclined—seems the least we can do to honor his memory. A small enough gesture to give back to our dear friend and extraordinary man.</p> <p>The first portion of this text was adapted from a talk presented by Tod Papageorge during a celebration of Richard Benson’s deanship, from 1995 to 2006, of the Yale School of Art.</p> </div> </div> </div> <footer id="footer"> <div id="about"> <h3>About This Page</h3> <p><b>A canvas for everyone.</b> This website is a wiki. All School of Art grad students, faculty, staff, and alums have the ability to change most of this site’s content (with some exceptions); and to add new content and pages.</p> <p> Content is the property of its various authors. When you contribute to this site, you agree to abide by Yale University academic and network use policy, and to act as a responsible member of our community. In this way, we hope the content of this site reflects the unique vitality of our school.</p> </div> <div id="contact"> <h3>Contact Us</h3> Yale School of Art<br> 1156 Chapel Street, POB 208339<br> New Haven, Connecticut, 06520-8339<br> (203) 432-2600 </div> </footer> </div> </body> </html>
chantisnake/COMP298
project2/Events/benson.html
HTML
gpl-3.0
13,527
"use strict"; /* Copyright (C) 2013-2017 Bryan Hughes <[email protected]> Aquarium Control is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Aquarium Control is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Aquarium Control. If not, see <http://www.gnu.org/licenses/>. */ Object.defineProperty(exports, "__esModule", { value: true }); // Force to "any" type, otherwise TypeScript thinks the type is too strict exports.cleaningValidationSchema = { type: 'object', properties: { time: { required: true, type: 'number' }, bioFilterReplaced: { required: true, type: 'boolean' }, mechanicalFilterReplaced: { required: true, type: 'boolean' }, spongeReplaced: { required: true, type: 'boolean' } } }; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiSUNsZWFuaW5nLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2NvbW1vbi9zcmMvSUNsZWFuaW5nLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTs7Ozs7Ozs7Ozs7Ozs7O0VBZUU7O0FBYUYsMEVBQTBFO0FBQzdELFFBQUEsd0JBQXdCLEdBQVE7SUFDM0MsSUFBSSxFQUFFLFFBQVE7SUFDZCxVQUFVLEVBQUU7UUFDVixJQUFJLEVBQUU7WUFDSixRQUFRLEVBQUUsSUFBSTtZQUNkLElBQUksRUFBRSxRQUFRO1NBQ2Y7UUFDRCxpQkFBaUIsRUFBRTtZQUNqQixRQUFRLEVBQUUsSUFBSTtZQUNkLElBQUksRUFBRSxTQUFTO1NBQ2hCO1FBQ0Qsd0JBQXdCLEVBQUU7WUFDeEIsUUFBUSxFQUFFLElBQUk7WUFDZCxJQUFJLEVBQUUsU0FBUztTQUNoQjtRQUNELGNBQWMsRUFBRTtZQUNkLFFBQVEsRUFBRSxJQUFJO1lBQ2QsSUFBSSxFQUFFLFNBQVM7U0FDaEI7S0FDRjtDQUNGLENBQUMifQ==
nebrius/aquarium-control
server/dist/common/src/ICleaning.js
JavaScript
gpl-3.0
1,996
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Controls; namespace Chess { public abstract class Screen : UserControl { public ScreenControl parentWindow; public ScreenControl ParentWindow { get { return parentWindow; } } protected Screen() { } public Screen(ScreenControl parentWindow) { this.parentWindow = parentWindow; } } }
TomHulme/P4P
Chess/Screen.cs
C#
gpl-3.0
468
package com.habitrpg.android.habitica.ui.activities; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.text.SpannableString; import android.text.style.UnderlineSpan; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TableRow; import android.widget.TextView; import com.amplitude.api.Amplitude; import com.facebook.AccessToken; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import com.habitrpg.android.habitica.APIHelper; import com.habitrpg.android.habitica.HostConfig; import com.habitrpg.android.habitica.R; import com.habitrpg.android.habitica.callbacks.HabitRPGUserCallback; import com.habitrpg.android.habitica.prefs.scanner.IntentIntegrator; import com.habitrpg.android.habitica.prefs.scanner.IntentResult; import com.magicmicky.habitrpgwrapper.lib.models.HabitRPGUser; import com.magicmicky.habitrpgwrapper.lib.models.UserAuthResponse; import org.json.JSONException; import org.json.JSONObject; import butterknife.Bind; import butterknife.BindString; import butterknife.ButterKnife; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; /** * @author Mickael Goubin */ public class LoginActivity extends AppCompatActivity implements Callback<UserAuthResponse>,HabitRPGUserCallback.OnUserReceived { private final static String TAG_ADDRESS="address"; private final static String TAG_USERID="user"; private final static String TAG_APIKEY="key"; private APIHelper mApiHelper; public String mTmpUserToken; public String mTmpApiToken; public Boolean isRegistering; private Menu menu; @BindString(R.string.SP_address_default) String apiAddress; //private String apiAddress; //private String apiAddress = "http://192.168.2.155:8080/"; // local testing private CallbackManager callbackManager; @Bind(R.id.login_btn) Button mLoginNormalBtn; @Bind(R.id.PB_AsyncTask) ProgressBar mProgressBar; @Bind(R.id.username) EditText mUsernameET; @Bind(R.id.password) EditText mPasswordET; @Bind(R.id.email) EditText mEmail; @Bind(R.id.confirm_password) EditText mConfirmPassword; @Bind(R.id.email_row) TableRow mEmailRow; @Bind(R.id.confirm_password_row) TableRow mConfirmPasswordRow; @Bind(R.id.login_button) LoginButton mFacebookLoginBtn; @Bind(R.id.forgot_pw_tv) TextView mForgotPWTV; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login_screen); //Set default values to avoid null-responses when requesting unedited settings PreferenceManager.setDefaultValues(this, R.xml.preferences_account_details, false); PreferenceManager.setDefaultValues(this, R.xml.preferences_fragment, false); ButterKnife.bind(this); mLoginNormalBtn.setOnClickListener(mLoginNormalClick); mFacebookLoginBtn.setReadPermissions("user_friends"); mForgotPWTV.setOnClickListener(mForgotPWClick); SpannableString content = new SpannableString(mForgotPWTV.getText()); content.setSpan(new UnderlineSpan(), 0, content.length(), 0); mForgotPWTV.setText(content); callbackManager = CallbackManager.Factory.create(); mFacebookLoginBtn.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { AccessToken accessToken = AccessToken.getCurrentAccessToken(); mApiHelper.connectSocial(accessToken.getUserId(), accessToken.getToken(), LoginActivity.this); } @Override public void onCancel() { Log.d("FB Login", "Cancelled"); } @Override public void onError(FacebookException exception) { Log.e("FB Login", "Error", exception); } }); HostConfig hc= PrefsActivity.fromContext(this); if(hc ==null) { hc = new HostConfig(apiAddress, "80", "", ""); } mApiHelper = new APIHelper(hc); this.isRegistering = true; JSONObject eventProperties = new JSONObject(); try { eventProperties.put("eventAction", "navigate"); eventProperties.put("eventCategory", "navigation"); eventProperties.put("hitType", "pageview"); eventProperties.put("page", this.getClass().getSimpleName()); } catch (JSONException exception) { } Amplitude.getInstance().logEvent("navigate", eventProperties); } private void resetLayout() { if (this.isRegistering) { if (this.mEmailRow.getVisibility() == View.GONE) { expand(this.mEmailRow); } if (this.mConfirmPasswordRow.getVisibility() == View.GONE) { expand(this.mConfirmPasswordRow); } } else { if (this.mEmailRow.getVisibility() == View.VISIBLE) { collapse(this.mEmailRow); } if (this.mConfirmPasswordRow.getVisibility() == View.VISIBLE) { collapse(this.mConfirmPasswordRow); } } } private View.OnClickListener mLoginNormalClick = new View.OnClickListener() { @Override public void onClick(View v) { mProgressBar.setVisibility(View.VISIBLE); if (isRegistering) { String username, email,password,cpassword; username = String.valueOf(mUsernameET.getText()).trim(); email = String.valueOf(mEmail.getText()).trim(); password = String.valueOf(mPasswordET.getText()); cpassword = String.valueOf(mConfirmPassword.getText()); if (username.length() == 0 || password.length() == 0 || email.length() == 0 || cpassword.length() == 0) { showValidationError(R.string.login_validation_error_fieldsmissing); return; } mApiHelper.registerUser(username,email,password, cpassword, LoginActivity.this); } else { String username,password; username = String.valueOf(mUsernameET.getText()).trim(); password = String.valueOf(mPasswordET.getText()); if (username.length() == 0 || password.length() == 0) { showValidationError(R.string.login_validation_error_fieldsmissing); return; } mApiHelper.connectUser(username,password, LoginActivity.this); } } }; private View.OnClickListener mForgotPWClick = new View.OnClickListener() { @Override public void onClick(View v) { String url = getString(R.string.SP_address_default); Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } }; public static void expand(final View v) { v.setVisibility(View.VISIBLE); } public static void collapse(final View v) { v.setVisibility(View.GONE); } private void startMainActivity() { Intent intent = new Intent(LoginActivity.this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } private void startSetupActivity() { Intent intent = new Intent(LoginActivity.this, SetupActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); finish(); } private void toggleRegistering() { this.isRegistering = !this.isRegistering; this.setRegistering(); } private void setRegistering() { MenuItem menuItem = menu.findItem(R.id.action_toggleRegistering); if (this.isRegistering) { this.mLoginNormalBtn.setText(getString(R.string.register_btn)); menuItem.setTitle(getString(R.string.login_btn)); mUsernameET.setHint(R.string.username); mPasswordET.setImeOptions(EditorInfo.IME_ACTION_NEXT); } else { this.mLoginNormalBtn.setText(getString(R.string.login_btn)); menuItem.setTitle(getString(R.string.register_btn)); mUsernameET.setHint(R.string.email_username); mPasswordET.setImeOptions(EditorInfo.IME_ACTION_DONE); } this.resetLayout(); } public void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); callbackManager.onActivityResult(requestCode, resultCode, intent); IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); if (scanResult != null) { try { Log.d("scanresult", scanResult.getContents()); this.parse(scanResult.getContents()); } catch(Exception e) { Log.e("scanresult", "Could not parse scanResult", e); } } } private void parse(String contents) { String adr,user,key; try { JSONObject obj; obj = new JSONObject(contents); adr = obj.getString(TAG_ADDRESS); user = obj.getString(TAG_USERID); key = obj.getString(TAG_APIKEY); Log.d("", "adr" + adr + " user:" + user + " key" + key); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = prefs.edit(); boolean ans = editor.putString(getString(R.string.SP_address), adr) .putString(getString(R.string.SP_APIToken), key) .putString(getString(R.string.SP_userID), user) .commit(); if(!ans) { throw new Exception("PB_string_commit"); } startMainActivity(); } catch (JSONException e) { showSnackbar(getString(R.string.ERR_pb_barcode)); e.printStackTrace(); } catch(Exception e) { if("PB_string_commit".equals(e.getMessage())) { showSnackbar(getString(R.string.ERR_pb_barcode)); } } } private void showSnackbar(String content) { Snackbar snackbar = Snackbar .make(this.findViewById(R.id.login_linear_layout), content, Snackbar.LENGTH_LONG); View snackbarView = snackbar.getView(); snackbarView.setBackgroundColor(Color.RED);//change Snackbar's background color; snackbar.show(); // Don’t forget to show! } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.login, menu); this.menu = menu; return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.action_toggleRegistering: toggleRegistering(); break; } return super.onOptionsItemSelected(item); } private void afterResults() { mProgressBar.setVisibility(View.INVISIBLE); } @Override public void success(UserAuthResponse userAuthResponse, Response response) { try { saveTokens(userAuthResponse.getToken(), userAuthResponse.getId()); } catch (Exception e) { e.printStackTrace(); } if (this.isRegistering) { this.startSetupActivity(); } else { JSONObject eventProperties = new JSONObject(); try { eventProperties.put("eventAction", "lofin"); eventProperties.put("eventCategory", "behaviour"); eventProperties.put("hitType", "event"); } catch (JSONException exception) { } Amplitude.getInstance().logEvent("login", eventProperties); this.startMainActivity(); } } private void saveTokens(String api, String user) throws Exception { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this); SharedPreferences.Editor editor = prefs.edit(); boolean ans = editor.putString(getString(R.string.SP_APIToken), api) .putString(getString(R.string.SP_userID), user) .putString(getString(R.string.SP_address),getString(R.string.SP_address_default)) .commit(); if(!ans) { throw new Exception("PB_string_commit"); } } @Override public void failure(RetrofitError error) { mProgressBar.setVisibility(View.GONE); } @Override public void onUserReceived(HabitRPGUser user) { try { saveTokens(mTmpApiToken, mTmpUserToken); } catch (Exception e) { e.printStackTrace(); } this.startMainActivity(); } @Override public void onUserFail() { mProgressBar.setVisibility(View.GONE); showSnackbar(getString(R.string.unknown_error)); } private void showValidationError(int resourceMessageString) { mProgressBar.setVisibility(View.GONE); new android.support.v7.app.AlertDialog.Builder(this) .setTitle(R.string.login_validation_error_title) .setMessage(resourceMessageString) .setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }) .setIcon(R.drawable.ic_warning_black) .show(); } }
yishanhe/habitrpg-android
Habitica/src/com/habitrpg/android/habitica/ui/activities/LoginActivity.java
Java
gpl-3.0
13,599
<?php namespace hemio\html; /** * The <code>figure</code> element represents a unit of content, optionally with * a caption, that is self-contained, that is typically referenced as a single * unit from the main flow of the document, and that can be moved away from the * main flow of the document without affecting the document’s meaning. * * @since version 1.0 * @url http://www.w3.org/TR/html5/grouping-content.html#the-figure-element */ class Figure extends Abstract_\ElementContent { use Trait_\DefaultElementContent; public static function tagName() { return 'figure'; } public function blnIsBlock() { return true; } }
qua-bla/html
src/Figure.php
PHP
gpl-3.0
683
/* * Copyright (C) 2010-2019 The ESPResSo project * Copyright (C) 2002,2003,2004,2005,2006,2007,2008,2009,2010 * Max-Planck-Institute for Polymer Research, Theory Group * * This file is part of ESPResSo. * * ESPResSo is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ESPResSo is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SCRIPT_INTERFACE_COM_FIXED_HPP #define SCRIPT_INTERFACE_COM_FIXED_HPP #include "script_interface/ScriptInterface.hpp" #include "core/comfixed_global.hpp" namespace ScriptInterface { class ComFixed : public AutoParameters<ComFixed> { public: ComFixed() { add_parameters({{"types", [](Variant const &v) { comfixed.set_fixed_types(get_value<std::vector<int>>(v)); }, []() { return comfixed.get_fixed_types(); }}}); } }; } // namespace ScriptInterface #endif
KaiSzuttor/espresso
src/script_interface/ComFixed.hpp
C++
gpl-3.0
1,418
/** * Copyright (C) 2010-2016 Structr GmbH * * This file is part of Structr <http://structr.org>. * * Structr is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * Structr is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Structr. If not, see <http://www.gnu.org/licenses/>. */ package org.structr.core.function; import org.structr.common.error.FrameworkException; import org.structr.common.error.SemanticErrorToken; import org.structr.core.GraphObject; import org.structr.core.app.StructrApp; import org.structr.core.property.PropertyKey; import org.structr.schema.action.ActionContext; import org.structr.schema.action.Function; /** * */ public class ErrorFunction extends Function<Object, Object> { public static final String ERROR_MESSAGE_ERROR = "Usage: ${error(...)}. Example: ${error(\"base\", \"must_equal\", int(5))}"; @Override public String getName() { return "error()"; } @Override public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { final Class entityType; final String type; if (entity != null) { entityType = entity.getClass(); type = entity.getType(); } else { entityType = GraphObject.class; type = "Base"; } try { if (sources == null) { throw new IllegalArgumentException(); } switch (sources.length) { case 1: throw new IllegalArgumentException(); case 2: { arrayHasLengthAndAllElementsNotNull(sources, 2); final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(entityType, sources[0].toString()); ctx.raiseError(422, new SemanticErrorToken(type, key, sources[1].toString())); break; } case 3: { arrayHasLengthAndAllElementsNotNull(sources, 3); final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(entityType, sources[0].toString()); ctx.raiseError(422, new SemanticErrorToken(type, key, sources[1].toString(), sources[2])); break; } default: logParameterError(entity, sources, ctx.isJavaScriptContext()); break; } } catch (final IllegalArgumentException e) { logParameterError(entity, sources, ctx.isJavaScriptContext()); return usage(ctx.isJavaScriptContext()); } return null; } @Override public String usage(boolean inJavaScriptContext) { return ERROR_MESSAGE_ERROR; } @Override public String shortDescription() { return "Signals an error to the caller"; } }
derkaiserreich/structr
structr-core/src/main/java/org/structr/core/function/ErrorFunction.java
Java
gpl-3.0
2,991
package com.risevision.gcslogs.delete; import com.risevision.gcslogs.auth.MockCredentialProvider; import java.util.logging.Logger; import java.util.Map; import java.util.HashMap; import org.junit.*; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import static com.risevision.gcslogs.BuildConfig.*; public class DeleteLoadJobFilesServletHandlerTest { Map<String, String[]> params; DeleteLoadJobFilesServletHandler deleter; @Before public void setUp() { params = new HashMap<String, String[]>(); params.put("jobId", new String[]{"testId"}); deleter = new DeleteLoadJobFilesServletHandler(params, new MockCredentialProvider()); } @Test public void itExists() { assertThat("it exists", deleter, isA(DeleteLoadJobFilesServletHandler.class)); } @Test public void itGetsTheJobId() { assertThat("the id exists", deleter.jobId, is(not(nullValue()))); } @Test public void itExtractsObjectNamesFromUris() { String uri = "gs://" + LOGS_BUCKET_NAME.toString() + "/folder/name"; assertThat("the name is correct", deleter.extractObjectName(uri), is("folder/name")); } @Test public void itExtractsBucketNamesFromUris() { String uri = "gs://" + LOGS_BUCKET_NAME.toString() + "/folder/name"; assertThat("the bucket is correct", deleter.extractBucketName(uri), is(LOGS_BUCKET_NAME.toString())); } }
Rise-Vision/storage-gcs-logging
src/test/java/com/risevision/gcslogs/delete/DeleteLoadJobFilesServletHandlerTest.java
Java
gpl-3.0
1,393
package org.maxgamer.rs.model.skill.prayer; import java.util.LinkedList; /** * @author netherfoam, alva */ public enum PrayerGroup { //Standard prayer book /** All prayers that boost defense */ DEFENSE(PrayerType.THICK_SKIN, PrayerType.ROCK_SKIN, PrayerType.STEEL_SKIN, PrayerType.CHIVALRY, PrayerType.PIETY, PrayerType.RIGOUR, PrayerType.AUGURY), /** All prayers that boost strength */ STRENGTH(PrayerType.BURST_OF_STRENGTH, PrayerType.SUPERHUMAN_STRENGTH, PrayerType.ULTIMATE_STRENGTH, PrayerType.CHIVALRY, PrayerType.PIETY), /** All prayers that boost attack */ ATTACK(PrayerType.CLARITY_OF_THOUGHT, PrayerType.IMPROVED_REFLEXES, PrayerType.INCREDIBLE_REFLEXES, PrayerType.CHIVALRY, PrayerType.PIETY), /** All prayers that boost range */ RANGE(PrayerType.SHARP_EYE, PrayerType.HAWK_EYE, PrayerType.EAGLE_EYE, PrayerType.RIGOUR), /** All prayers that boost magic */ MAGIC(PrayerType.MYSTIC_WILL, PrayerType.MYSTIC_LORE, PrayerType.MYSTIC_MIGHT, PrayerType.AUGURY), /** * most prayers that put a symbol above player head (Prot * (melee/magic/range), retribution, smite, redemption) */ STANDARD_SPECIAL(PrayerType.PROTECT_FROM_MELEE, PrayerType.PROTECT_FROM_MISSILES, PrayerType.PROTECT_FROM_MAGIC, PrayerType.RETRIBUTION, PrayerType.REDEMPTION, PrayerType.SMITE), /** Protect from melee/range/magic prayers */ PROTECT_DAMAGE(PrayerType.PROTECT_FROM_MELEE, PrayerType.PROTECT_FROM_MISSILES, PrayerType.PROTECT_FROM_MAGIC), //Curses prayer book /** Sap prayers (warrior, range, spirit) */ SAP(PrayerType.SAP_WARRIOR, PrayerType.SAP_RANGER, PrayerType.SAP_SPIRIT), /** * leech prayers (attack, range, magic, defence, strength, energy, special * attack) */ LEECH(PrayerType.LEECH_ATTACK, PrayerType.LEECH_RANGE, PrayerType.LEECH_MAGIC, PrayerType.LEECH_DEFENCE, PrayerType.LEECH_STRENGTH, PrayerType.LEECH_ENERGY, PrayerType.LEECH_SPECIAL_ATTACK), /** * similar to standard_special. Wrath, Soulsplit, deflect (magic, missiles, * melee) */ CURSE_SPECIAL(PrayerType.WRATH, PrayerType.SOUL_SPLIT, PrayerType.DEFLECT_MAGIC, PrayerType.DEFLECT_MISSILES, PrayerType.DEFLECT_MELEE), /** All deflections (magic, missiles, melee) */ DEFLECT(PrayerType.DEFLECT_MAGIC, PrayerType.DEFLECT_MISSILES, PrayerType.DEFLECT_MELEE); private PrayerType[] types; private PrayerGroup(PrayerType... types) { this.types = types; } public PrayerType[] getTypes() { return types; } /** * Returns true if this prayer group contains the given prayer. * @param type the prayer * @return true if it is contained, else false. */ public boolean contains(PrayerType type) { for (PrayerType p : this.types) { if (type == p) { return true; } } return false; } /** * Returns an array of groups that the given prayer is in. * @param type the prayer * @return an array of groups that the given prayer is in. */ public static LinkedList<PrayerGroup> getGroups(PrayerType type) { LinkedList<PrayerGroup> groups = new LinkedList<PrayerGroup>(); for (PrayerGroup g : values()) { if (g.contains(type)) { groups.add(g); } } return groups; } }
tehnewb/Titan
src/org/maxgamer/rs/model/skill/prayer/PrayerGroup.java
Java
gpl-3.0
3,118
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Colorinator</title> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <meta name="viewport" content="width=410"> <!-- jQuery --> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script> <!-- Wijmo CSS and script --> <link type="text/css" href="http://cdn.wijmo.com/themes/metro/jquery-wijmo.css" rel="stylesheet" title="metro-jqueryui" /> <link type="text/css" href="http://cdn.wijmo.com/jquery.wijmo-complete.all.2.1.5.min.css" rel="stylesheet" /> <script type="text/javascript" src="http://cdn.wijmo.com/jquery.wijmo-open.all.2.1.5.min.js"></script> <!-- KnockoutJS for MVVM--> <script type="text/javascript" src="http://cdn.wijmo.com/external/knockout-2.0.0.js"></script> <script type="text/javascript" src="http://cdn.wijmo.com/external/knockout.wijmo.js"></script> <script type="text/javascript"> //Create ViewModel var viewModel = function () { var self = this; self.red = ko.observable(120); self.green = ko.observable(120); self.blue = ko.observable(120); self.minRGB = ko.observable(0); self.maxRGB = ko.observable(255); self.rgbColor = ko.computed(function () { // Knockout tracks dependencies automatically. It knows that rgbColor depends on hue, saturation and lightness, because these get called when evaluating rgbColor. return "rgb(" + self.red() + ", " + self.green() + ", " + self.blue() + ")"; }, self); self.hslColor = ko.computed(function () { //Convert red, green and blue numbers to hue (degree), saturation (percentage) and lightness (percentage) var r = self.red() / 255, g = self.green() / 255, b = self.blue() / 255; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2; var hue, saturation, lightness; if (max == min) { h = s = 0; } 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; } hue = Math.round(h * 360); saturation = Math.round(s * 100) + "%"; lightness = Math.round(l * 100) + "%"; return "hsl(" + hue + ", " + saturation + ", " + lightness + ")"; }, self); self.hexColor = ko.computed({ read: function () { //Convert red, green and blue numbers to base 16 strings var r = self.red(), g = self.green(), b = self.blue(); var hex = 1 << 24 | r << 16 | g << 8 | b; return '#' + hex.toString(16).substr(1); }, write: function (value) { //This is a writable computed observable so that one can type in a hex color to update the RGB values. var r, g, b; if (value[0] === "#") { value = value.substr(1); } if (value.length < 3) { return; } else if (value.length > 6) { value = value.substr(0, 6); } else if (value.length === 3) { //Short code hex converted to full hex r = value.substr(0, 1) + value.substr(0, 1); g = value.substr(1, 1) + value.substr(1, 1); b = value.substr(2, 1) + value.substr(2, 1); value = r + g + b; } //Update ViewModel red, green and blue values self.red(parseInt(value.substr(0, 2), 16)); self.green(parseInt(value.substr(2, 2), 16)); self.blue(parseInt(value.substr(4, 2), 16)); }, owner: self }); }; //Bind ViewModel and Event Handlers $(document).ready(function () { var vm = new viewModel(); //check for hex color passed in URL getColorFromHash(); //Apply ViewModel bindings in markup ko.applyBindings(vm); //Trigger CSS3 animation to show color picker pane when ViewModel is initialized $(".wait").addClass("show").removeClass("wait"); //Check if browser supports hashchange event if ("onhashchange" in window) { window.onhashchange = getColorFromHash; } //Get hex color from URL and update ViewModel with value function getColorFromHash() { if (window.location.hash && window.location.hash != vm.hexColor()) { vm.hexColor(window.location.hash); } } }); </script> <style type="text/css"> body { font-family: "Segoe UI Light" , Frutiger, "Frutiger Linotype" , "Dejavu Sans" , "Helvetica Neue" , Arial, sans-serif; font-size: 14px; background: #000; } h1 { font-size: 2.4em; color: #fff; padding: 20px 0 0 6px; margin: 0; } .container { margin: 0 auto; width: 400px; } .wait { height: 1px; } .show { height: 530px; -webkit-transition: all 1.2s ease-out; -moz-transition: all 1.2s ease-out; -o-transition: all 1.2s ease-out; transition: all 1.2s ease-out; } .color-picker { overflow: hidden; background: #fff; padding: 20px; box-shadow: 5px 5px 50px rgba(0, 0, 0, 0.5); } .swatch { margin: 20px; width: 320px; height: 200px; box-shadow: 5px 5px 20px rgba(0, 0, 0, 0.5) inset; } .color-section { padding: 6px 0 0 0; } .color-label { width: 70px; display: inline-block; } .unit { width: 30px; } .color-value { width: 140px; } .color-slider { width: 200px; } .wijmo-wijslider-horizontal { display: inline-block; } </style> </head> <body data-bind="style: { background: hexColor }"> <div class="container"> <h1> Colorinator</h1> <div class="color-picker wait"> <div class="swatch" data-bind="style: { background: hexColor }"> </div> <div class="color-section"> <label class="color-label"> Red</label> <div data-bind="wijslider: { value: red, min: minRGB, max: maxRGB }" class="color-slider"> </div> <input type="text" data-bind="value: red, valueUpdate: 'keyup', wijtextbox: {}" class="unit" /> </div> <div class="color-section"> <label class="color-label"> Green</label> <div data-bind="wijslider: { value: green, min: minRGB, max: maxRGB }" class="color-slider"> </div> <input type="text" data-bind="value: green, valueUpdate: 'keyup', wijtextbox: {}" class="unit" /> </div> <div class="color-section"> <label class="color-label"> Blue</label> <div data-bind="wijslider: { value: blue, min: minRGB, max: maxRGB }" class="color-slider"> </div> <input type="text" data-bind="value: blue, valueUpdate: 'keyup', wijtextbox: {}" class="unit" /> </div> <div class="color-section"> <label class="color-label"> RGB Color</label> <input type="text" data-bind="value: rgbColor, disable: true, wijtextbox: { disabled: true }" class="color-value" /> <span data-bind="text: rgbColor"></span> </div> <div class="color-section"> <label class="color-label"> HSL Color</label> <input type="text" data-bind="value: hslColor, disable: true, wijtextbox: { disabled: true }" class="color-value" /> <span data-bind="text: hslColor"></span> </div> <div class="color-section"> <label class="color-label"> HEX Color</label> <input type="text" data-bind="value: hexColor, wijtextbox: { }" class="color-value" /> <a data-bind="text: hexColor, attr: { href: hexColor }" title="Link to this color"></a> </div> <p> Made with <a href="http://knockoutjs.com">KnockoutJS</a> and <a href="http://wijmo.com">Wijmo</a></p> </div> </div> </body> </html>
wijmo/Wijmo-Complete
demo-apps/colour/index.html
HTML
gpl-3.0
9,738
import ast import json import arrow import elasticsearch from bson import ObjectId from flask import request from eve.utils import config from eve.io.base import DataLayer try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse def parse_date(date_str): """Parse elastic datetime string.""" try: date = arrow.get(date_str) except TypeError: date = arrow.get(date_str[0]) return date.datetime def get_dates(schema): """Return list of datetime fields for given schema.""" dates = [config.LAST_UPDATED, config.DATE_CREATED] for field, field_schema in schema.items(): if field_schema['type'] == 'datetime': dates.append(field) return dates def format_doc(hit, schema, dates): """Format given doc to match given schema.""" doc = hit.get('_source', {}) doc.setdefault(config.ID_FIELD, hit.get('_id')) doc.setdefault('_type', hit.get('_type')) for key in dates: if key in doc: doc[key] = parse_date(doc[key]) return doc def noop(): pass def is_elastic(datasource): """Detect if given resource uses elastic.""" return datasource.get('backend') == 'elastic' or datasource.get('search_backend') == 'elastic' class ElasticJSONSerializer(elasticsearch.JSONSerializer): """Customize the JSON serializer used in Elastic""" def default(self, value): """Convert mongo.ObjectId.""" if isinstance(value, ObjectId): return str(value) return super(ElasticJSONSerializer, self).default(value) class ElasticCursor(object): """Search results cursor.""" no_hits = {'hits': {'total': 0, 'hits': []}} def __init__(self, hits=None, docs=None): """Parse hits into docs.""" self.hits = hits if hits else self.no_hits self.docs = docs if docs else [] def __getitem__(self, key): return self.docs[key] def first(self): """Get first doc.""" return self.docs[0] if self.docs else None def count(self, **kwargs): """Get hits count.""" return int(self.hits['hits']['total']) def extra(self, response): """Add extra info to response.""" if 'facets' in self.hits: response['_facets'] = self.hits['facets'] if 'aggregations' in self.hits: response['_aggregations'] = self.hits['aggregations'] def set_filters(query, base_filters): """Put together all filters we have and set them as 'and' filter within filtered query. :param query: elastic query being constructed :param base_filters: all filters set outside of query (eg. resource config, sub_resource_lookup) """ filters = [f for f in base_filters if f is not None] query_filter = query['query']['filtered'].get('filter', None) if query_filter is not None: if 'and' in query_filter: filters.extend(query_filter['and']) else: filters.append(query_filter) if filters: query['query']['filtered']['filter'] = {'and': filters} def set_sort(query, sort): query['sort'] = [] for (key, sortdir) in sort: sort_dict = dict([(key, 'asc' if sortdir > 0 else 'desc')]) query['sort'].append(sort_dict) def get_es(url): o = urlparse(url) es = elasticsearch.Elasticsearch(hosts=[{'host': o.hostname, 'port': o.port}]) es.transport.serializer = ElasticJSONSerializer() return es def get_indices(es): return elasticsearch.client.IndicesClient(es) class Elastic(DataLayer): """ElasticSearch data layer.""" serializers = { 'integer': int, 'datetime': parse_date, 'objectid': ObjectId, } def init_app(self, app): app.config.setdefault('ELASTICSEARCH_URL', 'http://localhost:9200/') app.config.setdefault('ELASTICSEARCH_INDEX', 'eve') self.index = app.config['ELASTICSEARCH_INDEX'] self.es = get_es(app.config['ELASTICSEARCH_URL']) self.create_index(self.index) self.put_mapping(app) def _get_field_mapping(self, schema): """Get mapping for given field schema.""" if 'mapping' in schema: return schema['mapping'] elif schema['type'] == 'datetime': return {'type': 'date'} elif schema['type'] == 'string' and schema.get('unique'): return {'type': 'string', 'index': 'not_analyzed'} def create_index(self, index=None): if index is None: index = self.index try: get_indices(self.es).create(self.index) except elasticsearch.TransportError: pass def put_mapping(self, app): """Put mapping for elasticsearch for current schema. It's not called automatically now, but rather left for user to call it whenever it makes sense. """ indices = get_indices(self.es) for resource, resource_config in app.config['DOMAIN'].items(): datasource = resource_config.get('datasource', {}) if not is_elastic(datasource): continue if datasource.get('source', resource) != resource: # only put mapping for core types continue properties = {} properties[config.DATE_CREATED] = self._get_field_mapping({'type': 'datetime'}) properties[config.LAST_UPDATED] = self._get_field_mapping({'type': 'datetime'}) for field, schema in resource_config['schema'].items(): field_mapping = self._get_field_mapping(schema) if field_mapping: properties[field] = field_mapping mapping = {'properties': properties} indices.put_mapping(index=self.index, doc_type=resource, body=mapping, ignore_conflicts=True) def find(self, resource, req, sub_resource_lookup): args = getattr(req, 'args', request.args if request else {}) source_config = config.SOURCES[resource] if args.get('source'): query = json.loads(args.get('source')) if 'filtered' not in query.get('query', {}): _query = query.get('query') query['query'] = {'filtered': {}} if _query: query['query']['filtered']['query'] = _query else: query = {'query': {'filtered': {}}} if args.get('q', None): query['query']['filtered']['query'] = _build_query_string(args.get('q'), default_field=args.get('df', '_all')) if 'sort' not in query: if req.sort: sort = ast.literal_eval(req.sort) set_sort(query, sort) elif self._default_sort(resource) and 'query' not in query['query']['filtered']: set_sort(query, self._default_sort(resource)) if req.max_results: query.setdefault('size', req.max_results) if req.page > 1: query.setdefault('from', (req.page - 1) * req.max_results) filters = [] filters.append(source_config.get('elastic_filter')) filters.append(source_config.get('elastic_filter_callback', noop)()) filters.append({'term': sub_resource_lookup} if sub_resource_lookup else None) filters.append(json.loads(args.get('filter')) if 'filter' in args else None) set_filters(query, filters) if 'facets' in source_config: query['facets'] = source_config['facets'] if 'aggregations' in source_config: query['aggs'] = source_config['aggregations'] args = self._es_args(resource) hits = self.es.search(body=query, **args) return self._parse_hits(hits, resource) def find_one(self, resource, req, **lookup): def is_found(hit): if 'exists' in hit: hit['found'] = hit['exists'] return hit.get('found', False) args = self._es_args(resource) if config.ID_FIELD in lookup: try: hit = self.es.get(id=lookup[config.ID_FIELD], **args) except elasticsearch.NotFoundError: return if not is_found(hit): return docs = self._parse_hits({'hits': {'hits': [hit]}}, resource) return docs.first() else: query = { 'query': { 'term': lookup } } try: args['size'] = 1 hits = self.es.search(body=query, **args) docs = self._parse_hits(hits, resource) return docs.first() except elasticsearch.NotFoundError: return def find_one_raw(self, resource, _id): args = self._es_args(resource) hit = self.es.get(id=_id, **args) return self._parse_hits({'hits': {'hits': [hit]}}, resource).first() def find_list_of_ids(self, resource, ids, client_projection=None): args = self._es_args(resource) return self._parse_hits(self.es.multi_get(ids, **args), resource) def insert(self, resource, doc_or_docs, **kwargs): ids = [] kwargs.update(self._es_args(resource)) for doc in doc_or_docs: doc.update(self.es.index(body=doc, id=doc.get('_id'), **kwargs)) ids.append(doc['_id']) get_indices(self.es).refresh(self.index) return ids def update(self, resource, id_, updates): args = self._es_args(resource, refresh=True) return self.es.update(id=id_, body={'doc': updates}, **args) def replace(self, resource, id_, document): args = self._es_args(resource, refresh=True) return self.es.index(body=document, id=id_, **args) def remove(self, resource, lookup=None): args = self._es_args(resource) if lookup: try: return self.es.delete(id=lookup.get('_id'), refresh=True, **args) except elasticsearch.NotFoundError: return else: query = {'query': {'match_all': {}}} return self.es.delete_by_query(body=query, **args) def is_empty(self, resource): args = self._es_args(resource) res = self.es.count(body={'query': {'match_all': {}}}, **args) return res.get('count', 0) == 0 def get_mapping(self, index, doc_type=None): return get_indices(self.es).get_mapping(index=index, doc_type=doc_type) def _parse_hits(self, hits, resource): """Parse hits response into documents.""" datasource = self._datasource(resource) schema = config.DOMAIN[datasource[0]]['schema'] dates = get_dates(schema) docs = [] for hit in hits.get('hits', {}).get('hits', []): docs.append(format_doc(hit, schema, dates)) return ElasticCursor(hits, docs) def _es_args(self, resource, refresh=None): """Get index and doctype args.""" datasource = self._datasource(resource) args = { 'index': self.index, 'doc_type': datasource[0], } if refresh: args['refresh'] = refresh return args def _fields(self, resource): """Get projection fields for given resource.""" datasource = self._datasource(resource) keys = datasource[2].keys() return ','.join(keys) + ','.join([config.LAST_UPDATED, config.DATE_CREATED]) def _default_sort(self, resource): datasource = self._datasource(resource) return datasource[3] def build_elastic_query(doc): """ Builds a query which follows ElasticSearch syntax from doc. 1. Converts {"q":"cricket"} to the below elastic query { "query": { "filtered": { "query": { "query_string": { "query": "cricket", "lenient": false, "default_operator": "AND" } } } } } 2. Converts a faceted query {"q":"cricket", "type":['text'], "source": "AAP"} to the below elastic query { "query": { "filtered": { "filter": { "and": [ {"terms": {"type": ["text"]}}, {"term": {"source": "AAP"}} ] }, "query": { "query_string": { "query": "cricket", "lenient": false, "default_operator": "AND" } } } } } :param doc: A document object which is inline with the syntax specified in the examples. It's the developer responsibility to pass right object. :returns ElasticSearch query """ elastic_query, filters = {"query": {"filtered": {}}}, [] for key in doc.keys(): if key == 'q': elastic_query['query']['filtered']['query'] = _build_query_string(doc['q']) else: _value = doc[key] filters.append({"terms": {key: _value}} if isinstance(_value, list) else {"term": {key: _value}}) set_filters(elastic_query, filters) return elastic_query def _build_query_string(q, default_field=None): """ Builds "query_string" object from 'q'. :param: q of type String :param: default_field :return: dictionary object. """ query_string = {'query_string': {'query': q, 'default_operator': 'AND'}} query_string['query_string'].update({'lenient': False} if default_field else {'default_field': default_field}) return query_string
amagdas/eve-elastic
eve_elastic/elastic.py
Python
gpl-3.0
13,856
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc on Thu Nov 22 16:43:24 EST 2007 --> <TITLE> Xalan-Java 2.7.1: Uses of Interface org.apache.xml.serializer.ExtendedLexicalHandler </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <!-- ========== START OF NAVBAR ========== --> <A NAME="navbar_top"><!-- --></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0"> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3"> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" TARGET="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ExtendedLexicalHandler.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD> </TR> </TABLE> <!-- =========== END OF NAVBAR =========== --> <HR> <CENTER> <H2> <B>Uses of Interface<br>org.apache.xml.serializer.ExtendedLexicalHandler</B></H2> </CENTER> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> Packages that use <A HREF="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html">ExtendedLexicalHandler</A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.xalan.xsltc.dom"><B>org.apache.xalan.xsltc.dom</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.xalan.xsltc.runtime"><B>org.apache.xalan.xsltc.runtime</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.xml.serializer"><B>org.apache.xml.serializer</B></A></TD> <TD>Processes SAX events into streams.&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.xalan.xsltc.dom"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> Uses of <A HREF="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html">ExtendedLexicalHandler</A> in <A HREF="../../../../../org/apache/xalan/xsltc/dom/package-summary.html">org.apache.xalan.xsltc.dom</A></FONT></TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TD COLSPAN=2>Classes in <A HREF="../../../../../org/apache/xalan/xsltc/dom/package-summary.html">org.apache.xalan.xsltc.dom</A> that implement <A HREF="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html">ExtendedLexicalHandler</A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/AdaptiveResultTreeImpl.html">AdaptiveResultTreeImpl</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;AdaptiveResultTreeImpl is a adaptive DOM model for result tree fragments (RTF).</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/dom/SimpleResultTreeImpl.html">SimpleResultTreeImpl</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This class represents a light-weight DOM model for simple result tree fragment(RTF).</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.xalan.xsltc.runtime"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> Uses of <A HREF="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html">ExtendedLexicalHandler</A> in <A HREF="../../../../../org/apache/xalan/xsltc/runtime/package-summary.html">org.apache.xalan.xsltc.runtime</A></FONT></TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TD COLSPAN=2>Classes in <A HREF="../../../../../org/apache/xalan/xsltc/runtime/package-summary.html">org.apache.xalan.xsltc.runtime</A> that implement <A HREF="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html">ExtendedLexicalHandler</A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xalan/xsltc/runtime/StringValueHandler.html">StringValueHandler</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.xml.serializer"><!-- --></A> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TD COLSPAN=2><FONT SIZE="+2"> Uses of <A HREF="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html">ExtendedLexicalHandler</A> in <A HREF="../../../../../org/apache/xml/serializer/package-summary.html">org.apache.xml.serializer</A></FONT></TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TD COLSPAN=2>Subinterfaces of <A HREF="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html">ExtendedLexicalHandler</A> in <A HREF="../../../../../org/apache/xml/serializer/package-summary.html">org.apache.xml.serializer</A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;interface</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/SerializationHandler.html">SerializationHandler</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This interface is the one that a serializer implements.</TD> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%"> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TD COLSPAN=2>Classes in <A HREF="../../../../../org/apache/xml/serializer/package-summary.html">org.apache.xml.serializer</A> that implement <A HREF="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html">ExtendedLexicalHandler</A></FONT></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/EmptySerializer.html">EmptySerializer</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This class is an adapter class.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/SerializerBase.html">SerializerBase</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This class acts as a base class for the XML "serializers" and the stream serializers.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/ToHTMLSAXHandler.html">ToHTMLSAXHandler</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Deprecated.</B>&nbsp;<I>As of Xalan 2.7.1, replaced by the use of <A HREF="../../../../../org/apache/xml/serializer/ToXMLSAXHandler.html"><CODE>ToXMLSAXHandler</CODE></A>.</I></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/ToHTMLStream.html">ToHTMLStream</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This serializer takes a series of SAX or SAX-like events and writes its output to the given stream.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/ToSAXHandler.html">ToSAXHandler</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This class is used to provide a base behavior to be inherited by other To...SAXHandler serializers.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/ToStream.html">ToStream</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This abstract class is a base class for other stream serializers (xml, html, text ...) that write output to a stream.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/ToTextSAXHandler.html">ToTextSAXHandler</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Deprecated.</B>&nbsp;<I>As of Xalan 2.7.1, replaced by the use of <A HREF="../../../../../org/apache/xml/serializer/ToXMLSAXHandler.html"><CODE>ToXMLSAXHandler</CODE></A>.</I></TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/ToTextStream.html">ToTextStream</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This class is not a public API.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/ToUnknownStream.html">ToUnknownStream</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This class wraps another SerializationHandler.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/ToXMLSAXHandler.html">ToXMLSAXHandler</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This class receives notification of SAX-like events, and with gathered information over these calls it will invoke the equivalent SAX methods on a handler, the ultimate xsl:output method is known to be "xml".</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;class</CODE></FONT></TD> <TD><CODE><B><A HREF="../../../../../org/apache/xml/serializer/ToXMLStream.html">ToXMLStream</A></B></CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This class converts SAX or SAX-like calls to a serialized xml document.</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ========== START OF NAVBAR ========== --> <A NAME="navbar_bottom"><!-- --></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0"> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3"> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/xml/serializer/ExtendedLexicalHandler.html"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../index.html" TARGET="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="ExtendedLexicalHandler.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD> </TR> </TABLE> <!-- =========== END OF NAVBAR =========== --> <HR> Copyright © 2006 Apache XML Project. All Rights Reserved. </BODY> </HTML>
doughtnerd/POD
resources/Xalan/xalan-j_2.7.1-bin/docs/apidocs/org/apache/xml/serializer/class-use/ExtendedLexicalHandler.html
HTML
gpl-3.0
14,769
ProjectTop := /Volumes/Polaris/polymake include ${ProjectTop}/support/extension.make
solros/mypolytopes
Makefile
Makefile
gpl-3.0
85
=head1 NAME EPrints::Plugin::Screen::Search =cut package EPrints::Plugin::Screen::Search; use EPrints::Plugin::Screen::AbstractSearch; @ISA = ( 'EPrints::Plugin::Screen::AbstractSearch' ); use strict; sub new { my( $class, %params ) = @_; my $self = $class->SUPER::new(%params); $self->{appears} = []; push @{$self->{actions}}, "advanced", "savesearch"; return $self; } sub datasets { my( $self ) = @_; my $session = $self->{session}; my @datasets; foreach my $datasetid ($session->get_dataset_ids) { local $self->{processor}->{dataset} = $session->dataset( $datasetid ); next if !$self->can_be_viewed(); push @datasets, $datasetid; } return @datasets; } sub search_dataset { my( $self ) = @_; return $self->{processor}->{dataset}; } sub allow_advanced { shift->can_be_viewed( @_ ) } sub allow_export { shift->can_be_viewed( @_ ) } sub allow_export_redir { shift->can_be_viewed( @_ ) } sub allow_savesearch { my( $self ) = @_; return 0 if !$self->can_be_viewed(); my $user = $self->{session}->current_user; return defined $user && $user->allow( "create_saved_search" ); } sub can_be_viewed { my( $self ) = @_; # note this method is also used by $self->datasets() my $dataset = $self->{processor}->{dataset}; return 0 if !defined $dataset; my $searchid = $self->{processor}->{searchid}; if( $dataset->id eq "archive" ) { return $self->allow( "eprint_search" ); } elsif( defined($searchid) && (my $rc = $self->allow( $dataset->id . "/search/$searchid" )) ) { return $rc; } { return $self->allow( $dataset->id . "/search" ); } } sub get_controls_before { my( $self ) = @_; my @controls = $self->get_basic_controls_before; my $cacheid = $self->{processor}->{results}->{cache_id}; my $escexp = $self->{processor}->{search}->serialise; my $baseurl = URI->new( $self->{session}->get_uri ); $baseurl->query_form( cache => $cacheid, exp => $escexp, screen => $self->{processor}->{screenid}, dataset => $self->search_dataset->id, order => $self->{processor}->{search}->{custom_order}, ); # Maybe add links to the pagination controls to switch between simple/advanced # if( $self->{processor}->{searchid} eq "simple" ) # { # push @controls, { # url => "advanced", # label => $self->{session}->html_phrase( "lib/searchexpression:advanced_link" ), # }; # } my $user = $self->{session}->current_user; if( defined $user && $user->allow( "create_saved_search" ) ) { #my $cacheid = $self->{processor}->{results}->{cache_id}; #my $exp = $self->{processor}->{search}->serialise; my $url = $baseurl->clone; $url->query_form( $url->query_form, _action_savesearch => 1 ); push @controls, { url => "$url", label => $self->{session}->html_phrase( "lib/searchexpression:savesearch" ), }; } return @controls; } sub hidden_bits { my( $self ) = @_; my %bits = $self->SUPER::hidden_bits; my @datasets = $self->datasets; # if there's more than 1 dataset, then the search form will render the list of "search-able" datasets - see render_dataset below if( scalar( @datasets ) < 2 ) { $bits{dataset} = $self->{processor}->{dataset}->id; } return %bits; } sub render_result_row { my( $self, $session, $result, $searchexp, $n ) = @_; my $staff = $self->{processor}->{sconf}->{staff}; my $citation = $self->{processor}->{sconf}->{citation}; if( $staff ) { return $result->render_citation_link_staff( $citation, n => [$n,"INTEGER"] ); } else { return $result->render_citation_link( $citation, n => [$n,"INTEGER"] ); } } sub export_url { my( $self, $format ) = @_; my $plugin = $self->{session}->plugin( "Export::".$format ); if( !defined $plugin ) { EPrints::abort( "No such plugin: $format\n" ); } my $url = URI->new( $self->{session}->current_url() . "/export_" . $self->{session}->get_repository->get_id . "_" . $format . $plugin->param( "suffix" ) ); $url->query_form( $self->hidden_bits, _action_export => 1, output => $format, exp => $self->{processor}->{search}->serialise, n => scalar($self->{session}->param( "n" )), ); return $url; } sub action_advanced { my( $self ) = @_; my $adv_url; my $datasetid = $self->{session}->param( "dataset" ); $datasetid = "archive" if !defined $datasetid; # something odd happened if( $datasetid eq "archive" ) { $adv_url = $self->{session}->current_url( path => "cgi", "search/advanced" ); } else { $adv_url = $self->{session}->current_url( path => "cgi", "search/$datasetid/advanced" ); } $self->{processor}->{redirect} = $adv_url; } sub action_savesearch { my( $self ) = @_; my $ds = $self->{session}->dataset( "saved_search" ); my $searchexp = $self->{processor}->{search}; $searchexp->{searchid} = $self->{processor}->{searchid}; my $name = $searchexp->render_conditions_description; my $userid = $self->{session}->current_user->id; my $spec = $searchexp->freeze; my $results = $ds->search( filters => [ { meta_fields => [qw( userid )], value => $userid, }, { meta_fields => [qw( spec )], value => $spec, match => "EX" }, ]); my $savedsearch = $results->item( 0 ); my $screen; if( defined $savedsearch ) { $screen = "View"; } else { $screen = "Edit"; $savedsearch = $ds->create_dataobj( { userid => $self->{session}->current_user->id, name => $self->{session}->xml->text_contents_of( $name ), spec => $searchexp->freeze } ); } $self->{session}->xml->dispose( $name ); my $url = URI->new( $self->{session}->config( "userhome" ) ); $url->query_form( screen => "Workflow::$screen", dataset => "saved_search", dataobj => $savedsearch->id, ); $self->{session}->redirect( $url ); exit; } sub render_search_form { my( $self ) = @_; if( $self->{processor}->{searchid} eq "simple" && @{$self->{processor}->{sconf}->{search_fields}} == 1 ) { return $self->render_simple_form; } else { return $self->SUPER::render_search_form; } } sub render_preamble { my( $self ) = @_; my $pphrase = $self->{processor}->{sconf}->{"preamble_phrase"}; return $self->{session}->make_doc_fragment if !defined $pphrase; return $self->{session}->html_phrase( $pphrase ); } sub render_simple_form { my( $self ) = @_; my $session = $self->{session}; my $xhtml = $session->xhtml; my $xml = $session->xml; my $input; my $div = $xml->create_element( "div", class => "ep_block" ); my $form = $self->{session}->render_form( "get" ); $div->appendChild( $form ); my $label = $xml->create_element( "label", for => "q_merge", class => "ep_lbl_merge" ); $label->appendChild( $session->html_phrase( "lib/searchexpression:merge" ) ); $form->appendChild( $label ); # avoid adding "dataset", which is selectable here $form->appendChild( $self->SUPER::render_hidden_bits ); # maintain the order if it was specified (might break if dataset is # changed) $input = $xhtml->hidden_field( "order", $session->param( "order" ) ); $form->appendChild( $input ); $form->appendChild( $self->render_preamble ); $form->appendChild( $self->{processor}->{search}->render_simple_fields( 'aria-labelledby' => $session->phrase( "lib/searchexpression:action_search" ) ) ); $input = $xml->create_element( "input", type => "submit", name => "_action_search", value => $session->phrase( "lib/searchexpression:action_search" ), class => "ep_form_action_button", id => $session->phrase( "lib/searchexpression:action_search" ), ); $form->appendChild( $input ); $input = $xml->create_element( "input", type => "submit", name => "_action_advanced", value => $self->{session}->phrase( "lib/searchexpression:advanced_link" ), class => "ep_form_action_button ep_form_search_advanced_link", ); $form->appendChild( $input ); $form->appendChild( $xml->create_element( "br" ) ); $form->appendChild( $self->render_dataset ); return( $div ); } sub render_dataset { my( $self ) = @_; my $session = $self->{session}; my $xhtml = $session->xhtml; my $xml = $session->xml; my $frag = $xml->create_document_fragment; my @datasetids = $self->datasets; return $frag if @datasetids <= 1; foreach my $datasetid (sort @datasetids) { my $input = $xml->create_element( "input", name => "dataset", type => "radio", value => $datasetid ); if( $datasetid eq $self->{processor}->{dataset}->id ) { $input->setAttribute( checked => "yes" ); } my $label = $xml->create_element( "label", id=>$datasetid ); $frag->appendChild( $label ); $label->appendChild( $input ); $label->appendChild( $session->html_phrase( "datasetname_$datasetid" ) ); } return $frag; } sub properties_from { my( $self ) = @_; $self->SUPER::properties_from(); my $processor = $self->{processor}; my $repo = $self->{session}; my $dataset = $processor->{dataset}; my $searchid = $processor->{searchid}; return if !defined $dataset; return if !defined $searchid; # get the dataset's search configuration my $sconf = $dataset->search_config( $searchid ); $sconf = $self->default_search_config if !%$sconf; $processor->{sconf} = $sconf; $processor->{template} = $sconf->{template}; } sub default_search_config {} sub from { my( $self ) = @_; my $session = $self->{session}; my $processor = $self->{processor}; my $sconf = $processor->{sconf}; # This rather oddly now checks for the special case of one parameter, but # that parameter being a screenid, in which case the search effectively has # no parameters and should not default to action = 'search'. # maybe this can be removed later, but for a minor release this seems safest. if( !EPrints::Utils::is_set( $self->{processor}->{action} ) ) { my %params = map { $_ => 1 } $self->{session}->param(); foreach my $param (keys %{{$self->hidden_bits}}) { delete $params{$param}; } if( EPrints::Utils::is_set( $self->{session}->param( "output" ) ) ) { $self->{processor}->{action} = "export"; } elsif( scalar keys %params ) { $self->{processor}->{action} = "search"; } else { $self->{processor}->{action} = ""; } } my $satisfy_all = $self->{session}->param( "satisfyall" ); $satisfy_all = !defined $satisfy_all || $satisfy_all eq "ALL"; my $searchexp = $processor->{search}; if( !defined $searchexp ) { my $format = $processor->{searchid} . "/" . $processor->{dataset}->base_id; if( !defined $sconf ) { EPrints->abort( "No available configuration for search type $format" ); } $searchexp = $session->plugin( "Search" )->plugins( { session => $session, dataset => $self->search_dataset, keep_cache => 1, satisfy_all => $satisfy_all, %{$sconf}, filters => [ $self->search_filters, @{$sconf->{filters} || []}, ], }, type => "Search", can_search => $format, ); if( !defined $searchexp ) { EPrints->abort( "No available search plugin for $format" ); } $processor->{search} = $searchexp; } if( $searchexp->is_blank && $self->{processor}->{action} ne "newsearch" ) { my $ok = 0; if( my $id = $session->param( "cache" ) ) { $ok = $searchexp->from_cache( $id ); } if( !$ok && (my $exp = $session->param( "exp" )) ) { # cache expired $ok = $searchexp->from_string( $exp ); } if( !$ok ) { for( $searchexp->from_form ) { $self->{processor}->add_message( "warning", $_ ); } } } $sconf->{order_methods} = {} if !defined $sconf->{order_methods}; if( $searchexp->param( "result_order" ) ) { $sconf->{order_methods}->{"byrelevance"} = ""; } # have we been asked to reorder? if( defined( my $order_opt = $self->{session}->param( "order" ) ) ) { my $allowed_order = 0; foreach my $custom_order ( values %{$sconf->{order_methods}} ) { $allowed_order = 1 if $order_opt eq $custom_order; } my $custom_order; if( $allowed_order ) { $custom_order = $order_opt; } elsif( defined $sconf->{default_order} ) { $custom_order = $sconf->{order_methods}->{$sconf->{default_order}}; } else { $custom_order = ""; } $searchexp->{custom_order} = $custom_order; } # use default order else { $searchexp->{custom_order} = $sconf->{order_methods}->{$sconf->{default_order}}; } # feeds are always limited and ordered by -datestamp if( $self->{processor}->{action} eq "export" ) { my $output = $self->{session}->param( "output" ); my $export_plugin = $self->{session}->plugin( "Export::$output" ); if( !defined($self->{session}->param( "order" )) && defined($export_plugin) && $export_plugin->is_feed ) { # borrow the max from latest_tool (which we're replicating anyway) my $limit = $self->{session}->config( "latest_tool_modes", "default", "max" ); $limit = 20 if !$limit; my $n = $self->{session}->param( "n" ); if( $n && $n > 0 && $n < $limit) { $limit = $n; } $searchexp->{limit} = $limit; $searchexp->{custom_order} = "-datestamp"; } } # do actions $self->EPrints::Plugin::Screen::from; if( $searchexp->is_blank && $self->{processor}->{action} ne "export" ) { if( $self->{processor}->{action} eq "search" ) { $self->{processor}->add_message( "warning", $self->{session}->html_phrase( "lib/searchexpression:least_one" ) ); } $self->{processor}->{search_subscreen} = "form"; } } 1; =head1 COPYRIGHT =for COPYRIGHT BEGIN Copyright 2000-2011 University of Southampton. =for COPYRIGHT END =for LICENSE BEGIN This file is part of EPrints L<http://www.eprints.org/>. EPrints is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. EPrints is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with EPrints. If not, see L<http://www.gnu.org/licenses/>. =for LICENSE END
eprintsug/ulcc-core
perl_lib/EPrints/Plugin/Screen/Search.pm
Perl
gpl-3.0
14,057
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>PHP MySQL Database Interface: UnknownDatabaseException Klassenreferenz</title> <link href="../../tabs.css" rel="stylesheet" type="text/css"> <link href="../../doxygen.css" rel="stylesheet" type="text/css"> </head><body> <!-- Erzeugt von Doxygen 1.5.9 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="../../main.html"><span>Hauptseite</span></a></li> <li><a href="../../namespaces.html"><span>Namensbereiche</span></a></li> <li class="current"><a href="../../annotated.html"><span>Datenstrukturen</span></a></li> <li><a href="../../files.html"><span>Dateien</span></a></li> </ul> </div> <div class="tabs"> <ul> <li><a href="../../annotated.html"><span>Datenstrukturen</span></a></li> <li><a href="../../hierarchy.html"><span>Klassenhierarchie</span></a></li> <li><a href="../../functions.html"><span>Datenstruktur-Elemente</span></a></li> </ul> </div> </div> <div class="contents"> <h1>UnknownDatabaseException Klassenreferenz</h1><!-- doxytag: class="UnknownDatabaseException" --><!-- doxytag: inherits="DatabaseException" --><div class="dynheader"> Klassendiagramm für UnknownDatabaseException:</div> <div class="dynsection"> <p><center><img src="../../dc/daa/class_unknown_database_exception.png" usemap="#UnknownDatabaseException_map" border="0" alt=""></center> <map name="UnknownDatabaseException_map"> <area href="../../d1/d5d/class_database_exception.html" alt="DatabaseException" shape="rect" coords="0,0,171,24"> </map> </div> <table border="0" cellpadding="0" cellspacing="0"> <tr><td></td></tr> <tr><td colspan="2"><br><h2>Öffentliche Methoden</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">&nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="../../dc/daa/class_unknown_database_exception.html#d9192420bc35f927ea5bcc2b6da93b0c">__construct</a> ($message=null, $code=0, Exception $previous=null)</td></tr> </table> <hr><a name="_details"></a><h2>Ausführliche Beschreibung</h2> <a class="el" href="../../dc/daa/class_unknown_database_exception.html">UnknownDatabaseException</a> <hr><h2>Beschreibung der Konstruktoren und Destruktoren</h2> <a class="anchor" name="d9192420bc35f927ea5bcc2b6da93b0c"></a><!-- doxytag: member="UnknownDatabaseException::__construct" ref="d9192420bc35f927ea5bcc2b6da93b0c" args="($message=null, $code=0, Exception $previous=null)" --> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">__construct </td> <td>(</td> <td class="paramtype">$&nbsp;</td> <td class="paramname"> <em>message</em> = <code>null</code>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">$&nbsp;</td> <td class="paramname"> <em>code</em> = <code>0</code>, </td> </tr> <tr> <td class="paramkey"></td> <td></td> <td class="paramtype">Exception $&nbsp;</td> <td class="paramname"> <em>previous</em> = <code>null</code></td><td>&nbsp;</td> </tr> <tr> <td></td> <td>)</td> <td></td><td></td><td></td> </tr> </table> </div> <div class="memdoc"> <p> <dl compact><dt><b>Parameter:</b></dt><dd> <table border="0" cellspacing="2" cellpadding="0"> <tr><td valign="top"></td><td valign="top"><em>string</em>&nbsp;</td><td>$message </td></tr> <tr><td valign="top"></td><td valign="top"><em>number</em>&nbsp;</td><td>$code </td></tr> <tr><td valign="top"></td><td valign="top"><em>Exception</em>&nbsp;</td><td>$previous </td></tr> </table> </dl> <p>Erneute Implementation von <a class="el" href="../../d1/d5d/class_database_exception.html#d9192420bc35f927ea5bcc2b6da93b0c">DatabaseException</a>.</p> </div> </div><p> <hr>Die Dokumentation für diese Klasse wurde erzeugt aufgrund der Datei:<ul> <li>S:/Documents/Projekte/phpDBI/workbench/0.02/classes/exception/<a class="el" href="../../d1/d9b/_unknown_database_exception_8php.html">UnknownDatabaseException.php</a></ul> </div> <hr size="1"><address style="text-align: right;"><small>Erzeugt am Fri Dec 25 15:32:56 2009 für PHP MySQL Database Interface von&nbsp; <a href="http://www.doxygen.org/index.html"> <img src="../../doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.9 </small></address> </body> </html>
keil/phpDBI-MySQL-Database-Interface-
documentation/html/dc/daa/class_unknown_database_exception.html
HTML
gpl-3.0
4,592
/* * ASpark * Copyright (C) 2015 Nikolay Platov * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nikoladasm.aspark; import java.io.IOException; import java.io.InputStream; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.netty.buffer.ByteBuf; import static nikoladasm.aspark.HttpMethod.*; public final class ASparkUtil { private static final String PARAMETERS_PATTERN = "(?i)(:[A-Z_][A-Z_0-9]*)"; private static final Pattern PATTERN = Pattern.compile(PARAMETERS_PATTERN); private static final String DEFAULT_ACCEPT_TYPE = "*/*"; private static final String REGEXP_METACHARS = "<([{\\^-=$!|]})?*+.>"; private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; private static final String FOLDER_SEPARATOR = "/"; private static final String WINDOWS_FOLDER_SEPARATOR = "\\"; private static final String TOP_PATH = ".."; private static final String CURRENT_PATH = "."; private static final String QUERY_KEYS_PATTERN = "\\s*\\[?\\s*([^\\]\\[\\s]+)\\s*\\]?\\s*"; private static final Pattern QK_PATTERN = Pattern.compile(QUERY_KEYS_PATTERN); private ASparkUtil() {} private static String processRegexPath(String path, String asteriskReplacement, String slashAsteriskReplacement) { String pathToUse = sanitizePath(path); int length = pathToUse.length(); StringBuilder sb = new StringBuilder(); boolean startWithWildcard = false; for (int i = 0; i < length; i++) { char c = pathToUse.charAt(i); if (i == 0 && c == '*') { sb.append(asteriskReplacement); startWithWildcard = true; continue; } if (i == length-2 && c == '/' && pathToUse.charAt(i+1) == '*') { if (startWithWildcard) throw new IllegalArgumentException("Path can't contain first and last star wildcard"); sb.append(slashAsteriskReplacement); break; } if (i == length-1 && c == '*') { if (startWithWildcard) throw new IllegalArgumentException("Path can't contain first and last star wildcard"); sb.append(asteriskReplacement); continue; } if (REGEXP_METACHARS.contains(String.valueOf(c))) { sb.append('\\').append(c); continue; } sb.append(c); } return sb.toString(); } public static Pattern buildParameterizedPathPattern(String path, Map<String, Integer> parameterNamesMap, Boolean startWithWildcard) { String pathToUse = processRegexPath(path, "(.*)", "(?:/?|/(.+))"); Matcher parameterMatcher = PATTERN.matcher(pathToUse); int i = 1; while (parameterMatcher.find()) { String parameterName = parameterMatcher.group(1); if (parameterNamesMap.containsKey(parameterName)) throw new ASparkException("Duplicate parameter name."); parameterNamesMap.put(parameterName, i); i++; } return Pattern.compile("^"+parameterMatcher.replaceAll("([^/]+)")+"$"); } public static Pattern buildPathPattern(String path) { String pathToUse = processRegexPath(path, ".*", "(?:/?|/.+)"); return Pattern.compile("^"+pathToUse+"$"); } public static boolean isAcceptContentType(String requestAcceptTypes, String routeAcceptType) { if (requestAcceptTypes == null) return routeAcceptType.trim().equals(DEFAULT_ACCEPT_TYPE); String[] requestAcceptTypesArray = requestAcceptTypes.split(","); String[] rtat = routeAcceptType.trim().split("/"); for (int i=0; i<requestAcceptTypesArray.length; i++) { String requestAcceptType = requestAcceptTypesArray[i].split(";")[0]; String[] rqat = requestAcceptType.trim().split("/"); if (((rtat[0].equals("*")) ? true : rqat[0].trim().equals(rtat[0])) && ((rtat[1].equals("*")) ? true : rqat[1].equals(rtat[1]))) return true; } return false; } public static long copyStreamToByteBuf(InputStream input, ByteBuf buf) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; long count = 0; int n = 0; while ((n = input.read(buffer)) != -1) { buf.writeBytes(buffer, 0, n); count += n; } return count; } public static String collapsePath(String path) { String pathToUse = path.trim(); if (pathToUse.isEmpty()) return pathToUse; String rpath = pathToUse.replace(WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR); String[] directories = rpath.split(FOLDER_SEPARATOR); Deque<String> newDirectories = new LinkedList<>(); for (int i=0; i<directories.length; i++) { String directory = directories[i].trim(); if (directory.equals(TOP_PATH) && !newDirectories.isEmpty()) newDirectories.removeLast(); else if (!directory.equals(CURRENT_PATH) && !directory.isEmpty()) newDirectories.addLast(directory); } String result = FOLDER_SEPARATOR; for (String directory : newDirectories) result += directory + FOLDER_SEPARATOR; if (!path.startsWith(FOLDER_SEPARATOR)) result = result.substring(1); if (!path.endsWith(FOLDER_SEPARATOR) && result.equals(FOLDER_SEPARATOR)) result = result.substring(0, result.length()-1); return result; } public static boolean isEqualHttpMethod(HttpMethod requestHttpMethod, HttpMethod routeHttpMethod) { if (requestHttpMethod.equals(HEAD) && routeHttpMethod.equals(GET)) return true; return requestHttpMethod.equals(routeHttpMethod); } public static ParamsMap parseParams(Map<String, List<String>> params) { ParamsMap result = new ParamsMap(); params.forEach((keys, values) -> { ParamsMap root = result; Matcher keyMatcher = QK_PATTERN.matcher(keys); while (keyMatcher.find()) { String key = keyMatcher.group(1); root = root.createIfAbsentAndGet(key); } root.values(values.toArray(new String[values.size()])); }); return result; } public static ParamsMap parseUniqueParams(Map<String, String> params) { ParamsMap result = new ParamsMap(); params.forEach((key, value) -> { result.createIfAbsentAndGet(key).value(value); }); return result; } public static String sanitizePath(String path) { String pathToUse = collapsePath(path); if (pathToUse.isEmpty()) return pathToUse; if (pathToUse.endsWith("/")) pathToUse = pathToUse.substring(0, pathToUse.length()-1); return pathToUse; } public static String mimeType(String file, Properties mimeTypes) { int extIndex = file.lastIndexOf('.'); extIndex = (extIndex < 0 ) ? 0 : extIndex; String ext = file.substring(extIndex); return mimeTypes.getProperty(ext, "application/octet-stream"); } }
NikolaDasm/aspark
src/nikoladasm/aspark/ASparkUtil.java
Java
gpl-3.0
7,066
package controller; import java.io.IOException; import java.sql.Time; import java.util.Calendar; import java.util.List; import java.util.TimeZone; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.json.simple.JSONObject; import utils.Common; import utils.Constant; import utils.MessageProperties; import dao.HocKyDao; import dao.OnlDao; import dao.WeekDao; import dao.impl.HocKyDaoImpl; import dao.impl.OnlDaoImpl; import dao.impl.PositionDaoImpl; import dao.impl.WeekDaoImpl; import entity.HocKy; import entity.Onl; import entity.Position; import entity.User; import entity.Week; /** * Servlet implementation class OnlController */ @WebServlet("/jsp/onl.htm") public class OnlController extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); User user = (User) session.getAttribute("user"); // get list học kỳ HocKyDao hocKyDao = new HocKyDaoImpl(); List<HocKy> listHocKy = hocKyDao.getListHocKy(); request.setAttribute("listHocKy", listHocKy); // lấy học kỳ hiện tại String currentHocKy = hocKyDao.getHocKy(Common.getNow()); request.setAttribute("currentHocKy", currentHocKy); // lấy danh sách tuần theo học kỳ hiện tại WeekDao weekDao = new WeekDaoImpl(); List<Week> listWeek = weekDao.getListWeek(currentHocKy); request.setAttribute("listWeek", listWeek); // lấy tuần hiện tại Week currentWeek = weekDao.getCurrentWeek(Common.getNow()); request.setAttribute("currentWeek", currentWeek); // lấy lịch trực trong tuần List<Onl> listOnl = new OnlDaoImpl().getListOnl(null, currentWeek.getWeekId(), user.getUserId()); request.setAttribute(Constant.ACTION, "viewOnl"); request.setAttribute("listOnl", listOnl); request.getRequestDispatcher("view_onl_cal.jsp").forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ @SuppressWarnings({ "unchecked", "deprecation" }) protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String action = request.getParameter("action"); if ("position".equals(action)) { double latitude = Double.parseDouble(request .getParameter("latitude")); double longitude = Double.parseDouble(request .getParameter("longitude")); long onlId = Long.parseLong(request.getParameter("id")); // lấy tọa độ phòng B1-502 Position position = new PositionDaoImpl().getPositionById("B1-502"); JSONObject jsonObject = new JSONObject(); ServletOutputStream out = response.getOutputStream(); if (position == null) { jsonObject.put(Constant.STATUS, false); jsonObject.put(Constant.DATA, MessageProperties.getData("ERR12")); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } // check vị trí if (!checkPosition(position, latitude, longitude)) { jsonObject.put(Constant.STATUS, false); jsonObject.put(Constant.DATA, MessageProperties.getData("ERR13")); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } // if (!(latitude >= 20 && latitude <= 22 && longitude >= 105 && // longitude <= 106)) { // String error = MessageProperties.getData("ERR09"); // jsonObject.put(Constant.STATUS, false); // jsonObject.put(Constant.DATA, error); // out.write(jsonObject.toJSONString().getBytes()); // out.flush(); // return; // } // check thời giạn click nhận giao ban Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone("Asia/Ho_Chi_Minh")); Time now = new Time(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND)); // lấy lịch trực bởi id OnlDao onlDao = new OnlDaoImpl(); Onl onl = onlDao.getOnlById(onlId); if (now.after(onl.getTimeStart()) && now.before(onl.getTimeEnd())) { // tính thời gian muộn int lateMin = (int) Math.round((double) ((now.getTime() - onl .getTimeStart().getTime()) / 1000) / 60); // thay đổi trạng thái onl.setLate(true); onl.setLateMin(lateMin); } else if (now.after(onl.getTimeEnd())) { // nghỉ String error = MessageProperties.getData("ERR14"); jsonObject.put(Constant.STATUS, false); jsonObject.put("flagHol", true); jsonObject.put(Constant.DATA, error); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } // cập nhật trạng thái nghỉ onl.setHol(false); // cập nhật if (!onlDao.update(onl, true)) { jsonObject.put(Constant.STATUS, false); jsonObject.put(Constant.DATA, MessageProperties.getData("ERR10")); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } jsonObject.put(Constant.STATUS, true); jsonObject.put(Constant.DATA, MessageProperties.getData("MSG04")); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } else if ("addReason".equals(action)) { JSONObject jsonObject = new JSONObject(); ServletOutputStream out = response.getOutputStream(); String reason = request.getParameter("reason"); long onlId = Long.parseLong(request.getParameter("id")); // update lý do if (!new OnlDaoImpl().setReason(reason, onlId)) { jsonObject.put(Constant.STATUS, false); jsonObject.put(Constant.DATA, MessageProperties.getData("ERR10")); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } jsonObject.put(Constant.STATUS, true); jsonObject.put(Constant.DATA, MessageProperties.getData("MSG01")); out.write(jsonObject.toJSONString().getBytes()); out.flush(); return; } } /** * check vị trí khi nhận giao ban * * @param position * tọa độ vị trí phòng B1-502 * @param latitude * vĩ độ lấy được ở vị trí hiện tại * @param longitude * kinh độ ở vị trí hiện tại * @return true nếu vị trí hiện tại trùng với vị trí phòng B1-502. flase nếu * ngược lại không trùng */ public boolean checkPosition(Position position, double latitude, double longitude) { double latitudeMin = Math.floor(position.getLatitude() * 1000000) / 1000000; double latitudeMax = Math.ceil(position.getLatitude() * 1000000) / 1000000; double longitudeMin = Math.floor(position.getLongitude() * 10000000) / 10000000; double longitudeMax = Math.ceil((position.getLongitude()) * 10000000) / 10000000; System.out.println(latitudeMin + " <= " + latitude + " <= "+ latitudeMax); System.out.println(longitudeMin + " <= " + longitude + " <= "+ longitudeMax); return latitudeMin <= latitude && latitude <= latitudeMax && longitudeMin <= longitude && longitude <= longitudeMax; } }
phuong95st/project-LA16
qlhoatdong2/src/controller/OnlController.java
Java
gpl-3.0
7,370
#ifndef __PLATFORM_H_ #define __PLATFORM_H_ #define STDOUT_IS_PS7_UART #define UART_DEVICE_ID 0 #include "xil_io.h" #include "xtmrctr.h" #include "assert.h" /* Write to memory location or register */ #define X_mWriteReg(BASE_ADDRESS, RegOffset, data) \ *(unsigned volatile int *)(BASE_ADDRESS + RegOffset) = ((unsigned volatile int) data); /* Read from memory location or register */ #define X_mReadReg(BASE_ADDRESS, RegOffset) \ *(unsigned volatile int *)(volatile)(BASE_ADDRESS + RegOffset); #define XUartChanged_IsTransmitFull(BaseAddress) \ ((Xil_In32((BaseAddress) + 0x2C) & \ 0x10) == 0x10) void wait_ms(unsigned int time); void init_platform(); void cleanup_platform(); void ChangedPrint(char *ptr); void timer_init(); void tic(); void toc(); u64 elapsed_time_us(); #endif
malkadi/FGPU
benchmark/MicroBlaze/src/platform.hpp
C++
gpl-3.0
818
<!DOCTYPE html> <!-- Copyright (C) 2017 ss This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --> <div style="min-height: 100px;"> <div [hidden]="result.length > 0"> <h4 style="text-align: center;" [translate]="'transport-map.search-result.no-result'"></h4> <h5 [translate]="'transport-map.search-result.no-result-desc'"></h5> <h5 [translate]="'transport-map.search-result.no-result-geocoder'"></h5> <h5>{{'transport-map.search-result.no-result-plain-schedule' | translate}} <span class="sr-link" (click)="goToSchedule()">{{'transport-map.search-result.no-result-plain-schedule-link' | translate}}</span></h5> <h5 [translate]="'transport-map.search-result.no-result-tooltip'"></h5> </div> <md-list *ngIf="mapComponent.activeProfile && result.length === 0"> <h3 md-subheader class="srl-result-h" [translate]="'transport-map.search-result.legend'"></h3> <md-list-item *ngFor="let typ of mapComponent.activeProfile.routeProfiles"> <span md-list-icon [style.background-color]="typ.lineColor" class="srl-route-label-2"></span> <p md-line style="line-height: 30px;" [translate]="'route-type.' + typ.name"></p> </md-list-item> </md-list> <div [hidden]="result.length < 1"> <md-list *ngIf="!flags.isDetailsOpen"> <h3 md-subheader class="srl-result-h" [translate]="'transport-map.search-result.found-results'" [translateParams]="{count: result.length}"></h3> <md-list-item *ngFor="let op of result" class="srl-item" (click)="showPath(op)" [@flyInOut]="op.animationTrigger"> <md-icon *ngIf="!mapComponent.isMobile()" md-list-icon [ngClass]="{'srl-selected-path': op === activePath}">chevron_right</md-icon> <p md-line style="line-height: 30px; height: 30px;"> <span *ngFor="let path of op.path" class="srl-route-label" [style.background-color]="path.route.type.lineColor" [style.font-size]="mapComponent.isMobile() ? '12px' : null" mdTooltip="{{path.description}}" mdTooltipPosition="above">{{path.route.namePrefix}}{{path.route.namePostfix}}</span> <span class="srl-time-lbl">{{tripPeriod(op)}}</span> </p> <md-icon mdTooltip="{{'transport-map.search-result.open-details' | translate }}" mdTooltipPosition="above" (click)="openDetails(op, $event)" style="margin-left: 5px" [ngClass]="{'srl-selected-path': op === activePath}">access_time</md-icon> </md-list-item> </md-list> <!-- DETAILS --> <div *ngIf="flags.isDetailsOpen" [@flyInOut]="detailsTrigger"> <md-grid-list cols="7" rowHeight="56px" > <md-grid-tile> <md-icon>schedule</md-icon> </md-grid-tile> <md-grid-tile colspan="5"> <h3 class="srl-details-h" [translate]="'transport-map.search-result.trip-details'"></h3> </md-grid-tile> <md-grid-tile> <button md-mini-fab mdTooltip="{{'transport-map.search-result.back-to-summary' | translate }}" mdTooltipPosition="above" (click)="closeDetails()" color="accent"> <md-icon>close</md-icon> </button> </md-grid-tile> </md-grid-list> <hr/> <div *ngFor="let p of activePath.path; let i = index;"> <md-grid-list cols="10" rowHeight="50px"> <md-grid-tile colspan="2"> <img [src]="'/rest/data/transport-profile/route/marker/' + p.route.type.id"> </md-grid-tile> <md-grid-tile colspan="6" class="srl-details-item" (click)="flyToBusStop(activePath.way[i][0])"> <p class="srl-d-bs-lbl">{{activePath.way[i][0].name}}</p> </md-grid-tile> <md-grid-tile colspan="2">{{getBusStopTime(i, 'start')}}</md-grid-tile> <md-grid-tile colspan="2"> <span class="srl-route-label" [style.background-color]="p.route.type.lineColor">{{p.route.namePrefix}}{{p.route.namePostfix}}</span> </md-grid-tile> <md-grid-tile colspan="6" class="srl-details-item" (click)="flyToWay(activePath.way[i])"> <p class="srl-d-bs-lbl">{{p.description}}</p> </md-grid-tile> <md-grid-tile colspan="2">{{pathTripDuration(i, p)}} {{'common.time.min' | translate}}</md-grid-tile> <md-grid-tile colspan="2"> <img [src]="'/rest/data/transport-profile/route/marker/' + p.route.type.id"> </md-grid-tile> <md-grid-tile colspan="6" class="srl-details-item" (click)="flyToBusStop(activePath.way[i][activePath.way[i].length - 1])"> <p class="srl-d-bs-lbl">{{activePath.way[i][activePath.way[i].length - 1].name}}</p> </md-grid-tile> <md-grid-tile colspan="2">{{getBusStopTime(i, 'end')}}</md-grid-tile> </md-grid-list> <hr/> </div> <!-- Summary --> <md-grid-list cols="8" rowHeight="50px"> <md-grid-tile> <md-icon>directions_run</md-icon> </md-grid-tile> <md-grid-tile colspan="5"> <p class="srl-d-bs-lbl" [translate]="'transport-map.search-result.full-distance'"></p> </md-grid-tile> <md-grid-tile colspan="2"> {{summaryDistance()}} {{'common.unit.km' | translate}} </md-grid-tile> <md-grid-tile> <md-icon>alarm</md-icon> </md-grid-tile> <md-grid-tile colspan="5"> <p class="srl-d-bs-lbl" [translate]="'transport-map.search-result.full-time'"></p> </md-grid-tile> <md-grid-tile colspan="2"> {{summaryTime()}} {{'common.time.min' | translate}} </md-grid-tile> </md-grid-list> <button md-raised-button (click)="closeDetails()" class="full-width"> <md-icon>chevron_left</md-icon> {{'transport-map.search-result.back-to-summary' | translate }} </button> </div> </div> </div>
StarshiStrelok/sonya
sonya-transport-html5/src/app/component2/search.result.list.html
HTML
gpl-3.0
7,582
import platform import glob from .io import DxlIO, Dxl320IO, DxlError from .error import BaseErrorHandler from .controller import BaseDxlController from .motor import DxlMXMotor, DxlAXRXMotor, DxlXL320Motor from ..robot import Robot def _get_available_ports(): """ Tries to find the available usb2serial port on your system. """ if platform.system() == 'Darwin': return glob.glob('/dev/tty.usb*') elif platform.system() == 'Linux': return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*') elif platform.system() == 'Windows': import _winreg import itertools ports = [] path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path) for i in itertools.count(): try: ports.append(str(_winreg.EnumValue(key, i)[1])) except WindowsError: return ports return [] def get_available_ports(only_free=False): ports = _get_available_ports() if only_free: ports = list(set(ports) - set(DxlIO.get_used_ports())) return ports def find_port(ids, strict=True): """ Find the port with the specified attached motor ids. :param list ids: list of motor ids to find :param bool strict: specify if all ids should be find (when set to False, only half motor must be found) .. warning:: If two (or more) ports are attached to the same list of motor ids the first match will be returned. """ for port in get_available_ports(): for DxlIOCls in (DxlIO, Dxl320IO): try: with DxlIOCls(port) as dxl: founds = len(dxl.scan(ids)) if strict and founds == len(ids): return port if not strict and founds >= len(ids) / 2: return port except DxlError: continue raise IndexError('No suitable port found for ids {}!'.format(ids)) def autodetect_robot(): """ Creates a :class:`~pypot.robot.robot.Robot` by detecting dynamixel motors on all available ports. """ motor_controllers = [] for port in get_available_ports(): for DxlIOCls in (DxlIO, Dxl320IO): dxl_io = DxlIOCls(port) ids = dxl_io.scan() if not ids: dxl_io.close() continue models = dxl_io.get_model(ids) motorcls = { 'MX': DxlMXMotor, 'RX': DxlAXRXMotor, 'AX': DxlAXRXMotor, 'XL': DxlXL320Motor } motors = [motorcls[model[:2]](id, model=model) for id, model in zip(ids, models)] c = BaseDxlController(dxl_io, motors) motor_controllers.append(c) return Robot(motor_controllers)
manon-cortial/pypot
pypot/dynamixel/__init__.py
Python
gpl-3.0
2,888
/* ----------------------------------------------------------------------------- This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ----------------------------------------------------------------------------- */ package ppm_java._dev.concept.example.event; import ppm_java.backend.TController; import ppm_java.typelib.IControllable; import ppm_java.typelib.IEvented; import ppm_java.typelib.VBrowseable; /** * */ class TSink extends VBrowseable implements IEvented, IControllable { public TSink (String id) { super (id); } public void OnEvent (int e, String arg0) { String msg; msg = GetID () + ": " + "Received messaging event. Message: " + arg0; System.out.println (msg); } public void Start () {/* Do nothing */} public void Stop () {/* Do nothing */} public void OnEvent (int e) {/* Do nothing */} public void OnEvent (int e, int arg0) {/* Do nothing */} public void OnEvent (int e, long arg0) {/* Do nothing */} protected void _Register () { TController.Register (this); } }
ustegrew/ppm-java
src/ppm_java/_dev/concept/example/event/TSink.java
Java
gpl-3.0
1,733
<?php // This file is part of VPL for Moodle - http://vpl.dis.ulpgc.es/ // // VPL for Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // VPL for Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with VPL for Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Class to show two files diff * * @package mod_vpl * @copyright 2012 Juan Carlos Rodríguez-del-Pino * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @author Juan Carlos Rodríguez-del-Pino <[email protected]> */ require_once dirname(__FILE__).'/../../../config.php'; require_once dirname(__FILE__).'/../locallib.php'; require_once dirname(__FILE__).'/../vpl.class.php'; require_once dirname(__FILE__).'/../vpl_submission.class.php'; require_once dirname(__FILE__).'/../views/sh_base.class.php'; require_once dirname(__FILE__).'/similarity_factory.class.php'; require_once dirname(__FILE__).'/similarity_base.class.php'; class vpl_diff{ /** * Remove chars and digits * @param $line string to process * @return string without chars and digits */ static function removeAlphaNum($line){ $ret=''; $l= strlen($line); //Parse line to remove alphanum chars for($i=0; $i<$l; $i++){ $c=$line[$i]; if(!ctype_alnum($c) && $c != ' '){ $ret.=$c; } } return $ret; } /** * Calculate the similarity of two lines * @param $line1 * @param $line2 * @return int (3 => trimmed equal, 2 =>removeAlphaNum , 1 => start of line , 0 => not equal) */ static function diffLine($line1,$line2){ //TODO Refactor. //This is a bad solution that must be rebuild to consider diferent languages //Compare trimed text $line1=trim($line1); $line2=trim($line2); if($line1==$line2){ if(strlen($line1)>0){ return 3; }else{ return 1; } } //Compare filtered text (removing alphanum) $rAN1=self::removeAlphaNum($line1); $limit = strlen($rAN1); if($limit>0){ if($limit>3){ $limite = 3; } if(strncmp($rAN1,self::removeAlphaNum($line2),$limit) == 0){ return 2; } } //Compare start of line $l=4; if($l>strlen($line1)){ $l=strlen($line1); } if($l>strlen($line2)){ $l=strlen($line2); } for($i=0; $i<$l; ++$i){ if($line1[$i] !=$line2[$i]){ break; } } return $i>0 ? 1:0; } static function newLineInfo($type,$ln1,$ln2=0){ $ret = new StdClass(); $ret->type = $type; $ret->ln1 = $ln1; $ret->ln2 = $ln2; return $ret; } /** * Initialize used matrix * @param $matrix matrix to initialize * @param $prev matrix to initialize * @param $nl1 number of rows * @param $nl2 number of columns * @return void */ static function initAuxiliarMatrices(&$matrix,&$prev,$nl1,$nl2){ // matrix[0..nl1+1][0..nl2+1]=0 $row = array_pad(array(),$nl2+1,0); $matrix = array_pad(array(),$nl1+1,$row); // prev[0..nl1+1][0..nl2+1]=0 $prev = $matrix; //update first column for($i=0; $i<=$nl1;$i++){ $matriz[$i][0]=0; $prev[$i][0]=-1; } //update first row for($j=1; $j<=$nl2;$j++){ $matriz[0][$j]=0; $prev[0][$j]=1; } } /** * Calculate diff for two array of lines * @param $lines1 array of string * @param $lines2 array of string * @return array of objects with info to show the two array of lines */ static function calculateDiff($lines1,$lines2){ $ret = array(); $nl1=count($lines1); $nl2=count($lines2); if($nl1==0 && $nl2==0){ return false; } if($nl1==0){ //There is no first file foreach($lines2 as $pos => $line){ $ret[] = self::newLineInfo('>',0,$pos+1); } return $ret; } if($nl2==0){ //There is no second file foreach($lines1 as $pos => $line){ $ret[] = self::newLineInfo('<',$pos+1); } return $ret; } self::initAuxiliarMatrices($matrix,$prev,$nl1,$nl2); //Matrix processing for($i=1; $i <= $nl1;$i++){ $line=$lines1[$i-1]; for($j=1; $j<=$nl2;$j++){ if($matrix[$i][$j-1]>$matrix[$i-1][$j]) { $max=$matrix[$i][$j-1]; $best = 1; }else{ $max=$matrix[$i-1][$j]; $best = -1; } $prize=self::diffLine($line,$lines2[$j-1]); if($matrix[$i-1][$j-1]+$prize>=$max){ $max=$matrix[$i-1][$j-1]+$prize; $best = 0; } $matrix[$i][$j]=$max; $prev[$i][$j]=$best; } } //Calculate show info $limit=$nl1+$nl2; $pairs = array(); $pi=$nl1; $pj=$nl2; while((!($pi == 0 && $pj == 0)) && $limit>0){ $pair = new stdClass(); $pair->i = $pi; $pair->j = $pj; $pairs[]=$pair; $p = $prev[$pi][$pj]; if($p == 0){ $pi--; $pj--; }elseif($p == -1){ $pi--; }else{ $pj--; } $limit--; } krsort($pairs); $prevpair = new stdClass(); $prevpair->i=0; $prevpair->j=0; foreach($pairs as $pair){ if($pair->i == $prevpair->i+1 && $pair->j == $prevpair->j+1){ //Regular advance if($lines1[$pair->i-1] == $lines2[$pair->j-1]){ //Equals $ret[]=self::newLineInfo('=',$pair->i,$pair->j); }else{ $ret[]=self::newLineInfo('#',$pair->i,$pair->j); } }elseif($pair->i == $prevpair->i+1){ //Removed next line $ret[]=self::newLineInfo('<',$pair->i); }elseif($pair->j == $prevpair->j+1){ //Added one line $ret[]=self::newLineInfo('>',0,$pair->j); }else{ debugging("Internal error ".print_r($pair,true)." ".print_r($prevpair,true)); } $prevpair=$pair; } return $ret; } static function show($filename1, $data1, $HTMLheader1, $filename2, $data2, $HTMLheader2) { //Get file lines $nl = vpl_detect_newline($data1); $lines1 = explode($nl,$data1); $nl = vpl_detect_newline($data2); $lines2 = explode($nl,$data2); //Get dif as an array of info $diff = self::calculateDiff($lines1,$lines2); if($diff === false){ return; } $separator= array('<'=>' <<< ', '>'=>' >>> ','='=>' === ','#'=>' ### '); $emptyline="&nbsp;\n"; $data1=''; $data2=''; $datal1=''; $datal2=''; $diffl=''; $lines1[-1]=''; $lines2[-1]=''; foreach($diff as $line){ $diffl.= $separator[$line->type]."\n"; if($line->ln1){ $datal1.=$line->ln1." \n"; $data1.=$lines1[$line->ln1-1]."\n"; }else{ $data1.=" \n"; $datal1.=$emptyline; } if($line->ln2){ $datal2.=$line->ln2." \n"; $data2.=$lines2[$line->ln2-1]."\n"; }else{ $data2.=" \n"; $datal2.=$emptyline; } } echo '<div style="width: 100%;min-width: 950px; overflow: auto">'; //Header echo '<div style="float:left; width: 445px">'; echo $HTMLheader1; echo '</div>'; echo '<div style="float:left; width: 445px">'; echo $HTMLheader2; echo '</div>'; echo '<div style="clear:both;"></div>'; //Files echo '<div style="float:left; text-align: right">'; echo '<pre class="'.vpl_sh_base::c_general.'">'; echo $datal1; echo '</pre>'; echo '</div>'; echo '<div style="float:left; width: 390px; overflow:auto">'; $shower= vpl_sh_factory::get_sh($filename1); $shower->print_file($filename1,$data1,false); echo '</div>'; echo '<div style="float:left">'; echo '<pre class="'.vpl_sh_base::c_general.'">'; echo $diffl; echo '</pre>'; echo '</div>'; echo '<div style="float:left; text-align: right;">'; echo '<pre class="'.vpl_sh_base::c_general.'">'; echo $datal2; echo '</pre>'; echo '</div>'; echo '<div style="float:left; width: 390px; overflow:auto">'; $shower= vpl_sh_factory::get_sh($filename2); $shower->print_file($filename2,$data2,false); echo '</div>'; echo '</div>'; echo '<div style="clear:both;"></div>'; } static function vpl_get_similfile($f,$vpl,&$HTMLheader,&$filename,&$data){ global $DB; $HTMLheader=''; $filename=''; $data=''; $type = required_param('type'.$f, PARAM_INT); if($type==1){ $subid = required_param('subid'.$f, PARAM_INT); $filename = required_param('filename'.$f, PARAM_TEXT); $subinstance = $DB->get_record('vpl_submissions',array('id' => $subid)); if($subinstance !== false){ $vpl = new mod_vpl(false,$subinstance->vpl); $vpl->require_capability(VPL_SIMILARITY_CAPABILITY); $submission = new mod_vpl_submission($vpl,$subinstance); $user = $DB->get_record('user', array('id' => $subinstance->userid)); if($user){ $HTMLheader .='<a href="'.vpl_mod_href('/forms/submissionview.php', 'id',$vpl->get_course_module()->id,'userid',$subinstance->userid).'">'; } $HTMLheader .=s($filename).' '; if($user){ $HTMLheader .= '</a>'; $HTMLheader .= $vpl->user_fullname_picture($user); } $fg = $submission->get_submitted_fgm(); $data = $fg->getFileData($filename); \mod_vpl\event\vpl_diff_viewed::log($submission); } }elseif($type == 2){ //FIXME adapt to moodle 2.x /* global $CFG; $dirname = required_param('dirname'.$f,PARAM_RAW); $filename = required_param('filename'.$f,PARAM_RAW); $base=$CFG->dataroot.'/'.$vpl->get_course()->id.'/'; $data = file_get_contents($base.$dirname.'/'.$filename); $HTMLheader .= $filename.' '.optional_param('username'.$f,'',PARAM_TEXT); */ }elseif($type == 3){ global $CFG; $data=''; $zipname = required_param('zipfile'.$f,PARAM_RAW); $filename = required_param('filename'.$f,PARAM_RAW); $HTMLheader .= $filename.' '.optional_param('username'.$f,'',PARAM_TEXT); $ext = strtoupper(pathinfo($zipfile,PATHINFO_EXTENSION)); if($ext != 'ZIP'){ print_error('nozipfile'); } $zip = new ZipArchive(); $zipfilename=self::get_zip_filepath($zipname); if($zip->open($zipfilename)){ $data=$zip->getFromName($filename); $zip->close(); } }else{ print_error('type error'); } } }
InstaLearn/phonegaptest3
mod/vpl/similarity/diff.class.php
PHP
gpl-3.0
12,386
package org.runnerup.notification; import android.annotation.TargetApi; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.support.v4.app.NotificationCompat; import org.runnerup.R; import org.runnerup.common.util.Constants; import org.runnerup.view.MainLayout; @TargetApi(Build.VERSION_CODES.FROYO) public class GpsBoundState implements NotificationState { private final Notification notification; public GpsBoundState(Context context) { NotificationCompat.Builder builder = new NotificationCompat.Builder(context); Intent i = new Intent(context, MainLayout.class); i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT); i.putExtra(Constants.Intents.FROM_NOTIFICATION, true); PendingIntent pi = PendingIntent.getActivity(context, 0, i, 0); builder.setContentIntent(pi); builder.setContentTitle(context.getString(R.string.activity_ready)); builder.setContentText(context.getString(R.string.ready_to_start_running)); builder.setSmallIcon(R.drawable.icon); builder.setOnlyAlertOnce(true); org.runnerup.util.NotificationCompat.setLocalOnly(builder); notification = builder.build(); } @Override public Notification createNotification() { return notification; } }
netmackan/runnerup
app/src/org/runnerup/notification/GpsBoundState.java
Java
gpl-3.0
1,443
<!DOCTYPE html> <html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml"> <head lang="en-GB"> <title>Ross Gammon’s Family Tree - Events</title> <meta charset="UTF-8" /> <meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" /> <meta name ="apple-mobile-web-app-capable" content="yes" /> <meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" /> <meta name="author" content="" /> <link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" /> <link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" /> <link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" /> </head> <body> <div id="header"> <h1 id="SiteTitle">Ross Gammon’s Family Tree</h1> </div> <div class="wrapper" id="nav" role="navigation"> <div class="container"> <ul class="menu" id="dropmenu"> <li><a href="../../../individuals.html" title="Individuals">Individuals</a></li> <li><a href="../../../index.html" title="Surnames">Surnames</a></li> <li><a href="../../../families.html" title="Families">Families</a></li> <li class = "CurrentSection"><a href="../../../events.html" title="Events">Events</a></li> <li><a href="../../../places.html" title="Places">Places</a></li> <li><a href="../../../sources.html" title="Sources">Sources</a></li> <li><a href="../../../repositories.html" title="Repositories">Repositories</a></li> <li><a href="../../../media.html" title="Media">Media</a></li> <li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li> </ul> </div> </div> <div class="content" id="EventDetail"> <h3>Birth</h3> <table class="infolist eventlist"> <tbody> <tr> <td class="ColumnAttribute">Gramps ID</td> <td class="ColumnGRAMPSID">E3500</td> </tr> <tr> <td class="ColumnAttribute">Date</td> <td class="ColumnColumnDate"> 1905 </td> </tr> </tbody> </table> <div class="subsection" id="references"> <h4>References</h4> <ol class="Col1" role="Volume-n-Page"type = 1> <li> <a href="../../../ppl/2/b/d15f5fe11fe5628177d349cc4b2.html"> ANDERSON, Laurence <span class="grampsid"> [I3142]</span> </a> </li> </ol> </div> </div> <div class="fullclear"></div> <div id="footer"> <p id="createdate"> Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:54:14<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a> </p> <p id="copyright"> </p> </div> </body> </html>
RossGammon/the-gammons.net
RossFamilyTree/evt/e/3/d15f5fe12036a978b3bf24e73e.html
HTML
gpl-3.0
2,704
package pl.idedyk.japanese.dictionary.web.html; import java.util.List; public class Ul extends HtmlElementCommon { public Ul() { super(); } public Ul(String clazz) { super(clazz); } public Ul(String clazz, String style) { super(clazz, style); } @Override protected String getTagName() { return "ul"; } @Override protected boolean isSupportHtmlElementList() { return true; } @Override protected List<String[]> getAdditionalTagAttributes() { return null; } }
dedyk/JapaneseDictionaryWeb
src/main/java/pl/idedyk/japanese/dictionary/web/html/Ul.java
Java
gpl-3.0
502
<?php /* checklinks.class.php ver.1.1 ** Author: Jason Henry www.yourarcadescript.com ** Please keep authorship info intact ** Nov. 26, 2011 ** ** Class is used to validate that a link exists on a given web page ** Usage example: ** include("checklinks.class.php"); ** $checklink = new checkLink; ** $response = $checklink->validateLink("www.website.com/links.html", "www.mywebsite.com"); ** $response will be: LINKDATAERROR(means unable to get data from the website) or LINKFOUND or LINKNOTFOUND or LINKFOUNDNOFOLLOW ** Updates in ver. 1.1 Added the port and path to the link choices to check allowing for a deep link search. Was returning a false negative. */ class checkLink { const LINKFOUND = 1; const LINKNOTFOUND = 0; const LINKFOUNDNOFOLLOW = 2; const LINKDATAERROR = 3; public function get_data($url) { $ch = curl_init(); $timeout = 5; $userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)'; curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); curl_setopt($ch,CURLOPT_URL,$url); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); $data = curl_exec($ch); curl_close($ch); return $data; } public function linkChoices($link) { $array = parse_url($link); $link1 = $array['host']; if (isset($array['port'])) { $link1 .= ":" . $array['port']; } if (isset($array['path'])) { $link1 .= $array['path']; } $links[0] = rtrim($link1,"/"); $links[1] = str_replace("www.", "", $links[0]); $links[2] = "http://".trim($links[1]); $links[3] = "http://www.".$links[1]; return $links; } public function validateLink($url, $url_tofind) { $page = $this->get_data($url); if (!$page) return LINKDATAERROR; $urlchoices = $this->linkChoices($url_tofind); $dom = new DOMDocument(); @$dom->loadHTML($page); $x = new DOMXPath($dom); foreach($x->query("//a") as $node) { $link = rtrim($node->getAttribute("href"), "/"); $rel = $node->getAttribute("rel"); if (in_array($link, $urlchoices)) { if(strtolower($rel) == "nofollow") { return LINKFOUNDNOFOLLOW; } else { return LINKFOUND; } } } return LINKNOTFOUND; } } ?>
Yourarcadescript/Version-2.5.2
includes/checklinks.class.php
PHP
gpl-3.0
2,197
"use strict"; function HelpTutorial() { let _getText = function() { return "HelpTutorial_Base"; }; this.getName = function(){ return "HelpTutorial_Base"; }; this.getImageId = function(){ return "button_help"; }; this.getText = _getText; } function HelpTutorialBuilding(name, image) { this.getName = function(){ return name; }; this.getImageId = function(){ return image; }; } function HelpQueueData(colonyState) { let queue = [new HelpTutorial()]; let available = []; let discovery = colonyState.getDiscovery(); for(let i = 0; i < discovery.length; i++) { if(discovery[i].startsWith("Resource_")) { queue.push(new HelpTutorialBuilding(discovery[i], discovery[i])); } } let technology = colonyState.getTechnology(); for(let i = 0; i < technology.length; i++) { let item = PrototypeLib.get(technology[i]); available.push(new HelpTutorialBuilding(technology[i], item.getBuildingImageId())); } QueueData.call(this, queue, available); this.getInfo = function(item) { let text = ""; if(item != null) { let imgSize = GetImageSize(ImagesLib.getImage(item.getImageId())); text += '<div class="queueInfo">'; if(item.getText != undefined) { text += '<div class="queueInfoTitle" style="height: ' + (imgSize.height + 5) + 'px;">'; text += '<img class="queueInfoTitleImage" style="height: ' + imgSize.height + 'px;" src="' + ImagesLib.getFileName(item.getImageId()) + '">'; text += '<div class="queueInfoTitleData queueInfoTitleName">' + TextRepository.get(item.getName()) + '</div>'; text += '</div>'; text += '<div class="queueInfoDetails">' + TextRepository.get(item.getName() + "Description") + '</div>'; } else { let baseImgSize = GetImageSize(ImagesLib.getImage("baseTile")); text += '<div class="queueInfoTitle" style="height: ' + (imgSize.height + 5) + 'px;">'; text += '<div style="float: left; height: ' + imgSize.height + 'px; background: url(\'' + ImagesLib.getFileName("baseTile") + '\') no-repeat; background-position: 0 ' + (imgSize.height - baseImgSize.height) + 'px;">'; text += '<img style="height: ' + imgSize.height + 'px; border-size: 0;" src="' + ImagesLib.getFileName(item.getImageId()) + '">'; text += '</div>'; text += '<div class="queueInfoTitleData">'; text += '<div class="queueInfoTitleName">' + TextRepository.get(item.getName()) + '</div>'; text += '<div class="queueInfoTitleDescription">' + TextRepository.get(item.getName() + "Description") + '</div>'; text += '</div>'; text += '</div>'; text += '<div class="queueInfoDetails">'; let proto = PrototypeLib.get(item.getName()); text += '<table>'; text += '<tr><td class="tableMainColumn">' + TextRepository.get("TerrainLayer") + ':</td><td></td><td>' + TextRepository.get(proto.getTerrainLayer()) + '</td></tr>'; let list; let listItem; if(proto.getBuildingTime() > 0 || Object.keys(proto.getBuildingCost()).length > 0) { //text += '<tr><td>' + TextRepository.get("BuildingTitle") + '</td></tr>'; text += '<tr><td>' + TextRepository.get("BuildingTime") + ':</td><td class="tableDataRight">' + proto.getBuildingTime() + '</td><td>' + TextRepository.get("TimeUnit") + '</td></tr>'; list = proto.getBuildingCost(); if(Object.keys(list).length > 0) { text += '<tr><td>' + TextRepository.get("BuildingCost") + ':</td></tr>'; for (listItem in list) { if(list.hasOwnProperty(listItem)) { text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td>'; if(list[listItem] > colonyState.getProduced(listItem)) { text += '<td class="colorError">' + TextRepository.get("unavailable") + '</td>'; } text += '</tr>'; } } } } if(proto.getRequiredResource() != null) { text += '<tr><td>' + TextRepository.get("Requirements") + ':</td><td>' + TextRepository.get(proto.getRequiredResource()) + '</td></tr>'; } list = proto.getCapacity(); if(Object.keys(list).length > 0) { text += '<tr><td>' + TextRepository.get("BuildingCapacity") + ':</td></tr>'; for (listItem in list) { if(list.hasOwnProperty(listItem)) { text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>'; } } } if((Object.keys(proto.getConsumption()).length + Object.keys(proto.getProduction()).length + Object.keys(proto.getProductionWaste()).length) > 0) { //text += '<tr><td>' + TextRepository.get("ProductionTitle") + '</td></tr>'; list = proto.getConsumption(); if(Object.keys(list).length > 0) { text += '<tr><td>' + TextRepository.get("BuildingConsumption") + ':</td></tr>'; for (listItem in list) { if(list.hasOwnProperty(listItem)) { text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>'; } } } list = proto.getProduction(); if(Object.keys(list).length > 0) { text += '<tr><td>' + TextRepository.get("BuildingProduction") + ':</td></tr>'; for (listItem in list) { if(list.hasOwnProperty(listItem)) { text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>'; } } } list = proto.getProductionWaste(); if(Object.keys(list).length > 0) { text += '<tr><td>' + TextRepository.get("BuildingWaste") + ':</td></tr>'; for (listItem in list) { if(list.hasOwnProperty(listItem)) { text += '<tr><td class="tableIndentation">' + TextRepository.get(listItem) + '</td><td class="tableDataRight">' + list[listItem] + '</td></tr>'; } } } } text += '</table>'; text += '</div>'; } text += '</div>'; } return text; }; this.isSortable = function() { return false; }; this.getTitle = function() { return "HelpTitle"; }; this.getQueueTitle = function() { return "HelpBase"; }; this.getAvailableTitle = function() { return "Buildings"; }; } HelpQueueData.inherits(QueueData);
Hiperblade/OutpostTLH
script/ViewQueueHelp.js
JavaScript
gpl-3.0
6,371
/* Dylan Secreast * [email protected] * CIS 415 Project 0 * This is my own work except for the base * code that was provided by Prof. Sventek */ #ifndef _DATE_H_INCLUDED_ #define _DATE_H_INCLUDED_ typedef struct date Date; /* * date_create creates a Date structure from `datestr` * `datestr' is expected to be of the form "dd/mm/yyyy" * returns pointer to Date structure if successful, * NULL if not (syntax error) */ Date *date_create(char *datestr); /* * date_duplicate creates a duplicate of `d' * returns pointer to new Date structure if successful, * NULL if not (memory allocation failure) */ Date *date_duplicate(Date *d); /* * date_compare compares two dates, returning <0, 0, >0 if * date1<date2, date1==date2, date1>date2, respectively */ int date_compare(Date *date1, Date *date2); /* * date_destroy returns any storage associated with `d' to the system */ void date_destroy(Date *d); #endif /* _DATE_H_INCLUDED_ */
DylanSecreast/uoregon-cis-portfolio
uoregon-cis-415/Projects/project0/date.h
C
gpl-3.0
1,010
/** * @file test-mus-got.cpp * @brief Test code for God of Thunder files. * * Copyright (C) 2010-2015 Adam Nielsen <[email protected]> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "test-music.hpp" class test_mus_got: public test_music { public: test_mus_got() { this->type = "got"; this->numInstruments = 1; this->indexInstrumentOPL = 0; this->indexInstrumentMIDI = -1; this->indexInstrumentPCM = -1; } void addTests() { this->test_music::addTests(); // c00: Normal this->isInstance(MusicType::Certainty::PossiblyYes, this->standard()); // c01: Too short this->isInstance(MusicType::Certainty::DefinitelyNo, STRING_WITH_NULLS( "\x01" "\x00\x00\x00" "\x00" )); // c02: Uneven length this->isInstance(MusicType::Certainty::DefinitelyNo, STRING_WITH_NULLS( "\x01\x00" "\x00\x20\xAE" "\x00" "\x00\x00\x00" "\x00" )); // c03: Bad signature this->isInstance(MusicType::Certainty::DefinitelyNo, STRING_WITH_NULLS( "\x02\x00" "\x00\x20\xAE" "\x00\x40\x7F" "\x00\x60\xED" "\x00\x80\xCB" "\x00\xE0\x06" "\x00\x23\xA7" "\x00\x43\x1F" "\x00\x63\x65" "\x00\x83\x43" "\x00\xE3\x02" "\x00\xC0\x04" "\x00\xA0\x44" "\x01\xB0\x32" "\x00\xB0\x12" "\x00\x00\x00" "\x00" )); // c04: Missing/incomplete loop-to-start marker this->isInstance(MusicType::Certainty::DefinitelyNo, STRING_WITH_NULLS( "\x01\x00" "\x00\x20\xAE" "\x00\x40\x7F" "\x00\x60\xED" "\x00\x80\xCB" "\x00\xE0\x06" "\x00\x23\xA7" "\x00\x43\x1F" "\x00\x63\x65" "\x00\x83\x43" "\x00\xE3\x02" "\x00\xC0\x04" "\x00\xA0\x44" "\x01\xB0\x32" "\x00\xB0\x12" "\x00\x00\x00" )); } virtual std::string standard() { return STRING_WITH_NULLS( "\x01\x00" "\x00\x20\xFF" "\x00\x40\xFF" "\x00\x60\xFF" "\x00\x80\xFF" "\x00\xE0\x07" "\x00\x23\x0E" "\x00\x43\xBE" "\x00\x63\xEE" "\x00\x83\xEE" "\x00\xE3\x06" "\x00\xC0\x0F" "\x00\xA0\x44" "\x01\xB0\x32" "\x00\xB0\x12" "\x00\x00\x00" "\x00" ); } }; IMPLEMENT_TESTS(mus_got);
Malvineous/libgamemusic
tests/test-mus-got.cpp
C++
gpl-3.0
2,799
#include <fstream> #include <algorithm> #include "anime_db.hpp" #include "trim.hpp" bool anime_database::dump_anime_db(const astd::filesystem::path& db_path, const anime_database& db) { bool result = false; std::ofstream stream{ db_path.c_str(), std::ios::out | std::ios::trunc }; if (stream) { result = true; configuration_input::dump_config(stream, db.input); for (auto& num : db.number_fetched) { stream << num << std::endl; } } return result; } std::pair<bool, anime_database> anime_database::parse_anime_db(const astd::filesystem::path& db_path) { std::pair<bool, anime_database> result{ false, anime_database() }; std::ifstream stream{ db_path.c_str() }; if (stream) { std::string line; result.first = true; bool ok = true; std::size_t line_num = 1; while (result.first && std::getline(stream, line)) { auto trimmed_line = xts::trim<char>(line); ok = ok && configuration_input::parse_line(trimmed_line, result.second.input); if (!ok) { if (std::all_of(trimmed_line.begin(), trimmed_line.end(), [](auto& c) { return std::isdigit(c) != 0 || c == '.'; })) //if the line is a interger/float { result.second.number_fetched.emplace_back(trimmed_line.to_string()); } else //something when bad { result.first = false; } } if (!result.first) std::cerr << "error at line : no " << line_num << " : " << line << std::endl; line_num++; } } return result; }
Surogate/raspberry_script
scan-auto-fetch/anime_db.cpp
C++
gpl-3.0
1,707
public class Main { public static void main(String[] args) { ProdutoContext manga = new ProdutoContext(); System.out.println("Quantia: " + manga.getQuantia()); manga.fazerCompra(5); manga.reestocar(5); manga.fazerCompra(5); manga.reestocar(15); System.out.println("Quantia: " + manga.getQuantia()); manga.fazerCompra(5); System.out.println("Quantia: " + manga.getQuantia()); } }
guilhermepo2/bcc
2015-2/POO2 - Praticas/Pratica08-1 - State/src/Main.java
Java
gpl-3.0
402