code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
/* Copyright (c) 2005 CodeSourcery, LLC. All rights reserved. */
/** @file initfin.hpp
@author Zack Weinberg
@date 2005-01-19
@brief VSIPL++ Library: [initfin] Initialization and finalization.
This file declares the mechanism for initialization and
finalization of the library's private data structures. Use of any
library routines while no \c vsipl object exists provokes
undefined behavior. */
#ifndef VSIP_INITFIN_HPP
#define VSIP_INITFIN_HPP
/***********************************************************************
Included Files
***********************************************************************/
#include <vsip/support.hpp>
#include <vsip/core/counter.hpp>
/***********************************************************************
Declarations
***********************************************************************/
/// All VSIPL++ interfaces live in namespace \c vsip.
namespace vsip
{
namespace impl
{
// Forward Declaration
class Par_service;
namespace profile
{
class Profiler_options;
} // namespace profile
} // namespace impl
/// Class for management of library private data structures.
///
/// While the VSIPL++ library is in use, at least one \c vsipl
/// object must exist. Creation of more \c vsipl objects has
/// no additional effect. The library remains usable until the
/// last vsipl object is destroyed.
///
/// Optionally, one may pass the program's command line arguments to
/// the vsipl constructor; they are then scanned for
/// implementation-defined options which modify the library's behavior.
/// (This only happens the first time a \c vsipl object is created.)
///
/// vsipl objects may not be copied.
class vsipl
{
public:
/// Constructor requesting default library behavior.
vsipl();
/// Constructor requesting command-line-dependent library behavior.
vsipl(int& argc, char**& argv);
/// Destructor.
~vsipl() VSIP_NOTHROW;
static impl::Par_service* impl_par_service()
{ return par_service_; }
private:
// These are declared to prevent the compiler from synthesizing
// default definitions; they are deliberately left undefined.
vsipl(const vsipl&); ///< Stub to block copy-initialization.
vsipl& operator=(const vsipl&); ///< Stub to block assignment.
// Internal variables:
/// Count of active \c vsipl objects.
static impl::Checked_counter use_count;
/// Parallel Service.
static impl::Par_service* par_service_;
/// Profiler.
static impl::profile::Profiler_options* profiler_opts_;
// Internal functions:
private:
/// Constructor worker function.
static void initialize_library(int& argc, char**& argv);
/// Destructor worker function.
static void finalize_library();
};
} // namespace vsip
#endif // initfin.hpp
| maxywb/vsipl | sourceryvsipl++-2.3/include/vsip/initfin.hpp | C++ | gpl-2.0 | 2,783 |
# -*- coding: utf-8 -*-
{
' (late)': ' (verspätet)',
'!=': '!=',
'!langcode!': 'de',
'!langname!': 'Deutsch (DE)',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '""Update" ist ein optionaler Ausdruck wie "Feld1 = \'newvalue". JOIN Ergebnisse können nicht aktualisiert oder gelöscht werden',
'%(nrows)s records found': '%(nrows)s Einträge gefunden',
'%d.%m.%Y': '%d.%m.%Y',
'%s %%(shop)': '%s %%(shop)',
'%s %%(shop[0])': '%s %%(shop[0])',
'%s %%{quark[0]}': '%s %%{quark[0]}',
'%s %%{row} deleted': '%s %%{row} gelöscht',
'%s %%{row} updated': '%s %%{row} aktualisiert',
'%s %%{shop[0]}': '%s %%{shop[0]}',
'%s %%{shop}': '%s %%{shop}',
'%s selected': '%s ausgewählt',
'%Y-%m-%d': '%d.%m.%Y',
'%Y-%m-%d %H:%M:%S': '%d.%m.%Y %H:%M:%S',
'+ And': '+ Und',
'+ Or': '+ Oder',
'<': '<',
'<=': '<=',
'=': '=',
'>': '>',
'>=': '>=',
'?': '?',
'@markmin\x01**Hello World**': '**Hallo Welt**',
'@markmin\x01An error occured, please [[reload %s]] the page': 'Ein Fehler ist aufgetreten, bitte [[laden %s]] Sie die Seite neu',
'A file ({filename}) was uploaded for task {task} by {firstname} {lastname} with the hash (SHA256) {hash}.': 'Eine Datei ({filename}) für die Aufgabe {task} mit dem Hash (SHA256) {hash} wurde von {firstname} {lastname} hochgeladen.',
'About': 'Über',
'Access Control': 'Zugangskontrolle',
'Add Record': 'Eintrag hinzufügen',
'Add record to database': 'Eintrag in Datenbank hinzufügen',
'Add this to the search as an AND term': 'Add this to the search as an AND term',
'Add this to the search as an OR term': 'Add this to the search as an OR term',
'admin': 'admin',
'Administrative Interface': 'Administrationsoberfläche',
'Administrator view: Task of all users are shown!': 'Administrator-Ansicht: Es werden die Aufgaben aller Benutzer angezeigt!',
'After the file was uploaded, the chosen teacher will be informed by email. The uploader also gets an email with the hash (SHA256) of the uploaded file.': 'Nach Betätigung des Upload-Buttons wird die Datei übermittelt und die ausgewählte Lehrkraft per Mail darüber informiert. Der Uploader bekommt ebenfalls eine Benachrichtigungsmail mit der Hash (SHA256) der hochgeladenen Datei.',
'Ajax Recipes': 'Ajax Rezepte',
'appadmin is disabled because insecure channel': 'Appadmin ist deaktiviert, wegen der Benutzung eines unsicheren Kanals',
'Apply changes': 'Änderungen übernehmen',
'Are you sure you want to delete this object?': 'Sind Sie sich sicher, dass Sie dieses Objekt löschen wollen?',
'AttendingClass': 'Klasse',
'Available Databases and Tables': 'Verfügbare Datenbanken und Tabellen',
'Back': 'Zurück',
'Buy this book': 'Dieses Buch kaufen',
"Buy web2py's book": "Buy web2py's book",
'cache': 'cache',
'Cache': 'Cache',
'Cache Cleared': 'Cache geleert',
'Cache Keys': 'Cache Schlüssel',
'Cannot be empty': 'Darf nicht leer sein',
'Change Password': 'Passwort ändern',
'Change password': 'Passwort ändern',
'Check to delete': 'Auswählen um zu löschen',
'Choose a file to be uploaded!': 'Wählen Sie eine Datei aus, die hochgeladen werden soll!',
'Choose a task:': 'Wählen Sie eine Aufgabe aus:',
'choose one': 'Wählen Sie einen aus',
'Class': 'Klasse',
'Clear': 'Löschen',
'Clear CACHE?': 'CACHE löschen?',
'Clear DISK': 'DISK löschen',
'Clear RAM': 'RAM löschen',
'Click on the link %(link)s to reset your password': 'Click on the link %(link)s to reset your password',
'Client IP': 'Client IP',
'Close': 'Schließen',
'Collect uploaded files': 'Hochgeladene Dateien einsammeln',
'Comma-separated export including columns not shown; fields from other tables are exported as raw values for faster export': 'Comma-separated export including columns not shown; fields from other tables are exported as raw values for faster export',
'Comma-separated export of visible columns. Fields from other tables are exported as they appear on-screen but this may be slow for many rows': 'Comma-separated export of visible columns. Fields from other tables are exported as they appear on-screen but this may be slow for many rows',
'Community': 'Community',
'Components and Plugins': 'Komponenten und Plugins',
'Config.ini': 'Config.ini',
'Confirm Password': 'Passwort bestätigen',
'contains': 'contains',
'Controller': 'Controller',
'Copyright': 'Copyright',
'Created By': 'Erstellt von',
'Created On': 'Erstellt am',
'CSV': 'CSV',
'CSV (hidden cols)': 'CSV (versteckte Spalten)',
'Current request': 'Derzeitiger Request',
'Current response': 'Derzeitige Response',
'Current session': 'Derzeitige Session',
'customize me!': 'Pass mich an!',
'data uploaded': 'Datei hochgeladen',
'Database': 'Datenbank',
'Database %s select': 'Datenbank %s ausgewählt',
'Database Administration (appadmin)': 'Datenbankadministration (appadmin)',
'db': 'db',
'DB Model': 'Muster-DB',
'Delete': 'Löschen',
'Delete:': 'Löschen:',
'Demo': 'Demo',
'Deployment Recipes': 'Entwicklungsrezepte',
'Description': 'Beschreibung',
'design': 'Design',
'Design': 'Design',
'DISK': 'DISK',
'Disk Cache Keys': 'Disk Cache Keys',
'Disk Cleared': 'Disk gelöscht',
'Documentation': 'Dokumentation',
"Don't know what to do?": 'Wissen Sie nicht weiter?',
'done!': 'Fertig!',
'Download': 'Download',
'Download all uploaded files...': 'Alle hochgeladenen Dateien herunterladen...',
'Download files': 'Dateien herunterladen',
'Duedate': 'Fälligkeit',
'DueDate': 'Fälligkeit',
'E-mail': 'Email',
'Edit': 'Bearbeiten',
'Edit current record': 'Diesen Eintrag editieren',
'Email and SMS': 'Email und SMS',
'Email sent': 'Email wurde versandt',
'Enter a valid email address': 'Geben Sie eine gültige Email-Adresse ein',
'Enter a value': 'Geben Sie einen Wert ein',
'Enter an integer between %(min)g and %(max)g': 'Eine Zahl zwischen %(min)g und %(max)g eingeben',
'enter an integer between %(min)g and %(max)g': 'eine Zahl zwischen %(min)g und %(max)g eingeben',
'enter date and time as %(format)s': 'ein Datum und eine Uhrzeit als %(format)s eingeben',
'Enter date as %(format)s': 'Geben Sie ein Datum mit dem Format %(format)s an',
'Enter from %(min)g to %(max)g characters': 'Geben Sie zwischen %(min)g und %(max)g Zeichen ein',
'Errors': 'Fehlermeldungen',
'Errors in form, please check it out.': 'Bitte überprüfen Sie das Formular, denn es enthält Fehler.',
'export as csv file': 'als csv Datei exportieren',
'Export:': 'Export:',
'FAQ': 'FAQ',
'file': 'file',
'file ## download': 'Datei ## herunterladen',
'File size is to large!': 'Datei ist zu groß!',
'File successfully uploaded': 'Datei erfolgreich hochgeladen',
'File successfully uploaded!': 'Datei erfolgreich hochgeladen!',
'File to be uploaded': 'Hochzuladene Datei',
'File uploaded for task {task}': 'Datei hochgeladen für Aufgabe {task}',
'First name': 'Vorname',
'First Name': 'Vorname',
'FirstName': 'FirstName',
'Forgot username?': 'Benutzernamen vergessen?',
'Forms and Validators': 'Forms und Validators',
'Free Applications': 'Kostenlose Anwendungen',
'Given task and teacher does not match!': 'Angegebene Aufgabe und Lehrkraft passen nicht zusammen!',
'Graph Model': 'Muster-Graph',
'Group %(group_id)s created': 'Gruppe %(group_id)s erstellt',
'Group ID': 'Gruppen ID',
'Group uniquely assigned to user %(id)s': 'Gruppe eindeutigem Benutzer %(id)s zugewiesen',
'Groups': 'Gruppen',
'Hash': 'Hash',
'Hello World': 'Hallo Welt',
'Hello World ## Kommentar': 'Hallo Welt ',
'Hello World## Kommentar': 'Hallo Welt',
'Help': 'Hilfe',
'Helping web2py': 'web2py helfen',
'Home': 'Startseite',
'Hosted on': 'Hosted on',
'How did you get here?': 'Wie sind Sie hier her gelangt?',
'HTML': 'HTML',
'HTML export of visible columns': 'Sichtbare Spalten nach HTML exportieren',
'Id': 'Id',
'import': 'Importieren',
'Import/Export': 'Importieren/Exportieren',
'in': 'in',
'Insufficient privileges': 'Keine ausreichenden Rechte',
'Internal State': 'Innerer Zustand',
'Introduction': 'Einführung',
'Invalid email': 'Ungültige Email',
'Invalid login': 'Ungültiger Login',
'Invalid Query': 'Ungültige Query',
'invalid request': 'Ungültiger Request',
'Is Active': 'Ist aktiv',
'JSON': 'JSON',
'JSON export of visible columns': 'Sichtbare Spalten nach JSON exportieren',
'Key': 'Schlüssel',
'Klasse': 'Klasse',
'Last name': 'Nachname',
'Last Name': 'Nachname',
'LastName': 'Nachname',
'Layout': 'Layout',
'Layout Plugins': 'Layout Plugins',
'Layouts': 'Layouts',
'Live Chat': 'Live Chat',
'Log In': 'Einloggen',
'Log Out': 'Ausloggen',
'Logged in': 'Eingeloggt',
'Logged out': 'Ausgeloggt',
'Login': 'Einloggen',
'Login to UpLoad': 'In UpLoad einloggen',
'Logout': 'Ausloggen',
'Lost Password': 'Passwort vergessen',
'Lost password?': 'Passwort vergessen?',
'Mail': 'Mail',
'Manage %(action)s': '%(action)s verwalten',
'Manage Access Control': 'Zugangskontrolle verwalten',
'Manage Cache': 'Cache verwalten',
'Manage tasks': 'Aufgaben verwalten',
'Manage teachers': 'Lehrkräfte verwalten',
'Memberships': 'Mitgliedschaften',
'Menu Model': 'Menü-Muster',
'Modified By': 'Verändert von',
'Modified On': 'Verändert am',
'My Sites': 'Meine Seiten',
'Nachname': 'Nachname',
'Name': 'Name',
'New password': 'Neues Passwort',
'New Record': 'Neuer Eintrag',
'new record inserted': 'neuer Eintrag hinzugefügt',
'New Search': 'Neue Suche',
'next %s rows': 'nächste %s Reihen',
'No databases in this application': 'Keine Datenbank in dieser Anwendung',
'No hash for upload given.': 'Kein Upload mit angegebener Hash gefunden',
'No records found': 'Keine Einträge gefunden',
'No task number given.': 'Es wurde keine Aufgabe gewählt.',
'Not Authorized': 'Zugriff verboten',
'not authorized': 'Zugriff verboten',
'not in': 'not in',
'Object or table name': 'Objekt- oder Tabellenname',
'Old password': 'Altes Passwort',
'Online book': 'Online book',
'Online examples': 'Online Beispiele',
'OpenForSubmission': 'Upload freigeschaltet',
'or import from csv file': 'oder von csv Datei importieren',
'Origin': 'Ursprung',
'Other Plugins': 'Andere Plugins',
'Other Recipes': 'Andere Rezepte',
'Overview': 'Überblick',
'Password': 'Passwort',
'Password changed': 'Passwort wurde geändert',
"Password fields don't match": 'Passwortfelder sind nicht gleich',
'Password reset': 'Passwort wurde zurückgesetzt',
'Permission': 'Zugriffsrecht',
'Permissions': 'Zugriffsrechte',
'please input your password again': 'Bitte geben Sie ihr Passwort erneut ein',
'Plugins': 'Plugins',
'Powered by': 'Unterstützt von',
'Preface': 'Allgemeines',
'previous %s rows': 'vorherige %s Reihen',
'Profile': 'Profil',
'Profile updated': 'Profil aktualisiert',
'pygraphviz library not found': 'pygraphviz Bibliothek wurde nicht gefunden',
'Python': 'Python',
'Query:': 'Query:',
'Quick Examples': 'Kurze Beispiele',
'RAM': 'RAM',
'RAM Cache Keys': 'RAM Cache Keys',
'Ram Cleared': 'Ram Cleared',
'Recipes': 'Rezepte',
'Record': 'Eintrag',
'record does not exist': 'Eintrag existiert nicht',
'Record ID': 'ID des Eintrags',
'Record id': 'id des Eintrags',
'Register': 'Register',
'Registration identifier': 'Registrierungsbezeichnung',
'Registration key': 'Registierungsschlüssel',
'Registration successful': 'Registrierung erfolgreich',
'Remember me (for 30 days)': 'Eingeloggt bleiben (30 Tage lang)',
'Request reset password': 'Request reset password',
'Request Reset Password': 'Request Reset Password',
'Reset Password': 'Reset Password',
'Reset Password key': 'Passwortschlüssel zurücksetzen',
'Role': 'Rolle',
'Roles': 'Rollen',
'Rows in Table': 'Tabellenreihen',
'Rows selected': 'Reihen ausgewählt',
'Save model as...': 'Speichere Vorlage als...',
'Search': 'Suche',
'Semantic': 'Semantik',
'SendMessages': 'Sende Nachrichten',
'Services': 'Dienste',
'Sign Up': 'Sign Up',
'Size of cache:': 'Cachegröße:',
'Spreadsheet-optimised export of tab-separated content including hidden columns. May be slow': 'Spreadsheet-optimised export of tab-separated content including hidden columns. May be slow',
'Spreadsheet-optimised export of tab-separated content, visible columns only. May be slow.': 'Spreadsheet-optimised export of tab-separated content, visible columns only. May be slow.',
'Start building a new search': 'Start building a new search',
'StartDate': 'Beginn',
'starts with': 'starts with',
'state': 'Status',
'Statistics': 'Statistik',
'Stylesheet': 'Stylesheet',
'Submission for given task no yet allowed!': 'Upload für die gegebene Aufgabe ist noch nicht erlaubt!',
'submit': 'Abschicken',
'Submit': 'Abschicken',
'SubmittedOnTime': 'Pünklich abgegeben',
'Submittedontime': 'Pünklich abgegeben',
'Success!': 'Erfolg!',
'Support': 'Support',
'Table': 'Tabelle',
'Task': 'Aufgabe',
'Task is currently not open for submission.': 'Für diese Aufgabe sind im Moment keine Uploads erlaubt.',
'Teacher': 'Lehrkraft',
'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'Die "query" ist eine Bedingung wie "db.tabelle1.feld1==\'wert\'". So etwas wie "db.tabelle1.feld1==db.tabelle2.feld2" resultiert in einem SQL JOIN.',
'The Core': 'Der Core',
'The output of the file is a dictionary that was rendered by the view %s': 'Die Ausgabe der Datei ist ein "dictionary", welches vom "view" %s gerendert wurde',
'The Views': 'Die Views',
'This App': 'Diese App',
'This email already has an account': 'Zu dieser Email-Adresse gibt es bereits einen Benutzer.',
'This exact file has been uploaded already by a user.': 'Exakt diese Datei wurde bereits von einem Benutzer hochgeladen.',
'This page only works with JavaScript.': 'Diese Seite funktioniert nur mit JavaScript.',
'Time in Cache (h:m:s)': 'Zeit im Cache (h:m:s)',
'Timestamp': 'Zeitstempel',
'Token': 'Token',
'Traceback': 'Traceback',
'TSV (Spreadsheets)': 'TSV (Tabellenkalkulation)',
'TSV (Spreadsheets, hidden cols)': 'TSV (Tabellenkalkulation, versteckte Spalten)',
'Twitter': 'Twitter',
'unable to parse csv file': 'csv Datei konnte nicht geparst werden',
'Update:': 'Update:',
'Upload file': 'Datei hochladen',
'UpLoad@BBS is used to upload presentations, project documentation and tests. To upload a file you have to fill out the form with information about the uploader, the teacher and the task for which you want to upload a file. Then you can choose a file to be uploaded. The maximum file size is 5MiB.': 'UpLoad@BBS dient dem einfachen Abgeben von Projektarbeiten, Präsentationen und Klassenarbeiten. Um eine Datei hochzuladen, müssen zunächst Informationen zum Absender, der Lehrkraft und der Aufgabe angegeben werden. Anschließend ist die abzugebende Datei auszuwählen. Die maximal erlaubte Dateigröße beträgt 5MiB.',
'UploadedFile': 'Hochgeladene Datei',
'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Benutze (...)&(...) für AND, (...)|(...) für OR, und ~(...) für NOT um komplexere Queries zu erstellen.',
'User': 'Benutzer',
'User %(id)s Logged-in': 'Benutzer %(id)s hat sich eingeloggt',
'User %(id)s Logged-out': 'Benutzer %(id)s hat sich ausgeloggt',
'User %(id)s Registered': 'Benutzer %(id)s hat sich registriert',
'User ID': 'Benutzer ID',
'Users': 'Benutzer',
'value already in database or empty': 'Wert ist bereits in der Datenbank oder leer',
'Value not in database': 'Ausgewählter Wert nicht in Datenbank enthalten',
'Verify Password': 'Passwort überprüfen',
'Videos': 'Videos',
'View': 'Ansicht',
'View uploaded file': 'Hochgeladene Datei ansehen',
'View uploaded files': 'Hochgeladene Dateien ansehen',
'View uploads': 'Hochgeladene Datei ansehen',
'Welcome': 'Willkommen',
'Welcome to web2py!': 'Willkommen bei web2py!',
'Which called the function %s located in the file %s': 'Welche die Funktion %s in der Datei %s aufrief',
'Working...': 'Arbeite...',
'Wrong token for given task.': 'Ungültiger Token für gewählte Aufgabe eingegeben.',
'Wrong token given!': 'Ungültiger Token eingegeben!',
'XML': 'XML',
'XML export of columns shown': 'XML export of columns shown',
'You already created a Task with the same name. Please delete the old task or rename this one.': 'Sie haben bereits eine Aufgabe mit diesem Namen erstellt. Bitte löschen sie die alte Aufgabe oder geben Sie einen anderen Namen an.',
'You already uploaded a file for this task!': 'Sie haben bereits eine Datei für diese Aufgabe hochgeladen!',
'You are successfully running web2py': 'web2py wird erfolgreich ausgeführt',
'You can modify this application and adapt it to your needs': 'Sie können diese Anwendung verändern und Ihren Bedürfnissen anpassen',
'You can only create tasks for yourself.': 'Sie dürfen nur eigene Aufgaben erstellen.',
'You visited the url %s': 'Sie haben die URL %s besucht',
'Your file ({filename}) with the hash (SHA256) {hash} has been successfully uploaded.': 'Ihre Datei ({filename}) mit dem Hash (SHA256) {hash} wurde erfolgreich hochgeladen.',
}
| wichmann/UpLoad | languages/de.py | Python | gpl-2.0 | 16,769 |
package nl.abevos.kikker.level;
import nl.abevos.kikker.KikkerGame;
import nl.abevos.kikker.actor.Frog;
import nl.abevos.kikker.environment.Platform;
import nl.abevos.kikker.environment.Wall;
import nl.abevos.kikker.manager.AssetManager;
import nl.abevos.kikker.manager.ContactListener;
import nl.abevos.kikker.screen.GameScreen;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.physics.box2d.Box2DDebugRenderer;
import com.badlogic.gdx.physics.box2d.World;
public class Level
{
private static World staticWorld;
private static Camera staticCamera;
private static Frog staticFrog;
private GameScreen screen;
private World world;
private Box2DDebugRenderer debugRenderer;
private Frog frog;
private Texture texture;
private Platform floor;
private Platform platform1;
private Platform ceiling;
private Wall leftWall;
private Wall rightWall;
public Level (GameScreen screen)
{
this.screen = screen;
}
public void load ()
{
world = new World(new Vector2(0, -9.8f), true);
world.setContactListener(new ContactListener());
Level.staticWorld = world;
Level.staticCamera = screen.getCamera();
frog = new Frog(0, 0, world);
Level.staticFrog = frog;
texture = AssetManager.getTexture("food");
floor = new Platform(0, - 256);
platform1 = new Platform(160, -170);
ceiling = new Platform(0, 256);
leftWall = new Wall(- 256, 0);
rightWall = new Wall(256, 0);
debugRenderer = new Box2DDebugRenderer();
}
public void cameraUpdate (OrthographicCamera camera)
{
camera.position.lerp(new Vector3(frog.getPosition().x, frog.getPosition().y, 0), camera.position.dst(frog.getPosition().x, frog.getPosition().y, 0) / 100f);
}
public void update (float delta)
{
world.step(1f / 30, 6, 4);
frog.update(delta);
}
public void draw ()
{
KikkerGame.batch().draw(texture, 0, 0);
floor.draw();
platform1.draw();
ceiling.draw();
leftWall.draw();
rightWall.draw();
frog.draw();
}
public void postDraw ()
{
debugRenderer.render(world, getCamera().combined);
}
public void dispose ()
{
world.dispose();
}
public static World getWorld ()
{
return Level.staticWorld;
}
public static Camera getCamera ()
{
return Level.staticCamera;
}
public static Frog getFrog ()
{
return Level.staticFrog;
}
}
| ManWithAJawharp/kikker | core/src/nl/abevos/kikker/level/Level.java | Java | gpl-2.0 | 2,508 |
package com.example.lpeng.tiptap;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.TextView;
import java.util.Timer;
public class StartActivity extends AppCompatActivity {
public void runMain() {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
//setContentView(R.layout.activity_main);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
/*Timer timer = new Timer();
timer.schedule();*/
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
//Log.i("tag", "This'll run 3000 milliseconds later");
TextView searchingText = (TextView) findViewById(R.id.searchingText);
searchingText.setVisibility(View.VISIBLE);
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
//Log.i("tag", "Again, This'll run 3000 milliseconds later");
runMain();
}
}, 3000);
}
}, 3000);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_start, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| werdnanoslen/eBusker | UI/app/src/main/java/com/example/lpeng/tiptap/StartActivity.java | Java | gpl-2.0 | 2,293 |
/* This file is part of the KDE libraries
Copyright (C) 2000 Stephan Kulow <coolo@kde.org>
Waldo Bastian <bastian@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "kio/sessiondata.h"
#include "kio/slaveconfig.h"
#include "kio/scheduler.h"
#include "kio/authinfo.h"
#include "kio/slave.h"
#include <qptrlist.h>
#include <qdict.h>
#include <dcopclient.h>
#include <kdebug.h>
#include <kglobal.h>
#include <kprotocolmanager.h>
#include <kprotocolinfo.h>
#include <assert.h>
#include <kstaticdeleter.h>
#include <kdesu/client.h>
// Slaves may be idle for MAX_SLAVE_IDLE time before they are being returned
// to the system wide slave pool. (3 minutes)
#define MAX_SLAVE_IDLE (3*60)
using namespace KIO;
template class QDict<KIO::Scheduler::ProtocolInfo>;
Scheduler *Scheduler::instance = 0;
class KIO::SlaveList: public QPtrList<Slave>
{
public:
SlaveList() { }
};
//
// There are two kinds of protocol:
// (1) The protocol of the url
// (2) The actual protocol that the io-slave uses.
//
// These two often match, but not necasserily. Most notably, they don't
// match when doing ftp via a proxy.
// In that case (1) is ftp, but (2) is http.
//
// JobData::protocol stores (2) while Job::url().protocol() returns (1).
// The ProtocolInfoDict is indexed with (2).
//
// We schedule slaves based on (2) but tell the slave about (1) via
// Slave::setProtocol().
class KIO::Scheduler::JobData
{
public:
JobData() : checkOnHold(false) { }
public:
QString protocol;
QString proxy;
bool checkOnHold;
};
class KIO::Scheduler::ExtraJobData: public QPtrDict<KIO::Scheduler::JobData>
{
public:
ExtraJobData() { setAutoDelete(true); }
};
class KIO::Scheduler::ProtocolInfo
{
public:
ProtocolInfo() : maxSlaves(1), skipCount(0)
{
joblist.setAutoDelete(false);
}
QPtrList<SimpleJob> joblist;
SlaveList activeSlaves;
int maxSlaves;
int skipCount;
QString protocol;
};
class KIO::Scheduler::ProtocolInfoDict : public QDict<KIO::Scheduler::ProtocolInfo>
{
public:
ProtocolInfoDict() { }
KIO::Scheduler::ProtocolInfo *get( const QString &protocol);
};
KIO::Scheduler::ProtocolInfo *
KIO::Scheduler::ProtocolInfoDict::get(const QString &protocol)
{
ProtocolInfo *info = find(protocol);
if (!info)
{
info = new ProtocolInfo;
info->protocol = protocol;
info->maxSlaves = KProtocolInfo::maxSlaves( protocol );
insert(protocol, info);
}
return info;
}
Scheduler::Scheduler()
: DCOPObject( "KIO::Scheduler" ),
QObject(kapp, "scheduler"),
slaveTimer(0, "Scheduler::slaveTimer"),
coSlaveTimer(0, "Scheduler::coSlaveTimer"),
cleanupTimer(0, "Scheduler::cleanupTimer")
{
checkOnHold = true; // !! Always check with KLauncher for the first request.
slaveOnHold = 0;
protInfoDict = new ProtocolInfoDict;
slaveList = new SlaveList;
idleSlaves = new SlaveList;
coIdleSlaves = new SlaveList;
extraJobData = new ExtraJobData;
sessionData = new SessionData;
slaveConfig = SlaveConfig::self();
connect(&slaveTimer, SIGNAL(timeout()), SLOT(startStep()));
connect(&coSlaveTimer, SIGNAL(timeout()), SLOT(slotScheduleCoSlave()));
connect(&cleanupTimer, SIGNAL(timeout()), SLOT(slotCleanIdleSlaves()));
busy = false;
}
Scheduler::~Scheduler()
{
protInfoDict->setAutoDelete(true);
delete protInfoDict; protInfoDict = 0;
delete idleSlaves; idleSlaves = 0;
delete coIdleSlaves; coIdleSlaves = 0;
slaveList->setAutoDelete(true);
delete slaveList; slaveList = 0;
delete extraJobData; extraJobData = 0;
delete sessionData; sessionData = 0;
instance = 0;
}
void
Scheduler::debug_info()
{
}
bool Scheduler::process(const QCString &fun, const QByteArray &data, QCString &replyType, QByteArray &replyData )
{
if ( fun != "reparseSlaveConfiguration(QString)" )
return DCOPObject::process( fun, data, replyType, replyData );
slaveConfig = SlaveConfig::self();
replyType = "void";
QDataStream stream( data, IO_ReadOnly );
QString proto;
stream >> proto;
kdDebug( 7006 ) << "reparseConfiguration( " << proto << " )" << endl;
KProtocolManager::reparseConfiguration();
slaveConfig->reset();
sessionData->reset();
NetRC::self()->reload();
Slave *slave = slaveList->first();
for (; slave; slave = slaveList->next() )
if ( slave->slaveProtocol() == proto || proto.isEmpty() )
{
slave->send( CMD_REPARSECONFIGURATION );
slave->resetHost();
}
return true;
}
QCStringList Scheduler::functions()
{
QCStringList funcs = DCOPObject::functions();
funcs << "void reparseSlaveConfiguration(QString)";
return funcs;
}
void Scheduler::_doJob(SimpleJob *job) {
JobData *jobData = new JobData;
jobData->protocol = KProtocolManager::slaveProtocol(job->url(), jobData->proxy);
// kdDebug(7006) << "Scheduler::_doJob protocol=" << jobData->protocol << endl;
if (job->command() == CMD_GET)
{
jobData->checkOnHold = checkOnHold;
checkOnHold = false;
}
extraJobData->replace(job, jobData);
newJobs.append(job);
slaveTimer.start(0, true);
#ifndef NDEBUG
if (newJobs.count() > 150)
kdDebug() << "WARNING - KIO::Scheduler got more than 150 jobs! This shows a misuse in your app (yes, a job is a QObject)." << endl;
#endif
}
void Scheduler::_scheduleJob(SimpleJob *job) {
newJobs.removeRef(job);
JobData *jobData = extraJobData->find(job);
if (!jobData)
{
kdFatal(7006) << "BUG! _ScheduleJob(): No extraJobData for job!" << endl;
return;
}
QString protocol = jobData->protocol;
// kdDebug(7006) << "Scheduler::_scheduleJob protocol=" << protocol << endl;
ProtocolInfo *protInfo = protInfoDict->get(protocol);
protInfo->joblist.append(job);
slaveTimer.start(0, true);
}
void Scheduler::_cancelJob(SimpleJob *job) {
// kdDebug(7006) << "Scheduler: canceling job " << job << endl;
Slave *slave = job->slave();
if ( !slave )
{
// was not yet running (don't call this on a finished job!)
JobData *jobData = extraJobData->find(job);
if (!jobData)
return; // I said: "Don't call this on a finished job!"
newJobs.removeRef(job);
ProtocolInfo *protInfo = protInfoDict->get(jobData->protocol);
protInfo->joblist.removeRef(job);
// Search all slaves to see if job is in the queue of a coSlave
slave = slaveList->first();
for(; slave; slave = slaveList->next())
{
JobList *list = coSlaves.find(slave);
if (list && list->removeRef(job))
break; // Job was found and removed.
// Fall through to kill the slave as well!
}
if (!slave)
{
extraJobData->remove(job);
return; // Job was not yet running and not in a coSlave queue.
}
}
kdDebug(7006) << "Scheduler: killing slave " << slave->slave_pid() << endl;
slave->kill();
_jobFinished( job, slave );
slotSlaveDied( slave);
}
void Scheduler::startStep()
{
while(newJobs.count())
{
(void) startJobDirect();
}
QDictIterator<KIO::Scheduler::ProtocolInfo> it(*protInfoDict);
while(it.current())
{
if (startJobScheduled(it.current())) return;
++it;
}
}
void Scheduler::setupSlave(KIO::Slave *slave, const KURL &url, const QString &protocol, const QString &proxy , bool newSlave, const KIO::MetaData *config)
{
QString host = url.host();
int port = url.port();
QString user = url.user();
QString passwd = url.pass();
if ((newSlave) ||
(slave->host() != host) ||
(slave->port() != port) ||
(slave->user() != user) ||
(slave->passwd() != passwd))
{
slaveConfig = SlaveConfig::self();
MetaData configData = slaveConfig->configData(protocol, host);
sessionData->configDataFor( configData, protocol, host );
configData["UseProxy"] = proxy;
QString autoLogin = configData["EnableAutoLogin"].lower();
if ( autoLogin == "true" )
{
NetRC::AutoLogin l;
l.login = user;
bool usern = (protocol == "ftp");
if ( NetRC::self()->lookup( url, l, usern) )
{
configData["autoLoginUser"] = l.login;
configData["autoLoginPass"] = l.password;
if ( usern )
{
QString macdef;
QMap<QString, QStringList>::ConstIterator it = l.macdef.begin();
for ( ; it != l.macdef.end(); ++it )
macdef += it.key() + '\\' + it.data().join( "\\" ) + '\n';
configData["autoLoginMacro"] = macdef;
}
}
}
if (config)
configData += *config;
slave->setConfig(configData);
slave->setProtocol(url.protocol());
slave->setHost(host, port, user, passwd);
}
}
bool Scheduler::startJobScheduled(ProtocolInfo *protInfo)
{
if (protInfo->joblist.isEmpty())
return false;
// kdDebug(7006) << "Scheduling job" << endl;
debug_info();
bool newSlave = false;
SimpleJob *job = 0;
Slave *slave = 0;
if (protInfo->skipCount > 2)
{
bool dummy;
// Prevent starvation. We skip the first entry in the queue at most
// 2 times in a row. The
protInfo->skipCount = 0;
job = protInfo->joblist.at(0);
slave = findIdleSlave(protInfo, job, dummy );
}
else
{
bool exact=false;
SimpleJob *firstJob = 0;
Slave *firstSlave = 0;
for(uint i = 0; (i < protInfo->joblist.count()) && (i < 10); i++)
{
job = protInfo->joblist.at(i);
slave = findIdleSlave(protInfo, job, exact);
if (!firstSlave)
{
firstJob = job;
firstSlave = slave;
}
if (!slave) break;
if (exact) break;
}
if (!exact)
{
slave = firstSlave;
job = firstJob;
}
if (job == firstJob)
protInfo->skipCount = 0;
else
protInfo->skipCount++;
}
if (!slave)
{
if ( protInfo->maxSlaves > static_cast<int>(protInfo->activeSlaves.count()) )
{
newSlave = true;
slave = createSlave(protInfo, job, job->url());
if (!slave)
slaveTimer.start(0, true);
}
}
if (!slave)
{
// kdDebug(7006) << "No slaves available" << endl;
// kdDebug(7006) << " -- active: " << protInfo->activeSlaves.count() << endl;
return false;
}
protInfo->activeSlaves.append(slave);
idleSlaves->removeRef(slave);
protInfo->joblist.removeRef(job);
// kdDebug(7006) << "scheduler: job started " << job << endl;
JobData *jobData = extraJobData->find(job);
setupSlave(slave, job->url(), jobData->protocol, jobData->proxy, newSlave);
job->start(slave);
slaveTimer.start(0, true);
return true;
}
bool Scheduler::startJobDirect()
{
debug_info();
SimpleJob *job = newJobs.take(0);
JobData *jobData = extraJobData->find(job);
if (!jobData)
{
kdFatal(7006) << "BUG! startjobDirect(): No extraJobData for job!"
<< endl;
return false;
}
QString protocol = jobData->protocol;
ProtocolInfo *protInfo = protInfoDict->get(protocol);
bool newSlave = false;
bool dummy;
// Look for matching slave
Slave *slave = findIdleSlave(protInfo, job, dummy);
if (!slave)
{
newSlave = true;
slave = createSlave(protInfo, job, job->url());
}
if (!slave)
return false;
idleSlaves->removeRef(slave);
// kdDebug(7006) << "scheduler: job started " << job << endl;
setupSlave(slave, job->url(), protocol, jobData->proxy, newSlave);
job->start(slave);
return true;
}
static Slave *searchIdleList(SlaveList *idleSlaves, const KURL &url, const QString &protocol, bool &exact)
{
QString host = url.host();
int port = url.port();
QString user = url.user();
exact = true;
for( Slave *slave = idleSlaves->first();
slave;
slave = idleSlaves->next())
{
if ((protocol == slave->slaveProtocol()) &&
(host == slave->host()) &&
(port == slave->port()) &&
(user == slave->user()))
return slave;
}
exact = false;
// Look for slightly matching slave
for( Slave *slave = idleSlaves->first();
slave;
slave = idleSlaves->next())
{
if (protocol == slave->slaveProtocol())
return slave;
}
return 0;
}
Slave *Scheduler::findIdleSlave(ProtocolInfo *, SimpleJob *job, bool &exact)
{
Slave *slave = 0;
JobData *jobData = extraJobData->find(job);
if (!jobData)
{
kdFatal(7006) << "BUG! findIdleSlave(): No extraJobData for job!" << endl;
return 0;
}
if (jobData->checkOnHold)
{
slave = Slave::holdSlave(jobData->protocol, job->url());
if (slave)
return slave;
}
if (slaveOnHold)
{
// Make sure that the job wants to do a GET or a POST, and with no offset
bool bCanReuse = (job->command() == CMD_GET);
KIO::TransferJob * tJob = dynamic_cast<KIO::TransferJob *>(job);
if ( tJob )
{
bCanReuse = (job->command() == CMD_GET || job->command() == CMD_SPECIAL);
if ( bCanReuse )
{
KIO::MetaData outgoing = tJob->outgoingMetaData();
QString resume = (!outgoing.contains("resume")) ? QString::null : outgoing["resume"];
kdDebug(7006) << "Resume metadata is '" << resume << "'" << endl;
bCanReuse = (resume.isEmpty() || resume == "0");
}
}
// kdDebug(7006) << "bCanReuse = " << bCanReuse << endl;
if (bCanReuse)
{
if (job->url() == urlOnHold)
{
kdDebug(7006) << "HOLD: Reusing held slave for " << urlOnHold.prettyURL() << endl;
slave = slaveOnHold;
}
else
{
kdDebug(7006) << "HOLD: Discarding held slave (" << urlOnHold.prettyURL() << ")" << endl;
slaveOnHold->kill();
}
slaveOnHold = 0;
urlOnHold = KURL();
}
if (slave)
return slave;
}
return searchIdleList(idleSlaves, job->url(), jobData->protocol, exact);
}
Slave *Scheduler::createSlave(ProtocolInfo *protInfo, SimpleJob *job, const KURL &url)
{
int error;
QString errortext;
Slave *slave = Slave::createSlave(protInfo->protocol, url, error, errortext);
if (slave)
{
slaveList->append(slave);
idleSlaves->append(slave);
connect(slave, SIGNAL(slaveDied(KIO::Slave *)),
SLOT(slotSlaveDied(KIO::Slave *)));
connect(slave, SIGNAL(slaveStatus(pid_t,const QCString &,const QString &, bool)),
SLOT(slotSlaveStatus(pid_t,const QCString &, const QString &, bool)));
connect(slave,SIGNAL(authorizationKey(const QCString&, const QCString&, bool)),
sessionData,SLOT(slotAuthData(const QCString&, const QCString&, bool)));
connect(slave,SIGNAL(delAuthorization(const QCString&)), sessionData,
SLOT(slotDelAuthData(const QCString&)));
}
else
{
kdError() <<": couldn't create slave : " << errortext << endl;
if (job)
{
protInfo->joblist.removeRef(job);
extraJobData->remove(job);
job->slotError( error, errortext );
}
}
return slave;
}
void Scheduler::slotSlaveStatus(pid_t, const QCString &, const QString &, bool)
{
}
void Scheduler::_jobFinished(SimpleJob *job, Slave *slave)
{
JobData *jobData = extraJobData->take(job);
if (!jobData)
{
kdFatal(7006) << "BUG! _jobFinished(): No extraJobData for job!" << endl;
return;
}
ProtocolInfo *protInfo = protInfoDict->get(jobData->protocol);
delete jobData;
slave->disconnect(job);
protInfo->activeSlaves.removeRef(slave);
if (slave->isAlive())
{
JobList *list = coSlaves.find(slave);
if (list)
{
assert(slave->isConnected());
assert(!coIdleSlaves->contains(slave));
coIdleSlaves->append(slave);
if (!list->isEmpty())
coSlaveTimer.start(0, true);
return;
}
else
{
assert(!slave->isConnected());
idleSlaves->append(slave);
slave->setIdle();
_scheduleCleanup();
// slave->send( CMD_SLAVE_STATUS );
}
}
if (protInfo->joblist.count())
{
slaveTimer.start(0, true);
}
}
void Scheduler::slotSlaveDied(KIO::Slave *slave)
{
assert(!slave->isAlive());
ProtocolInfo *protInfo = protInfoDict->get(slave->slaveProtocol());
protInfo->activeSlaves.removeRef(slave);
if (slave == slaveOnHold)
{
slaveOnHold = 0;
urlOnHold = KURL();
}
idleSlaves->removeRef(slave);
JobList *list = coSlaves.find(slave);
if (list)
{
// coSlave dies, kill jobs waiting in queue
disconnectSlave(slave);
}
if (!slaveList->removeRef(slave))
kdDebug(7006) << "Scheduler: BUG!! Slave " << slave << "/" << slave->slave_pid() << " died, but is NOT in slaveList!!!\n" << endl;
else
slave->deref(); // Delete slave
}
void Scheduler::slotCleanIdleSlaves()
{
for(Slave *slave = idleSlaves->first();slave;)
{
if (slave->idleTime() >= MAX_SLAVE_IDLE)
{
// kdDebug(7006) << "Removing idle slave: " << slave->slaveProtocol() << " " << slave->host() << endl;
Slave *removeSlave = slave;
slave = idleSlaves->next();
idleSlaves->removeRef(removeSlave);
slaveList->removeRef(removeSlave);
removeSlave->connection()->close();
removeSlave->deref();
}
else
{
slave = idleSlaves->next();
}
}
_scheduleCleanup();
}
void Scheduler::_scheduleCleanup()
{
if (idleSlaves->count())
{
if (!cleanupTimer.isActive())
cleanupTimer.start( MAX_SLAVE_IDLE*1000, true );
}
}
void Scheduler::_putSlaveOnHold(KIO::SimpleJob *job, const KURL &url)
{
Slave *slave = job->slave();
slave->disconnect(job);
if (slaveOnHold)
{
slaveOnHold->kill();
}
slaveOnHold = slave;
urlOnHold = url;
slaveOnHold->suspend();
}
void Scheduler::_publishSlaveOnHold()
{
if (!slaveOnHold)
return;
slaveOnHold->hold(urlOnHold);
}
void Scheduler::_removeSlaveOnHold()
{
if (slaveOnHold)
{
slaveOnHold->kill();
}
slaveOnHold = 0;
urlOnHold = KURL();
}
Slave *
Scheduler::_getConnectedSlave(const KURL &url, const KIO::MetaData &config )
{
QString proxy;
QString protocol = KProtocolManager::slaveProtocol(url, proxy);
bool dummy;
Slave *slave = searchIdleList(idleSlaves, url, protocol, dummy);
if (!slave)
{
ProtocolInfo *protInfo = protInfoDict->get(protocol);
slave = createSlave(protInfo, 0, url);
}
if (!slave)
return 0; // Error
idleSlaves->removeRef(slave);
setupSlave(slave, url, protocol, proxy, true, &config);
slave->send( CMD_CONNECT );
connect(slave, SIGNAL(connected()),
SLOT(slotSlaveConnected()));
connect(slave, SIGNAL(error(int, const QString &)),
SLOT(slotSlaveError(int, const QString &)));
coSlaves.insert(slave, new QPtrList<SimpleJob>());
// kdDebug(7006) << "_getConnectedSlave( " << slave << ")" << endl;
return slave;
}
void
Scheduler::slotScheduleCoSlave()
{
Slave *nextSlave;
slaveConfig = SlaveConfig::self();
for(Slave *slave = coIdleSlaves->first();
slave;
slave = nextSlave)
{
nextSlave = coIdleSlaves->next();
JobList *list = coSlaves.find(slave);
assert(list);
if (list && !list->isEmpty())
{
SimpleJob *job = list->take(0);
coIdleSlaves->removeRef(slave);
// kdDebug(7006) << "scheduler: job started " << job << endl;
assert(!coIdleSlaves->contains(slave));
KURL url =job->url();
QString host = url.host();
int port = url.port();
if (slave->host() == "<reset>")
{
QString user = url.user();
QString passwd = url.pass();
MetaData configData = slaveConfig->configData(url.protocol(), url.host());
slave->setConfig(configData);
slave->setProtocol(url.protocol());
slave->setHost(host, port, user, passwd);
}
assert(slave->protocol() == url.protocol());
assert(slave->host() == host);
assert(slave->port() == port);
job->start(slave);
}
}
}
void
Scheduler::slotSlaveConnected()
{
Slave *slave = (Slave *)sender();
// kdDebug(7006) << "slotSlaveConnected( " << slave << ")" << endl;
slave->setConnected(true);
disconnect(slave, SIGNAL(connected()),
this, SLOT(slotSlaveConnected()));
emit slaveConnected(slave);
assert(!coIdleSlaves->contains(slave));
coIdleSlaves->append(slave);
coSlaveTimer.start(0, true);
}
void
Scheduler::slotSlaveError(int errorNr, const QString &errorMsg)
{
Slave *slave = (Slave *)sender();
if (!slave->isConnected() || (coIdleSlaves->find(slave) != -1))
{
// Only forward to application if slave is idle or still connecting.
emit slaveError(slave, errorNr, errorMsg);
}
}
bool
Scheduler::_assignJobToSlave(KIO::Slave *slave, SimpleJob *job)
{
// kdDebug(7006) << "_assignJobToSlave( " << job << ", " << slave << ")" << endl;
QString dummy;
if ((slave->slaveProtocol() != KProtocolManager::slaveProtocol( job->url(), dummy ))
||
(!newJobs.removeRef(job)))
{
kdDebug(7006) << "_assignJobToSlave(): ERROR, nonmatching or unknown job." << endl;
job->kill();
return false;
}
JobList *list = coSlaves.find(slave);
assert(list);
if (!list)
{
kdDebug(7006) << "_assignJobToSlave(): ERROR, unknown slave." << endl;
job->kill();
return false;
}
assert(list->contains(job) == 0);
list->append(job);
coSlaveTimer.start(0, true); // Start job on timer event
return true;
}
bool
Scheduler::_disconnectSlave(KIO::Slave *slave)
{
// kdDebug(7006) << "_disconnectSlave( " << slave << ")" << endl;
JobList *list = coSlaves.take(slave);
assert(list);
if (!list)
return false;
// Kill jobs still in queue.
while(!list->isEmpty())
{
Job *job = list->take(0);
job->kill();
}
delete list;
coIdleSlaves->removeRef(slave);
assert(!coIdleSlaves->contains(slave));
disconnect(slave, SIGNAL(connected()),
this, SLOT(slotSlaveConnected()));
disconnect(slave, SIGNAL(error(int, const QString &)),
this, SLOT(slotSlaveError(int, const QString &)));
if (slave->isAlive())
{
idleSlaves->append(slave);
slave->send( CMD_DISCONNECT );
slave->setIdle();
slave->setConnected(false);
_scheduleCleanup();
}
return true;
}
void
Scheduler::_checkSlaveOnHold(bool b)
{
checkOnHold = b;
}
void
Scheduler::_registerWindow(QWidget *wid)
{
if (!wid)
return;
QObject *obj = static_cast<QObject *>(wid);
if (!m_windowList.contains(obj))
{
// We must store the window Id because by the time
// the destroyed signal is emitted we can no longer
// access QWidget::winId() (already destructed)
WId windowId = wid->winId();
m_windowList.insert(obj, windowId);
connect(wid, SIGNAL(destroyed(QObject *)),
this, SLOT(slotUnregisterWindow(QObject*)));
QByteArray params;
QDataStream stream(params, IO_WriteOnly);
stream << windowId;
if( !kapp->dcopClient()->send( "kded", "kded",
"registerWindowId(long int)", params ) )
kdDebug(7006) << "Could not register window with kded!" << endl;
}
}
void
Scheduler::slotUnregisterWindow(QObject *obj)
{
if (!obj)
return;
QMap<QObject *, WId>::Iterator it = m_windowList.find(obj);
if (it == m_windowList.end())
return;
WId windowId = it.data();
disconnect( it.key(), SIGNAL(destroyed(QObject *)),
this, SLOT(slotUnregisterWindow(QObject*)));
m_windowList.remove( it );
if (kapp)
{
QByteArray params;
QDataStream stream(params, IO_WriteOnly);
stream << windowId;
kapp->dcopClient()->send( "kded", "kded",
"unregisterWindowId(long int)", params );
}
}
Scheduler* Scheduler::self() {
if ( !instance ) {
instance = new Scheduler;
}
return instance;
}
void Scheduler::virtual_hook( int id, void* data )
{ DCOPObject::virtual_hook( id, data ); }
#include "scheduler.moc"
| iegor/kdelibs | kio/kio/scheduler.cpp | C++ | gpl-2.0 | 25,930 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using FourOfAKind.MapClasses;
using System.Drawing;
namespace FourOfAKind.Navigation
{
public class Map
{
public bool isReady = true;
public List<Intersection> Intersections;
public List<Track> Tracks;
public double Zoom;
public PointDouble Offset = new PointDouble(-200, -200);
public PointDouble TempOffset = new PointDouble(-200, -200);
public Point CursorPos = Point.Empty;
public PointDouble RealCursorPos = new PointDouble(0,0);
public int TrackStartID = -1;
public List<PointDouble> TrackPoints = new List<PointDouble>();
public Map()
{
this.Zoom = 1.0;
this.Intersections = new List<Intersection>();
this.Tracks = new List<Track>();
}
/// <summary>
/// Znajduje węzeł po ID. Zwraca null jeżeli węzeł nie istnieje
/// </summary>
/// <param name="ID"></param>
/// <returns></returns>
public Intersection getIntersectionByID(int ID)
{
foreach (Intersection one in this.Intersections)
{
if (one.ID == ID) return one;
}
return null;
}
/// <summary>
/// Ustawia wartość pozycji kursora i przelicza ją na współrzędne w jednostkach mapy
/// </summary>
/// <param name="input"></param>
public void SetCursorPos(Point input)
{
CursorPos = input;
RealCursorPos = new PointDouble(CursorPos.X / Zoom - Offset.X, CursorPos.Y / Zoom - Offset.Y);
}
public void RecalcBounds(Size canvasSize)
{
double sumX = 0;
int numX = 0;
double sumY = 0;
int numY = 0;
double top = 0;
double bottom = 0;
double left = 0;
double right = 0;
foreach (Intersection one in this.Intersections)
{
sumX += one.Location.X;
sumY += one.Location.Y;
numX++;
numY++;
if (one.Location.X < left) left = one.Location.X;
if (one.Location.X > right) right = one.Location.X;
if (one.Location.Y < top) top = one.Location.Y;
if (one.Location.Y > bottom) bottom = one.Location.Y;
}
this.Offset = new PointDouble(-sumX / numX, -sumY / numY);
double width = right - left + 10;
double height = bottom - top + 10;
if(width>=height)
{
this.Zoom = Math.Floor((double)canvasSize.Width / width);
}
else
{
this.Zoom = Math.Floor((double)canvasSize.Height / height);
}
}
/// <summary>
/// Pobiera następne ID dla węzła. Jeżeli to pierwszy węzeł nadaje mu ID = 1
/// </summary>
/// <returns></returns>
public int NextIntersectionID()
{
if (this.Intersections.Count > 0)
return this.Intersections.Last().ID + 1;
else
return 1;
}
/// <summary>
/// Pobiera następne ID dla toru. Jeżeli to pierwszy tor nadaje mu ID = 1
/// </summary>
/// <returns></returns>
public int NextTrackID()
{
if (this.Tracks.Count > 0)
return this.Tracks.Last().ID + 1;
else
return 1;
}
/// <summary>
/// Zapis do pliku. Dokumentacja formatu dostępna w folderze Karo/DokumentacjaMapy
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool SaveToFile(string filename)
{
try
{
this.isReady = false;
List<string> intersTxt = new List<string>();
List<string> trakcsTxt = new List<string>();
// Tworzenie pliku węzłów
// Każdy węzeł zaczyna się od I a następnie podane są jego dane
foreach (Intersection one in this.Intersections)
{
List<string> temp = new List<string>();
temp.Add("I");
temp.Add(XmlConvert.ToString(one.ID));
temp.Add(one.Name);
temp.Add(XmlConvert.ToString(one.Location.X));
temp.Add(XmlConvert.ToString(one.Location.Y));
intersTxt.Add(String.Join(",", temp.ToArray()));
}
// Tworzenie pliku torów
// Linia zaczynajaca się od T oznacza początek danych toru
// Linia zaczynajaca się od W oznacza punkt pośredni toru
// Tor kończy się wraz z rozpoczęciem innego toru od linii T, pustą linią lub końcem pliku
foreach (Track one in this.Tracks)
{
List<string> temp = new List<string>();
temp.Add("T");
temp.Add(XmlConvert.ToString(one.ID));
temp.Add(one.Name);
temp.Add(XmlConvert.ToString(one.Start));
temp.Add(XmlConvert.ToString(one.End));
temp.Add(XmlConvert.ToString(one.Waypoints.Length));
trakcsTxt.Add(String.Join(",", temp.ToArray()));
foreach (PointDouble waypoint in one.Waypoints)
{
List<string> tempWay = new List<string>();
tempWay.Add("W");
tempWay.Add(XmlConvert.ToString(waypoint.X));
tempWay.Add(XmlConvert.ToString(waypoint.Y));
trakcsTxt.Add(String.Join(",", tempWay.ToArray()));
}
}
// Oddzielenie węzłów od torów pusta linią
intersTxt.Add("");
// Dodanie torów do treści węzłów
intersTxt.AddRange(trakcsTxt);
// Zapis węzłów i torów do wspólnego pliku
File.WriteAllLines(filename, intersTxt);
this.isReady = true;
return true;
}
catch (Exception e)
{
Log.AddToConsole("Błąd zapisywania mapy (line " + e.LineNumber().ToString() + "): " + e.Message, "error");
this.isReady = true;
return false;
}
}
/// <summary>
/// Odczyt z pliku. Dokumentacja formatu dostępna w folderze Karo/DokumentacjaMapy
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public bool LoadFromFile(string filename)
{
try
{
this.isReady = false;
string[] readText = File.ReadAllLines(filename);
this.Intersections = new List<Intersection>();
this.Tracks = new List<Track>();
for (int i = 0; i < readText.Length; i++)
{
string lineT = readText[i].Trim();
if(lineT.Length>0)
{
string[] split = lineT.Split((",").ToArray());
switch (split[0])
{
case "I":
if (split.Length == 5)
{
this.Intersections.Add(new Intersection(XmlConvert.ToInt32(split[1]), split[2], new PointDouble(XmlConvert.ToDouble(split[3]), XmlConvert.ToDouble(split[4]))));
}
break;
case "T":
if (split.Length == 5)
{
this.Tracks.Add(new Track(XmlConvert.ToInt32(split[1]), split[2], XmlConvert.ToInt32(split[3]), XmlConvert.ToInt32(split[4])));
}
else if (split.Length == 6)
{
this.Tracks.Add(new Track(XmlConvert.ToInt32(split[1]), split[2], XmlConvert.ToInt32(split[3]), XmlConvert.ToInt32(split[4]), XmlConvert.ToInt32(split[5])));
for(int j = 0; j < XmlConvert.ToInt32(split[5]); j++)
{
i++;
if (i >= readText.Length) break;
string[] splitW = readText[i].Trim().Split((",").ToArray());
if (splitW.Length > 0)
{
if (splitW[0] == "W")
{
this.Tracks.Last().Waypoints[j] = new PointDouble(XmlConvert.ToDouble(splitW[1]), XmlConvert.ToDouble(splitW[2]));
}
else
{
break;
}
}
else
{
break;
}
}
}
break;
}
}
}
this.isReady = true;
return true;
}
catch (Exception e)
{
Log.AddToConsole("Błąd wczytywania mapy (line " + e.LineNumber().ToString() + "): " + e.Message, "error");
this.isReady = true;
return false;
}
}
}
}
| PKM-dreamteam/turbulent-turtle | Karo/FourOfAKind/FourOfAKind/MapClasses/Map.cs | C# | gpl-2.0 | 10,399 |
<?php foreach ($heroes as $key => $value) : ?>
<?php
$remove[] = "'";
$linkPrimaryName = str_replace($remove,"", $value['PrimaryName']);
// $linkPrimaryName = preg_replace("/'/", "", $value['PrimaryName']);
$replace1[] = ".";
$replace2[] = " ";
$replace3[] = "-";
$linkPrimaryName = str_replace($replace1,"", $linkPrimaryName);
$linkPrimaryName = str_replace($replace2,"-", $linkPrimaryName);
if ($value['PrimaryName'] == 'Li Li') {
$linkPrimaryName = str_replace($replace3,"", $linkPrimaryName);
}
switch ($value['PrimaryName']):
case 'Cho': { $linkPrimaryName = "chogall";
break; }
case 'Gall': { $linkPrimaryName = "chogall";
break;}
endswitch;
// dsm($linkPrimaryName);
$lowerHero = strtolower($linkPrimaryName);
?>
<?php print "<a href='http://us.battle.net/heroes/en/heroes/{$lowerHero}/'>" . $value['PrimaryName'] ."<br>" .
$value['Group'] . "</a><br/>"; ?>
<?php endforeach; ?>
| Jeborivo/hots | sites/all/modules/hots/templates/hots-block--block.tpl.php | PHP | gpl-2.0 | 958 |
/*
* Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/>
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "InstanceScript.h"
#include "nexus.h"
#include "Player.h"
#define NUMBER_OF_ENCOUNTERS 4
enum Factions
{
FACTION_HOSTILE_FOR_ALL = 16
};
class instance_nexus : public InstanceMapScript
{
public:
instance_nexus() : InstanceMapScript("instance_nexus", 576) { }
InstanceScript* GetInstanceScript(InstanceMap* map) const override
{
return new instance_nexus_InstanceMapScript(map);
}
struct instance_nexus_InstanceMapScript : public InstanceScript
{
instance_nexus_InstanceMapScript(Map* map) : InstanceScript(map)
{
SetHeaders(DataHeader);
memset(&m_auiEncounter, 0, sizeof(m_auiEncounter));
}
uint32 m_auiEncounter[NUMBER_OF_ENCOUNTERS];
ObjectGuid Anomalus;
ObjectGuid Keristrasza;
ObjectGuid AnomalusContainmentSphere;
ObjectGuid OrmoroksContainmentSphere;
ObjectGuid TelestrasContainmentSphere;
std::string strInstData;
void OnCreatureCreate(Creature* creature) override
{
Map::PlayerList const &players = instance->GetPlayers();
uint32 TeamInInstance = 0;
if (!players.isEmpty())
{
if (Player* player = players.begin()->GetSource())
TeamInInstance = player->GetTeam();
}
switch (creature->GetEntry())
{
case 26763:
Anomalus = creature->GetGUID();
break;
case 26723:
Keristrasza = creature->GetGUID();
break;
// Alliance npcs are spawned by default, if you are alliance, you will fight against horde npcs.
case 26800:
{
if (ServerAllowsTwoSideGroups())
creature->setFaction(FACTION_HOSTILE_FOR_ALL);
if (TeamInInstance == ALLIANCE)
creature->UpdateEntry(26799);
break;
}
case 26802:
{
if (ServerAllowsTwoSideGroups())
creature->setFaction(FACTION_HOSTILE_FOR_ALL);
if (TeamInInstance == ALLIANCE)
creature->UpdateEntry(26801);
break;
}
case 26805:
{
if (ServerAllowsTwoSideGroups())
creature->setFaction(FACTION_HOSTILE_FOR_ALL);
if (TeamInInstance == ALLIANCE)
creature->UpdateEntry(26803);
break;
}
case 27949:
{
if (ServerAllowsTwoSideGroups())
creature->setFaction(FACTION_HOSTILE_FOR_ALL);
if (TeamInInstance == ALLIANCE)
creature->UpdateEntry(27947);
break;
}
case 26796:
{
if (ServerAllowsTwoSideGroups())
creature->setFaction(FACTION_HOSTILE_FOR_ALL);
if (TeamInInstance == ALLIANCE)
creature->UpdateEntry(26798);
break;
}
}
}
void OnGameObjectCreate(GameObject* go) override
{
switch (go->GetEntry())
{
case 188527:
{
AnomalusContainmentSphere = go->GetGUID();
if (m_auiEncounter[1] == DONE)
go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
break;
}
case 188528:
{
OrmoroksContainmentSphere = go->GetGUID();
if (m_auiEncounter[2] == DONE)
go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
break;
}
case 188526:
{
TelestrasContainmentSphere = go->GetGUID();
if (m_auiEncounter[0] == DONE)
go->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
break;
}
}
}
uint32 GetData(uint32 identifier) const override
{
switch (identifier)
{
case DATA_MAGUS_TELESTRA_EVENT: return m_auiEncounter[0];
case DATA_ANOMALUS_EVENT: return m_auiEncounter[1];
case DATA_ORMOROK_EVENT: return m_auiEncounter[2];
case DATA_KERISTRASZA_EVENT: return m_auiEncounter[3];
}
return 0;
}
void SetData(uint32 identifier, uint32 data) override
{
switch (identifier)
{
case DATA_MAGUS_TELESTRA_EVENT:
{
if (data == DONE)
{
GameObject* Sphere = instance->GetGameObject(TelestrasContainmentSphere);
if (Sphere)
Sphere->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
}
m_auiEncounter[0] = data;
break;
}
case DATA_ANOMALUS_EVENT:
{
if (data == DONE)
{
if (GameObject* Sphere = instance->GetGameObject(AnomalusContainmentSphere))
Sphere->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
}
m_auiEncounter[1] = data;
break;
}
case DATA_ORMOROK_EVENT:
{
if (data == DONE)
{
if (GameObject* Sphere = instance->GetGameObject(OrmoroksContainmentSphere))
Sphere->RemoveFlag(GAMEOBJECT_FLAGS, GO_FLAG_NOT_SELECTABLE);
}
m_auiEncounter[2] = data;
break;
}
case DATA_KERISTRASZA_EVENT:
m_auiEncounter[3] = data;
break;
}
if (data == DONE)
{
OUT_SAVE_INST_DATA;
std::ostringstream saveStream;
saveStream << m_auiEncounter[0] << ' ' << m_auiEncounter[1] << ' ' << m_auiEncounter[2] << ' '
<< m_auiEncounter[3];
strInstData = saveStream.str();
SaveToDB();
OUT_SAVE_INST_DATA_COMPLETE;
}
}
ObjectGuid GetGuidData(uint32 uiIdentifier) const override
{
switch (uiIdentifier)
{
case DATA_ANOMALUS: return Anomalus;
case DATA_KERISTRASZA: return Keristrasza;
case ANOMALUS_CONTAINMET_SPHERE: return AnomalusContainmentSphere;
case ORMOROKS_CONTAINMET_SPHERE: return OrmoroksContainmentSphere;
case TELESTRAS_CONTAINMET_SPHERE: return TelestrasContainmentSphere;
}
return ObjectGuid::Empty;
}
std::string GetSaveData() override
{
return strInstData;
}
void Load(const char *chrIn)
{
if (!chrIn)
{
OUT_LOAD_INST_DATA_FAIL;
return;
}
OUT_LOAD_INST_DATA(chrIn);
std::istringstream loadStream(chrIn);
loadStream >> m_auiEncounter[0] >> m_auiEncounter[1] >> m_auiEncounter[2] >> m_auiEncounter[3];
for (uint8 i = 0; i < NUMBER_OF_ENCOUNTERS; ++i)
if (m_auiEncounter[i] == IN_PROGRESS)
m_auiEncounter[i] = NOT_STARTED;
OUT_LOAD_INST_DATA_COMPLETE;
}
};
};
void AddSC_instance_nexus()
{
new instance_nexus();
}
| madisodr/legacy-core | src/server/scripts/Northrend/Nexus/Nexus/instance_nexus.cpp | C++ | gpl-2.0 | 9,267 |
namespace ObAuto
{
partial class MainForm
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows 窗体设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.kryTheme = new ComponentFactory.Krypton.Toolkit.KryptonPalette(this.components);
this.kryMngMain = new ComponentFactory.Krypton.Toolkit.KryptonManager(this.components);
this.krySplitCntMain = new ComponentFactory.Krypton.Toolkit.KryptonSplitContainer();
this.krySplitCntTop = new ComponentFactory.Krypton.Toolkit.KryptonSplitContainer();
this.kryBtnOpenMng = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.kryHdTitle = new ComponentFactory.Krypton.Toolkit.KryptonHeader();
this.kryGbxSet = new ComponentFactory.Krypton.Toolkit.KryptonGroupBox();
this.krySeparator = new ComponentFactory.Krypton.Toolkit.KryptonSeparator();
this.kryBtnSave = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.kryBtnDo = new ComponentFactory.Krypton.Toolkit.KryptonButton();
this.krySplitCntDbTb = new ComponentFactory.Krypton.Toolkit.KryptonSplitContainer();
this.kryLbxDbTb = new ComponentFactory.Krypton.Toolkit.KryptonListBox();
this.kryPnlDbTip = new ComponentFactory.Krypton.Toolkit.KryptonPanel();
this.kryLblDbTip = new ComponentFactory.Krypton.Toolkit.KryptonLabel();
this.kryCbxDb = new ComponentFactory.Krypton.Toolkit.KryptonComboBox();
this.tabCtrlMain = new System.Windows.Forms.TabControl();
this.tabPgModel = new System.Windows.Forms.TabPage();
this.kryRTbxModel = new ComponentFactory.Krypton.Toolkit.KryptonRichTextBox();
this.tabPgQuery = new System.Windows.Forms.TabPage();
this.kryRTbxQuery = new ComponentFactory.Krypton.Toolkit.KryptonRichTextBox();
this.tabPgPermit = new System.Windows.Forms.TabPage();
this.kryRTbxPermit = new ComponentFactory.Krypton.Toolkit.KryptonRichTextBox();
this.tabPgDAL = new System.Windows.Forms.TabPage();
this.kryRTbxDAL = new ComponentFactory.Krypton.Toolkit.KryptonRichTextBox();
this.tabPgBLL = new System.Windows.Forms.TabPage();
this.kryRTbxBLL = new ComponentFactory.Krypton.Toolkit.KryptonRichTextBox();
this.tabPgAspx = new System.Windows.Forms.TabPage();
this.kryRTbxHtml = new ComponentFactory.Krypton.Toolkit.KryptonRichTextBox();
this.tabPgJs = new System.Windows.Forms.TabPage();
this.kryRTbxJs = new ComponentFactory.Krypton.Toolkit.KryptonRichTextBox();
this.tabPgSDK = new System.Windows.Forms.TabPage();
this.kryRTbxSDK = new ComponentFactory.Krypton.Toolkit.KryptonRichTextBox();
this.tabPgCtrl = new System.Windows.Forms.TabPage();
this.kryRTbxCtrl = new ComponentFactory.Krypton.Toolkit.KryptonRichTextBox();
this.tabPgView = new System.Windows.Forms.TabPage();
this.kryRTbxView = new ComponentFactory.Krypton.Toolkit.KryptonRichTextBox();
this.tabPgSql = new System.Windows.Forms.TabPage();
this.kryRTbxSql = new ComponentFactory.Krypton.Toolkit.KryptonRichTextBox();
this.tabPgDescri = new System.Windows.Forms.TabPage();
this.kryRTbxDescri = new ComponentFactory.Krypton.Toolkit.KryptonRichTextBox();
((System.ComponentModel.ISupportInitialize)(this.krySplitCntMain)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.krySplitCntMain.Panel1)).BeginInit();
this.krySplitCntMain.Panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.krySplitCntMain.Panel2)).BeginInit();
this.krySplitCntMain.Panel2.SuspendLayout();
this.krySplitCntMain.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.krySplitCntTop)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.krySplitCntTop.Panel1)).BeginInit();
this.krySplitCntTop.Panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.krySplitCntTop.Panel2)).BeginInit();
this.krySplitCntTop.Panel2.SuspendLayout();
this.krySplitCntTop.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryGbxSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.kryGbxSet.Panel)).BeginInit();
this.kryGbxSet.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.krySeparator)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.krySplitCntDbTb)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.krySplitCntDbTb.Panel1)).BeginInit();
this.krySplitCntDbTb.Panel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.krySplitCntDbTb.Panel2)).BeginInit();
this.krySplitCntDbTb.Panel2.SuspendLayout();
this.krySplitCntDbTb.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryPnlDbTip)).BeginInit();
this.kryPnlDbTip.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.kryCbxDb)).BeginInit();
this.tabCtrlMain.SuspendLayout();
this.tabPgModel.SuspendLayout();
this.tabPgQuery.SuspendLayout();
this.tabPgPermit.SuspendLayout();
this.tabPgDAL.SuspendLayout();
this.tabPgBLL.SuspendLayout();
this.tabPgAspx.SuspendLayout();
this.tabPgJs.SuspendLayout();
this.tabPgSDK.SuspendLayout();
this.tabPgCtrl.SuspendLayout();
this.tabPgView.SuspendLayout();
this.tabPgSql.SuspendLayout();
this.tabPgDescri.SuspendLayout();
this.SuspendLayout();
//
// kryTheme
//
this.kryTheme.BasePaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Office2007Silver;
//
// kryMngMain
//
this.kryMngMain.GlobalPalette = this.kryTheme;
this.kryMngMain.GlobalPaletteMode = ComponentFactory.Krypton.Toolkit.PaletteModeManager.Custom;
//
// krySplitCntMain
//
this.krySplitCntMain.Cursor = System.Windows.Forms.Cursors.Default;
this.krySplitCntMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.krySplitCntMain.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.krySplitCntMain.IsSplitterFixed = true;
this.krySplitCntMain.Location = new System.Drawing.Point(0, 0);
this.krySplitCntMain.Name = "krySplitCntMain";
this.krySplitCntMain.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// krySplitCntMain.Panel1
//
this.krySplitCntMain.Panel1.Controls.Add(this.krySplitCntTop);
this.krySplitCntMain.Panel1MinSize = 107;
//
// krySplitCntMain.Panel2
//
this.krySplitCntMain.Panel2.Controls.Add(this.krySplitCntDbTb);
this.krySplitCntMain.Size = new System.Drawing.Size(764, 542);
this.krySplitCntMain.SplitterDistance = 107;
this.krySplitCntMain.SplitterWidth = 2;
this.krySplitCntMain.TabIndex = 0;
//
// krySplitCntTop
//
this.krySplitCntTop.Cursor = System.Windows.Forms.Cursors.Default;
this.krySplitCntTop.Dock = System.Windows.Forms.DockStyle.Fill;
this.krySplitCntTop.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.krySplitCntTop.IsSplitterFixed = true;
this.krySplitCntTop.Location = new System.Drawing.Point(0, 0);
this.krySplitCntTop.Name = "krySplitCntTop";
this.krySplitCntTop.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// krySplitCntTop.Panel1
//
this.krySplitCntTop.Panel1.Controls.Add(this.kryBtnOpenMng);
this.krySplitCntTop.Panel1.Controls.Add(this.kryHdTitle);
this.krySplitCntTop.Panel1MinSize = 36;
//
// krySplitCntTop.Panel2
//
this.krySplitCntTop.Panel2.Controls.Add(this.kryGbxSet);
this.krySplitCntTop.Panel2.Controls.Add(this.krySeparator);
this.krySplitCntTop.Panel2.Controls.Add(this.kryBtnSave);
this.krySplitCntTop.Panel2.Controls.Add(this.kryBtnDo);
this.krySplitCntTop.Size = new System.Drawing.Size(764, 107);
this.krySplitCntTop.SplitterDistance = 36;
this.krySplitCntTop.SplitterWidth = 1;
this.krySplitCntTop.TabIndex = 0;
//
// kryBtnOpenMng
//
this.kryBtnOpenMng.Dock = System.Windows.Forms.DockStyle.Right;
this.kryBtnOpenMng.Location = new System.Drawing.Point(721, 0);
this.kryBtnOpenMng.Name = "kryBtnOpenMng";
this.kryBtnOpenMng.Size = new System.Drawing.Size(43, 36);
this.kryBtnOpenMng.TabIndex = 1;
this.kryBtnOpenMng.Values.Text = "Mng";
this.kryBtnOpenMng.Click += new System.EventHandler(this.kryBtnOpenMng_Click);
//
// kryHdTitle
//
this.kryHdTitle.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryHdTitle.Location = new System.Drawing.Point(0, 0);
this.kryHdTitle.Name = "kryHdTitle";
this.kryHdTitle.Size = new System.Drawing.Size(764, 36);
this.kryHdTitle.TabIndex = 0;
this.kryHdTitle.Values.Description = "AutoCode 。";
this.kryHdTitle.Values.Heading = "Obsidian";
this.kryHdTitle.Values.Image = global::ObAuto.Properties.Resources.win;
//
// kryGbxSet
//
this.kryGbxSet.CaptionStyle = ComponentFactory.Krypton.Toolkit.LabelStyle.KeyTip;
this.kryGbxSet.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryGbxSet.Location = new System.Drawing.Point(145, 0);
this.kryGbxSet.Name = "kryGbxSet";
this.kryGbxSet.Size = new System.Drawing.Size(619, 70);
this.kryGbxSet.TabIndex = 3;
this.kryGbxSet.Text = "#";
this.kryGbxSet.Values.Heading = "#";
//
// krySeparator
//
this.krySeparator.Dock = System.Windows.Forms.DockStyle.Left;
this.krySeparator.Location = new System.Drawing.Point(140, 0);
this.krySeparator.Name = "krySeparator";
this.krySeparator.Size = new System.Drawing.Size(5, 70);
this.krySeparator.SplitterWidth = 3;
this.krySeparator.TabIndex = 1;
//
// kryBtnSave
//
this.kryBtnSave.Dock = System.Windows.Forms.DockStyle.Left;
this.kryBtnSave.Enabled = false;
this.kryBtnSave.Location = new System.Drawing.Point(70, 0);
this.kryBtnSave.Name = "kryBtnSave";
this.kryBtnSave.Size = new System.Drawing.Size(70, 70);
this.kryBtnSave.TabIndex = 1;
this.kryBtnSave.Values.Text = "Save.";
this.kryBtnSave.Click += new System.EventHandler(this.kryBtnSave_Click);
//
// kryBtnDo
//
this.kryBtnDo.Dock = System.Windows.Forms.DockStyle.Left;
this.kryBtnDo.Location = new System.Drawing.Point(0, 0);
this.kryBtnDo.Name = "kryBtnDo";
this.kryBtnDo.Size = new System.Drawing.Size(70, 70);
this.kryBtnDo.TabIndex = 0;
this.kryBtnDo.Values.Text = "Do.";
this.kryBtnDo.Click += new System.EventHandler(this.kryBtnDo_Click);
//
// krySplitCntDbTb
//
this.krySplitCntDbTb.Cursor = System.Windows.Forms.Cursors.Default;
this.krySplitCntDbTb.Dock = System.Windows.Forms.DockStyle.Fill;
this.krySplitCntDbTb.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.krySplitCntDbTb.IsSplitterFixed = true;
this.krySplitCntDbTb.Location = new System.Drawing.Point(0, 0);
this.krySplitCntDbTb.Name = "krySplitCntDbTb";
//
// krySplitCntDbTb.Panel1
//
this.krySplitCntDbTb.Panel1.Controls.Add(this.kryLbxDbTb);
this.krySplitCntDbTb.Panel1.Controls.Add(this.kryPnlDbTip);
this.krySplitCntDbTb.Panel1MinSize = 140;
//
// krySplitCntDbTb.Panel2
//
this.krySplitCntDbTb.Panel2.Controls.Add(this.tabCtrlMain);
this.krySplitCntDbTb.Size = new System.Drawing.Size(764, 433);
this.krySplitCntDbTb.SplitterDistance = 140;
this.krySplitCntDbTb.SplitterWidth = 2;
this.krySplitCntDbTb.TabIndex = 0;
//
// kryLbxDbTb
//
this.kryLbxDbTb.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryLbxDbTb.Location = new System.Drawing.Point(0, 48);
this.kryLbxDbTb.Name = "kryLbxDbTb";
this.kryLbxDbTb.Size = new System.Drawing.Size(140, 385);
this.kryLbxDbTb.TabIndex = 1;
//
// kryPnlDbTip
//
this.kryPnlDbTip.Controls.Add(this.kryLblDbTip);
this.kryPnlDbTip.Controls.Add(this.kryCbxDb);
this.kryPnlDbTip.Dock = System.Windows.Forms.DockStyle.Top;
this.kryPnlDbTip.Location = new System.Drawing.Point(0, 0);
this.kryPnlDbTip.Name = "kryPnlDbTip";
this.kryPnlDbTip.Size = new System.Drawing.Size(140, 48);
this.kryPnlDbTip.TabIndex = 0;
//
// kryLblDbTip
//
this.kryLblDbTip.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryLblDbTip.Location = new System.Drawing.Point(0, 21);
this.kryLblDbTip.Name = "kryLblDbTip";
this.kryLblDbTip.Size = new System.Drawing.Size(140, 27);
this.kryLblDbTip.TabIndex = 1;
this.kryLblDbTip.Values.Text = "";
//
// kryCbxDb
//
this.kryCbxDb.Dock = System.Windows.Forms.DockStyle.Top;
this.kryCbxDb.DropDownWidth = 140;
this.kryCbxDb.Location = new System.Drawing.Point(0, 0);
this.kryCbxDb.Name = "kryCbxDb";
this.kryCbxDb.Size = new System.Drawing.Size(140, 21);
this.kryCbxDb.TabIndex = 0;
//
// tabCtrlMain
//
this.tabCtrlMain.Controls.Add(this.tabPgModel);
this.tabCtrlMain.Controls.Add(this.tabPgQuery);
this.tabCtrlMain.Controls.Add(this.tabPgPermit);
this.tabCtrlMain.Controls.Add(this.tabPgDAL);
this.tabCtrlMain.Controls.Add(this.tabPgBLL);
this.tabCtrlMain.Controls.Add(this.tabPgAspx);
this.tabCtrlMain.Controls.Add(this.tabPgJs);
this.tabCtrlMain.Controls.Add(this.tabPgSDK);
this.tabCtrlMain.Controls.Add(this.tabPgCtrl);
this.tabCtrlMain.Controls.Add(this.tabPgView);
this.tabCtrlMain.Controls.Add(this.tabPgSql);
this.tabCtrlMain.Controls.Add(this.tabPgDescri);
this.tabCtrlMain.Dock = System.Windows.Forms.DockStyle.Fill;
this.tabCtrlMain.HotTrack = true;
this.tabCtrlMain.Location = new System.Drawing.Point(0, 0);
this.tabCtrlMain.Name = "tabCtrlMain";
this.tabCtrlMain.SelectedIndex = 0;
this.tabCtrlMain.ShowToolTips = true;
this.tabCtrlMain.Size = new System.Drawing.Size(622, 433);
this.tabCtrlMain.TabIndex = 0;
//
// tabPgModel
//
this.tabPgModel.BackColor = System.Drawing.Color.Red;
this.tabPgModel.Controls.Add(this.kryRTbxModel);
this.tabPgModel.ForeColor = System.Drawing.SystemColors.ControlText;
this.tabPgModel.Location = new System.Drawing.Point(4, 22);
this.tabPgModel.Name = "tabPgModel";
this.tabPgModel.Padding = new System.Windows.Forms.Padding(1);
this.tabPgModel.Size = new System.Drawing.Size(614, 407);
this.tabPgModel.TabIndex = 0;
this.tabPgModel.Text = "1.Model";
this.tabPgModel.ToolTipText = "实体模型类";
//
// kryRTbxModel
//
this.kryRTbxModel.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryRTbxModel.Location = new System.Drawing.Point(1, 1);
this.kryRTbxModel.Name = "kryRTbxModel";
this.kryRTbxModel.Palette = this.kryTheme;
this.kryRTbxModel.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Custom;
this.kryRTbxModel.Size = new System.Drawing.Size(612, 405);
this.kryRTbxModel.TabIndex = 0;
this.kryRTbxModel.Text = "";
//
// tabPgQuery
//
this.tabPgQuery.BackColor = System.Drawing.Color.Red;
this.tabPgQuery.Controls.Add(this.kryRTbxQuery);
this.tabPgQuery.Location = new System.Drawing.Point(4, 22);
this.tabPgQuery.Name = "tabPgQuery";
this.tabPgQuery.Padding = new System.Windows.Forms.Padding(1);
this.tabPgQuery.Size = new System.Drawing.Size(614, 407);
this.tabPgQuery.TabIndex = 1;
this.tabPgQuery.Text = "1.Query";
this.tabPgQuery.ToolTipText = "查询模型类";
//
// kryRTbxQuery
//
this.kryRTbxQuery.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryRTbxQuery.Location = new System.Drawing.Point(1, 1);
this.kryRTbxQuery.Name = "kryRTbxQuery";
this.kryRTbxQuery.Palette = this.kryTheme;
this.kryRTbxQuery.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Custom;
this.kryRTbxQuery.Size = new System.Drawing.Size(612, 405);
this.kryRTbxQuery.TabIndex = 1;
this.kryRTbxQuery.Text = "";
//
// tabPgPermit
//
this.tabPgPermit.BackColor = System.Drawing.Color.Red;
this.tabPgPermit.Controls.Add(this.kryRTbxPermit);
this.tabPgPermit.Location = new System.Drawing.Point(4, 22);
this.tabPgPermit.Name = "tabPgPermit";
this.tabPgPermit.Padding = new System.Windows.Forms.Padding(1);
this.tabPgPermit.Size = new System.Drawing.Size(614, 407);
this.tabPgPermit.TabIndex = 11;
this.tabPgPermit.Text = "1.Permit";
this.tabPgPermit.ToolTipText = "权限实体类";
//
// kryRTbxPermit
//
this.kryRTbxPermit.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryRTbxPermit.Location = new System.Drawing.Point(1, 1);
this.kryRTbxPermit.Name = "kryRTbxPermit";
this.kryRTbxPermit.Palette = this.kryTheme;
this.kryRTbxPermit.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Custom;
this.kryRTbxPermit.Size = new System.Drawing.Size(612, 405);
this.kryRTbxPermit.TabIndex = 2;
this.kryRTbxPermit.Text = "";
//
// tabPgDAL
//
this.tabPgDAL.BackColor = System.Drawing.Color.Gold;
this.tabPgDAL.Controls.Add(this.kryRTbxDAL);
this.tabPgDAL.Location = new System.Drawing.Point(4, 22);
this.tabPgDAL.Name = "tabPgDAL";
this.tabPgDAL.Padding = new System.Windows.Forms.Padding(1);
this.tabPgDAL.Size = new System.Drawing.Size(614, 407);
this.tabPgDAL.TabIndex = 2;
this.tabPgDAL.Text = "2.DAL";
this.tabPgDAL.ToolTipText = "数据访问类";
//
// kryRTbxDAL
//
this.kryRTbxDAL.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryRTbxDAL.Location = new System.Drawing.Point(1, 1);
this.kryRTbxDAL.Name = "kryRTbxDAL";
this.kryRTbxDAL.Palette = this.kryTheme;
this.kryRTbxDAL.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Custom;
this.kryRTbxDAL.Size = new System.Drawing.Size(612, 405);
this.kryRTbxDAL.TabIndex = 1;
this.kryRTbxDAL.Text = "";
//
// tabPgBLL
//
this.tabPgBLL.BackColor = System.Drawing.Color.Gold;
this.tabPgBLL.Controls.Add(this.kryRTbxBLL);
this.tabPgBLL.Location = new System.Drawing.Point(4, 22);
this.tabPgBLL.Name = "tabPgBLL";
this.tabPgBLL.Padding = new System.Windows.Forms.Padding(1);
this.tabPgBLL.Size = new System.Drawing.Size(614, 407);
this.tabPgBLL.TabIndex = 3;
this.tabPgBLL.Text = "2.BLL";
this.tabPgBLL.ToolTipText = "业务逻辑类";
//
// kryRTbxBLL
//
this.kryRTbxBLL.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryRTbxBLL.Location = new System.Drawing.Point(1, 1);
this.kryRTbxBLL.Name = "kryRTbxBLL";
this.kryRTbxBLL.Palette = this.kryTheme;
this.kryRTbxBLL.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Custom;
this.kryRTbxBLL.Size = new System.Drawing.Size(612, 405);
this.kryRTbxBLL.TabIndex = 0;
this.kryRTbxBLL.Text = "";
//
// tabPgAspx
//
this.tabPgAspx.BackColor = System.Drawing.Color.LimeGreen;
this.tabPgAspx.Controls.Add(this.kryRTbxHtml);
this.tabPgAspx.Location = new System.Drawing.Point(4, 22);
this.tabPgAspx.Name = "tabPgAspx";
this.tabPgAspx.Padding = new System.Windows.Forms.Padding(1);
this.tabPgAspx.Size = new System.Drawing.Size(614, 407);
this.tabPgAspx.TabIndex = 5;
this.tabPgAspx.Text = "3.ASPX";
this.tabPgAspx.ToolTipText = "后台ASPX页面HTML代码";
//
// kryRTbxHtml
//
this.kryRTbxHtml.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryRTbxHtml.Location = new System.Drawing.Point(1, 1);
this.kryRTbxHtml.Name = "kryRTbxHtml";
this.kryRTbxHtml.Palette = this.kryTheme;
this.kryRTbxHtml.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Custom;
this.kryRTbxHtml.Size = new System.Drawing.Size(612, 405);
this.kryRTbxHtml.TabIndex = 0;
this.kryRTbxHtml.Text = "";
//
// tabPgJs
//
this.tabPgJs.BackColor = System.Drawing.Color.LimeGreen;
this.tabPgJs.Controls.Add(this.kryRTbxJs);
this.tabPgJs.Location = new System.Drawing.Point(4, 22);
this.tabPgJs.Name = "tabPgJs";
this.tabPgJs.Padding = new System.Windows.Forms.Padding(1);
this.tabPgJs.Size = new System.Drawing.Size(614, 407);
this.tabPgJs.TabIndex = 6;
this.tabPgJs.Text = "3.JS";
this.tabPgJs.ToolTipText = "后台页面对应JavaScript接口文件";
//
// kryRTbxJs
//
this.kryRTbxJs.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryRTbxJs.Location = new System.Drawing.Point(1, 1);
this.kryRTbxJs.Name = "kryRTbxJs";
this.kryRTbxJs.Palette = this.kryTheme;
this.kryRTbxJs.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Custom;
this.kryRTbxJs.Size = new System.Drawing.Size(612, 405);
this.kryRTbxJs.TabIndex = 1;
this.kryRTbxJs.Text = "";
//
// tabPgSDK
//
this.tabPgSDK.BackColor = System.Drawing.Color.BlueViolet;
this.tabPgSDK.Controls.Add(this.kryRTbxSDK);
this.tabPgSDK.Location = new System.Drawing.Point(4, 22);
this.tabPgSDK.Name = "tabPgSDK";
this.tabPgSDK.Padding = new System.Windows.Forms.Padding(1);
this.tabPgSDK.Size = new System.Drawing.Size(614, 407);
this.tabPgSDK.TabIndex = 4;
this.tabPgSDK.Text = "4.SDK";
this.tabPgSDK.ToolTipText = "SDK接口辅助类";
//
// kryRTbxSDK
//
this.kryRTbxSDK.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryRTbxSDK.Location = new System.Drawing.Point(1, 1);
this.kryRTbxSDK.Name = "kryRTbxSDK";
this.kryRTbxSDK.Palette = this.kryTheme;
this.kryRTbxSDK.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Custom;
this.kryRTbxSDK.Size = new System.Drawing.Size(612, 405);
this.kryRTbxSDK.TabIndex = 1;
this.kryRTbxSDK.Text = "";
//
// tabPgCtrl
//
this.tabPgCtrl.BackColor = System.Drawing.Color.BlueViolet;
this.tabPgCtrl.Controls.Add(this.kryRTbxCtrl);
this.tabPgCtrl.Location = new System.Drawing.Point(4, 22);
this.tabPgCtrl.Name = "tabPgCtrl";
this.tabPgCtrl.Padding = new System.Windows.Forms.Padding(1);
this.tabPgCtrl.Size = new System.Drawing.Size(614, 407);
this.tabPgCtrl.TabIndex = 8;
this.tabPgCtrl.Text = "4.Ctrl";
this.tabPgCtrl.ToolTipText = "前台项目控制器";
//
// kryRTbxCtrl
//
this.kryRTbxCtrl.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryRTbxCtrl.Location = new System.Drawing.Point(1, 1);
this.kryRTbxCtrl.Name = "kryRTbxCtrl";
this.kryRTbxCtrl.Palette = this.kryTheme;
this.kryRTbxCtrl.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Custom;
this.kryRTbxCtrl.Size = new System.Drawing.Size(612, 405);
this.kryRTbxCtrl.TabIndex = 2;
this.kryRTbxCtrl.Text = "";
//
// tabPgView
//
this.tabPgView.BackColor = System.Drawing.Color.BlueViolet;
this.tabPgView.Controls.Add(this.kryRTbxView);
this.tabPgView.Location = new System.Drawing.Point(4, 22);
this.tabPgView.Name = "tabPgView";
this.tabPgView.Padding = new System.Windows.Forms.Padding(1);
this.tabPgView.Size = new System.Drawing.Size(614, 407);
this.tabPgView.TabIndex = 9;
this.tabPgView.Text = "4.View";
this.tabPgView.ToolTipText = "前台项目视图";
//
// kryRTbxView
//
this.kryRTbxView.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryRTbxView.Location = new System.Drawing.Point(1, 1);
this.kryRTbxView.Name = "kryRTbxView";
this.kryRTbxView.Palette = this.kryTheme;
this.kryRTbxView.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Custom;
this.kryRTbxView.Size = new System.Drawing.Size(612, 405);
this.kryRTbxView.TabIndex = 3;
this.kryRTbxView.Text = "";
//
// tabPgSql
//
this.tabPgSql.BackColor = System.Drawing.Color.DodgerBlue;
this.tabPgSql.Controls.Add(this.kryRTbxSql);
this.tabPgSql.Location = new System.Drawing.Point(4, 22);
this.tabPgSql.Name = "tabPgSql";
this.tabPgSql.Padding = new System.Windows.Forms.Padding(1);
this.tabPgSql.Size = new System.Drawing.Size(614, 407);
this.tabPgSql.TabIndex = 7;
this.tabPgSql.Text = "5.SQL";
this.tabPgSql.ToolTipText = "SQL数据文件";
//
// kryRTbxSql
//
this.kryRTbxSql.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryRTbxSql.Location = new System.Drawing.Point(1, 1);
this.kryRTbxSql.Name = "kryRTbxSql";
this.kryRTbxSql.Palette = this.kryTheme;
this.kryRTbxSql.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Custom;
this.kryRTbxSql.Size = new System.Drawing.Size(612, 405);
this.kryRTbxSql.TabIndex = 1;
this.kryRTbxSql.Text = "";
//
// tabPgDescri
//
this.tabPgDescri.BackColor = System.Drawing.Color.DarkGray;
this.tabPgDescri.Controls.Add(this.kryRTbxDescri);
this.tabPgDescri.Location = new System.Drawing.Point(4, 22);
this.tabPgDescri.Name = "tabPgDescri";
this.tabPgDescri.Padding = new System.Windows.Forms.Padding(1);
this.tabPgDescri.Size = new System.Drawing.Size(614, 407);
this.tabPgDescri.TabIndex = 10;
this.tabPgDescri.Text = "6.Descri";
this.tabPgDescri.ToolTipText = "实体,接口描述";
//
// kryRTbxDescri
//
this.kryRTbxDescri.Dock = System.Windows.Forms.DockStyle.Fill;
this.kryRTbxDescri.Location = new System.Drawing.Point(1, 1);
this.kryRTbxDescri.Name = "kryRTbxDescri";
this.kryRTbxDescri.Palette = this.kryTheme;
this.kryRTbxDescri.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Custom;
this.kryRTbxDescri.Size = new System.Drawing.Size(612, 405);
this.kryRTbxDescri.TabIndex = 3;
this.kryRTbxDescri.Text = "";
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(764, 542);
this.Controls.Add(this.krySplitCntMain);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "MainForm";
this.Palette = this.kryTheme;
this.PaletteMode = ComponentFactory.Krypton.Toolkit.PaletteMode.Custom;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Obsidian Framwork";
this.TextExtra = "Hello World~";
this.Load += new System.EventHandler(this.MainForm_Load);
((System.ComponentModel.ISupportInitialize)(this.krySplitCntMain.Panel1)).EndInit();
this.krySplitCntMain.Panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.krySplitCntMain.Panel2)).EndInit();
this.krySplitCntMain.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.krySplitCntMain)).EndInit();
this.krySplitCntMain.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.krySplitCntTop.Panel1)).EndInit();
this.krySplitCntTop.Panel1.ResumeLayout(false);
this.krySplitCntTop.Panel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.krySplitCntTop.Panel2)).EndInit();
this.krySplitCntTop.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.krySplitCntTop)).EndInit();
this.krySplitCntTop.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryGbxSet.Panel)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.kryGbxSet)).EndInit();
this.kryGbxSet.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.krySeparator)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.krySplitCntDbTb.Panel1)).EndInit();
this.krySplitCntDbTb.Panel1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.krySplitCntDbTb.Panel2)).EndInit();
this.krySplitCntDbTb.Panel2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.krySplitCntDbTb)).EndInit();
this.krySplitCntDbTb.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.kryPnlDbTip)).EndInit();
this.kryPnlDbTip.ResumeLayout(false);
this.kryPnlDbTip.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.kryCbxDb)).EndInit();
this.tabCtrlMain.ResumeLayout(false);
this.tabPgModel.ResumeLayout(false);
this.tabPgQuery.ResumeLayout(false);
this.tabPgPermit.ResumeLayout(false);
this.tabPgDAL.ResumeLayout(false);
this.tabPgBLL.ResumeLayout(false);
this.tabPgAspx.ResumeLayout(false);
this.tabPgJs.ResumeLayout(false);
this.tabPgSDK.ResumeLayout(false);
this.tabPgCtrl.ResumeLayout(false);
this.tabPgView.ResumeLayout(false);
this.tabPgSql.ResumeLayout(false);
this.tabPgDescri.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
public ComponentFactory.Krypton.Toolkit.KryptonPalette kryTheme;
public ComponentFactory.Krypton.Toolkit.KryptonManager kryMngMain;
private ComponentFactory.Krypton.Toolkit.KryptonSplitContainer krySplitCntMain;
private ComponentFactory.Krypton.Toolkit.KryptonSplitContainer krySplitCntTop;
private ComponentFactory.Krypton.Toolkit.KryptonHeader kryHdTitle;
private ComponentFactory.Krypton.Toolkit.KryptonButton kryBtnOpenMng;
private ComponentFactory.Krypton.Toolkit.KryptonComboBox kryCbxDb;
private ComponentFactory.Krypton.Toolkit.KryptonSeparator krySeparator;
private ComponentFactory.Krypton.Toolkit.KryptonSplitContainer krySplitCntDbTb;
private ComponentFactory.Krypton.Toolkit.KryptonPanel kryPnlDbTip;
private ComponentFactory.Krypton.Toolkit.KryptonLabel kryLblDbTip;
private ComponentFactory.Krypton.Toolkit.KryptonListBox kryLbxDbTb;
private System.Windows.Forms.TabControl tabCtrlMain;
private System.Windows.Forms.TabPage tabPgModel;
private System.Windows.Forms.TabPage tabPgQuery;
private System.Windows.Forms.TabPage tabPgDAL;
private ComponentFactory.Krypton.Toolkit.KryptonButton kryBtnSave;
private ComponentFactory.Krypton.Toolkit.KryptonButton kryBtnDo;
private ComponentFactory.Krypton.Toolkit.KryptonGroupBox kryGbxSet;
private ComponentFactory.Krypton.Toolkit.KryptonRichTextBox kryRTbxModel;
private ComponentFactory.Krypton.Toolkit.KryptonRichTextBox kryRTbxQuery;
private ComponentFactory.Krypton.Toolkit.KryptonRichTextBox kryRTbxDAL;
private System.Windows.Forms.TabPage tabPgBLL;
private System.Windows.Forms.TabPage tabPgSDK;
private System.Windows.Forms.TabPage tabPgAspx;
private System.Windows.Forms.TabPage tabPgJs;
private System.Windows.Forms.TabPage tabPgSql;
private ComponentFactory.Krypton.Toolkit.KryptonRichTextBox kryRTbxBLL;
private ComponentFactory.Krypton.Toolkit.KryptonRichTextBox kryRTbxSDK;
private ComponentFactory.Krypton.Toolkit.KryptonRichTextBox kryRTbxHtml;
private ComponentFactory.Krypton.Toolkit.KryptonRichTextBox kryRTbxJs;
private ComponentFactory.Krypton.Toolkit.KryptonRichTextBox kryRTbxSql;
private System.Windows.Forms.TabPage tabPgCtrl;
private System.Windows.Forms.TabPage tabPgView;
private System.Windows.Forms.TabPage tabPgDescri;
private ComponentFactory.Krypton.Toolkit.KryptonRichTextBox kryRTbxCtrl;
private ComponentFactory.Krypton.Toolkit.KryptonRichTextBox kryRTbxView;
private ComponentFactory.Krypton.Toolkit.KryptonRichTextBox kryRTbxDescri;
private System.Windows.Forms.TabPage tabPgPermit;
private ComponentFactory.Krypton.Toolkit.KryptonRichTextBox kryRTbxPermit;
}
}
| caideyuan/ObsidianToolkit | MainForm.Designer.cs | C# | gpl-2.0 | 37,364 |
#!/usr/bin/python
import pygeoip
import json
from logsparser.lognormalizer import LogNormalizer as LN
import gzip
import glob
import socket
import urllib2
IP = 'IP.Of,Your.Server'
normalizer = LN('/usr/local/share/logsparser/normalizers')
gi = pygeoip.GeoIP('../GeoLiteCity.dat')
def complete(text, state):
return (glob.glob(text+'*')+[none])[state]
def sshcheck():
attacks = {}
users = {}
try:
import readline, rlcompleter
readline.set_completer_delims(' \t\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(complete)
except ImportError:
print 'No Tab Completion'
LOGs = raw_input('Enter the path to the log file: ')
for LOG in LOGs.split(' '):
if LOG.endswith('.gz'):
auth_logs = gzip.GzipFile(LOG, 'r')
else:
auth_logs = open(LOG, 'r')
if len(LOGs) is '1':
print "Parsing log file"
else:
print "Parsing log files"
for log in auth_logs:
l = {"raw": log }
normalizer.normalize(l)
if l.get('action') == 'fail' and l.get('program') == 'sshd':
u = l['user']
p = l['source_ip']
o1, o2, o3, o4 = [int(i) for i in p.split('.')]
if o1 == 192 and o2 == 168 or o1 == 172 and o2 in range(16, 32) or o1 == 10:
print "Private IP, %s No geolocation data" %str(p)
attacks[p] = attacks.get(p, 0) + 1
getip()
dojson(attacks, IP)
def getip():
global IP
if IP is 0:
try:
i = urllib2.Request("http://icanhazip.com")
p = urllib2.urlopen(i)
IP = p.read()
except:
print "can't seem to grab your IP please set IP variable so We can better map attacks"
def dojson(attacks, IP):
data = {}
for i,(a,p) in enumerate(attacks.iteritems()):
datalist = [{ 'ip': a, 'attacks': p, 'local_ip': IP }]
data[i] = datalist
newdata = data
newjson = json.dumps(newdata)
print json.loads(newjson)
send(newjson)
def send(data):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('Ip.Of.Your.Server', 9999))
s.sendall(data)
s.close()
try:
sshcheck()
except KeyboardInterrupt:
print '\nCtrl+C Exiting...'
exit(0)
| radman404/Who-s-attacking-me-now-- | wamnclient.py | Python | gpl-2.0 | 2,126 |
package sjy.elwg.notation;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
public class OrnamentDialog extends JDialog implements ActionListener{
/**
* ÐòÁкÅ
*/
private static final long serialVersionUID = 2647829265264720382L;
/**
* ´°¿Ú´óС
*/
private static final int DIALOG_WIDTH = 100;
private static final int DIALOG_HEIGHT = 135;
/**
* ÑÝ×à·ûºÅÀàÐÍ
*/
private String symboleType = "none";
ImageIcon iconMarcato = new ImageIcon(("pic/marcato.png"));
ImageIcon iconMartellatoDown = new ImageIcon(("pic/martellatoDown.png"));
ImageIcon iconMartellatoUp = new ImageIcon(("pic/martellatoUp.png"));
ImageIcon iconStaccato = new ImageIcon(("pic/staccato.png"));
ImageIcon iconTenuto = new ImageIcon(("pic/tenuto.png"));
ImageIcon iconStaccatissimoDown = new ImageIcon(("pic/staccatissimoDown.png"));
ImageIcon iconStaccatissimoUp = new ImageIcon(("pic/staccatissimoUp.png"));
ImageIcon iconStaccatoTenutoUp = new ImageIcon(("pic/staccatoTenutoUp.png"));
ImageIcon iconStaccatoTenutoDown = new ImageIcon(("pic/staccatoTenutoDown.png"));
ImageIcon iconFermata = new ImageIcon(("pic/fermata.png"));
ImageIcon iconPedalStart = new ImageIcon(("pic/pedalstart.png"));
ImageIcon iconPedalEnd = new ImageIcon(("pic/pedalend.png"));
ImageIcon iconBreath = new ImageIcon(("pic/breath.png"));
// ImageIcon iconTremoloBeam1 = new ImageIcon(("pic/TremoloBeam1.png"));
// ImageIcon iconTremoloBeam2 = new ImageIcon(("pic/TremoloBeam2.png"));
// ImageIcon iconTremoloBeam3 = new ImageIcon(("pic/TremoloBeam3.png"));
/**
* °´Å¥
*/
private JButton btMarcato = new JButton(iconMarcato);
private JButton btMartellatoDown = new JButton(iconMartellatoDown);
private JButton btMartellatoUp = new JButton(iconMartellatoUp);
private JButton btStaccato = new JButton(iconStaccato);
private JButton btTenuto = new JButton(iconTenuto);
private JButton btStaccatissimoDown = new JButton(iconStaccatissimoDown);
private JButton btStaccatissimoUp = new JButton(iconStaccatissimoUp);
private JButton btStaccatoTenutoUp = new JButton(iconStaccatoTenutoUp);
private JButton btStaccatoTenutoDown = new JButton(iconStaccatoTenutoDown);
private JButton btFermata = new JButton(iconFermata);
private JButton btPedalStart = new JButton(iconPedalStart);
private JButton btPedalEnd = new JButton(iconPedalEnd);
private JButton btBreath = new JButton(iconBreath);
// private JButton btTremoloBeam1 = new JButton(iconTremoloBeam1);
// private JButton btTremoloBeam2 = new JButton(iconTremoloBeam2);
// private JButton btTremoloBeam3 = new JButton(iconTremoloBeam3);
public OrnamentDialog(){
super();
setLayout(null);
setSize(DIALOG_WIDTH, DIALOG_HEIGHT);
initComponents();
setModal(true);
addFunctionListener(this);
}
void addFunctionListener(ActionListener l) {
// TODO Auto-generated method stub
btMarcato.addActionListener(l);
btMartellatoDown.addActionListener(l);
btMartellatoUp.addActionListener(l);
btStaccato.addActionListener(l);
btTenuto.addActionListener(l);
btStaccatissimoDown.addActionListener(l);
btStaccatissimoUp.addActionListener(l);
btStaccatoTenutoUp.addActionListener(l);
btStaccatoTenutoDown.addActionListener(l);
btFermata.addActionListener(l);
btPedalStart.addActionListener(l);
btPedalEnd.addActionListener(l);
btBreath.addActionListener(l);
// btTremoloBeam1.addActionListener(l);
// btTremoloBeam2.addActionListener(l);
// btTremoloBeam3.addActionListener(l);
}
/**
* ³õʼ»¯°´Å¥
*/
public void initComponents(){
setLayout(null);
add(btMarcato);
add(btMartellatoDown);
add(btMartellatoUp);
add(btStaccato);
add(btTenuto);
add(btStaccatissimoDown);
add(btStaccatissimoUp);
add(btStaccatoTenutoUp);
add(btStaccatoTenutoDown);
add(btFermata);
add(btPedalStart);
add(btPedalEnd);
add(btBreath);
// add(btTremoloBeam1);
// add(btTremoloBeam2);
// add(btTremoloBeam3);
int x = 8; int y = 5;
btMarcato.setBounds(x, y, 20, 25);
x += 20;
btMartellatoDown.setBounds(x, y, 20, 25);
x += 20;
btMartellatoUp.setBounds(x, y, 20, 25);
x += 20;
btStaccato.setBounds(x, y, 20, 25);
x += 20;
btTenuto.setBounds(x, y, 20, 25);
x = 8; y += 30;
btStaccatissimoDown.setBounds(x, y, 20, 25);
x += 20;
btStaccatissimoUp.setBounds(x, y, 20, 25);
x += 20;
btStaccatoTenutoUp.setBounds(x, y, 20, 25);
x += 20;
btStaccatoTenutoDown.setBounds(x, y, 20, 25);
x += 20;
btFermata.setBounds(x, y, 20, 25);
x = 8; y+= 30;
btPedalStart.setBounds(x, y, 20, 25);
x += 20;
btPedalEnd.setBounds(x, y, 20, 25);
x += 20;
btBreath.setBounds(x, y, 20, 25);
x += 20;
// btTremoloBeam1.setBounds(x, y, 20, 25);
// x += 20;
// btTremoloBeam2.setBounds(x, y, 20, 25);
// x = 8; y+= 30;
// btTremoloBeam3.setBounds(x, y, 20, 25);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == btMarcato){
symboleType = "accent";
dispose();
}else if(e.getSource() == btMartellatoDown){
symboleType = "strongAccentDown";
dispose();
}else if(e.getSource() == btMartellatoUp){
symboleType = "strongAccentUp";
dispose();
}else if(e.getSource() == btStaccato){
symboleType = "staccato";
dispose();
}else if(e.getSource() == btTenuto){
symboleType = "tenuto";
dispose();
}else if(e.getSource() == btStaccatissimoDown){
symboleType = "staccatissimoDown";
dispose();
}else if(e.getSource() == btStaccatissimoUp){
symboleType = "staccatissimoUp";
dispose();
}else if(e.getSource() == btStaccatoTenutoUp){
symboleType = "staccatoTenutoUp";
dispose();
}else if(e.getSource() == btStaccatoTenutoDown){
symboleType = "staccatoTenutoDown";
dispose();
}else if(e.getSource() == btFermata){
symboleType = "fermata";
dispose();
}else if(e.getSource() == btPedalStart){
symboleType = "pedalStart";
dispose();
}else if(e.getSource() == btPedalEnd){
symboleType = "pedalEnd";
dispose();
}else if(e.getSource() == btBreath){
symboleType = "breath";
dispose();
}
// else if(e.getSource() == btTremoloBeam1){
// type = "tremoloBeam1";
// dispose();
// }else if(e.getSource() == btTremoloBeam2){
// type = "tremoloBeam2";
// dispose();
// }else if(e.getSource() == btTremoloBeam3){
// type = "tremoloBeam3";
// dispose();
// }
}
public String getSymbolType() {
return symboleType;
}
public void setType(String type) {
this.symboleType = type;
}
}
| squallyou/LScore | src/sjy/elwg/notation/OrnamentDialog.java | Java | gpl-2.0 | 6,587 |
/* profiler-plugin.js is part of Aloha Editor project http://aloha-editor.org
*
* Aloha Editor is a WYSIWYG HTML5 inline editing library and editor.
* Copyright (c) 2010-2012 Gentics Software GmbH, Vienna, Austria.
* Contributors http://aloha-editor.org/contribution.php
*
* Aloha Editor 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 any later version.
*
* Aloha Editor 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
* As an additional permission to the GNU GPL version 2, you may distribute
* non-source (e.g., minimized or compacted) forms of the Aloha-Editor
* source code without the copy of the GNU GPL normally required,
* provided you include this license notice and a URL through which
* recipients can access the Corresponding Source.
*/
/* Aloha Profiler
* --------------
* Provides a useful interface to profile some of Aloha components and their
* methods.
*
* Potentially process intensive methods:
* Aloha.Profiler.profileAlohaComponent('Markup.preProcessKeyStrokes')
* Aloha.Profiler.profileAlohaComponent('Selection._updateSelection')
*/
window.define( [
'aloha/core',
'aloha/plugin',
'aloha/editable',
// 'aloha/sidebar',
'aloha/selection',
'aloha/markup',
'aloha/contenthandlermanager',
'aloha/floatingmenu',
'aloha/console',
'css!profiler/css/profiler'
], function( Aloha, Plugin, /* Sidebar */ Editable, Selection, Markup,
ContentHandlerManager, FloatingMenu, console ) {
// 'caller', 'callee', and 'arguments' properties may not be accessed on
// strict mode functions or the arguments objects for calls to them
//
var jQuery = Aloha.jQuery,
profiledFunctions = [],
// get the arguments string literal of this function, and split it into
// an array of names
argsStr = ( /function[^\(]*\(([^\)]+)/g ).exec( arguments.callee.toString() ),
argNames = argsStr ? argsStr[1].replace( /^\s+|\s+$/g, '' ).split( /\,\s*/ ) : [],
args = Array.prototype.slice.call( arguments );
/**
* @param {String} path dot seperated path to resolve inside a given object
* or browser window
* @param {?Object} object inwhich to resolve a path. If no object is
* passed, the browser window object will be used instead
* @return {?} Object
*/
function resolvePath(path, obj) {
if ( typeof path !== 'string' ) {
return path;
}
if ( !obj || typeof obj !== 'object' ) {
obj = window;
}
var parts = path.split( '.' ),
i = 0,
j = parts.length;
for ( ; i < j; ++i ) {
obj = obj[ parts[ i ] ];
if ( typeof obj === 'undefined' ) {
console.error(
'Aloha.Profiler',
'Property "' + parts[ i ] + '" does not exist' +
( i ? ' in object ' + parts.slice( 0, i ).join( '.' ) : '' )
);
return null;
}
}
return obj;
};
function parseObjectPath( path, obj ) {
if ( typeof path !== 'string' ) {
return null;
}
var parts = path.split( '.' ),
pathToProp = parts.slice( 0, Math.max( 1, parts.length - 1 ) ).join( '.' ),
prop;
obj = resolvePath( pathToProp, obj );
if ( !obj ) {
return null;
}
if ( parts.length > 1 ) {
var lastProp = parts[ parts.length - 1 ];
if ( typeof obj[ lastProp ] === 'undefined' ) {
console.error( 'Aloha.Profiler',
'Property "' + lastProp + '" does not exist in object ' +
pathToProp );
} else {
prop = lastProp;
}
}
return {
obj : obj[ prop ],
path : path,
parentObj : obj,
propName : prop
};
};
var panel;
function initSidebarPanel(sidebar) {
sidebar.addPanel( {
id : 'aloha-devtool-profiler-panel',
title : 'Aloha Profiler',
expanded : true,
activeOn : true,
content : '' +
'<div id="aloha-devtool-profiler-container">' +
'<input id="aloha-devtool-profiler-input" ' +
'value="Aloha.Profiler.profileAlohaComponent(\'Markup.preProcessKeyStrokes\')" />' +
'<ul id="aloha-devtool-profiler-console"></ul>' +
'</div>',
onInit : function() {
this.content.find( 'input#aloha-devtool-profiler-input' ).keydown( function( event ) {
// Handle ENTER
if ( event.keyCode === 13 ) {
var input = jQuery( this );
var value = input.val();
if ( value ) {
eval( value );
PanelConsole.log( value );
input.val( '' );
}
}
} );
}
} );
sidebar.show().open();
};
var PanelConsole = {
log: function() {
jQuery( '#aloha-devtool-profiler-console' )
.prepend( '<li>' +
Array.prototype.slice.call( arguments ).join( ' ' ) +
'</li>' );
}
}
Aloha.Profiler = Plugin.create( 'profiler', {
/**
* Explose all dependencies to allow easy access. eg:
* If the 5th dependency was Markup, then:
* Aloha.Profiler.profile(Aloha.Profiler.alohaObjects[4], 'preProcessKeyStrokes')
* would start profiling the Markup.preProcessKeyStrokes method.
*/
loadedDependencies: Array.prototype.slice.call( arguments ),
/**
* Provides a better interface to access various components of Aloha.
* eg: Aloha.Profiler.profile(Aloha.Profiler.alohaComponents[ 'Markup' ], 'preProcessKeyStrokes')
*/
alohaComponents: {},
panel: null,
/**
* Initializes Profiler plugin by populating alohaComponents with all
* arguments of our define function, mapping name, to object
*/
init: function() {
var j = argNames.length;
while ( --j >= 0 ) {
this.alohaComponents[ argNames[ j ] ] = args[ j ];
}
var that = this;
Aloha.ready( function() {
if ( Aloha.Sidebar && Aloha.Sidebar.right ) {
that.panel = initSidebarPanel( Aloha.Sidebar.right );
}
} );
},
log: function() {
PanelConsole.log.apply( PanelConsole, arguments );
},
/**
* Shortcut to profile one of the Aloha components that was required by
* Aloha Profiler.
*
* @param {String} path
* @param {String} fnName
*/
profileAlohaComponent: function( path, fnName ) {
var parts = parseObjectPath( path, this.alohaComponents );
return this.profile( parts.parentObj, fnName || parts.propName );
},
/**
* @param {(Object|String)} obj object or path to object that contains
* the function we want to profile. Or the path to the
* function itself
* @param {String} fnName name of function inside obj, which we want to
* profile
* @param {?Function(Function, Array):Boolean} intercept functiont to
* call each time this method is invoked
*/
profile: function( obj, fnName, intercept ) {
var path,
parts,
objIndex = -1,
i;
if ( typeof obj === 'string' ) {
parts = parseObjectPath( obj );
obj = parts.parentObj;
path = parts.path + ( fnName ? '.' + fnName : '' );
if ( parts.propName ) {
if ( typeof parts.obj === 'function' ) {
fnName = parts.propName;
} else if ( parts.obj === 'object' ) {
obj = parts.obj;
}
}
}
if ( !obj || !fnName || typeof obj[ fnName ] !== 'function' ) {
return;
}
for ( i = 0; i < profiledFunctions.length; ++i ) {
if ( profiledFunctions[ i ] === obj ) {
objIndex = i;
if ( profiledFunctions[ i ][ fnName ] ) {
return;
}
}
}
var fn = obj[ fnName ];
var that = this;
// In IE typeof window.console.log returns "object!!!"
if ( window.console && window.console.log ) {
if ( objIndex === -1 ) {
objIndex = profiledFunctions.push( obj ) - 1;
}
profiledFunctions[ objIndex ][ fnName ] = fn;
obj[ fnName ] = function() {
if ( typeof intercept === 'function' ) {
intercept( fn, arguments );
}
// window.console.time( fnName );
var start = +( new Date() );
var returnValue = fn.apply( obj, arguments );
// window.console.timeEnd( fnName );
that.log( ( path || fnName ) + ': ' +
( ( new Date() ) - start ) + 'ms' );
return returnValue;
};
}
},
/**
* @return {String} "Aloha.Profiler"
*/
toString: function() {
return 'Aloha.Profiler';
}
} );
return Aloha.Profiler;
} );
| bitcodes/pinecones | sites/all/libraries/aloha/aloha/plugins/extra/profiler/lib/profiler-plugin.js | JavaScript | gpl-2.0 | 8,987 |
<?php
return array(
'banner'=>'Banner',
'affiliate'=>'Affiliate',
'delete_confirm'=>'Wollen Sie den Banner wirklich löschen?',
'new_banner'=>'Neuen Banner',
'uploads_disabled'=>'Hochladen ist deaktiviert.',
'err_foundfile'=>'Im Verzeichnispfad ist bereits eine Datei vorhanden.',
'err_cantmkdir'=>'Konnte Verzeichnis nicht erstellen.',
'err_unknown'=>'Ein unbekannter Fehler ist aufgetreten. Bitte wenden Sie sich an die Exponent Entwickler.',
);
?> | exponentcms/exponent-cms-1 | subsystems/lang/deu_DE/modules/bannermodule/views/Banner Manager.php | PHP | gpl-2.0 | 463 |
# -*- coding: utf-8 -*-
import logging
# define here the methods needed to be run at install time
def importVarious(context):
if context.readDataFile('sc.blueprints.soundcloud_various.txt') is None:
return
logger = logging.getLogger('sc.blueprints.soundcloud')
# add here your custom methods that need to be run when
# sc.blueprints.soundcloud is installed
| jsbueno/sc.blueprints.soundcloud | sc/blueprints/soundcloud/setuphandlers.py | Python | gpl-2.0 | 386 |
// SmartDom
// SmartDom.Service
// RtuSerialModbusMaster.cs
//
// Created by Marcin Kowal.
// Copyright (c) 2015. All rights reserved.
//
namespace SmartDom.Service.ModbusAdapters
{
using System;
using System.IO.Ports;
using System.Threading.Tasks;
using Modbus.Device;
using SmartDom.Service.MediaAdapters;
public class RtuSerialModbusMaster : IModbusMasterAdapter
{
private readonly ModbusMaster modbus;
/// <summary>
/// Initializes a new instance of the <see cref="RtuSerialModbusMaster" /> class.
/// </summary>
/// <param name="mediaAbstractAdapter">The media abstract adapter.</param>
public RtuSerialModbusMaster(MediaAbstractAdapter<SerialPort> mediaAbstractAdapter)
{
this.modbus = ModbusSerialMaster.CreateRtu(mediaAbstractAdapter.Media);
}
/// <summary>
/// Reads the holding registers.
/// </summary>
/// <param name="slaveAddress">The slave address.</param>
/// <param name="startAddress">The start address.</param>
/// <param name="numberOfPoints">The number of points.</param>
/// <returns></returns>
public ushort[] ReadHoldingRegisters(byte slaveAddress, ushort startAddress, ushort numberOfPoints)
{
return this.modbus.ReadHoldingRegisters(slaveAddress, startAddress, numberOfPoints);
}
/// <summary>
/// Reads the holding registers asynchronously
/// </summary>
/// <param name="slaveAddress">The slave address.</param>
/// <param name="startAddress">The start address.</param>
/// <param name="numberOfPoints">The number of points.</param>
/// <returns></returns>
public async Task<ushort[]> ReadHoldingRegistersAsync(
byte slaveAddress,
ushort startAddress,
ushort numberOfPoints)
{
return await this.modbus.ReadHoldingRegistersAsync(slaveAddress, startAddress, numberOfPoints);
}
/// <summary>
/// Writes the multiple registers.
/// </summary>
/// <param name="slaveAddress">The slave address.</param>
/// <param name="startAddress">The start address.</param>
/// <param name="data">The data.</param>
public void WriteMultipleRegisters(byte slaveAddress, ushort startAddress, ushort[] data)
{
this.modbus.WriteMultipleRegisters(slaveAddress, startAddress, data);
}
/// <summary>
/// Writes the multiple registers asynchronously
/// </summary>
/// <param name="slaveAddress">The slave address.</param>
/// <param name="startAddress">The start address.</param>
/// <param name="data">The data.</param>
/// <returns></returns>
public async Task WriteMultipleRegistersAsync(byte slaveAddress, ushort startAddress, ushort[] data)
{
await this.modbus.WriteMultipleRegistersAsync(slaveAddress, startAddress, data);
}
// Dispose() calls Dispose(true)
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
// The bulk of the clean-up code is implemented in Dispose(bool)
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (this.modbus != null)
{
this.modbus.Dispose();
}
}
}
}
} | MarcinKowal/SmartDom | SmartDom/SmartDom.Service/ModbusAdapters/RtuSerialModbusMaster.cs | C# | gpl-2.0 | 3,563 |
/*
* Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.glass.ui.lens;
import java.util.Map;
import com.sun.glass.ui.Pixels;
import com.sun.glass.ui.View;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.Buffer;
import com.sun.glass.events.ViewEvent;
final class LensView extends View {
protected LensView() {
super();
}
// Constants
private static long multiClickTime = 300;
private static int multiClickMaxX = 2;
private static int multiClickMaxY = 2;
// view variables
private int x;
private int y;
private long nativePtr;
protected static long _getMultiClickTime() {
if (multiClickTime == -1) {
//multiClickTime = _getMultiClickTime_impl();
//currently calling a native function is meaningless
multiClickTime = 300;
}
return multiClickTime;
}
protected static int _getMultiClickMaxX() {
if (multiClickMaxX == -1) {
//multiClickMaxX = _getMultiClickMaxX_impl();
//currently calling a native function is meaningless
multiClickMaxX = 2;
}
return multiClickMaxX;
}
protected static int _getMultiClickMaxY() {
if (multiClickMaxY == -1) {
//multiClickMaxY = _getMultiClickMaxY_impl();
//currently calling a native function is meaningless
multiClickMaxY = 2;
}
return multiClickMaxY;
}
native private void _paintInt(long ptr, int w, int h, IntBuffer ints,
int[] array, int offset);
native private void _paintByte(long ptr, int w, int h, ByteBuffer bytes,
byte[] array, int offset);
native private void _paintIntDirect(long ptr, int w, int h, Buffer buffer);
@Override
protected void _enableInputMethodEvents(long ptr, boolean enable) {
}
@Override
protected long _getNativeView(long ptr) {
//this method is a Windows hack, see View.java for more details
// we just ignore it
return ptr;
}
@Override
protected int _getX(long ptr) {
return x;
}
@Override
protected int _getY(long ptr) {
return y;
}
@Override
protected void _scheduleRepaint(long ptr) {
// native code is there but does nothing yet
//throw new UnsupportedOperationException("Not supported yet.");
LensLogger.getLogger().info("Ignoring repaint");
}
@Override protected void _uploadPixels(long nativeViewPtr, Pixels pixels) {
if (getWindow() != null) {
Buffer data = pixels.getPixels();
int width = pixels.getWidth();
int height = pixels.getHeight();
if (data.isDirect() == true) {
_paintIntDirect(nativeViewPtr, width, height, data);
} else if (data.hasArray() == true) {
if (pixels.getBytesPerComponent() == 1) {
ByteBuffer bytes = (ByteBuffer)data;
_paintByte(nativeViewPtr, width, height, bytes,
bytes.array(), bytes.arrayOffset());
} else {
IntBuffer ints = (IntBuffer)data;
int[] intArray = ints.array();
_paintInt(nativeViewPtr, width, height, ints,
intArray, ints.arrayOffset());
}
}
}
}
/**
* Events
*/
protected void _notifyMove(int x, int y) {
// used to update x,y for _getX(), _getY()
this.x = x;
this.y = y;
notifyView(ViewEvent.MOVE);
}
protected void _notifyKey(int type, int keyCode, char[] keyChars,
int modifiers) {
notifyKey(type, keyCode, keyChars, modifiers);
}
protected void _notifyMouse(int type, int button,
int x, int y, int xAbs, int yAbs, int modifiers,
boolean isPopupTrigger, boolean isSynthesized) {
notifyMouse(type, button, x, y, xAbs, yAbs, modifiers, isPopupTrigger,
isSynthesized);
}
protected void _notifyScroll(int x, int y, int xAbs, int yAbs,
double deltaX, double deltaY, int modifiers,
int lines, int chars,
int defaultLines, int defaultChars,
double xMultiplier, double yMultiplier) {
notifyScroll(x, y, xAbs, yAbs, deltaX, deltaY,
modifiers, lines, chars,
defaultLines, defaultChars, xMultiplier, yMultiplier);
}
protected void _notifyRepaint(int x, int y, int width, int height) {
notifyRepaint(x, y, width, height);
}
protected void _notifyResize(int width, int height) {
notifyResize(width, height);
}
protected void _notifyViewEvent(int viewEvent) {
notifyView(viewEvent);
}
//DnD
protected void _notifyDragEnter(int x, int y, int absx, int absy, int recommendedDropAction) {
notifyDragEnter(x, y, absx, absy, recommendedDropAction);
}
protected void _notifyDragLeave() {
notifyDragLeave();
}
protected void _notifyDragDrop(int x, int y, int absx, int absy, int recommendedDropAction) {
notifyDragDrop(x, y, absx, absy, recommendedDropAction);
}
protected void _notifyDragOver(int x, int y, int absx, int absy, int recommendedDropAction) {
notifyDragOver(x, y, absx, absy, recommendedDropAction);
}
//Menu event - i.e context menu hint (usually mouse right click)
protected void _notifyMenu(int x, int y, int xAbs, int yAbs, boolean isKeyboardTrigger) {
notifyMenu(x, y, xAbs, yAbs, isKeyboardTrigger);
}
/**
* Native methods
*/
@Override
protected long _create(Map caps) {
this.nativePtr = _createNativeView(caps);
return this.nativePtr;
}
private native long _createNativeView(Map caps);
/**
* Assuming this is used to lock the surface for painting
*/
@Override
native protected void _begin(long ptr);
/**
* Assuming this is used to unlock the surface after painting is
* done
*/
@Override
native protected void _end(long ptr);
@Override
native protected void _setParent(long ptr, long parentPtr);
@Override
native protected boolean _close(long ptr);
@Override
native protected boolean _enterFullscreen(long ptr, boolean animate,
boolean keepRatio,
boolean hideCursor);
@Override
native protected void _exitFullscreen(long ptr, boolean animate);
@Override
public String toString() {
return "LensView[nativePtr=0x" + Long.toHexString(nativePtr) + "]";
}
}
| maiklos-mirrors/jfx78 | modules/graphics/src/main/java/com/sun/glass/ui/lens/LensView.java | Java | gpl-2.0 | 8,152 |
<?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/>.
// CLAMP # 194 2010-06-23 bobpuffer
require_once '../../../config.php';
require_once $CFG->libdir.'/gradelib.php';
require_once $CFG->dirroot.'/grade/lib.php';
require_once $CFG->dirroot.'/grade/report/laegrader/lib.php';
require_once $CFG->dirroot.'/grade/report/laegrader/locallib.php'; // END OF HACK
require_js(array('yui_yahoo', 'yui_dom', 'yui_event', 'yui_container', 'yui_connection', 'yui_dragdrop', 'yui_element'));
$courseid = required_param('id', PARAM_INT); // course id
$page = optional_param('page', 0, PARAM_INT); // active page
$perpageurl = optional_param('perpage', 0, PARAM_INT);
$edit = optional_param('edit', -1, PARAM_BOOL); // sticky editting mode
$itemid = optional_param('sortitemid', 0, PARAM_ALPHANUM); // item to zerofill
$sortitemid = optional_param('sortitemid', 0, PARAM_ALPHANUM); // sort by which grade item
$action = optional_param('action', 0, PARAM_ALPHAEXT);
$move = optional_param('move', 0, PARAM_INT);
$type = optional_param('type', 0, PARAM_ALPHA);
$target = optional_param('target', 0, PARAM_ALPHANUM);
$toggle = optional_param('toggle', NULL, PARAM_INT);
$toggle_type = optional_param('toggle_type', 0, PARAM_ALPHANUM);
/// basic access checks
if (!$course = get_record('course', 'id', $courseid)) {
print_error('nocourseid');
}
require_login($course);
$context = get_context_instance(CONTEXT_COURSE, $course->id);
require_capability('gradereport/laegrader:view', $context);
require_capability('moodle/grade:viewall', $context);
/// return tracking object
$gpr = new grade_plugin_return(array('type'=>'report', 'plugin'=>'laegrader', 'courseid'=>$courseid, 'page'=>$page));
/// last selected report session tracking
if (!isset($USER->grade_last_report)) {
$USER->grade_last_report = array();
}
$USER->grade_last_report[$course->id] = 'laegrader';
/// Build editing on/off buttons
if (!isset($USER->gradeediting)) {
$USER->gradeediting = array();
}
if (has_capability('moodle/grade:edit', $context)) {
if (!isset($USER->gradeediting[$course->id])) {
$USER->gradeediting[$course->id] = 0;
}
if (($edit == 1) and confirm_sesskey()) {
$USER->gradeediting[$course->id] = 1;
} else if (($edit == 0) and confirm_sesskey()) {
$USER->gradeediting[$course->id] = 0;
}
// page params for the turn editting on
$options = $gpr->get_options();
$options['sesskey'] = sesskey();
// allow for always editing config
if (get_user_preferences('grade_report_gradeeditalways')) {
$USER->gradeediting[$course->id] = 1;
} else {
if ($USER->gradeediting[$course->id]) {
$options['edit'] = 0;
$string = get_string('turneditingoff');
} else {
$options['edit'] = 1;
$string = get_string('turneditingon');
}
$buttons = print_single_button('index.php', $options, $string, 'get', '_self', true);
}
} else {
$USER->gradeediting[$course->id] = 0;
$buttons = '';
}
$gradeserror = array();
//first make sure we have proper final grades - this must be done before constructing of the grade tree
grade_regrade_final_grades($courseid);
$reportname = get_string('modulename', 'gradereport_laegrader');
// Initialise the grader report object
$report = new grade_report_laegrader($courseid, $gpr, $context, $page, $sortitemid); // END OF HACK
// make sure separate group does not prevent view
if ($report->currentgroup == -2) {
print_grade_page_head($COURSE->id, 'report', 'laegrader', $reportname, false, null, $buttons);
print_heading(get_string("notingroup"));
print_footer($course);
exit;
}
/// processing posted grades & feedback here
if ($data = data_submitted() and confirm_sesskey() and has_capability('moodle/grade:edit', $context)) {
$warnings = $report->process_data($data);
} else {
$warnings = array();
}
// final grades MUST be loaded after the processing
$report->load_users();
$numusers = $report->get_numusers();
$report->load_final_grades();
// AT THIS POINT WE HAVE ACCURATE GRADES FOR DISPLAY
if ($action === 'quick-dump') {
$report->quick_dump();
} elseif ($action === 'zerofill' && !is_null($itemid)) {
/// bunch of code here
echo '';
foreach ($report->grades as $usergrades) {
}
}
/// Print header
print_grade_page_head($COURSE->id, 'report', 'laegrader', $reportname, false, null, $buttons);
echo $report->group_selector;
echo '<div class="clearer"></div>';
// echo $report->get_toggles_html();
//show warnings if any
foreach($warnings as $warning) {
notify($warning);
}
$studentsperpage = 0;
/// because our names aren't a separate fixed table we eliminate altogether need for get_studentnameshtml()
//$reporthtml .= $report->get_studentnameshtml();
$reporthtml = '<br /><table id="user-grades" class="gradestable flexible boxaligncenter generaltable"><tbody>';
$reporthtml .= $report->get_headerhtml();
// need to add a class to the icons so they can be differientiated in css
//$reporthtml .= $report->get_iconshtml();
$reporthtml .= str_replace('iconsmall','iconsmall iconcenter',$report->get_iconshtml());
$reporthtml .= $report->get_rangehtml();
$reporthtml .= $report->get_avghtml(true);
$reporthtml .= $report->get_avghtml();
$reporthtml .= $report->get_studentshtml();
$reporthtml .= $report->get_endhtml();
// this report doesn't need a closing div tag
//$reporthtml .= '</div>';
$headerrows = ($USER->gradeediting[$courseid]) ? 2 : 1;
$headerrows += ($report->get_pref('showaverages')) ? 1 : 0;
$headerrows += ($report->get_pref('showranges')) ? 1 : 0;
$headercols = ($report->get_pref('showuseridnumber')) ? 3 : 2;
$scrolling = get_user_preferences('grade_report_laegraderreportheight');
$scrolling = $scrolling == null ? 380 : 300 + ($scrolling * 40);
$headerinit = "fxheaderInit('user-grades', $scrolling," . $headerrows . ',' . $headercols . ');';
$reporthtml .=
'<script src="' . $CFG->wwwroot . '/grade/report/laegrader/fxHeader_0.3.min.js" type="text/javascript"></script>
<script type="text/javascript">' .$headerinit . 'fxheader(); </script>';
$reporthtml .=
'<script src="' . $CFG->wwwroot . '/grade/report/laegrader/jquery-1.4.2.min.js" type="text/javascript"></script>';
$reporthtml .=
'<script src="' . $CFG->wwwroot . '/grade/report/laegrader/my_jslib.js" type="text/javascript"></script>';
// print submit button
if ($USER->gradeediting[$course->id]) {
echo '<form name="gradesedit" action="index.php" method="post">';
echo '<div>';
echo '<input type="hidden" value="'.$courseid.'" name="id" />';
echo '<input type="hidden" value="'.sesskey().'" name="sesskey" />';
echo '<input type="hidden" value="grader" name="report"/>';
}
echo $reporthtml;
// print submit button
if ($USER->gradeediting[$course->id] && ($report->get_pref('showquickfeedback') || $report->get_pref('quickgrading'))) {
echo '<div class="submit"><input type="submit" value="'.get_string('update').'" /></div>';
echo '</div></form>';
}
// prints paging bar at bottom for large pages
if (!empty($studentsperpage) && $studentsperpage >= 20) {
print_paging_bar($numusers, $report->page, $studentsperpage, $report->pbarurl);
}
print_footer($course);
// CLAMP # 194 2010-06-23 end
?>
| bobpuffer/1.9.12-LAE1.3 | grade/report/laegrader/index.php | PHP | gpl-2.0 | 8,012 |
jQuery.noConflict();
jQuery(document).ready(function(){
/**
* This will remove username/password text in the login form fields
**/
jQuery('.username, .password').focusout(function(){
if(jQuery(this).val() != '') {
jQuery(this).css({backgroundPosition: "0 -32px"});
} else {
jQuery(this).css({backgroundPosition: "0 0"});
}
});
jQuery('.username, .password').focusin(function(){
if(jQuery(this).val() == '') {
jQuery(this).css({backgroundPosition: "0 -32px"});
}
});
/**
* Message Notify Drop Down
**/
jQuery('.messagenotify .wrap, .alertnotify .wrap').click(function(){
var t = jQuery(this).parent();
var url = t.attr('href');
if(t.hasClass('showmsg')) {
t.removeClass('showmsg');
t.find('.thicon').removeClass('thiconhover');
t.parent().find('.dropbox').remove();
} else {
jQuery('.topheader li').each(function(){
jQuery(this).find('.showmsg').removeClass('showmsg');
jQuery(this).find('.thicon').removeClass('thiconhover');
jQuery(this).find('.dropbox').remove();
});
t.addClass('showmsg');
t.find('.thicon').addClass('thiconhover');
t.parent().append('<div class="dropbox"></div>');
jQuery.post(url,function(data){
jQuery('.dropbox').append(data);
});
}
return false;
});
jQuery(document).click(function(event) {
var msglist = jQuery('.dropbox');
if(!jQuery(event.target).is('.dropbox')) {
if(msglist.is(":visible")) {
msglist.prev().removeClass('showmsg');
msglist.prev().find('.thicon').removeClass('thiconhover');
msglist.remove();
}
}
});
/**
* Login form validation
**/
jQuery('#loginform').submit(function(){
var username = jQuery('.username').val();
var password = jQuery('.password').val();
if(username == '' && password == '') {
jQuery('.loginNotify').slideDown('fast');
return false;
} else {
return true;
}
});
/**
* Sidebar accordion
**/
jQuery('#accordion h3').click(function() {
if(jQuery(this).hasClass('open')) {
jQuery(this).removeClass('open');
jQuery(this).next().slideUp('fast');
} else {
jQuery(this).addClass('open');
jQuery(this).next().slideDown('fast');
} return false;
});
/**
* Widget Box Toggle
**/
jQuery('.widgetbox h3, .widgetbox2 h3').hover(function(){
jQuery(this).addClass('arrow');
return false;
},function(){
jQuery(this).removeClass('arrow');
return false;
});
jQuery('.widgetbox h3, .widgetbox2 h3').toggle(function(){
jQuery(this).next().slideUp('fast');
jQuery(this).css({MozBorderRadius: '3px',
WebkitBorderRadius: '3px',
borderRadius: '3px'});
return false;
},function(){
jQuery(this).next().slideDown('fast');
jQuery(this).css({MozBorderRadius: '3px 3px 0 0',
WebkitBorderRadius: '3px 3px 0 0',
borderRadius: '3px 3px 0 0'});
return false;
});
/**
* Notification
**/
jQuery('.notification .close').click(function(){
jQuery(this).parent().fadeOut();
});
/** Make footer always at the bottom**/
if(jQuery('body').height() > jQuery(window).height()) {
jQuery('.footer').removeClass('footer_float');
}
/**DROP DOWN MENU**/
jQuery(".subnav").css({display: "none"}); // Opera Fix
jQuery(".tabmenu li").hover(function(){
jQuery(this).find('ul:first').css({visibility: "visible",display: "none"}).show(400);
},function(){
jQuery(this).find('ul:first').css({visibility: "hidden"});
});
}); | berryjace/www | crm/assets/docs/theme/template/js/custom/general.js | JavaScript | gpl-2.0 | 3,455 |
<?php
//
// +----------------------------------------------------------------------+
// |zen-cart Open Source E-commerce |
// +----------------------------------------------------------------------+
// | Copyright (c) 2003 The zen-cart developers |
// | |
// | http://www.zen-cart.com/index.php |
// | |
// | Portions Copyright (c) 2003 osCommerce |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the GPL license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available through the world-wide-web at the following url: |
// | http://www.zen-cart.com/license/2_0.txt. |
// | If you did not receive a copy of the zen-cart license and are unable |
// | to obtain it through the world-wide-web, please send a note to |
// | license@zen-cart.com so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// $Id: shippinginfo.php 1969 2005-09-13 06:57:21Z drbyte $
//
define('NAVBAR_TITLE', 'Livraisons & Retours');
define('HEADING_TITLE', 'Livraisons & Retours');
define('TEXT_INFORMATION', 'Vos conditions de livraison et de retour devraient être ici');
?> | EasyLovine/ZencTbi | includes/languages/french/shippinginfo.php | PHP | gpl-2.0 | 1,565 |
module NavigationHelper
def page_links_for_navigation
link = Struct.new(:name, :url)
[link.new("Home", root_path),
link.new("Archives", archives_path)] +
Page.order('title').collect { |page| link.new(page.title, page_path(page.slug)) }
end
def category_links_for_navigation
link = Struct.new(:name, :url)
@popular_tags ||= Tag.all.reject { |tag| tag.taggings.empty? }.sort_by { |tag| tag.taggings.size }.reverse
@popular_tags.collect { |tag| link.new(tag.name, posts_path(:tag => tag.name)) }
end
def class_for_tab(tab_name, index)
classes = []
classes << 'current' if "admin/#{tab_name.downcase}" == params[:controller]
classes << 'first' if index == 0
classes.join(' ')
end
end
| JohnnyBurst/enkyish | app/helpers/navigation_helper.rb | Ruby | gpl-2.0 | 743 |
package org.inspire.guide.metadata;
import java.util.ArrayList;
import java.util.List;
/**
* Actions that can be performed within the
* Bukkit scheduler framework.
* <p/>
* These actions are self-contained, so when run() is
* executed, any action that will be performed does NOT require
* any additional outside information.
* <p/>
* User: InspiredIdealist
* Date: 1/11/14
*/
public abstract class Action implements Runnable {
private static List<Action> ACTIONS_AVAILABLE = new ArrayList<Action>();
private Type type;
private String description;
public Action(Type type, String description) {
this.type = type;
this.description = description;
ACTIONS_AVAILABLE.add(this); //May need to place this elsewhere. But this should work for now.
}
public Type getType() {
return type;
}
@Override
public abstract String toString();
public String getDescription() {
return description;
}
public static List<Action> getActionsAvailable() {
return ACTIONS_AVAILABLE;
}
/**
* Flag that denotes whether or not the rule can execute without
* the user specifying it.
*
* @return true if it is autonomous, false if not
*/
public abstract boolean isAutonomous();
/**
* The action to run. Call this to do the action.
*/
public abstract void run();
}
| InspiredIdealist/Trace-Framework | src/main/java/org/inspire/guide/metadata/Action.java | Java | gpl-2.0 | 1,404 |
<?php
/**
* Kunena Component
* @package Kunena.Framework
* @subpackage Forum.Message.Attachment
*
* @copyright (C) 2008 - 2015 Kunena Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
* @link http://www.kunena.org
**/
defined ( '_JEXEC' ) or die ();
/**
* Class KunenaAttachment
*
* @property int $id
* @property int $userid
* @property int $mesid
* @property int $protected
* @property string $hash
* @property int $size
* @property string $folder
* @property string $filetype
* @property string $filename
* @property string $filename_real
* @property string $caption
*
* @property int $width Image width (0 for non-images).
* @property int $height Image height (0 for non-images).
*
* @since K4.0
*/
class KunenaAttachment extends KunenaDatabaseObject
{
/**
* @var int
*/
public $id = null;
protected $_table = 'KunenaAttachments';
protected $path;
protected $width;
protected $height;
protected $shortname;
/**
* @var bool
*/
public $disabled = false;
protected static $_directory = 'media/kunena/attachments';
protected static $actions = array(
'read'=>array('Read'),
'createimage'=>array(),
'createfile'=>array(),
'delete'=>array('Exists', 'Own'),
);
/**
* @param mixed $identifier
* @param bool $reload
*
* @return KunenaAttachment
*
* @since K4.0
*/
public static function getInstance($identifier = null, $reload = false)
{
return KunenaAttachmentHelper::get($identifier, $reload);
}
/**
* Destructor deletes the files from the filesystem if attachment isn't stored in database.
*
* @since K4.0
*/
public function __destruct()
{
if (!$this->exists())
{
$this->deleteFile();
}
}
/**
* Getter function.
*
* @param string $property
*
* @return string
* @throws InvalidArgumentException
*
* @since K4.0
*/
public function __get($property)
{
if ($this->width == null)
{
$this->initialize();
}
switch ($property)
{
case 'width':
return $this->width;
case 'height':
return $this->height;
}
throw new InvalidArgumentException(sprintf('Property "%s" is not defined', $property));
}
/**
* Check if attachment is image.
*
* @return bool True if attachment is image.
*
* @since K4.0
*/
public function isImage()
{
return (stripos($this->filetype, 'image/') !== false);
}
/**
* Get path for the file.
*
* @param bool $thumb
*
* @return string|false Path to the file or false if file doesn't exist.
*
* @since K4.0
*/
public function getPath($thumb = false)
{
if ($thumb)
{
$path = JPATH_ROOT . "/{$this->folder}/thumb/{$this->filename}";
$path = is_file($path) ? $path : false;
}
else
{
$path = JPATH_ROOT . "/{$this->folder}/{$this->filename}";
$path = is_file($path) ? $path : false;
}
return $path;
}
/**
* Get filename for output.
*
* @param bool $escape
*
* @return string
*
* @since K4.0
*/
public function getFilename($escape = true)
{
$filename = $this->protected ? $this->filename_real : $this->filename;
return $escape ? htmlspecialchars($filename, ENT_COMPAT, 'UTF-8') : $filename;
}
/**
* Get extension of file for output.
*
* @param bool $escape
*
* @return string
*
* @since K4.0
*/
public function getExtension($escape = true)
{
$filename = $this->protected ? $this->filename_real : $this->filename;
$extension = pathinfo($filename, PATHINFO_EXTENSION);
return $escape ? htmlspecialchars($extension, ENT_COMPAT, 'UTF-8') : $extension;
}
/**
* This function shortens long filenames for display purposes.
*
* The first 8 characters of the filename, followed by three dots and the last 5 character of the filename.
*
* @param int $front
* @param int $back
* @param string $filler
* @param bool $escape
*
* @return string
*
* @since K4.0
*/
public function getShortName($front = 10, $back = 8, $filler = '...', $escape = true)
{
if ($this->shortname === null)
{
$this->shortname = KunenaAttachmentHelper::shortenFileName($this->getFilename(false), $front, $back, $filler);
}
return $escape ? htmlspecialchars($this->shortname, ENT_COMPAT, 'UTF-8') : $this->shortname;
}
/**
* Get URL pointing to the attachment.
*
* @param bool $thumb
* @param bool $inline
* @param bool $escape
*
* @return string
*
* @since K4.0
*/
public function getUrl($thumb = false, $inline = true, $escape = true)
{
$protect = (bool) KunenaConfig::getInstance()->attachment_protection;
// Use direct URLs to the attachments if protection is turned off and file wasn't protected.
if (!$protect && !$this->protected)
{
$file = $this->folder . '/' . $this->filename;
$fileThumb = $this->folder . '/thumb/' . $this->filename;
if (!is_file(JPATH_ROOT . '/' . $fileThumb))
{
$fileThumb = $file;
}
$url = ($thumb ? $fileThumb : $file);
return $escape ? htmlspecialchars($url, ENT_COMPAT, 'UTF-8') : $url;
}
// Route attachment through Kunena.
$thumb = $thumb ? '&thumb=1' : '';
$download = $inline ? '' : '&download=1';
$filename = urlencode($this->getFilename(false));
return KunenaRoute::_("index.php?option=com_kunena&view=attachment&id={$this->id}{$thumb}{$download}&format=raw", $escape);
}
/**
* Get attachment layout.
*
* @return KunenaLayout
*/
public function getLayout()
{
return KunenaLayout::factory('Attachment/Item')->set('attachment', $this);
}
/**
* @return string
* @deprecated K4.0
*/
public function getTextLink()
{
return (string) KunenaLayout::factory('Attachment/Item')->set('attachment', $this)->setLayout('textlink');
}
/**
* @return string
* @deprecated K4.0
*/
public function getImageLink()
{
return $this->isImage()
? (string) KunenaLayout::factory('Attachment/Item')->set('attachment', $this)->setLayout('image') : null;
}
/**
* @return string
* @deprecated K4.0
*/
public function getThumbnailLink()
{
return (string) KunenaLayout::factory('Attachment/Item')->set('attachment', $this)->setLayout('thumbnail');
}
/**
* Get message to which attachment has been attached into.
*
* NOTE: Returns message object even if there isn't one. Please call $message->exists() to check if it exists.
*
* @return KunenaForumMessage
*
* @since K4.0
*/
public function getMessage()
{
return KunenaForumMessageHelper::get($this->mesid);
}
/**
* Get author of the attachment.
*
* @return KunenaUser
*
* @since K4.0
*/
public function getAuthor()
{
return KunenauserHelper::get($this->userid);
}
/**
* Returns true if user is authorised to do the action.
*
* @param string $action
* @param KunenaUser $user
*
* @return bool
*
* @since K4.0
*/
public function isAuthorised($action = 'read', KunenaUser $user = null)
{
return !$this->tryAuthorise($action, $user, false);
}
/**
* Throws an exception if user isn't authorised to do the action.
*
* @param string $action
* @param KunenaUser $user
* @param bool $throw
*
* @return KunenaExceptionAuthorise|null
* @throws KunenaExceptionAuthorise
* @throws InvalidArgumentException
*
* @since K4.0
*/
public function tryAuthorise($action = 'read', KunenaUser $user = null, $throw = true)
{
// Special case to ignore authorisation.
if ($action == 'none')
{
return null;
}
// Load user if not given.
if ($user === null)
{
$user = KunenaUserHelper::getMyself();
}
// Unknown action - throw invalid argument exception.
if (!isset(self::$actions[$action]))
{
throw new InvalidArgumentException(JText::sprintf('COM_KUNENA_LIB_AUTHORISE_INVALID_ACTION', $action), 500);
}
// Load message authorisation.
$exception = $this->getMessage()->tryAuthorise('attachment.'.$action, $user, false);
// Check authorisation.
if (!$exception)
{
foreach (self::$actions[$action] as $function)
{
$authFunction = 'authorise'.$function;
$exception = $this->$authFunction($user);
if ($exception) break;
}
}
// Throw or return the exception.
if ($throw && $exception)
{
throw $exception;
}
return $exception;
}
/**
* @param string $action
* @param mixed $user
* @param bool $silent
*
* @return bool
* @deprecated K4.0
*/
public function authorise($action='read', $user=null, $silent=false)
{
if ($user === null)
{
$user = KunenaUserHelper::getMyself();
}
elseif (!($user instanceof KunenaUser))
{
$user = KunenaUserHelper::get($user);
}
$exception = $this->tryAuthorise($action, $user, false);
if ($silent === false && $exception)
{
$this->setError($exception->getMessage());
}
if ($silent !== null)
{
return !$exception;
}
return $exception ? $exception->getMessage() : null;
}
/**
* @param string $key
* @param null|int $catid
*
* @return bool
*
* @since K4.0
*/
function upload($key = 'kattachment', $catid = null)
{
jimport( 'joomla.filesystem.folder' );
$config = KunenaFactory::getConfig();
$input = JFactory::getApplication()->input;
$fileInput = $input->files->get($key);
$upload = KunenaUpload::getInstance(KunenaAttachmentHelper::getExtensions($catid, $this->userid));
$uploadBasePath = JPATH_ROOT . '/media/kunena/attachments/' . $this->userid . '/';
if ( !JFolder::exists($uploadBasePath) )
{
mkdir(JPATH_ROOT . '/media/kunena/attachments/' . $this->userid . '/');
}
$upload->splitFilename($fileInput['name']);
$fileInput['name'] = preg_replace('/[[:space:]]/', '',$fileInput['name']);
$fileNameWithoutExt = JFile::stripExt($fileInput['name']);
$fileExt = JFile::getExt($fileInput['name']);
$fileNameWithExt = $fileInput['name'];
if (file_exists($uploadBasePath . $fileInput['name'])) {
for ($i=2; file_exists($uploadBasePath . $fileNameWithoutExt . '.' . $fileExt); $i++) {
$fileNameWithoutExt = $fileNameWithoutExt . "-$i";
$fileNameWithExt = $fileNameWithoutExt. '.' . $fileExt;
}
}
$fileInput['name'] = $fileNameWithExt;
$file = $upload->upload($fileInput, $uploadBasePath . $fileNameWithoutExt);
if ($file->success)
{
if ( extension_loaded('fileinfo') )
{
$finfo = new finfo(FILEINFO_MIME);
$type = $finfo->file($uploadBasePath . $fileNameWithExt);
}
else
{
$info = getimagesize($uploadBasePath . $fileNameWithExt);
$type = $info['mime'];
}
if (stripos($type, 'image/') !== false)
{
$imageInfo = KunenaImage::getImageFileProperties($uploadBasePath . $fileNameWithExt);
if (number_format($file->size / 1024, 2) > $config->imagesize || $imageInfo->width > $config->imagewidth || $imageInfo->height > $config->imageheight)
{
// Calculate quality for both JPG and PNG.
$quality = $config->imagequality;
if ($quality < 1 || $quality > 100)
{
$quality = 70;
}
if ($imageInfo->type == IMAGETYPE_PNG)
{
$quality = intval(($quality - 1) / 10);
}
$options = array('quality' => $quality);
try
{
$image = new KunenaImage($uploadBasePath . $fileNameWithExt);
$image = $image->resize($config->imagewidth, $config->imagewidth, false);
$image->toFile($uploadBasePath . $fileNameWithExt, $imageInfo->type, $options);
unset($image);
}
catch (Exception $e)
{
// TODO: better error message.
echo $e->getMessage();
return false;
}
}
$this->filetype = $imageInfo->mime;
}
$this->protected = (bool) $config->attachment_protection;
$this->hash = md5_file($uploadBasePath . $fileNameWithExt);
$this->size = $file->size;
$this->folder = 'media/kunena/attachments/' . $this->userid;
$this->filename = $fileInput['name'];
$this->filename_real = $uploadBasePath . $fileNameWithExt;
$this->caption = '';
return true;
}
}
/**
* Set attachment file.
*
* Copies the attachment into proper location and makes sure that all the unset fields get properly assigned.
*
* @param string $source Absolute path to the upcoming attachment.
* @param string $basename Filename without extension.
* @param string $extension File extension.
* @param bool $unlink Whether to delete the original file or not.
* @param bool $overwrite If not allowed, throw exception if the file exists.
*
* @return bool
* @throws InvalidArgumentException
* @throws RuntimeException
*
* @since K4.0
*/
public function saveFile($source, $basename = null, $extension = null, $unlink = false, $overwrite = false)
{
if (!is_file($source))
{
throw new InvalidArgumentException(__CLASS__.'::'.__METHOD__.'(): Attachment file not found.');
}
// Hash, size and MIME are set during saving, so let's deal with all other variables.
$this->userid = is_null($this->userid) ? KunenaUserHelper::getMyself() : $this->userid;
$this->folder = is_null($this->folder) ? "media/kunena/attachments/{$this->userid}" : $this->folder;
$this->protected = is_null($this->protected) ? (bool) KunenaConfig::getInstance()->attachment_protection : $this->protected;
if (!$this->filename_real)
{
$this->filename_real = $this->filename;
}
if (!$this->filename || $this->filename == $this->filename_real)
{
if (!$basename || !$extension)
{
throw new InvalidArgumentException(__CLASS__.'::'.__METHOD__.'(): Parameters $basename or $extension not provided.');
}
// Find available filename.
$this->filename = KunenaAttachmentHelper::getAvailableFilename(
$this->folder, $basename, $extension, $this->protected
);
}
// Create target directory if it does not exist.
if (!KunenaFolder::exists(JPATH_ROOT . "/{$this->folder}") && !KunenaFolder::create(JPATH_ROOT . "/{$this->folder}"))
{
throw new RuntimeException(JText::_('Failed to create attachment directory.'));
}
$destination = JPATH_ROOT . "/{$this->folder}/{$this->filename}";
// Move the file into the final location (if not already in there).
if ($source != $destination)
{
// Create target directory if it does not exist.
if (!$overwrite && is_file($destination))
{
throw new RuntimeException(JText::sprintf('Attachment %s already exists.'), $this->filename_real);
}
if ($unlink)
{
@chmod($source, 0644);
}
$success = KunenaFile::copy($source, $destination);
if (!$success)
{
throw new RuntimeException(JText::sprintf('COM_KUNENA_UPLOAD_ERROR_NOT_MOVED', $destination));
}
KunenaPath::setPermissions($destination);
if ($unlink)
{
unlink($source);
}
}
return $this->save();
}
// Internal functions
/**
* @internal
* @since K4.0
*/
protected function initialize()
{
$path = $this->getPath();
if ($path && $this->isImage())
{
list($this->width, $this->height) = getimagesize($path);
}
else
{
$this->width = $this->height = 0;
}
}
/**
* @internal
* @since K4.0
*/
protected function deleteFile()
{
if (self::$_directory != substr($this->folder, 0, strlen(self::$_directory)))
{
return;
}
$path = JPATH_ROOT . "/{$this->folder}";
$filename = $path.'/'.$this->filename;
if (is_file($filename))
{
KunenaFile::delete($filename);
}
$filename = $path.'/raw/'.$this->filename;
if (is_file($filename))
{
KunenaFile::delete($filename);
}
$filename = $path.'/thumb/'.$this->filename;
if (is_file($filename))
{
KunenaFile::delete($filename);
}
}
/**
* @param KunenaUser $user
*
* @return KunenaExceptionAuthorise|null
*
* @since K4.0
*/
protected function authoriseExists(KunenaUser $user)
{
// Checks if attachment exists
if (!$this->exists())
{
return new KunenaExceptionAuthorise(JText::_('COM_KUNENA_ATTACHMENT_NO_ACCESS'), 404);
}
return null;
}
/**
* @param KunenaUser $user
*
* @return KunenaExceptionAuthorise|null
*
* @since K4.0
*/
protected function authoriseRead(KunenaUser $user)
{
// Checks if attachment exists
if (!$this->exists())
{
return new KunenaExceptionAuthorise(JText::_('COM_KUNENA_ATTACHMENT_NO_ACCESS'), 404);
}
if (!$user->exists())
{
$config = KunenaConfig::getInstance();
if ($this->isImage() && !$config->showimgforguest)
{
return new KunenaExceptionAuthorise(JText::_('COM_KUNENA_SHOWIMGFORGUEST_HIDEIMG'), 401);
}
if (!$this->isImage() && !$config->showfileforguest)
{
return new KunenaExceptionAuthorise(JText::_('COM_KUNENA_SHOWIMGFORGUEST_HIDEFILE'), 401);
}
}
return null;
}
/**
* @param KunenaUser $user
*
* @return KunenaExceptionAuthorise|null
*
* @since K4.0
*/
protected function authoriseOwn(KunenaUser $user)
{
// Checks if attachment is users own or user is moderator in the category (or global)
if (($user->userid && $this->userid != $user->userid) && !$user->isModerator($this->getMessage()->getCategory()))
{
return new KunenaExceptionAuthorise(JText::_('COM_KUNENA_ATTACHMENT_NO_ACCESS'), 403);
}
return null;
}
}
| ytsebro/slavic | libraries/kunena/attachment/attachment.php | PHP | gpl-2.0 | 17,808 |
<?php get_header(); ?>
<section id="primary" class="hfeed">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<section id="single-wrapper">
<article <?php post_class() ?> id="post-<?php the_ID(); ?>">
<h1 class="entry-title"><?php the_title(); ?></h1>
<div class="entry-meta entry-header">
<span class="author"><?php the_author_posts_link(); ?></span>
<span class="meta-sep"> | </span>
<span class="published"><?php if( date('Yz') == get_the_time('Yz') ) {echo 'Сегодня';} else { the_time( get_option('date_format') );}; ?></span>
<span class="meta-sep"> | </span>
<span class="entry-categories"><?php the_category(', ') ?></span>
<?php edit_post_link( __('edit', 'estete'), '<span class="edit-post">[', ']</span>' ); ?>
</div>
<div class="entry-meta1">
<span class="comment-count"><?php comments_number('0', '1', '%'); ?></span>
<span class="meta-sep"> | </span>
<span class="views-count"><?php if(function_exists('the_views')) { the_views(); } ?></span>
<span class="meta-sep"> | </span>
<span class="votes-count"><?php $ThumbUpID = 'post_'.get_the_ID(); echo ThumbsUp::item($ThumbUpID)->votes_balance; ?></span>
<div id="social_button-top">
<noindex>
<div id="bt_vk">
<div id="vk_like-1"></div>
<script type="text/javascript">
VK.Widgets.Like("vk_like-1", {type: "mini"});
</script>
</div>
<div id="bt_twitter">
<a href="http://twitter.com/share" class="twitter-share-button" data-via="estete_net" data-lang="en">>Tweet</a>
</div>
<div id="bt_plusone">
<div class="g-plusone" data-size="medium" data-href="<?php the_permalink() ?>"></div>
</div>
<div id="bt_facebookr">
<iframe src="http://www.facebook.com/plugins/like.php?href=<?php the_permalink() ?>&layout=button_count&show_faces=true&width=82&action=like&font=arial&colorscheme=light&height=21&locale=en_US" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:82px; height:21px;" allowTransparency="true"></iframe>
</div>
</noindex>
</div>
</div>
<?php if ($e_insert_image == "true") { ?>
<?php
if ( (function_exists('has_post_thumbnail')) && (has_post_thumbnail()) ) { ?>
<div class="post-thumb-single">
<?php the_post_thumbnail('thumbnail-lead',array('title' => "")); ?>
</div>
<?php } } ?>
<div class="entry-content">
<?php the_content(); ?>
<?php wp_link_pages(array('before' => '<p><strong>'.__('Pages:', 'estete').'</strong> ', 'after' => '</p>', 'next_or_number' => 'number')); ?>
<div id="tags">
<span class="tags"><strong>Теги:</strong></span> <?php the_tags('', ', ', ''); ?>
</div>
<div class="thumbsup-single">
<?php $ThumbUpID = 'post_'.get_the_ID(); echo ThumbsUp::item($ThumbUpID)->template('up_down')->options('align=right'); ?>
</div>
</div>
<div id="social_button-bottom">
<noindex>
<div id="bt_vk">
<div id="vk_like-2"></div>
<script type="text/javascript">
VK.Widgets.Like("vk_like-2", {type: "mini"});
</script>
</div>
<div id="bt_twitter">
<a href="http://twitter.com/share" class="twitter-share-button" data-via="estete_net" data-lang="en">Tweet</a>
</div>
<div id="bt_plusone">
<div class="g-plusone" data-size="medium" data-href="<?php the_permalink() ?>"></div>
</div>
<div id="bt_facebookr">
<iframe src="http://www.facebook.com/plugins/like.php?href=<?php the_permalink() ?>&layout=button_count&show_faces=true&width=82&action=like&font=arial&colorscheme=light&height=21&locale=en_US" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:82px; height:21px;" allowTransparency="true"></iframe>
</div>
<div id="yandex_share">
<script type="text/javascript" src="//yandex.st/share/share.js" charset="utf-8"></script>
<div class="yashare-auto-init" data-yashareL10n="ru" data-yashareType="none" data-yashareQuickServices="vkontakte,facebook,moimir,lj"></div>
</div>
</noindex>
</div>
<div id="related-posts" class="clearfix">
<?php
$backup = $post;
$categories = get_the_category($post->ID);
if ($categories) {
$category_ids = array();
foreach($categories as $individual_category) $category_ids[] = $individual_category->term_id;
$args=array(
'category__in' => $category_ids,
'post__not_in' => array($post->ID),
'showposts'=> 4,
'orderby'=> rand,
'caller_get_posts'=>1
);
$related_posts = new wp_query($args);
if( $related_posts->have_posts() ) { ?>
<h3 class="widget-title">Интересные посты:</h3>
<?php while ($related_posts->have_posts()) {
$related_posts->the_post();?>
<div class="post-container">
<?php if ( (function_exists('has_post_thumbnail')) && (has_post_thumbnail()) ) { ?>
<div class="overlay_zoom">
<?php the_post_thumbnail('thumbnail-related',array('title' => "")); ?>
<div class="overlay_zoom_mask">
<a class="zoom_link" href="<?php the_permalink(); ?>"></a>
</div>
</div>
<div class="post-title">
<p><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</div>
<?php } ?>
</div>
<?php
}
}
}
$post = $backup;
wp_reset_query();
?>
</div>
</article>
<nav class="post-navigation clearfix">
<?php
$prev_post = get_adjacent_post(false, '', true);
$next_post = get_adjacent_post(false, '', false); ?>
<?php if ($prev_post) : $prev_post_url = get_permalink($prev_post->ID); $prev_post_title = $prev_post->post_title; ?>
<a class="post-prev" href="<?php echo $prev_post_url; ?>"><em>Предыдущий пост</em><span><?php echo $prev_post_title; ?></span></a>
<?php endif; ?>
<?php if ($next_post) : $next_post_url = get_permalink($next_post->ID); $next_post_title = $next_post->post_title; ?>
<a class="post-next" href="<?php echo $next_post_url; ?>"><em>Следующий пост</em><span><?php echo $next_post_title; ?></span></a>
<?php endif; ?>
</nav>
</section>
<?php comments_template('', true); ?>
<?php endwhile; else: ?>
<article id="post-0" <?php post_class() ?>>
<h1 class="entry-title"><?php _e('Error 404 - Not Found', 'estete') ?></h1>
<div class="entry-content">
<p><?php _e("Sorry, but you are looking for something that isn't here.", "framework") ?></p>
<?php get_search_form(); ?>
</div>
</article>
<?php endif; ?>
</section>
<?php include( TEMPLATEPATH . '/sidebar-single.php' ); ?>
<?php get_footer(); ?> | yenbekbay/estete | theme/single.php | PHP | gpl-2.0 | 6,353 |
package ComputationalServer.ServerCore;
import java.io.IOException;
import java.net.Socket;
import GenericCommonClasses.GenericProtocol;
/**
* <p>
* ConnectionEstabilisherThread is responsible for asynchronous connection
* estabilishment and asynchronous message retrieval.
* </p>
* <p>
* Retrieved message is put into message queue and processes by other
* ComputationalServer threads.
* </p>
*
* @author Piotr Waszkiewicz
* @version 1.0
*
*/
class ConnectionEstabilisherThread extends Thread
{
/******************/
/* VARIABLES */
/******************/
ComputationalServerCore core;
/******************/
/* FUNCTIONS */
/******************/
/**
* <p>
* Create ConnectionEstabilisherThread with reference to server core.
* </p>
*
* @param core
*/
ConnectionEstabilisherThread(ComputationalServerCore core)
{
super();
this.core = core;
}
@Override
public void run()
{
while (true)
{
try
{
Socket clientSocket = core.serverSocket.accept();
retrieveClientMessage(clientSocket);
}
catch (IOException e)
{
}
}
}
private void retrieveClientMessage(final Socket clientSocket)
{
// Start procedure in new thread to not block other connections
new Thread(new Runnable()
{
@Override
public void run()
{
try
{
core.messageQueue.add(new ClientMessage(GenericProtocol
.receiveMessage(clientSocket), clientSocket));
core.queueSemaphore.release();
}
catch (IOException e)
{
}
// do not close input stream here
// it should be done in message parsing routine!
}
}).start();
}
}
| Waszker/IO_projekt | ComputationalCluster/src/ComputationalServer/ServerCore/ConnectionEstabilisherThread.java | Java | gpl-2.0 | 1,621 |
<?
/*
DATE CREATED : 05/09/07
LAST MODIFIED: 14/11/08 - rahadi
10/10/09 - rahadi (publikasi tidak harus ada penelitian)
10/10/09 - rahadi (publikasi tidak harus ada penelitian)
01/06/10 - rahadi (penambahan frm_tgl_publikasi2)
KEGUNAAN : ENTRY SURAT TUGAS PUBLIKASI
VARIABEL : $act adalah untuk menentukan action yang akan dilakukan. 1: simpan; 2: hapus; 3:batal;
*/
session_start();
include("../include/js_function.js");
require("../include/global.php");
require("../include/fungsi.php");
f_connecting();
mysql_select_db($DB);
if ($act==1)
{ // simpan data
// Pemeriksaan tanggal, apakah tanggal yang dimasukkan valid
//echo "<br>frm_tgl_go_A=".$frm_tgl_go;
if ($frm_tgl_go!='')
{
if (datetomysql($frm_tgl_go))
{
$frm_tgl_go = datetomysql($frm_tgl_go);
}
else
{
$error = 1;
$pesan = $pesan."Tanggal Berangkat tidak valid";
}
}
//echo "<br>frm_tgl_go_B=".$frm_tgl_go;
if ($frm_tgl_dtg!='')
{
if (datetomysql($frm_tgl_dtg))
{
$frm_tgl_dtg = datetomysql($frm_tgl_dtg);
}
else
{
$error = 1;
$pesan = $pesan."Tanggal Kembali tidak valid";
}
}
//echo "<br>frm_tgl_terbit=".$frm_tgl_terbit;
if ($frm_tgl_terbit!='')
{
if (datetomysql($frm_tgl_terbit))
{
$frm_tgl_terbit = datetomysql($frm_tgl_terbit);
}
else
{
$error = 1;
$pesan = $pesan."Tanggal terbit tidak valid";
}
}
//echo "<br>frm_tgl_terbit=".$frm_tgl_terbit;
if ($frm_tgl_publikasi!='')
{
if (datetomysql($frm_tgl_publikasi))
{
$frm_tgl_publikasi = datetomysql($frm_tgl_publikasi);
}
else
{
$error = 1;
$pesan = $pesan."Tanggal Publikasi Awal tidak valid";
}
}
if ($frm_tgl_publikasi2!='')
{
if (datetomysql($frm_tgl_publikasi2))
{
$frm_tgl_publikasi2 = datetomysql($frm_tgl_publikasi2);
}
else
{
$error = 1;
$pesan = $pesan."Tanggal Publikasi Akhir tidak valid";
}
}
// Kode dan nama harus diisi
/*if (($frm_no_st_pub_now) or ($frm_jenis) or ($frm_kode_dsn1=='') or ($frm_judul=='') or ($frm_TET=='') or ($frm_TNET=='') or ($frm_tugas=='') or ($frm_status=='') or ($frm_hari_go=='') or
($frm_tgl_go=='') or ($frm_pukul_go=='') or ($frm_tempat_go=='') or ($frm_transportasi_go=='') or ($frm_hari_dtg=='') or
($frm_tgl_dtg=='') or ($frm_pukul_dtg=='') or ($frm_transportasi_dtg=='')) */
if ($frm_jenis==1) {
$frm_sifat_pen="Mandiri";
}
else if ($frm_jenis==2) {
$frm_sifat_pen="Kelompok";
}
//($frm_dana_lokal=='') or
if (($frm_no_st_pub_now=='') or ($frm_jenis=='') or ($frm_kode_dsn1=='') or ($frm_ska_publikasi=='') or ($frm_tipe_publikasi=='') or ($frm_judul=='') or
($frm_id_sumber_dana=='') or ($frm_TET=='') or ($frm_tugas=='') or ($frm_status=='') or ($frm_hari_go=='') or
($frm_tgl_go=='') or ($frm_pukul_go=='') or ($frm_tempat_go=='') or ($frm_transportasi_go=='') or ($frm_hari_dtg=='') or
($frm_tgl_dtg=='') or ($frm_pukul_dtg=='') or ($frm_transportasi_dtg==''))
{
$error = 1;
$pesan=$pesan."Maaf, Anda harus mengisi data Surat Tugas Publikasi dengan lengkap. ";
}
if ($error==1)
{
$pesan=$pesan."<br>Gagal menyimpan data - ". mysql_error();
}
if ($error !=1) // Jika semua isian form valid
{
// data no_st_pub tidak ada, berarti record baru
/*echo "<br>frm_no_st_pub_now= ".$frm_no_st_pub_now;
echo "<br>frm_kode_dsn1= ".$frm_kode_dsn1;
echo "<br>frm_kode_dsn2= ".$frm_kode_dsn2;
echo "<br>frm_kode_dsn3= ".$frm_kode_dsn3;
echo "<br>frm_kode_dsn4= ".$frm_kode_dsn4;
echo "<br>frm_kode_dsn5= ".$frm_kode_dsn5;
echo "<br>frm_status= ".$frm_status;
echo "<br>frm_TET= ".$frm_TET;
echo "<br>frm_TNET= ".$frm_TNET;
echo "<br>frm_tugas= ".$frm_tugas;
echo "<br>frm_hari_go= ".$frm_hari_go;
echo "<br>frm_tgl_go= ".$frm_tgl_go;
echo "<br>frm_pukul_go= ".$frm_pukul_go;
echo "<br>frm_tempat_go= ".$frm_tempat_go;
echo "<br>frm_transportasi_go= ".$frm_transportasi_go;
echo "<br>frm_hari_dtg= ".$frm_hari_dtg;
echo "<br>frm_tgl_dtg= ".$frm_tgl_dtg;
echo "<br>frm_pukul_dtg= ".$frm_pukul_dtg;
echo "<br><br>frm_biaya= ".$frm_biaya;
echo "<br>chk_airport= ".$chk_airport;
echo "<br>chk_fiskal= ".$chk_fiskal;
echo "<br>chk_visa= ".$chk_visa;
echo "<br>chk_uang_saku= ".$chk_uang_saku;
echo "<br>chk_akomodasi= ".$chk_akomodasi;
echo "<br>frm_lainnya= ".$frm_lainnya;
echo "<br>frm_ndt= ".$frm_ndt;
echo "<br>frm_jenis= ".$frm_jenis;
/*/
if ($chk_airport=='on'){
$chk_airport=1;}
else
{ $chk_airport=0;}
if ($chk_fiskal=='on'){
$chk_fiskal=1;}
else
{ $chk_fiskal=0;}
if ($chk_visa=='on'){
$chk_visa=1;}
else
{ $chk_visa=0;}
if ($chk_uang_saku=='on'){
$chk_uang_saku=1;}
else
{ $chk_uang_saku=0;}
if ($chk_akomodasi=='on'){
$chk_akomodasi=1;}
else
{ $chk_akomodasi=0;}
$jum=0;
for ($i = 1; $i <= 5; $i++) {
$kd_dsn="frm_kode_dsn".$i;
if ((isset($$kd_dsn)) and ($$kd_dsn <>''))
{
//echo "<br>$i.".$kd_dsn;
$jum++;
}
}
// BEGIN UBAH TABEL #########################################################################################################
$res_cek_pub= mysql_query("SELECT publikasi.no_st_pub
FROM publikasi
WHERE publikasi.no_st_pub='".$frm_no_st_pub_now."'");
$maxrows_pub=mysql_num_rows($res_cek_pub);
if ($maxrows_pub >= 1)
{
$result_1_1 = mysql_query("UPDATE publikasi SET `no_legalitas` = '$frm_no_legalitas_now',
`jenis` = $frm_jenis,
`publikasi` = '$frm_ska_publikasi',
`tgl_publikasi` = '$frm_tgl_publikasi',
`tgl_publikasi2` = '$frm_tgl_publikasi2',
`jurn_pros` = '$frm_tipe_publikasi',
`kode_kary` = '$frm_kode_dsn1',
`kode_kary2` = '$frm_kode_dsn2',
`kode_kary3` = '$frm_kode_dsn3',
`kode_kary4` = '$frm_kode_dsn4',
`kode_kary5` = '$frm_kode_dsn5',
`status` = '$frm_status',
`TET_sub` = '$frm_TET',
`TNET_sub` = '$frm_TNET',
`judul` = '$frm_judul',
`tugas` = '$frm_tugas',
`pub_ISBN` = '$frm_ISBN',
`pub_volume`= '$frm_volume',
`pub_penyelenggara` = '$frm_penyelenggara',
`pub_tgl_pub` = '$frm_tgl_publikasi',
`pub_no_paten` = '$frm_no_paten',
`pub_pemberi_paten` = '$frm_pemberi_paten',
`pub_tgl_paten` = '$frm_tgl_terbit',
`pub_id_sumber_dana` = '$frm_id_sumber_dana',
`pub_jum_dana_lokal` = '$frm_dana_lokal',
`pub_jum_dana_asing` = '$frm_dana_asing',
`hari_go` = '$frm_hari_go',
`tgl_go` = '$frm_tgl_go',
`pukul_go` = '$frm_pukul_go',
`tempat_go` = '$frm_tempat_go',
`transport_go` = '$frm_transportasi_go',
`hari_dtg` = '$frm_hari_dtg',
`tgl_dtg` = '$frm_tgl_dtg',
`pukul_dtg` = '$frm_pukul_dtg',
`transport_dtg` = '$frm_transportasi_dtg',
`biaya` = '$frm_biaya',
`L_ap_tax` = $chk_airport,
`L_fiskal` = $chk_fiskal,
`L_visa` = $chk_visa,
`L_saku` = $chk_uang_saku,
`L_akomo` = $chk_akomodasi,
`L_other` = '$frm_lainnya',
`ndt_terakhir` = '$frm_ndt'
WHERE `no_st_pub`='$frm_no_st_pub_now'");
if ($result_1_1)
{
$pesan = $pesan."<br>Data telah diubah";
}
else
{
$pesan = $pesan."<br>Gagal mengubah data 1-1 - ". mysql_error();
}
}
else
{
$result_1_2 = mysql_query("INSERT INTO publikasi ( `no_legalitas` , `no_st_pub` , `urut_st_pub` , `jenis`, `publikasi`, `tgl_publikasi`, `tgl_publikasi2`, `jurn_pros`,
`kode_kary`, `kode_kary2`, `kode_kary3`, `kode_kary4`, `kode_kary5`, `status`, `TET_sub`, `TNET_sub`, `judul`, `tugas`,
`pub_ISBN`, `pub_volume`, `pub_penyelenggara`, `pub_tgl_pub`, `pub_no_paten`, `pub_pemberi_paten`, `pub_tgl_paten`,
`pub_id_sumber_dana`, `pub_jum_dana_lokal`, `pub_jum_dana_asing`,
`hari_go` , `tgl_go` , `pukul_go` , `tempat_go` , `transport_go` ,
`hari_dtg` , `tgl_dtg` , `pukul_dtg` , `transport_dtg` , `biaya` ,
`L_ap_tax` , `L_fiskal` , `L_visa` , `L_saku` , `L_akomo` , `L_other` , `ndt_terakhir`)
VALUES ( '".$frm_no_legalitas_now."', '".$frm_no_st_pub_now."', NULL, ".$frm_jenis.", '".$frm_ska_publikasi."', '".$frm_tgl_publikasi."', '".$frm_tgl_publikasi2."', '".$frm_tipe_publikasi."',
'".$frm_kode_dsn1."', '".$frm_kode_dsn2."', '".$frm_kode_dsn3."', '".$frm_kode_dsn4."', '".$frm_kode_dsn5."', '".$frm_status."', '".$frm_TET."', '".$frm_TNET."', '".$frm_judul."', '".$frm_tugas."',
'".$frm_ISBN."', '".$frm_volume."', '".$frm_penyelenggara."', '".$frm_tgl_publikasi."', '".$frm_no_paten."', '".$frm_pemberi_paten."', '".$frm_tgl_terbit."',
'".$frm_id_sumber_dana."','".$frm_dana_lokal."', '".$frm_dana_asing."',
'".$frm_hari_go."','".$frm_tgl_go."', '".$frm_pukul_go."', '".$frm_tempat_go."', '".$frm_transportasi_go."',
'".$frm_hari_dtg."', '".$frm_tgl_dtg."', '".$frm_pukul_dtg."','".$frm_transportasi_dtg."', '".$frm_biaya."',
".$chk_airport.", ".$chk_fiskal.", ".$chk_visa.", ".$chk_uang_saku.", ".$chk_akomodasi.", '".$frm_lainnya."', '".$frm_ndt."') " );
if ($result_1_2)
{
$pesan = $pesan."<br>Data telah ditambahkan";
}
else
{
$pesan = $pesan."<br>Gagal menambahkan data 1-2 - ". mysql_error();
}
}
//########################## CEK penelitian apa no ST_pub sudah ada..?
/*$res_cek_ti= mysql_query("SELECT penelitian.kode_pen
FROM penelitian
WHERE penelitian.kode_pen='".$frm_no_st_pub_now."'");
$maxrows_ti=mysql_num_rows($res_cek_ti);
if ($maxrows_ti >= 1)
{
$result = mysql_query("UPDATE penelitian SET `no_legalitas` = '$frm_no_legalitas_now',
`publikasi` = $frm_ska_publikasi,
`jurn_pros` = $frm_tipe_publikasi,
`judul` ='$frm_judul',
`tanggal_mulai`='$frm_tgl_go',
`tanggal_selesai`='$frm_tgl_dtg',
`jenis_pen`= '$frm_jenis',
`pub_ISBN` = '$frm_ISBN',
`pub_Volume`= '$frm_volume',
`pub_tempat` = '$frm_tempat_go',
`pub_penyelenggara` = '$frm_penyelenggara',
`pub_tanggal` = '$frm_tgl_publikasi',
`id_sumber_dana` ='$frm_id_sumber_dana',
`dana` = '$frm_dana',
`dana_asing` = '$frm_dana_asing',
`no_paten` = '$frm_no_paten',
`pemberi_paten` = '$frm_pemberi_paten'
WHERE `kode_pen`='$frm_no_st_pub_now'");
if ($result_2_1)
{
$pesan = $pesan."<br>Data telah diubah";
}
else
{
$pesan = $pesan."<br>Gagal mengubah Penelitian - ". mysql_error();
}
}
else
{
$pesan = $pesan."<br>Silahkan masukkan data penelitian terlebih dahulu!";
}
*/
// TULISAN ILMIAH
/*$res_cek_ti= mysql_query("SELECT tulisan_ilmiah.no_st_pub
FROM tulisan_ilmiah
WHERE tulisan_ilmiah.no_st_pub='".$frm_no_st_pub_now."'");
$maxrows_ti=mysql_num_rows($res_cek_ti);
if ($maxrows_ti >= 1)
{
$result_2_1= mysql_query("UPDATE tulisan_ilmiah SET `kode_dosen1` ='$frm_kode_dsn1',
`kode_dosen2` ='$frm_kode_dsn2',
`kode_dosen3` ='$frm_kode_dsn3',
`kode_dosen4` ='$frm_kode_dsn4',
`kode_dosen5` ='$frm_kode_dsn5',
`publikasi` = $frm_ska_publikasi,
`jurn_pros` = $frm_tipe_publikasi,
`jurusan_id`= $frm_TET,
`judul` ='$frm_judul',
`tanggal_terbit` ='$frm_tgl_terbit',
`jumlah_peneliti`= $jum,
`id_sumber_dana` ='$frm_id_sumber_dana',
`dana` = '$frm_dana',
`dana_asing` = '$frm_dana_asing',
`kode_buku` = '$frm_kode_buku',
`man_kel` = '$frm_sifat_pen',
`pub_ISBN` = '$frm_ISBN',
`pub_Volume`= '$frm_volume',
`pub_tempat` = '$frm_tempat_publikasi',
`pub_penyelenggara` = '$frm_penyelenggara',
`pub_tanggal` = '$frm_tgl_publikasi',
`no_paten` = '$frm_no_paten',
`pemberi_paten` = '$frm_pemberi_paten'
WHERE `no_st_pub` = '$frm_no_st_pub_now'");
if ($result_2_1)
{
$pesan = $pesan."<br>Data telah diubah";
}
else
{
$pesan = $pesan."<br>Gagal mengubah data 2-1 - ". mysql_error();
}
}
else
{
$result_2_2 = mysql_query("INSERT INTO tulisan_ilmiah(`id_pen`,
`no_st_pub`,
`kode_dosen1`,
`kode_dosen2`,
`kode_dosen3`,
`kode_dosen4`,
`kode_dosen5`,
`publikasi`,
`jurn_pros`,
`jurusan_id`,
`judul`,
`tanggal_terbit`,
`jumlah_peneliti`,
`id_sumber_dana`,
`dana`,
`dana_asing`,
`kode_buku`,
`man_kel`,
`pub_ISBN`,
`pub_Volume`,
`pub_tempat`,
`pub_penyelenggara`,
`pub_tanggal`,
`no_paten`,
`pemberi_paten`,
`nama_media`,
`id_status_media`) VALUES
( NULL, '".$frm_no_st_pub_now."', '".$frm_kode_dsn1."', '".$frm_kode_dsn2."', '".$frm_kode_dsn3."', '".$frm_kode_dsn4."', '".$frm_kode_dsn5."', ".$frm_ska_publikasi.", ".$frm_tipe_publikasi.", ".$frm_TET.", '".$frm_judul."', '".$frm_tgl_terbit."', ".$jum.", ".$frm_id_sumber_dana.", '".$frm_dana."', '".$frm_dana_asing."', '---', '".$frm_sifat_pen."', '".$frm_ISBN."', '".$frm_volume."', '".$frm_tempat_publikasi."', '".$frm_penyelenggara."', '".$frm_tgl_publikasi."', '".$frm_no_paten."', '".$frm_pemberi_paten."','---',0) " );
if ($result_2_2)
{
$pesan = $pesan."<br>Data telah ditambahkan";
}
else
{
$pesan = $pesan."<br>Gagal menambahkan data 2-2 - ". mysql_error();
}
}*/
// END UBAH TABEL #########################################################################################################
}
}
if ($act==2) { // hapus data
$result = mysql_query("DELETE FROM publikasi WHERE no_st_pub = '".$no_st."'");
if ($result) {$pesan = "data telah dihapus"; }else{ $pesan = "gagal menghapus data";}
$result = mysql_query("DELETE FROM tulisan_ilmiah WHERE no_st_pub = '".$no_st."'");
if ($result) {$pesan = "data telah dihapus"; }else{ $pesan = "gagal menghapus data";}
//$result = mysql_query("DELETE FROM tulisan_ilmiah WHERE no_st_pub = '".$no_st."'");
//if ($result) {$pesan = "data telah dihapus"; }else{ $pesan = "gagal menghapus data";}
}
// Kalau data sudah ditambahkan ke dalam database, form dikosongkan siap untuk diisi data baru
if (($act!=0)and($error!=1))
{
$frm_exist=0;
$jum=0;
$frm_jenis = "";
$frm_no_st_pub_now = "";
$frm_ska_publikasi = "";
$frm_tipe_publikasi = "";
$frm_judul = "";
$frm_ISBN = "";
$frm_volume = "";
$frm_penyelenggara = "";
$frm_tgl_publikasi="00/00/0000";
$frm_tgl_publikasi2="00/00/0000";
//echo "<br>frm_tgl_publikasi=".$frm_tgl_publikasi;
//exit();
$frm_tgl_terbit="00/00/0000";
$frm_tgl_dtg="00/00/0000";
$frm_tgl_go="00/00/0000";
//echo "<br>frm_tgl_go_PPP=".$frm_tgl_go;
$frm_kode_dsn1="";
$frm_kode_dsn2="";
$frm_kode_dsn3="";
$frm_kode_dsn4="";
$frm_kode_dsn5="";
$frm_status="";
$frm_TET="";
$frm_TNET="";
$frm_tugas="";
$frm_no_paten = "";
$frm_pemberi_paten = "";
$frm_id_sumber_dana = "";
$frm_dana = "";
$frm_dana_asing = "";
$frm_hari_go = "";
$frm_pukul_go="";
$frm_tempat_go="";
$frm_transportasi_go="";
$frm_hari_dtg="";
$frm_tgl_dtg="";
$frm_pukul_dtg="";
$frm_transportasi_dtg="";
$frm_biaya="";
$chk_airport="";
$chk_fiskal="";
$chk_visa="";
$chk_uang_saku="";
$chk_akomodasi="";
$frm_lainnya="";
$frm_ndt="";
}
else
{
// kalau user mengisi kode, kemudian pindah ke isian yang lain, maka di check apakah data kode sudah ada, kalau sudah ada maka data akan ditampilkan
if ($frm_no_st_pub_now!='') {
/*$result = mysql_query("Select dosen.kode,
dosen.nama,
publikasi.no_st_pub,
publikasi.urut_st_pub,
publikasi.kode_kary,
publikasi.kode_kary2,
publikasi.kode_kary3,
publikasi.kode_kary4,
publikasi.kode_kary5,
publikasi.status,
publikasi.jenis,
publikasi.TET_sub,
publikasi.TNET_sub,
publikasi.tugas,
publikasi.hari_go,
DATE_FORMAT(publikasi.tgl_go,'%d/%m/%Y') as tgl_go,
publikasi.pukul_go,
publikasi.tempat_go,
publikasi.transport_go,
publikasi.hari_dtg,
DATE_FORMAT(publikasi.tgl_dtg,'%d/%m/%Y') as tgl_dtg,
publikasi.pukul_dtg,
publikasi.transport_dtg,
publikasi.biaya,
publikasi.L_ap_tax,
publikasi.L_fiskal,
publikasi.L_visa,
publikasi.L_saku,
publikasi.L_akomo,
publikasi.L_other,
publikasi.ndt_terakhir,
tulisan_ilmiah.publikasi,
tulisan_ilmiah.jurn_pros,
tulisan_ilmiah.judul,
tulisan_ilmiah.pub_ISBN,
tulisan_ilmiah.pub_Volume,
tulisan_ilmiah.pub_penyelenggara,
DATE_FORMAT(tulisan_ilmiah.pub_tanggal,'%d/%m/%Y') as pub_tanggal,
tulisan_ilmiah.no_paten,
tulisan_ilmiah.pemberi_paten,
DATE_FORMAT(tulisan_ilmiah.tanggal_terbit,'%d/%m/%Y') as tanggal_terbit,
tulisan_ilmiah.id_sumber_dana,
tulisan_ilmiah.dana,
tulisan_ilmiah.dana_asing
FROM publikasi, dosen, tulisan_ilmiah
WHERE publikasi.kode_kary=dosen.kode AND
publikasi.no_st_pub=tulisan_ilmiah.no_st_pub AND
publikasi.no_st_pub='".$frm_no_st_pub_now."'");*/
$result = mysql_query("Select publikasi.no_legalitas,
publikasi.no_st_pub,
publikasi.urut_st_pub,
publikasi.jenis,
publikasi.publikasi AS skala_pub,
publikasi.jurn_pros AS tipe_pub,
publikasi.kode_kary,
publikasi.kode_kary2,
publikasi.kode_kary3,
publikasi.kode_kary4,
publikasi.kode_kary5,
publikasi.status,
publikasi.TET_sub,
publikasi.TNET_sub,
publikasi.judul AS judul_publikasi,
publikasi.tugas,
publikasi.pub_ISBN,
publikasi.pub_volume,
publikasi.pub_penyelenggara,
DATE_FORMAT(publikasi.pub_tgl_pub,'%d/%m/%Y') as pub_tgl_pub,
DATE_FORMAT(publikasi.tgl_publikasi,'%d/%m/%Y') as tgl_publikasi,
DATE_FORMAT(publikasi.tgl_publikasi2,'%d/%m/%Y') as tgl_publikasi2,
publikasi.pub_no_paten,
publikasi.pub_pemberi_paten,
publikasi.pub_tgl_paten,
publikasi.pub_id_sumber_dana,
publikasi.pub_jum_dana_lokal,
publikasi.pub_jum_dana_asing,
publikasi.hari_go,
DATE_FORMAT(publikasi.tgl_go,'%d/%m/%Y') as tgl_go,
publikasi.pukul_go,
publikasi.tempat_go,
publikasi.transport_go,
publikasi.hari_dtg,
DATE_FORMAT(publikasi.tgl_dtg,'%d/%m/%Y') as tgl_dtg,
publikasi.pukul_dtg,
publikasi.transport_dtg,
publikasi.biaya,
publikasi.L_ap_tax,
publikasi.L_fiskal,
publikasi.L_visa,
publikasi.L_saku,
publikasi.L_akomo,
publikasi.L_other,
publikasi.ndt_terakhir
FROM publikasi
WHERE publikasi.no_st_pub='".$frm_no_st_pub_now."'");
if ($row = mysql_fetch_array($result)) {
//echo "<br>HERE SATU";
$frm_exist=1;
$frm_no_legalitas_now = $row["no_legalitas"];
$frm_no_st_pub_now = $row["no_st_pub"];
$frm_jenis = $row["jenis"];
$frm_ska_publikasi = $row["skala_pub"];
$frm_tipe_publikasi = $row["tipe_pub"];
$frm_kode_dsn1 = $row["kode_kary"];
$frm_kode_dsn2 = $row["kode_kary2"];
$frm_kode_dsn3 = $row["kode_kary3"];
$frm_kode_dsn4 = $row["kode_kary4"];
$frm_kode_dsn5 = $row["kode_kary5"];
$frm_status = $row["status"];
$frm_TET = $row["TET_sub"];
$frm_TNET = $row["TNET_sub"];
$frm_judul = $row["judul_publikasi"];
$frm_tugas = $row["tugas"];
$frm_ISBN = $row["pub_ISBN"];
$frm_volume = $row["pub_Volume"];
$frm_penyelenggara = $row["pub_penyelenggara"];
$frm_tgl_publikasi = $row["frm_tgl_publikasi"];
$frm_tgl_publikasi2 = $row["frm_tgl_publikasi2"];
$frm_no_paten = $row["pub_no_paten"];
$frm_pemberi_paten = $row["pub_pemberi_paten"];
$frm_tgl_terbit = $row["pub_tgl_paten"];
$frm_id_sumber_dana = $row["pub_id_sumber_dana"];
$frm_dana_lokal = $row["pub_jum_dana_lokal"];
$frm_dana_asing = $row["pub_jum_dana_asing"];
$chk_airport = $row["L_ap_tax"];
$chk_fiskal = $row["L_fiskal"];
$chk_visa = $row["L_visa"];
$chk_uang_saku = $row["L_saku"];
$chk_akomodasi = $row["L_akomo"];
$frm_lainnya = $row["L_other"];
/*if (($row["pub_tgl_pub"]=="")or($row["pub_tgl_pub"]==NULL)or($row["pub_tgl_pub"]=="00/00/0000")) {
$frm_tgl_publikasi ="00/00/0000"; }else {
$frm_tgl_publikasi =$row["pub_tgl_pub"];}*/
if (($row["tgl_publikasi"]=="")or($row["tgl_publikasi"]==NULL)or($row["tgl_publikasi"]=="00/00/0000")) {
$frm_tgl_publikasi ="00/00/0000"; }else {
$frm_tgl_publikasi =$row["tgl_publikasi"];}
if (($row["tgl_publikasi2"]=="")or($row["tgl_publikasi2"]==NULL)or($row["tgl_publikasi2"]=="00/00/0000")) {
$frm_tgl_publikasi2 ="00/00/0000"; }else {
$frm_tgl_publikasi2 =$row["tgl_publikasi2"];}
if (($row["tanggal_terbit"]=="")or($row["tanggal_terbit"]==NULL)or($row["tanggal_terbit"]=="00/00/0000")) {
$frm_tgl_terbit ="00/00/0000"; }else {
$frm_tgl_terbit =$row["tanggal_terbit"];}
$frm_no_paten=$row["no_paten"];
$frm_pemberi_paten=$row["pemberi_paten"];
$frm_hari_go = $row["hari_go"];
if (($row["tgl_go"]=="")or($row["tgl_go"]==NULL)or($row["tgl_go"]=="00/00/0000")) {
$frm_tgl_go =""; }else {
$frm_tgl_go =$row["tgl_go"];}
$frm_pukul_go = $row["pukul_go"];
$frm_tempat_go = $row["tempat_go"];
$frm_transportasi_go = $row["transport_go"];
$frm_hari_dtg = $row["hari_dtg"];
if (($row["tgl_dtg"]=="")or($row["tgl_dtg"]==NULL)or($row["tgl_dtg"]=="00/00/0000")) {
$frm_tgl_dtg =""; }else {
$frm_tgl_dtg =$row["tgl_dtg"];}
$frm_pukul_dtg = $row["pukul_dtg"];
$frm_transportasi_dtg = $row["transport_dtg"];
$frm_pukul_dtg = $row["pukul_dtg"];
$frm_biaya = $row["biaya"];
$frm_ndt = $row["ndt_terakhir"];
/*
echo "<br>frm_no_st_pub_now= ".$frm_no_st_pub_now;
echo "<br>frm_kode_dsn1= ".$frm_kode_dsn1;
echo "<br>frm_kode_dsn2= ".$frm_kode_dsn2;
echo "<br>frm_kode_dsn3= ".$frm_kode_dsn3;
echo "<br>frm_kode_dsn4= ".$frm_kode_dsn4;
echo "<br>frm_kode_dsn5= ".$frm_kode_dsn5;
echo "<br>frm_status= ".$frm_status;
echo "<br>frm_TET= ".$frm_TET;
echo "<br>frm_TNET= ".$frm_TNET;
echo "<br>frm_tugas= ".$frm_tugas;
echo "<br>frm_hari_go= ".$frm_hari_go;
echo "<br>frm_tgl_go= ".$frm_tgl_go;
echo "<br>frm_pukul_go= ".$frm_pukul_go;
echo "<br>frm_tempat_go= ".$frm_tempat_go;
echo "<br>frm_transportasi_go= ".$frm_transportasi_go;
echo "<br>frm_hari_dtg= ".$frm_hari_dtg;
echo "<br>frm_tgl_dtg= ".$frm_tgl_dtg;
echo "<br>frm_pukul_dtg= ".$frm_pukul_dtg;
echo "<br>frm_transportasi_dtg= ".$frm_transportasi_dtg;*/
}
else
{
$frm_exist=0;
//$frm_no_st_pub_now="";
//echo "<br>H E R E dua<br>";
//echo "<br>judul=".$row["judul"];
//exit();
// if ($row["judul"]=='') {
$frm_no_legalitas_now = "";
$chk_airport = "";
$chk_fiskal = "";
$chk_visa = "";
$chk_uang_saku = "";
$chk_akomodasi = "";
$frm_lainnya = "";
//$frm_jenis = "";
//$frm_no_st_pub_now = "";
$frm_ska_publikasi = "";
$frm_tipe_publikasi = "";
$frm_judul = "";
$frm_ISBN = "";
$frm_volume = "";
$frm_penyelenggara = "";
$frm_tgl_publikasi = "00/00/0000";
$frm_tgl_publikasi2 = "00/00/0000";
$frm_tgl_terbit = "00/00/0000";
$frm_no_paten = "";
$frm_pemberi_paten = "";
$frm_id_sumber_dana = "";
$frm_dana_lokal = "";
$frm_dana_asing = "";
$frm_kode_dsn1 = "";
$frm_kode_dsn2 = "";
$frm_kode_dsn3 = "";
$frm_kode_dsn4 = "";
$frm_kode_dsn5 = "";
$frm_status = "";
$frm_TET = "";
$frm_TNET = "";
$frm_tugas = "";
$frm_hari_go = "";
$frm_tgl_go = "";
$frm_pukul_go = "";
$frm_tempat_go = "";
$frm_transportasi_go = "";
$frm_hari_dtg = "";
$frm_tgl_dtg = "";
$frm_pukul_dtg = "";
$frm_transportasi_dtg = "";
$frm_pukul_dtg = "";
$frm_biaya = "";
$frm_ndt = "";
//$frm_jenis="";
//}
}
}
}
?>
<html>
<head>
<meta http-equiv="Refresh" content="1420; URL=pen_st_publikasi_entry.php">
<link href="../css/style2.css" rel="stylesheet" type="text/css">
<script language="JavaScript" src="../include/tanggalan.js">
</script>
<SCRIPT language=Javascript>
<!--
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
//-->
</SCRIPT>
<style type="text/css">
<!--
.style1 {font-size: 10px}
-->
</style>
</head>
<body class="body">
<form name="publikasi" id="publikasi" action="pen_st_publikasi_entry.php" method="post">
<table width="100%" border="0" align="center" cellpadding="2" cellspacing="0" class="body">
<tr>
<td colspan="4"><img src="spacer" height="1"></td>
</tr>
<tr>
<td colspan="4"><font color="#FF0000" ><strong><?php echo $pesan; ?></strong></font></td>
</tr>
<tr>
<td colspan="4"> <hr size="1" color="#FF9900">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="89%"><font color="#0099CC" size="1"><strong>ENTRY DATA ~ </strong>SURAT TUGAS PUBLIKASI</font></td>
<td width="11%" bgcolor="#0099CC"><div align="center"><strong><font color="#FFFFFF">DOSEN</font></strong></div></td>
</tr>
</table>
<hr size="1" color="#FF9900"> </td>
</tr>
<tr>
<td width="93"> </td>
<td width="212"> </td>
<td width="5"> </td>
<td width="646"><input name="frm_exist" type="hidden" id="frm_exist" value="<?php echo $frm_exist; ?>" ></td>
</tr>
<tr>
<td> </td>
<td nowrap>Jenis Surat Tugas </td>
<td><div align="center"><strong>:</strong></div></td>
<td>
<select name="frm_jenis" id="frm_jenis" class="tekboxku" onChange="document.publikasi.submit()">
<!--select name="frm_jenis" id="frm_jenis" class="tekboxku" <? //if ($frm_no_st_pub_now =='') {?> onBlur="document.publikasi.submit();" <? // }?>-->
<? if (isset($frm_jenis)) {?>
<option value="1" <? if ($frm_jenis=="1") echo "selected"?>>satu orang</option>
<option value="2" <? if ($frm_jenis=="2") echo "selected"?>>lebih dari satu</option>
<? } else {?>
<option value="">---Pilih---</option>
<option value="1">satu orang</option>
<option value="2">lebih dari satu</option>
<? }?>
</select>
<font color="#FF0000">*</font></td>
</tr>
<tr>
<td> </td>
<td nowrap> </td>
<td><div align="center"></div></td>
<td>
<?
$result_ST_last = mysql_query("SELECT no_st_pub, urut_st_pub, no_legalitas FROM publikasi ORDER BY urut_st_pub DESC LIMIT 1");
$row_ST_last = mysql_fetch_array($result_ST_last);
?>
</td>
</tr>
<tr>
<td> </td>
<td nowrap>No ST publikasi sebelumnya</td>
<td><strong>:</strong></td>
<td><input name="frm_no_st_pub_lama" type="text" id="frm_no_st_pub_lama" size="25" maxlength="5" value="<?php echo $row_ST_last['no_st_pub']; ?>" class="tekboxku" readonly="true">
<font color="#FF0000">*</font></td>
</tr>
<tr>
<td> </td>
<td nowrap>No ST publikasi sekarang </td>
<td><strong>:</strong></td>
<td><input name="frm_no_st_pub_now" id="frm_no_st_pub_now" type="text" onBlur="document.publikasi.submit();" value="<?php echo $frm_no_st_pub_now; ?>" size="25" maxlength="25" class="tekboxku">
<font color="#FF0000">*</font></td>
</tr>
<tr>
<td> </td>
<td nowrap> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td nowrap>No Legalitas sebelumnya </td>
<td><strong>:</strong></td>
<td><input name="frm_no_legalitas_lama" type="text" id="frm_no_legalitas_lama" size="25" maxlength="5" value="<?php echo $row_ST_last['no_legalitas']; ?>" class="tekboxku" readonly="true">
<font color="#FF0000">*</font></td>
</tr>
<tr>
<td> </td>
<td nowrap>No Legalitas sekarang </td>
<td><strong>:</strong></td>
<td><input name="frm_no_legalitas_now" id="frm_no_legalitas_now2" type="text" value="<?php echo $frm_no_legalitas_now; ?>" size="25" maxlength="25" class="tekboxku">
<font color="#FF0000">*</font></td>
</tr>
<tr>
<td> </td>
<td nowrap> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td nowrap>Skala Publikasi</td>
<td><strong>:</strong></td>
<td><? //echo "<br>frm_ska_publikasi=".$frm_ska_publikasi;?>
<select name="frm_ska_publikasi" id="frm_ska_publikasi" class="tekboxku">
<option value="0" <?php if ($frm_ska_publikasi==0){echo "selected";}?>>Tidak ada data</option>
<option value="1" <?php if ($frm_ska_publikasi==1){echo "selected";}?>>Regional</option>
<option value="2" <?php if ($frm_ska_publikasi==2){echo "selected";}?>>Nasional</option>
<option value="3" <?php if ($frm_ska_publikasi==3){echo "selected";}?>>Internasional</option>
</select>
<font color="#FF0000">*</font></td>
</tr>
<tr>
<td> </td>
<td nowrap> Tipe Publikasi </td>
<td><strong>:</strong></td>
<td><? //echo "pub=".$frm_tipe_publikasi;?>
<select name="frm_tipe_publikasi" id="frm_tipe_publikasi" class="tekboxku">
<option value="0" <?php if ($frm_tipe_publikasi==0){echo "selected";}?>>Tidak ada data</option>
<option value="1" <?php if ($frm_tipe_publikasi==1){echo "selected";}?>>Jurnal</option>
<option value="2" <?php if ($frm_tipe_publikasi==2){echo "selected";}?>>Prosiding</option>
</select>
<font color="#FF0000">*</font> <font color="#FF0000" size="1"><em>Prosiding</em>: dipresentasikan <strong>|</strong> <em>Jurnal</em>: tanpa dipresentasikan</font> </td>
</tr>
<tr>
<td> </td>
<td valign="top" nowrap>Judul</td>
<td valign="top"><strong>:</strong></td>
<td><textarea name="frm_judul" id="frm_judul" cols="50" class="tekboxku" wrap="soft"><?php echo $frm_judul; ?></textarea>
<font color="#FF0000">*</font></td>
</tr>
<tr>
<td> </td>
<td nowrap>ISBN/ISSN</td>
<td><strong>:</strong></td>
<td><input name="frm_ISBN" type="text" class="tekboxku" id="frm_ISBN" value="<?php echo $frm_ISBN; ?>" size="30" maxlength="50">
</td>
</tr>
<tr>
<td> </td>
<td nowrap>Volume</td>
<td><strong>:</strong></td>
<td><input name="frm_volume" type="text" class="tekboxku" id="frm_volume" value="<?php echo $frm_volume; ?>" size="30" maxlength="50"></td>
</tr>
<tr>
<td> </td>
<td nowrap> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td nowrap> Penyelenggara </td>
<td><strong>:</strong></td>
<td><input name="frm_penyelenggara" type="text" class="tekboxku" id="frm_penyelenggara" value="<?php echo $frm_penyelenggara; ?>" size="50" maxlength="50">
</td>
</tr>
<tr>
<td> </td>
<td nowrap> Tanggal Publikasi </td>
<td><strong>:</strong></td>
<td><input name="frm_tgl_publikasi" type="text" class="tekboxku" id="frm_tgl_publikasi" value="<?php echo $frm_tgl_publikasi; ?>" size="10" maxlength="10">
<A Href="javascript:show_calendar('publikasi.frm_tgl_publikasi',0,0,'DD/MM/YYYY')"> <img src="../img/date.png" width="22" height="22" align="absbottom" border=0> </A>(dd/mm/yyyy) <strong>s/d</strong> <input name="frm_tgl_publikasi2" type="text" class="tekboxku" id="frm_tgl_publikasi2" value="<?php echo $frm_tgl_publikasi2; ?>" size="10" maxlength="10">
<A Href="javascript:show_calendar('publikasi.frm_tgl_publikasi2',0,0,'DD/MM/YYYY')"> <img src="../img/date.png" width="22" height="22" align="absbottom" border=0> </A>(dd/mm/yyyy)</td>
</tr>
<tr>
<td> </td>
<td nowrap> No. Hak Paten </td>
<td><strong>:</strong></td>
<td><input name="frm_no_paten" type="text" class="tekboxku" id="frm_no_paten" value="<?php echo $frm_no_paten; ?>" size="50" maxlength="50"></td>
</tr>
<tr>
<td> </td>
<td nowrap> Pemberi Hak Paten </td>
<td><strong>:</strong></td>
<td><input name="frm_pemberi_paten" type="text" class="tekboxku" id="frm_pemberi_paten" value="<?php echo $frm_pemberi_paten; ?>" size="50" maxlength="50"></td>
</tr>
<tr>
<td> </td>
<td nowrap> Tanggal Terbit </td>
<td><strong>:</strong></td>
<td><input name="frm_tgl_terbit" type="text" class="tekboxku" id="frm_tgl_terbit" value="<?php echo $frm_tgl_terbit; ?>" size="10" maxlength="10">
<A Href="javascript:show_calendar('publikasi.frm_tgl_terbit',0,0,'DD/MM/YYYY')"> <img src="../img/date.png" width="22" height="22" align="absbottom" border=0> </A>(dd/mm/yyyy)</td>
</tr>
<tr>
<td> </td>
<td nowrap> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td nowrap>Sumber Dana</td>
<td><strong>:</strong></td>
<td><? //echo "id_sumber_dana=".$frm_id_sumber_dana;?>
<select name="frm_id_sumber_dana" id="frm_id_sumber_dana" class="tekboxku">
<option <?php if ($frm_id_sumber_dana==''){echo "selected";}?>>--- Pilih ---</option>
<?php
$result1 = @mysql_query("SELECT id, nama FROM sumber_dana ORDER BY nama ASC");
$c=0;
while ($row1=@mysql_fetch_object($result1)) {
$c=$c+1;
?>
<option value="<?php echo $row1->id; ?>" <?php if ($frm_id_sumber_dana==$row1->id) { echo "selected"; }?> ><?php echo $row1->nama; ?></option>
<?php
}
?>
</select>
<font color="#FF0000">*</font> </td>
</tr>
<tr>
<td> </td>
<td nowrap>Nominal Dana</td>
<td><strong>:</strong></td>
<td>Rp.
<? //onkeypress="return isNumberKey(event)"?>
<input type="text" name="frm_dana_lokal" id="frm_dana_lokal" value="<?php echo $frm_dana_lokal; ?>" class="tekboxku">
<font color="#FF0000" size="1">misal : 3.000.000</font></td>
</tr>
<tr>
<td> </td>
<td nowrap>Nominal Dana (asing) </td>
<td><strong>:</strong></td>
<td><input type="text" name="frm_dana_asing" id="frm_dana_asing" value="<?php echo $frm_dana_asing; ?>" class="tekboxku">
<font color="#FF0000" size="1">misal : US 800 | AUD 517 | JPY 1100</font></td>
</tr>
<tr>
<td> </td>
<td nowrap> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td nowrap>Ketua</td>
<td><div align="center"><strong>:</strong></div></td>
<td>
<select name="frm_kode_dsn1" id="frm_kode_dsn1" class="tekboxku">
<option <?php if ($frm_kode_dsn1==''){echo "selected";}?> value="">-- NPK Dosen --</option>
<?php
$result1 = @mysql_query("Select kode, nama from dosen where (length(kode)=6) ORDER BY kode");
$c=0;
while ($row1=@mysql_fetch_object($result1)) {
$c=$c+1;
?>
<option value="<?php echo $row1->kode; ?>" <?php if ($frm_kode_dsn1==$row1->kode) { echo "selected"; }?> ><?php echo $row1->kode; ?>
- <?php echo $row1->nama; ?></option>
<?php }?>
</select>
<font color="#FF0000">*</font>
<!--a href="#" onClick="return popitup('pen_st_publikasi_entry_cari_dosen.php')">C a r i</a-->
</td>
</tr>
<?
if (isset($frm_jenis) or ($frm_jenis!="")) //lebih dari satu orang
{
if ($frm_jenis=="2"){
?>
<tr>
<td> </td>
<td nowrap>Nama anggota 1 </td>
<td><strong>:</strong></td>
<td><select name="frm_kode_dsn2" id="frm_kode_dsn2" class="tekboxku">
<option <?php if ($frm_kode_dsn2==''){echo "selected";}?> value="">-- NPK Dosen --</option>
<?php
$result1 = @mysql_query("SELECT kode, nama FROM dosen order by kode ASC");
$c=0;
while ($row1=@mysql_fetch_object($result1)) {
$c=$c+1;
?>
<option value="<?php echo $row1->kode; ?>" <?php if ($frm_kode_dsn2==$row1->kode) { echo "selected"; }?> ><?php echo $row1->kode; ?> - <?php echo $row1->nama; ?></option>
<?php }?>
</select>
</td>
</tr>
<tr>
<td> </td>
<td nowrap>Nama anggota 2 </td>
<td><strong>:</strong></td>
<td>
<select name="frm_kode_dsn3" id="frm_kode_dsn3" class="tekboxku">
<option <?php if ($frm_kode_dsn3==''){echo "selected";}?> value="">-- NPK Dosen --</option>
<?php
$result1 = @mysql_query("Select kode, nama from dosen order by kode ASC");
$c=0;
while ($row1=@mysql_fetch_object($result1)) {
$c=$c+1;
?>
<option value="<?php echo $row1->kode; ?>" <?php if ($frm_kode_dsn3==$row1->kode) { echo "selected"; }?> ><?php echo $row1->kode; ?> - <?php echo $row1->nama; ?></option>
<?php }?>
</select>
</td>
</tr>
<tr>
<td> </td>
<td nowrap>Nama anggota 3 </td>
<td><strong>:</strong></td>
<td><select name="frm_kode_dsn4" id="frm_kode_dsn4" class="tekboxku">
<option <?php if ($frm_kode_dsn4==''){echo "selected";}?> value="">-- NPK Dosen --</option>
<?php
$result1 = @mysql_query("Select kode, nama from dosen order by kode ASC");
$c=0;
while ($row1=@mysql_fetch_object($result1)) {
$c=$c+1;
?>
<option value="<?php echo $row1->kode; ?>" <?php if ($frm_kode_dsn4==$row1->kode) { echo "selected"; }?> ><?php echo $row1->kode; ?> - <?php echo $row1->nama; ?></option>
<?php }?>
</select>
</td>
</tr>
<tr>
<td> </td>
<td nowrap>Nama anggota 4 </td>
<td><strong>:</strong></td>
<td>
<select name="frm_kode_dsn5" id="frm_kode_dsn5" class="tekboxku">
<option <?php if ($frm_kode_dsn5==''){echo "selected";}?> value="">-- NPK Dosen --</option>
<?php
$result1 = @mysql_query("Select kode, nama from dosen order by kode ASC");
$c=0;
while ($row1=@mysql_fetch_object($result1)) {
$c=$c+1;
?>
<option value="<?php echo $row1->kode; ?>" <?php if ($frm_kode_dsn5==$row1->kode) { echo "selected"; }?> ><?php echo $row1->kode; ?> - <?php echo $row1->nama; ?></option>
<?php }?>
</select>
</td>
</tr>
<?
//END
}
}?>
<tr>
<td> </td>
<td colspan="3"><? //echo "jum= ".$jum;?></td>
</tr>
<tr>
<td> </td>
<td colspan="3"><table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td width="26%"><u>JABATAN</u></td>
<td width="1%"> </td>
<td width="73%"> </td>
</tr>
<tr>
<td nowrap>Sebagai TET Sub. Sistem </td>
<td><div align="center"><strong>:</strong></div></td>
<td>
<select name="frm_TET" id="frm_TET" class="tekboxku">
<option value="" <? if ($frm_TET=='') echo "selected";?>>---Pilih---</option>
<?php
//f_connecting();
//mysql_select_db($DB);
$result3 = @mysql_query("SELECT id, jurusan FROM jurusan");
$c=0;
while(($row3 = mysql_fetch_object($result3)))
{
$c=$c+1;
//echo "<option value=".$row3["id"].">".$row3["nama"];
?>
<option value="<?php echo $row3->id; ?>" <?php if ($frm_TET==$row3->id) { echo "selected"; }?> ><?php echo $row3->jurusan; ?></option>
<?
}
?>
</select>
<font color="#FF0000">*</font></td>
</tr>
<tr>
<td nowrap>Sebagai TNET Sub. Sistem </td>
<td><div align="center"><strong>:</strong></div></td>
<td>
<select name="frm_TNET" id="frm_TNET" class="tekboxku">
<option value="" <? if ($frm_TNET=='') echo "selected";?>>---Pilih---</option>
<?php
//f_connecting();
//mysql_select_db($DB);
$result3 = @mysql_query("SELECT id,jurusan FROM jurusan");
$c=0;
while(($row3 = mysql_fetch_object($result3)))
{
$c=$c+1;
//echo "<option value=".$row3["id"].">".$row3["nama"];
?>
<option value="<?php echo $row3->id; ?>" <?php if ($frm_TNET==$row3->id) { echo "selected"; }?> ><?php echo $row3->jurusan; ?></option>
<? }?>
</select>
</td>
</tr>
<tr>
<td>Status</td>
<td><div align="center"><strong>:</strong></div></td>
<td><select name="frm_status" id="frm_status" class="tekboxku">
<? if (isset($frm_status)) {?>
<option>Pilih</option>
<option value="Penyaji" <? if ($frm_status=="Penyaji") echo "selected"?>>Penyaji</option>
<option value="Peserta" <? if ($frm_status=="Peserta") echo "selected"?>>Peserta</option>
<? } else {?>
<option>Pilih</option>
<option value="Penyaji">Penyaji</option>
<option value="Peserta">Peserta</option>
<? }?>
</select>
<font color="#FF0000">*</font></td>
</tr>
<tr>
<td width="26%" valign="top" nowrap>Tugas</td>
<td valign="top"><div align="center"><strong>:</strong></div></td>
<td><textarea name="frm_tugas" id="textarea" cols="50" class="tekboxku"><?php echo $frm_tugas; ?></textarea>
<font color="#FF0000">*</font> </td>
</tr>
</table></td>
</tr>
<tr>
<td> </td>
<td colspan="3"> </td>
</tr>
<tr>
<td> </td>
<td colspan="3"><table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td><u>BERANGKAT</u></td>
<td width="1%"> </td>
<td width="79%"> </td>
</tr>
<tr>
<td>Hari</td>
<td><strong>:</strong></td>
<td>
<select name="frm_hari_go" id="frm_hari_go" class="tekboxku">
<? if (isset($frm_hari_go)) {?>
<option>--Pilih--</option>
<option value="Senin" <? if ($frm_hari_go=="Senin") echo "selected"?>>Senin</option>
<option value="Selasa" <? if ($frm_hari_go=="Selasa") echo "selected"?>>Selasa</option>
<option value="Rabu" <? if ($frm_hari_go=="Rabu") echo "selected"?>>Rabu</option>
<option value="Kamis" <? if ($frm_hari_go=="Kamis") echo "selected"?>>Kamis</option>
<option value="Jumat" <? if ($frm_hari_go=="Jumat") echo "selected"?>>Jumat</option>
<option value="Sabtu" <? if ($frm_hari_go=="Sabtu") echo "selected"?>>Sabtu</option>
<option value="Minggu" <? if ($frm_hari_go=="Minggu") echo "selected"?>>Minggu</option>
<? } else {?>
<option>--Pilih--</option>
<option value="Senin">Senin</option>
<option value="Selasa">Selasa</option>
<option value="Rabu">Rabu</option>
<option value="Kamis">Kamis</option>
<option value="Jumat">Jumat</option>
<option value="Sabtu">Sabtu</option>
<option value="Minggu">Minggu</option>
<? }?>
</select>
<font color="#FF0000">*</font></td>
</tr>
<tr>
<td>Tanggal</td>
<td><strong>:</strong></td>
<td><input name="frm_tgl_go" type="text" class="tekboxku" id="frm_tgl_go" value="<?php echo $frm_tgl_go; ?>" size="10" maxlength="10">
<A Href="javascript:show_calendar('publikasi.frm_tgl_go',0,0,'DD/MM/YYYY')">
<img src="../img/date.png" width="22" height="22" align="absbottom" border=0>
</A>(dd/mm/yyyy) <font color="#FF0000">*</font></td>
</tr>
<tr>
<td>Pukul</td>
<td><strong>:</strong></td>
<td><input name="frm_pukul_go" type="text" class="tekboxku" id="frm_pukul_go" value="<?php echo $frm_pukul_go; ?>" size="6" maxlength="5">
<font color="#FF0000">*<span class="style1">(format 24 jam, misal= 17:30)</span></font></td>
</tr>
<tr>
<td>Tempat</td>
<td><strong>:</strong></td>
<td><input name="frm_tempat_go" type="text" class="tekboxku" id="frm_tempat_go" value="<?php echo $frm_tempat_go; ?>" size="50" maxlength="50">
<font color="#FF0000">*<span class="style1"> tempat acara dilaksanakan</span></font></td>
</tr>
<tr>
<td width="25%" valign="top" nowrap>Fasilitas Transportasi</td>
<td valign="top"><strong>:</strong></td>
<td><input name="frm_transportasi_go" type="text" class="tekboxku" id="frm_transportasi_go" size="50" maxlength="100" value="<?php echo $frm_transportasi_go; ?>">
<font color="#FF0000">*</font></td>
</tr>
</table></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td colspan="3"><table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td><u>KEMBALI</u></td>
<td width="1%"> </td>
<td width="79%"> </td>
</tr>
<tr>
<td>Hari</td>
<td><strong>:</strong></td>
<td>
<select name="frm_hari_dtg" id="frm_hari_dtg" class="tekboxku">
<? if (isset($frm_hari_dtg)) {?>
<option>--Pilih--</option>
<option value="Senin" <? if ($frm_hari_dtg=="Senin") echo "selected"?>>Senin</option>
<option value="Selasa" <? if ($frm_hari_dtg=="Selasa") echo "selected"?>>Selasa</option>
<option value="Rabu" <? if ($frm_hari_dtg=="Rabu") echo "selected"?>>Rabu</option>
<option value="Kamis" <? if ($frm_hari_dtg=="Kamis") echo "selected"?>>Kamis</option>
<option value="Jumat" <? if ($frm_hari_dtg=="Jumat") echo "selected"?>>Jumat</option>
<option value="Sabtu" <? if ($frm_hari_dtg=="Sabtu") echo "selected"?>>Sabtu</option>
<option value="Minggu" <? if ($frm_hari_dtg=="Minggu") echo "selected"?>>Minggu</option>
<? } else {?>
<option>--Pilih--</option>
<option value="Senin">Senin</option>
<option value="Selasa">Selasa</option>
<option value="Rabu">Rabu</option>
<option value="Kamis">Kamis</option>
<option value="Jumat">Jumat</option>
<option value="Sabtu">Sabtu</option>
<option value="Minggu">Minggu</option>
<? }?>
</select>
<font color="#FF0000">*</font></td>
</tr>
<tr>
<td>Tanggal</td>
<td><strong>:</strong></td>
<td><input name="frm_tgl_dtg" type="text" class="tekboxku" id="frm_tgl_dtg" value="<?php echo $frm_tgl_dtg;?>" size="10" maxlength="10">
<A Href="javascript:show_calendar('publikasi.frm_tgl_dtg',0,0,'DD/MM/YYYY')"> <img src="../img/date.png" width="22" height="22" align="absbottom" border=0> </A>(dd/mm/yyyy) <font color="#FF0000">*</font></td>
</tr>
<tr>
<td>Pukul</td>
<td><strong>:</strong></td>
<td><input name="frm_pukul_dtg" type="text" class="tekboxku" id="frm_pukul_dtg" value="<?php echo $frm_pukul_dtg; ?>" size="6" maxlength="5">
<font color="#FF0000">*<span class="style1">(format 24 jam, misal= 17:30)</span></font></td>
</tr>
<tr>
<td width="25%" nowrap>Fasilitas Transportasi</td>
<td><strong>:</strong></td>
<td>
<input name="frm_transportasi_dtg" type="text" class="tekboxku" id="frm_transportasi_dtg" size="50" maxlength="100" value="<?php echo $frm_transportasi_dtg; ?>">
<font color="#FF0000">*</font></td>
</tr>
</table></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td colspan="3"><table width="100%" border="0" cellspacing="0" cellpadding="2">
<tr>
<td colspan="3" valign="top"> </td>
</tr>
<tr>
<td colspan="3" valign="top"><u>Pembiayaan yang diperlukan (berikan tanda check pada kotak/lengkapi isian yang tersedia)</u></td>
</tr>
<tr>
<td valign="top"> </td>
<td valign="top"> </td>
<td> </td>
</tr>
<tr>
<td valign="top">Biaya program <br>
(Rp. / Mata Uang Asing) </td>
<td valign="top"><strong>:</strong></td>
<? //onKeyPress="return isNumberKey(event)" ?>
<td valign="top"><input name="frm_biaya" id="frm_biaya" type="text" class="tekboxku" size="20" maxlength="30" value="<?php echo $frm_biaya; ?>" >
<font color="#FF0000" size="1">misal: Rp.700.000 | US 850 *</font></td>
</tr>
<tr>
<td width="25%" valign="top">Lain-lain </td>
<td width="1%" valign="top"><strong>:</strong></td>
<td width="79%"><table width="90%" border="0" cellspacing="0" cellpadding="3">
<tr>
<td width="21%"><input type="checkbox" name="chk_airport" id="chk_airport" <? if ($chk_airport=='1') echo "checked";?>>
Airport Tax </td>
<td width="8%"> </td>
<td width="71%"><input type="checkbox" name="chk_fiskal" id="chk_fiskal" <? if ($chk_fiskal==1) echo "checked";?>>
Fiskal Luar Negeri </td>
</tr>
<tr>
<td><input type="checkbox" name="chk_visa" id="chk_visa" <? if ($chk_visa==1) echo "checked";?>>
Visa</td>
<td> </td>
<td><input type="checkbox" name="chk_uang_saku" id="chk_uang_saku" <? if ($chk_uang_saku==1) echo "checked";?>>
Uang Saku (biaya hidup) </td>
</tr>
<tr>
<td nowrap><input type="checkbox" name="chk_akomodasi" id="chk_akomodasi" <? if ($chk_akomodasi==1) echo "checked";?>>
Akomodasi</td>
<td> </td>
<td>
<script language="javascript">
function cek()
{
if (document.getElementById("chk_lainnya").checked==true)
{
document.getElementById("frm_lainnya").disabled=false;
}
else if (document.getElementById("chk_lainnya").checked==false)
{
document.getElementById("frm_lainnya").disabled=true;
}
}
</script>
<input type="checkbox" name="chk_lainnya" id="chk_lainnya" onClick="cek();" <? if ($frm_lainnya <>'') echo "checked";?>>
<input name="frm_lainnya" id="frm_lainnya" type="text" class="tekboxku" size="40" maxlength="255" value="<?php echo $frm_lainnya; ?>" disabled>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td nowrap> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td width="25%" valign="top" nowrap>Non degree training terakhir </td>
<td valign="top"><strong>:</strong></td>
<td>
<textarea name="frm_ndt" id="frm_ndt" cols="50" class="tekboxku"><?php echo $frm_ndt; ?></textarea>
</td>
</tr>
</table></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td>
<input type="submit" name="Submit" id="Submit" value="Simpan" onClick="this.form.action+='?act=1&jum=<? echo $jum;?>';this.form.submit();" class="tombol">
<input type="reset" name="Submit2" id="Submit2" value="Batal" onClick="this.form.action+='?act=3';this.form.submit();" class="tombol">
<?php if ($frm_no_st_pub_now) { ?>
<input type="button" name="Submit3" id="Submit3" value="Hapus" onClick="if(confirm('Hapus ?')){this.form.action+='?act=2&no_st=<?php echo $frm_no_st_pub_now;?>';this.form.submit()};" class="tombol">
<input type="submit" name="submit1" id="submit1" value="PRINT" onClick="cetak();" class="tombol">
<?php } ?></td>
</tr>
<tr>
<td colspan="4"> </td>
</tr>
<tr>
<td colspan="4"><font color="#FF0000" size="1">*</font><font size="1"> =
compulsory / harus diisi</font></td>
</tr>
</table>
</form>
</body>
</html> | fiafayo/bonecrusher | dosen/pen_st_publikasi_entry.php | PHP | gpl-2.0 | 57,076 |
/*
* Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.graalvm.wasm;
import com.oracle.truffle.api.ExactMath;
import static java.lang.Integer.compareUnsigned;
/**
* The class {@code WasmMath} contains methods for performing specific numeric operations such as
* unsigned arithmetic, which are not built in Java nor provided by the {@link Math} class.
*/
public final class WasmMath {
/**
* The number of logical bits in the significand of a {@code double}, <strong>excluding</strong>
* the implicit bit.
*/
private static final long DOUBLE_SIGNIFICAND_WIDTH = 52;
/**
* Bit mask to isolate the significand field of a <code>double</code>.
*/
public static final long DOUBLE_SIGNIFICAND_BIT_MASK = 0x000FFFFFFFFFFFFFL;
/**
* The spacing between two consecutive {@code float} values (aka Unit in the Last Place) in the
* range [2^31, 2^32): 2^40.
*/
private static final long FLOAT_POWER_63_ULP = (long) Math.ulp(0x1p63f);
/**
* The spacing between two consecutive {@code double} values (aka Unit in the Last Place) in the
* range [2^63, 2^64): 2^11.
*/
private static final long DOUBLE_POWER_63_ULP = (long) Math.ulp(0x1p63);
/**
* Don't let anyone instantiate this class.
*/
private WasmMath() {
}
/**
* Returns the sum of two unsigned ints.
*
* @throws ArithmeticException if the operation overflows
*/
public static int addExactUnsigned(int a, int b) {
// See GR-28305 for more background and possible intrinsification of this method.
final int result = a + b;
if (compareUnsigned(result, a) < 0) {
throw new ArithmeticException("unsigned int overflow");
}
return result;
}
/**
* Returns the minimum of two unsigned ints.
*/
public static int minUnsigned(int a, int b) {
return compareUnsigned(a, b) < 0 ? a : b;
}
/**
* Returns the maximum of two unsigned ints.
*/
public static int maxUnsigned(int a, int b) {
return compareUnsigned(a, b) > 0 ? a : b;
}
/**
* Returns the value of the {@code long} argument as an {@code int}; throwing an exception if
* the value overflows an unsigned {@code int}.
*
* @throws ArithmeticException if the argument is outside of the unsigned int32 range
* @since 1.8
*/
public static int toUnsignedIntExact(long value) {
if (value < 0 || value > 0xffff_ffffL) {
throw new ArithmeticException("unsigned int overflow");
}
return (int) value;
}
/**
* Converts the given unsigned {@code int} to the closest {@code float} value.
*/
public static float unsignedIntToFloat(int x) {
return unsignedIntToLong(x);
}
/**
* Converts the given unsigned {@code int} to the closest {@code double} value.
*/
public static double unsignedIntToDouble(int x) {
return unsignedIntToLong(x);
}
/**
* Converts the given unsigned {@code int} to the corresponding {@code long}.
*/
public static long unsignedIntToLong(int x) {
// See https://stackoverflow.com/a/22938125.
return x & 0xFFFFFFFFL;
}
/**
* Converts the given unsigned {@code long} to the closest {@code float} value.
*/
public static float unsignedLongToFloat(long x) {
if (x >= 0) {
// If the first bit is not set, then we can simply cast which is faster.
return x;
}
// Transpose x from [Integer.MIN_VALUE,-1] to [0, Integer.MAX_VALUE]
final long shiftedX = x + Long.MIN_VALUE;
// We cannot simply compute 0x1p63f + shiftedX because it yields incorrect results in some
// edge cases due to rounding twice (conversion to long, and addition). See
// https://github.com/WebAssembly/spec/issues/421 and mentioned test cases for more context.
// Instead, we manually compute the offset from 0x1p63f.
final boolean roundUp = shiftedX % FLOAT_POWER_63_ULP > FLOAT_POWER_63_ULP / 2;
final long offset = (shiftedX / FLOAT_POWER_63_ULP) + (roundUp ? 1 : 0);
// Return the offset-nth next floating-point value starting from 2^63. This is equivalent to
// incrementing the significand (as Math.nextUp would do) offset times.
return 0x1p63f + (offset * (float) FLOAT_POWER_63_ULP);
}
/**
* Converts the given unsigned {@code long} to the closest {@code double} value.
*/
public static double unsignedLongToDouble(long x) {
if (x >= 0) {
// If the first bit is not set, then we can simply cast which is faster.
return x;
}
// Transpose x from [Long.MIN_VALUE,-1] to [0, Long.MAX_VALUE].
final long shiftedX = x + Long.MIN_VALUE;
// We cannot simply compute 0x1p63 + shiftedX because it yields incorrect results in some
// edge cases due to rounding twice (conversion to long, and addition). See
// https://github.com/WebAssembly/spec/issues/421 and mentioned test cases for more context.
// Instead, we manually compute the offset from 0x1p63.
final boolean roundUp = shiftedX % DOUBLE_POWER_63_ULP > DOUBLE_POWER_63_ULP / 2;
final long offset = (shiftedX / DOUBLE_POWER_63_ULP) + (roundUp ? 1 : 0);
// Return the offset-nth next floating-point value starting form 2^63. This is equivalent to
// incrementing the significand (as Math.nextUp would do) offset times.
return 0x1p63 + (offset * (double) DOUBLE_POWER_63_ULP);
}
/**
* Removes the decimal part (aka truncation or rounds towards zero) of the given float and
* converts it to a <strong>signed</strong> long.
* <p>
* The operation is saturating: if the float is smaller than {@link Integer#MIN_VALUE} or larger
* than {@link Integer#MAX_VALUE}, then respectively {@link Integer#MIN_VALUE} or
* {@link Integer#MAX_VALUE} is returned.
*/
public static long truncFloatToLong(float x) {
return truncDoubleToLong(x);
}
/**
* Removes the decimal part (aka truncation or rounds towards zero) of the given double and
* converts it to a <strong>signed</strong> long.
* <p>
* The operation is saturating: if the double is smaller than {@link Long#MIN_VALUE} or larger
* than {@link Long#MAX_VALUE}, then respectively {@link Long#MIN_VALUE} or
* {@link Long#MAX_VALUE} is returned.
*/
public static long truncDoubleToLong(double x) {
return (long) ExactMath.truncate(x);
}
/**
* Removes the decimal part (aka truncation or rounds towards zero) of the given float and
* converts it to an <strong>unsigned</strong> long.
* <p>
* The operation is saturating: if the float is smaller than 0 or larger than 2^32 - 1, then
* respectively 0 or 2^32 - 1 is returned.
*/
public static long truncFloatToUnsignedLong(float x) {
return truncDoubleToUnsignedLong(x);
}
/**
* Removes the decimal part (aka truncation or rounds towards zero) of the given double and
* converts it to an <strong>unsigned</strong> long.
* <p>
* The operation is saturating: if the double is smaller than 0 or larger than 2^64 - 1, then
* respectively 0 or 2^64 - 1 is returned.
*/
public static long truncDoubleToUnsignedLong(double x) {
if (x < Long.MAX_VALUE) {
// If the first bit is not set, then we use the signed variant which is faster.
return truncDoubleToLong(x);
}
// There is no direct way to convert a double to an _unsigned_ long in Java. Therefore we
// manually split the binary representation of x into significand (aka base or mantissa) and
// exponent, and compute the resulting long by shifting the significand.
final long shift = Math.getExponent(x) - DOUBLE_SIGNIFICAND_WIDTH;
final long xBits = Double.doubleToRawLongBits(x);
final long significand = (1L << DOUBLE_SIGNIFICAND_WIDTH) | (xBits & DOUBLE_SIGNIFICAND_BIT_MASK);
if (shift >= Long.SIZE - DOUBLE_SIGNIFICAND_WIDTH) {
// Saturation: if x is too large to convert to a long, we return the highest possible
// value (all bits set).
return 0xffff_ffff_ffff_ffffL;
} else if (shift > 0) {
// Multiply significand by 2^shift.
return significand << shift;
}
// Should not reach here because x >= Long.MAX_VALUE, so shift >=
// (Math.getExponent(Long.MAX_VALUE) - DOUBLE_SIGNIFICAND_WIDTH) == 11.
if (shift >= -DOUBLE_SIGNIFICAND_WIDTH) {
// Multiply significand by 2^shift == divide significand by 2^(-shift).
return significand >> -shift;
} else {
// Saturation: if x is too small to convert to a long, we return 0.
return 0;
}
}
}
| smarr/Truffle | wasm/src/org.graalvm.wasm/src/org/graalvm/wasm/WasmMath.java | Java | gpl-2.0 | 11,005 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Homework2_Problem1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hewlett-Packard")]
[assembly: AssemblyProduct("Homework2_Problem1")]
[assembly: AssemblyCopyright("Copyright © Hewlett-Packard 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a3dab498-fe33-40ca-85c4-e9475bbb8053")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| Meowse/TechnicolorMillinery | Chris.DelaPena/Homework 1/Homework2_Problem1/Homework2_Problem1/Properties/AssemblyInfo.cs | C# | gpl-2.0 | 1,442 |
package org.vidogram.messenger.exoplayer.f;
public final class f
{
public final int a;
public final int b;
public final int c;
public final int d;
public final int e;
public final int f;
public final int g;
public final long h;
public f(byte[] paramArrayOfByte, int paramInt)
{
paramArrayOfByte = new l(paramArrayOfByte);
paramArrayOfByte.a(paramInt * 8);
this.a = paramArrayOfByte.c(16);
this.b = paramArrayOfByte.c(16);
this.c = paramArrayOfByte.c(24);
this.d = paramArrayOfByte.c(24);
this.e = paramArrayOfByte.c(20);
this.f = (paramArrayOfByte.c(3) + 1);
this.g = (paramArrayOfByte.c(5) + 1);
this.h = paramArrayOfByte.c(36);
}
public int a()
{
return this.g * this.e;
}
public long b()
{
return this.h * 1000000L / this.e;
}
}
/* Location: G:\programs\dex2jar-2.0\vidogram-dex2jar.jar
* Qualified Name: org.vidogram.messenger.exoplayer.f.f
* JD-Core Version: 0.6.0
*/ | Robert0Trebor/robert | TMessagesProj/src/main/java/org/vidogram/messenger/exoplayer/f/f.java | Java | gpl-2.0 | 979 |
package org.jmlspecs.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CodeJavaMath {
}
| shunghsiyu/OpenJML_XOR | JMLAnnotations/src/org/jmlspecs/annotation/CodeJavaMath.java | Java | gpl-2.0 | 254 |
package roart.pacman.graphic;
public interface Shapes {
byte PACMAN0_BITS[]= {(byte) 0x3c,(byte) 0x7e,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0x7e,(byte) 0x3c};
byte PACMANRIGHT_BITS[]= {(byte) 0x3c,(byte) 0x68,(byte) 0xf0,(byte) 0xe0,(byte) 0xe0,(byte) 0xf0,(byte) 0x78,(byte) 0x3c};
byte PACMANLEFT_BITS[]={(byte) 0x3c,(byte) 0x16,(byte) 0x0f,(byte) 0x07,(byte) 0x07,(byte) 0x0f,(byte) 0x1e,(byte) 0x3c};
byte PACMANUP_BITS[]= {(byte) 0x00,(byte) 0x00,(byte) 0x81,(byte) 0xc3,(byte) 0xa7,(byte) 0xff,(byte) 0x7e,(byte) 0x3c};
byte PACMANDOWN_BITS[]= {(byte) 0x3c,(byte) 0x7e,(byte) 0xff,(byte) 0xa7,(byte) 0xc3,(byte) 0x81,(byte) 0x00,(byte) 0x00};
byte VERTWALL_BITS[]={(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c};
byte HORIWALL_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0x00,(byte) 0x00};
byte BLANK_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00};
byte CROSS_BITS[]={(byte) 0x3c,(byte) 0x3c,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0x3c,(byte) 0x3c};
byte FOOD_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0x18,(byte) 0x3c,(byte) 0x3c,(byte) 0x18,(byte) 0x00,(byte) 0x00};
byte SUPERFOOD_BITS[]={(byte) 0x00,(byte) 0x3c,(byte) 0x7e,(byte) 0x7e,(byte) 0x7e,(byte) 0x7e,(byte) 0x3c,(byte) 0x00};
byte GHOST_BITS[]={(byte) 0x18,(byte) 0x7e,(byte) 0xff,(byte) 0xdb,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0xa5};
byte CORNER1_BITS[]={(byte) 0x3c,(byte) 0x3e,(byte) 0x3f,(byte) 0x3f,(byte) 0x3f,(byte) 0x1f,(byte) 0x00,(byte) 0x00};
byte CORNER4_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0x1f,(byte) 0x3f,(byte) 0x3f,(byte) 0x3f,(byte) 0x3e,(byte) 0x3c};
byte CORNER3_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0xf8,(byte) 0xfc,(byte) 0xfc,(byte) 0xfc,(byte) 0x7c,(byte) 0x3c};
byte CORNER2_BITS[]={(byte) 0x3c,(byte) 0x7c,(byte) 0xfc,(byte) 0xfc,(byte) 0xfc,(byte) 0xf8,(byte) 0x00,(byte) 0x00};
byte SPECWALL_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0xff,(byte) 0x00,(byte) 0x00,(byte) 0xff,(byte) 0x00,(byte) 0x00};
byte BONUSPOINT_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0x24,(byte) 0x18,(byte) 0x18,(byte) 0x24,(byte) 0x00,(byte) 0x00};
byte BONUSLIFE_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0x1c,(byte) 0x38,(byte) 0x38,(byte) 0x1c,(byte) 0x00,(byte) 0x00};
byte E0_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0xf8,(byte) 0xfc,(byte) 0xfc,(byte) 0xf8,(byte) 0x00,(byte) 0x00};
byte E90_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0x18,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c};
byte E180_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0x1f,(byte) 0x3f,(byte) 0x3f,(byte) 0x1f,(byte) 0x00,(byte) 0x00};
byte E270_BITS[]={(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x3c,(byte) 0x18,(byte) 0x00,(byte) 0x00};
byte T0_BITS[]={(byte) 0x00,(byte) 0x00,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0x7e,(byte) 0x3c};
byte T90_BITS[]={(byte) 0x3c,(byte) 0x3e,(byte) 0x3f,(byte) 0x3f,(byte) 0x3f,(byte) 0x3f,(byte) 0x3e,(byte) 0x3c};
byte T180_BITS[]={(byte) 0x3c,(byte) 0x7e,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0xff,(byte) 0x00,(byte) 0x00};
byte T270_BITS[]={(byte) 0x3c,(byte) 0x7c,(byte) 0xfc,(byte) 0xfc,(byte) 0xfc,(byte) 0xfc,(byte) 0x7c,(byte) 0x3c};
// #elif defined VTX //vt??? unix only
// byte pacman0_bits[]={'P'};
// byte pacmanleft_bits[]={'P'};
// byte pacmanright_bits[]={'P'};
// byte pacmanup_bits[]= {'P'};
// byte pacmandown_bits[]= {'P'};
// byte vertwall_bits[]={'|'};
// byte horiwall_bits[]={'-'};
// byte blank_bits[]={' '};
// byte cross_bits[]={'+'};
// byte food_bits[]={'.'};
// byte superfood_bits[]={'o'};
// byte ghost_bits[]={'G'};
// byte corner2_bits[]={'X'};
// byte corner3_bits[]={'X'};
// byte corner4_bits[]={'X'};
// byte corner1_bits[]={'X'};
// byte specwall_bits[]={'_'};
// byte bonuspoint_bits[]={'?'};
// byte bonuslife_bits[]={'p'};
// byte e180_bits[]={'-'};
// byte e90_bits[]={'|'};
// byte e0_bits[]={'-'};
// byte e270_bits[]={'|'};
// byte t0_bits[]={'-'};
// byte t270_bits[]={'|'};
// byte t180_bits[]={'-'};
// byte t90_bits[]={'|'};
// #endif
}
| rroart/pacman | src/main/java/roart/pacman/graphic/Shapes.java | Java | gpl-2.0 | 4,172 |
<?php
namespace UmnLib\Core\Isbn;
class Isbn13 extends Isbn
{
/*
# $Revision: 2.8 $
# $Id: ISBN13.pm,v 2.8 2007/09/17 02:34:58 comdog Exp $
package Business::ISBN13;
use strict;
use base qw(Business::ISBN);
use Business::ISBN qw(:all);
use Data::Dumper;
use subs qw(
_checksum
INVALID_COUNTRY_CODE
INVALID_PUBLISHER_CODE
BAD_CHECKSUM
GOOD_ISBN
BAD_ISBN
);
use vars qw(
$VERSION
$debug
);
use Carp qw(carp croak cluck);
my $debug = 0;
$VERSION = '2.05';
*/
//sub _max_length { 13 }
public static function maxLength()
{
return 13;
}
// This is clunky; shouldn't need a type at all, especially since
// we support only OO for PHP.
//sub _set_type { $_[0]->{type} = 'ISBN13' }
/*
sub _parse_prefix
{
my $isbn = $_[0]->isbn; # stupid workaround for 'Can't modify non-lvalue subroutine call'
( $isbn =~ /\A(97[89])(.{10})\z/g )[0];
}
*/
public static function parsePrefix($isbn)
{
preg_match('/^(97[89])(.{10})$/', $isbn, $matches);
if (!isset($matches[1])) {
throw new \InvalidArgumentException("ISBN13 '$isbn' has an invalid prefix.");
}
return $matches[1];
}
/*
sub _set_prefix
{
croak "Cannot set prefix [$_[1]] on an ISBN-13"
unless $_[1] =~ m/\A97[89]\z/;
$_[0]->{prefix} = $_[1];
}
*/
public function setPrefix($prefix)
{
if (preg_match('/^97[89]$/', $prefix)) {
$this->prefix = $prefix;
return $this;
}
throw new \InvalidArgumentException("Prefix '$prefix' is invalid.");
}
/*
sub _hyphen_positions
{
[
$_[0]->_prefix_length,
$_[0]->_prefix_length + $_[0]->_group_code_length,
$_[0]->_prefix_length + $_[0]->_group_code_length + $_[0]->_publisher_code_length,
$_[0]->_checksum_pos,
]
}
*/
// Important: these positions will be used in reverse order!!!
public function hyphenPositions()
{
$prefixLength = strlen($this->prefix());
$groupCodeLength = strlen($this->groupCode());
return array(
$prefixLength,
$prefixLength + $groupCodeLength,
$prefixLength + $groupCodeLength + strlen($this->publisherCode()),
$this->checksumPos(),
);
}
/*
# sub group { 'Bookland' }
sub as_isbn10
{
my $self = shift;
return unless $self->prefix eq '978';
my $isbn10 = Business::ISBN->new(
substr( $self->isbn, 3 )
);
$isbn10->fix_checksum;
return $isbn10;
}
*/
public function asIsbn10()
{
$isbn10MinusChecksum =
$this->groupCode() .
$this->publisherCode() .
$this->articleCode();
$isbn10Checksum =
Isbn10::calculateChecksum($isbn10MinusChecksum);
$paramIsbn = $isbn10MinusChecksum . $isbn10Checksum;
$isbn10 = new Isbn10(array(
'isbn' => $paramIsbn,
));
return $isbn10;
}
/*
sub as_isbn13
{
my $self = shift;
my $isbn13 = Business::ISBN->new( $self->as_string );
$isbn13->fix_checksum;
return $isbn13;
}
*/
public function asIsbn13()
{
$isbn13 = new Isbn13(array(
'isbn' => $this->isbn(),
));
return $isbn13;
}
/*
#internal function. you don't get to use this one.
sub _checksum
{
my $data = $_[0]->isbn;
return unless defined $data;
my @digits = split //, $data;
my $sum = 0;
foreach my $index ( 0, 2, 4, 6, 8, 10 )
{
$sum += substr($data, $index, 1);
$sum += 3 * substr($data, $index + 1, 1);
}
#take the next higher multiple of 10 and subtract the sum.
#if $sum is 37, the next highest multiple of ten is 40. the
#check digit would be 40 - 37 => 3.
my $checksum = ( 10 * ( int( $sum / 10 ) + 1 ) - $sum ) % 10;
return $checksum;
}
*/
// I found "_checksum" non-descriptive, so I call it "calculateChecksum".
public static function calculateChecksum( $isbnMinusChecksum )
{
if (strlen($isbnMinusChecksum) != self::maxLength() -1) {
throw new \InvalidArgumentException("Invalid length for argument isbnMinusChecksum '$isbnMinusChecksum'.");
}
$sum = 0;
foreach (array(0,2,4,6,8,10) as $index) {
//$sum += substr($isbn, $index, 1);
//$sum += 3 * substr($isbn, $index + 1, 1);
$sum += substr($isbnMinusChecksum, $index, 1);
$sum += 3 * substr($isbnMinusChecksum, $index + 1, 1);
}
// Take the next higher multiple of 10 and subtract the sum.
// If $sum is 37, the next highest multiple of ten is 40. The
// check digit would be 40 - 37 => 3.
$checksum = (10 * ((int)($sum/10) + 1) - $sum) % 10;
return $checksum;
}
}
/*
1;
__END__
=head1 NAME
Business::ISBN13 - work with 13 digit International Standard Book Numbers
=head1 SYNOPSIS
See L<Business::ISBN>
=head1 DESCRIPTION
See L<Business::ISBN>
=head1 SOURCE AVAILABILITY
This source is in Github.
http://github.com/briandfoy/business--isbn/tree/master
=head1 AUTHOR
brian d foy C<< <bdfoy@cpan.org> >>
=head1 COPYRIGHT AND LICENSE
Copyright (c) 2001-2009, brian d foy, All Rights Reserved.
You may redistribute this under the same terms as Perl itself.
=cut
*/
| UMNLibraries/isbn-php | src/Isbn13.php | PHP | gpl-2.0 | 5,000 |
<?php
namespace MineBlock\WorldGenerator;
use pocketmine\level\generator\Generator;
use pocketmine\level\generator\GenerationChunkManager;
use pocketmine\math\Vector3;
use pocketmine\utils\Random;
use pocketmine\block\Block;
class OreTreeFlatGN extends Generator{
private $level, $options, $random, $floatSeed;
public function getSettings(){
return $this->options;
}
public function getName(){
return "oretreeflat";
}
public function __construct(array $option = []){
$this->options = [];
}
public function init(GenerationChunkManager $level, Random $random){
$this->level = $level;
$this->random = $random;
$this->floatSeed = $this->random->nextFloat();
}
public function generateChunk($chunkX, $chunkZ){
$this->random->setSeed((int) (($chunkX * 0xdead + $chunkZ * 0xbeef) * $this->floatSeed));
$chunk = $this->level->getChunk($chunkX, $chunkZ);
$list = [1 => 1000, 16 => 50, 15 => 20, 73 => 10, 14 => 6, 21 => 4, 56 => 3];
$blocks = [];
foreach($list as $k => $v){
for($f = 0; $f < $v; $f++)
$blocks[] = $k;
}
$rX = rand(0, 5);
$rZ = rand(0, 5);
$rrX = rand(6, 11);
$rrZ = rand(6, 11);
foreach([[0, 3, 1, 18, 12], [0, 3, 2, 18, 12], [0, 3, 3, 18, 12], [1, 3, 0, 18, 12], [1, 3, 1, 18, 12], [1, 3, 2, 18, 12], [1, 3, 3, 18, 12], [1, 3, 4, 18, 12], [1, 4, 1, 18, 12], [1, 4, 2, 18, 12], [1, 4, 3, 18, 12], [1, 5, 2, 18, 12], [2, 0, 2, 17, 0], [2, 1, 2, 17, 0], [2, 2, 2, 17, 0], [2, 3, 0, 18, 12], [2, 3, 1, 18, 12], [2, 3, 2, 17, 0], [2, 3, 3, 18, 12], [2, 3, 4, 18, 12], [2, 4, 1, 18, 12], [2, 4, 2, 17, 0], [2, 4, 3, 18, 12], [2, 5, 1, 18, 12], [2, 5, 2, 18, 12], [2, 5, 3, 18, 12], [3, 3, 0, 18, 12], [3, 3, 1, 18, 12], [3, 3, 2, 18, 12], [3, 3, 3, 18, 12], [3, 3, 4, 18, 12], [3, 4, 1, 18, 12], [3, 4, 2, 18, 12], [3, 4, 3, 18, 12], [3, 5, 2, 18, 12], [4, 3, 1, 18, 12], [4, 3, 2, 18, 12], [4, 3, 3, 18, 12]] as $b){
$chunk->setBlockId($b[0] + $rX, $b[1] + 64, $b[2] + $rZ, $b[3]);
$chunk->setBlockData($b[0] + $rX, $b[1] + 64, $b[2] + $rZ, $b[4]);
$chunk->setBlockId($b[0] + $rrX, $b[1] + 64, $b[2] + $rrZ, $b[3]);
$chunk->setBlockData($b[0] + $rrX, $b[1] + 64, $b[2] + $rrZ, $b[4]);
}
for($z = 0; $z < 16; $z++){
for($x = 0; $x < 16; $x++){
$chunk->setBlockId($x, 0, $z, 7);
$chunk->setBlockId($x, 62, $z, 3);
$chunk->setBlockId($x, 63, $z, 2);
}
}
for($y = 1; $y < 61; $y++){
for($z = 0; $z < 16; $z++){
for($x = 0; $x < 16; $x++){
$chunk->setBlockId($x, $y, $z, $blocks[array_rand($blocks)]);
}
}
}
}
public function populateChunk($chunkX, $chunkZ){}
public function getSpawn(){
return new Vector3(128, 3, 128);
}
} | rj0495/PocketMinePlugin | WorldGenerator/src/MineBlock/WorldGenerator/OreTreeFlatGN.php | PHP | gpl-2.0 | 2,722 |
<?php
use mvc\routing\routingClass as routing;
$id = controlCalidadTableClass::ID;
$fecha = controlCalidadTableClass::FECHA;
$variedad = controlCalidadTableClass::VARIEDAD;
$edad = controlCalidadTableClass::EDAD;
$brix = controlCalidadTableClass::BRIX;
$ph = controlCalidadTableClass::PH;
$ar = controlCalidadTableClass::AR;
$sacarosa = controlCalidadTableClass::SACAROSA;
$pureza = controlCalidadTableClass::PUREZA;
$empleado_id = controlCalidadTableClass::EMPLEADO_ID;
$proveedor_id = controlCalidadTableClass::PROVEEDOR_ID;
$pdf = new FPDF('l', 'mm', 'letter');
$pdf->AddPage();
$pdf->Cell(80);
$pdf->SetFont('courier','B',12);
$pdf->Image(routing::getInstance()->getUrlImg('logoProyecto.jpg'),0,0,280);
$pdf ->Ln(50);
$pdf->Cell(245,10,'REPORTE CONTROL CALIDAD',1,1,'C');
$pdf->Cell(45,10, utf8_decode("FECHA"),1);
$pdf->Cell(24,10, utf8_decode("VARIEDAD"),1);
$pdf->Cell(15,10, utf8_decode("EDAD"),1);
$pdf->Cell(15,10, utf8_decode("BRIX"),1);
$pdf->Cell(15,10, utf8_decode("PH"),1);
$pdf->Cell(15,10, utf8_decode("AR"),1);
$pdf->Cell(26,10, utf8_decode("SACAROSA"),1);
$pdf->Cell(20,10, utf8_decode("PUREZA"),1);
$pdf->Cell(35,10, utf8_decode("EMPLEADO"),1);
$pdf->Cell(35,10, utf8_decode("PROVEEDOR"),1);
$pdf->Ln();
foreach ($objControlCalidad as $control){
$pdf->Cell(45,10, utf8_decode($control->$fecha),1);
$pdf->Cell(24,10, utf8_decode($control->$variedad),1);
$pdf->Cell(15,10, utf8_decode($control->$edad),1);
$pdf->Cell(15,10, utf8_decode($control->$brix),1);
$pdf->Cell(15,10, utf8_decode($control->$ph),1);
$pdf->Cell(15,10, utf8_decode($control->$ar),1);
$pdf->Cell(26,10, utf8_decode($control->$sacarosa),1);
$pdf->Cell(20,10, utf8_decode($control->$pureza),1);
$pdf->Cell(35,10, utf8_decode(controlCalidadTableClass::getNameEmpleado($control->$empleado_id)),1);
$pdf->Cell(35,10, utf8_decode(controlCalidadTableClass::getNameProveedor($control->$proveedor_id)),1);
$pdf ->Ln();
}
$pdf->Output();
| Carlosbarrera585c/Laura | view/controlCalidad/reportTemplate.pdf.php | PHP | gpl-2.0 | 2,033 |
package models
import (
"fmt"
"github.com/confur-me/confur-api/db"
"time"
)
type Event struct {
ID uint `gorm:"primary_key" json:"id"`
ConferenceSlug *string `sql:"not null;index" binding:"required" json:"conference_slug"`
Conference *Conference `json:"conference,omitempty" gorm:"foreignkey:conference_slug"`
Scope *string `sql:"not null;index" json:"scope" binding:"required"`
Title string `sql:"type:text" binding:"required" json:"title"`
Description string `sql:"type:text" json:"description"`
Country string `sql:"index:idx_country_state_city_address" json:"country"`
City string `sql:"index:idx_country_state_city_address" json:"city"`
State string `sql:"index:idx_country_state_city_address" json:"state"`
Address string `sql:"type:text;index:idx_country_state_city_address" json:"address"`
Speakers *[]Speaker `gorm:"many2many:events_speakers" json:"speakers,omitempty"`
Videos *[]Video `json:"videos,omitempty"`
VideosCount uint `sql:"not null;default:0" json:"videos_count"`
Thumbnail string `json:"thumbnail"`
IsActive *bool `sql:"not null;index" binding:"required" json:"-"`
StartsAt *time.Time `sql:"index" json:"starts_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"deleted_at,omitempty"`
}
type eventService struct {
Service
}
func NewEventService(params map[string]interface{}) *eventService {
s := new(eventService)
s.params = params
return s
}
func (this *eventService) Event() (*Event, error) {
var (
resource Event
err error
)
if conn, ok := db.Connection(); ok {
if v, ok := this.params["event"]; ok {
err = conn.Scopes(Active).Where("id = ?", v).Preload("Conference").First(&resource).Error
}
}
return &resource, err
}
func (this *eventService) Events() (*[]Event, error) {
var err error
collection := make([]Event, 0)
if conn, ok := db.Connection(); ok {
query := &conn
limit := 20 // Defaults to 20 items per page
page := 1
if v, ok := this.params["conference"]; ok {
query = query.Where("conference_slug = ?", v)
}
if v, ok := this.params["query"]; ok {
// FIXME: CHECK injection possibility
query = query.Where("title ILIKE ?", fmt.Sprintf("%%%v%%", v))
}
if _, ok := this.params["shuffle"]; ok {
query = query.Where("random() < 0.1")
}
if v, ok := this.params["limit"]; ok {
if v.(int) <= 50 {
limit = v.(int)
}
}
if v, ok := this.params["page"]; ok {
page = v.(int)
}
err = query.Scopes(Active, Paginate(limit, page)).Preload("Conference").Find(&collection).Error
}
return &collection, err
}
| confur-me/confur-api | api/models/event.go | GO | gpl-2.0 | 2,741 |
// **********************************************************************
//
// Generated by the ORBacus IDL to Java Translator
//
// Copyright (c) 2000
// Object Oriented Concepts, Inc.
// Billerica, MA, USA
//
// All Rights Reserved
//
// **********************************************************************
// Version: 4.0.5
package edu.iris.Fissures.IfNetwork;
//
// IDL:iris.edu/Fissures/IfNetwork/Response:1.0
//
final public class ResponseHelper
{
public static void
insert(org.omg.CORBA.Any any, Response val)
{
org.omg.CORBA.portable.OutputStream out = any.create_output_stream();
write(out, val);
any.read_value(out.create_input_stream(), type());
}
public static Response
extract(org.omg.CORBA.Any any)
{
if(any.type().equivalent(type()))
return read(any.create_input_stream());
else
throw new org.omg.CORBA.BAD_OPERATION();
}
private static org.omg.CORBA.TypeCode typeCode_;
public static org.omg.CORBA.TypeCode
type()
{
if(typeCode_ == null)
{
org.omg.CORBA.ORB orb = org.omg.CORBA.ORB.init();
org.omg.CORBA.StructMember[] members = new org.omg.CORBA.StructMember[2];
members[0] = new org.omg.CORBA.StructMember();
members[0].name = "the_sensitivity";
members[0].type = SensitivityHelper.type();
members[1] = new org.omg.CORBA.StructMember();
members[1].name = "stages";
members[1].type = StageSeqHelper.type();
typeCode_ = orb.create_struct_tc(id(), "Response", members);
}
return typeCode_;
}
public static String
id()
{
return "IDL:iris.edu/Fissures/IfNetwork/Response:1.0";
}
public static Response
read(org.omg.CORBA.portable.InputStream in)
{
Response _ob_v = new Response();
_ob_v.the_sensitivity = SensitivityHelper.read(in);
_ob_v.stages = StageSeqHelper.read(in);
return _ob_v;
}
public static void
write(org.omg.CORBA.portable.OutputStream out, Response val)
{
SensitivityHelper.write(out, val.the_sensitivity);
StageSeqHelper.write(out, val.stages);
}
}
| crotwell/fissuresIDL | src/main/java/edu/iris/Fissures/IfNetwork/ResponseHelper.java | Java | gpl-2.0 | 2,254 |
<?php
/**
* @version 1.0.0
* @package com_propuestas
* @copyright Copyright (C) 2015. Todos los derechos reservados.
* @license Licencia Pública General GNU versión 2 o posterior. Consulte LICENSE.txt
* @author Daniel Gustavo Álvarez Gaitán <info@danielalvarez.com.co> - http://danielalvarez.com.co
*/
// No direct access
defined('_JEXEC') or die;
require_once JPATH_COMPONENT . '/controller.php';
/**
* Tipo controller class.
*/
class PropuestasControllerTipo extends PropuestasController {
/**
* Method to check out an item for editing and redirect to the edit form.
*
* @since 1.6
*/
public function edit() {
$app = JFactory::getApplication();
// Get the previous edit id (if any) and the current edit id.
$previousId = (int) $app->getUserState('com_propuestas.edit.tipo.id');
$editId = JFactory::getApplication()->input->getInt('id', null, 'array');
// Set the user id for the user to edit in the session.
$app->setUserState('com_propuestas.edit.tipo.id', $editId);
// Get the model.
$model = $this->getModel('Tipo', 'PropuestasModel');
// Check out the item
if ($editId) {
$model->checkout($editId);
}
// Check in the previous user.
if ($previousId && $previousId !== $editId) {
$model->checkin($previousId);
}
// Redirect to the edit screen.
$this->setRedirect(JRoute::_('index.php?option=com_propuestas&view=tipoform&layout=edit', false));
}
/**
* Method to save a user's profile data.
*
* @return void
* @since 1.6
*/
public function publish() {
// Initialise variables.
$app = JFactory::getApplication();
//Checking if the user can remove object
$user = JFactory::getUser();
if ($user->authorise('core.edit', 'com_propuestas') || $user->authorise('core.edit.state', 'com_propuestas')) {
$model = $this->getModel('Tipo', 'PropuestasModel');
// Get the user data.
$id = $app->input->getInt('id');
$state = $app->input->getInt('state');
// Attempt to save the data.
$return = $model->publish($id, $state);
// Check for errors.
if ($return === false) {
$this->setMessage(JText::sprintf('Save failed: %s', $model->getError()), 'warning');
}
// Clear the profile id from the session.
$app->setUserState('com_propuestas.edit.tipo.id', null);
// Flush the data from the session.
$app->setUserState('com_propuestas.edit.tipo.data', null);
// Redirect to the list screen.
$this->setMessage(JText::_('COM_PROPUESTAS_ITEM_SAVED_SUCCESSFULLY'));
$menu = & JSite::getMenu();
$item = $menu->getActive();
$this->setRedirect(JRoute::_($item->link, false));
} else {
throw new Exception(500);
}
}
public function remove() {
// Initialise variables.
$app = JFactory::getApplication();
//Checking if the user can remove object
$user = JFactory::getUser();
if ($user->authorise($user->authorise('core.delete', 'com_propuestas'))) {
$model = $this->getModel('Tipo', 'PropuestasModel');
// Get the user data.
$id = $app->input->getInt('id', 0);
// Attempt to save the data.
$return = $model->delete($id);
// Check for errors.
if ($return === false) {
$this->setMessage(JText::sprintf('Delete failed', $model->getError()), 'warning');
} else {
// Check in the profile.
if ($return) {
$model->checkin($return);
}
// Clear the profile id from the session.
$app->setUserState('com_propuestas.edit.tipo.id', null);
// Flush the data from the session.
$app->setUserState('com_propuestas.edit.tipo.data', null);
$this->setMessage(JText::_('COM_PROPUESTAS_ITEM_DELETED_SUCCESSFULLY'));
}
// Redirect to the list screen.
$menu = & JSite::getMenu();
$item = $menu->getActive();
$this->setRedirect(JRoute::_($item->link, false));
} else {
throw new Exception(500);
}
}
}
| emeraldstudio/intranet | components/com_propuestas/controllers/tipo.php | PHP | gpl-2.0 | 4,524 |
#include <jni.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/features2d/features2d.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <vector>
#include "NativeVision/vision.h"
#include <time.h>
#include <android/log.h>
using namespace std;
using namespace cv;
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, "JNI_DEBUGGING", __VA_ARGS__)
double diffclock(clock_t clock1,clock_t clock2)
{
double diffticks=clock2-clock1;
double diffms=(diffticks*1000)/ CLOCKS_PER_SEC;
return diffms;
}
static Ptr<ORB> detector;
static Ptr<DescriptorMatcher> descriptorMatcher;
static vector<Mat> trainImages;
static bool training_complete = false;
static vector<string> billMapping;
extern "C" {
JNIEXPORT void JNICALL Java_com_artaveh_sepid_darwinwallet_Recognizer_nvInitialize(JNIEnv* env, jobject thiz)
{
LOGD( "Started nvInitialize" );
detector = getQueryDetector();
descriptorMatcher = getMatcher();
LOGD( "Finished nvInitialize" );
}
}
extern "C" {
JNIEXPORT void JNICALL Java_com_artaveh_sepid_darwinwallet_Recognizer_nvResetTrainedDatabase(JNIEnv* env, jobject thiz)
{
LOGD( "Started nvResetTrainedDatabase" );
training_complete = false;
descriptorMatcher = getMatcher();
trainImages.clear();
billMapping.clear();
LOGD( "Finished nvResetTrainedDatabase" );
}
}
extern "C" {
JNIEXPORT void JNICALL Java_com_artaveh_sepid_darwinwallet_Recognizer_nvTrainImage(JNIEnv* env, jobject thiz, jstring billname, jstring billpath)
{
//char* _imgBytes = (char*) env->GetPrimitiveArrayCritical(imgBytes, 0);
const char * _billpath = env->GetStringUTFChars(billpath, 0);
const char * _billname = env->GetStringUTFChars(billname, 0);
LOGD( "Started nvTrainImage" );
std::ostringstream out;
//std::ostringstream out;
//out << " : billname: " << _billname << ": BILLPATH: " << billpath << endl;
LOGD( out.str().c_str() );
//LOGD( "nvTrainImage: 1" );
//Mat mgray(1, bytelength, CV_8U, (unsigned char *)_imgBytes);
//LOGD( "nvTrainImage: 2" );
Mat img = imread(_billpath, 0);
//Mat img = imread("/sdcard/wallet/us/100b/full_pic.jpg", 0);
//LOGD( "nvTrainImage: 3" );
Mat trainData = trainImage( img, detector, descriptorMatcher );
out << "nvTrainImage: " << _billpath << " (" << trainData.rows << " x " << trainData.cols << ")" << endl;
LOGD( out.str().c_str() );
trainImages.push_back(trainData);
string billstr(_billname);
billMapping.push_back(billstr);
LOGD( "Finished nvTrainImage" );
env->ReleaseStringUTFChars(billpath, _billpath);
env->ReleaseStringUTFChars(billname, _billname);
//env->ReleasePrimitiveArrayCritical(imgBytes, _imgBytes, 0);
}
}
extern "C" {
JNIEXPORT void JNICALL Java_com_artaveh_sepid_darwinwallet_Recognizer_nvFinalizeTraining(JNIEnv* env, jobject thiz)
{
LOGD( "Started nvFinalizeTraining" );
descriptorMatcher->add(trainImages);
descriptorMatcher->train();
training_complete = true;
LOGD( "Finished nvFinalizeTraining" );
}
}
extern "C" {
JNIEXPORT jstring JNICALL Java_com_artaveh_sepid_darwinwallet_Recognizer_nvRecognize(JNIEnv* env, jobject thiz, jint width, jint height, jbyteArray yuv)
{
jbyte* _yuv = env->GetByteArrayElements(yuv, 0);
//jint* _bgra = env->GetIntArrayElements(bgra, 0);
LOGD( "Started nvFindFeatures" );
jstring response = env->NewStringUTF("");
if (training_complete == true)
{
clock_t begin;
clock_t end;
//Mat myuv(height + height/2, width, CV_8UC1, (unsigned char *)_yuv);
//Mat mbgra(height, width, CV_8UC4);
Mat mgray(height, width, CV_8UC1, (unsigned char *)_yuv);
//Mat myuv(width, 1, CV_8U, (unsigned char *)_yuv);
//Mat mgray = imdecode(myuv, 0);
//Please make attention about BGRA byte order
//ARGB stored in java as int array becomes BGRA at native level
//cvtColor(myuv, mbgra, CV_YUV420sp2BGR, 4);
vector<KeyPoint> v;
//FastFeatureDetector detector(50);
//detector.detect(mgray, v);
float divisor = 1;
if (height < width)
{
divisor = (((double) height) / 240);
}
else
{
divisor = (((double) width) / 240);
}
if (divisor == 0)
divisor = 1;
Size idealSize(width/divisor, height/divisor);
Mat mgray_small;
resize(mgray, mgray_small, idealSize);
Mat descriptors;
vector<DMatch> matches;
begin=clock();
//detector->detect(mgray_small, v);
//descriptorExtractor->compute( mgray_small, v, descriptors );
//surfStyleMatching( descriptorMatcher, descriptors, matches );
Mat* dummy;
//imwrite("/sdcard/wallet_debug.jpg", mgray_small );
bool debug_on = true;
int debug_matches[billMapping.size()];
RecognitionResult result = recognize( mgray_small, false, dummy, detector, descriptorMatcher, billMapping,
debug_on, debug_matches);
end=clock();
std::ostringstream out;
out << "time: " << diffclock(begin, end) << " ms | matches: " << matches.size() << endl;
if (debug_on)
{
for (int k = 0; k < billMapping.size(); k++)
out << " --" << billMapping[k] << " : " << debug_matches[k] << endl;
}
out << "orig_width: " << width << "orig_height: " << height << endl;
out << "divisor: " << divisor << endl;
//LOGD( (char*) out.str().c_str());
if (result.haswinner == false)
out << "No winner :(" << endl;
else
{
out << "Big Winner! " << result.winner << " : " << result.confidence << endl;
std::ostringstream responsetext;
responsetext << result.winner << "," << result.confidence;
response = env->NewStringUTF(responsetext.str().c_str());
}
LOGD( (char*) out.str().c_str());
//for( size_t i = 0; i < v.size(); i++ )
// circle(mbgra, Point(v[i].pt.x, v[i].pt.y), 10, Scalar(0,0,255,255));
}
LOGD( "Finished nvFindFeatures" );
//env->ReleaseIntArrayElements(bgra, _bgra, 0);
env->ReleaseByteArrayElements(yuv, _yuv, 0);
return response;
}
}
| saeedzareian/PersianDarwinWallet | jni/jni_recognizer.cpp | C++ | gpl-2.0 | 5,957 |
<?php
return [
'collector' => [
'name' => 'Microsoft SNDS',
'description' => 'Collects data from Microsoft SNDS to generate events',
'enabled' => false,
'location' => 'https://postmaster.live.com/snds/ipStatus.aspx',
'key' => '',
'aliasses' => [
'E-mail address harvesting' => 'detected_harvesting',
'Symantec Brightmail' => 'symantec_rbl',
'SpamHaus SBL/XBL' => 'spamhaus_rbl',
'Blocked due to user complaints or other evidence of spamming' => 'user_complaints',
]
],
'feeds' => [
'detected_harvesting' => [
'class' => 'HARVESTING',
'type' => 'ABUSE',
'enabled' => true,
'fields' => [
'first_ip',
'last_ip',
'blocked',
'feed',
],
'filters' => [
'first_ip',
'last_ip',
]
],
'symantec_rbl' => [
'class' => 'RBL_LISTED',
'type' => 'ABUSE',
'enabled' => true,
'fields' => [
'first_ip',
'last_ip',
'blocked',
'feed',
],
'filters' => [
'first_ip',
'last_ip',
]
],
'spamhaus_rbl' => [
'class' => 'RBL_LISTED',
'type' => 'ABUSE',
'enabled' => true,
'fields' => [
'first_ip',
'last_ip',
'blocked',
'feed',
],
'filters' => [
'first_ip',
'last_ip',
]
],
'user_complaints' => [
'class' => 'SPAM',
'type' => 'ABUSE',
'enabled' => true,
'fields' => [
'first_ip',
'last_ip',
'blocked',
'feed',
],
'filters' => [
'first_ip',
'last_ip',
]
],
],
];
| AbuseIO/collector-snds | config/Snds.php | PHP | gpl-2.0 | 2,257 |
<?php
/**
* Override or insert variables into the maintenance page template.
*
* @param $vars
* An array of variables to pass to the theme template.
*/
function ab2014_preprocess_maintenance_page(&$vars) {
// When a variable is manipulated or added in preprocess_html or
// preprocess_page, that same work is probably needed for the maintenance page
// as well, so we can just re-use those functions to do that work here.
// techdrill_preprocess_html($vars);
// techdrill_preprocess_page($vars);
// This preprocessor will also be used if the db is inactive. To ensure your
// theme is used, add the following line to your settings.php file:
// $conf['maintenance_theme'] = 'techdrill';
// Also, check $vars['db_is_active'] before doing any db queries.
}
function ab2014_menu_link(array $variables) {
$element = $variables['element'];
$sub_menu = '';
$element['#localized_options']['html'] = TRUE;
if ($element['#below']) {
$sub_menu = drupal_render($element['#below']);
}
if ($element['#original_link']['menu_name'] == "main-menu" && isset($element['#localized_options']['attributes']['title'])){
$element['#title'] .= '<span class="description">' . $element['#localized_options']['attributes']['title'] . '</span>';
}
$output = l($element['#title'], $element['#href'], $element['#localized_options']);
return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}
function ab2014_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'search_block_form') {
// Alternative (HTML5) placeholder attribute instead of using the javascript
$form['search_block_form']['#attributes']['placeholder'] = t('Search my website...');
}
if ($form_id == 'simplenews_block_form_1') {
// Alternative (HTML5) placeholder attribute instead of using the javascript
$form['mail']['#attributes']['placeholder'] = t('Enter email...');
}
}
function ab2014_page_alter(&$page) {
if (arg(0) == 'search') {
if (!empty($page['content']['system_main']['search_form'])) {
hide($page['content']['system_main']['search_form']);
}
}
}
function ab2014_status_messages(&$variables) {
$display = $variables['display'];
$output = '';
$status_heading = array(
'status' => t('Status message'),
'error' => t('Error message'),
'warning' => t('Warning message'),
);
foreach (drupal_get_messages($display) as $type => $messages) {
$output .= '<div class="messages ' . $type . '"><div class="container">';
if (!empty($status_heading[$type])) {
$output .= '<h2 class="element-invisible">' . $status_heading[$type] . '</h2>';
}
if (count($messages) > 1) {
$output .= " <ul>\n";
foreach ($messages as $message) {
$output .= ' <li>' . $message . "</li>\n";
}
$output .= " </ul>\n";
}
else {
$output .= $messages[0];
}
$output .= "</div></div>\n";
}
return $output;
}
function ab2014_form_user_login_alter(&$form, &$form_state) {
$form['name']['#description'] = t('');
$form['pass']['#description'] = t('');
// Shorter, inline request new password link.
$form['actions']['request_password'] = array(
'#markup' => l(t('Forgot your login details?'), 'user/password', array('attributes' => array('title' => t('Forgot your login details?')))),
);
}
function ab2014_field_collection_view($variables) {
$element = $variables['element'];
return $element['#children'];
}
/**
* Implements hook_modernizr_load_alter().
*
* @return
* An array to be output as yepnope testObjects.
*/
/* -- Delete this line if you want to use this function
function techdrill_modernizr_load_alter(&$load) {
}
/**
* Implements hook_preprocess_html()
*
* @param $vars
* An array of variables to pass to the theme template.
*/
/**
* Override or insert variables into the page template.
*
* @param $vars
* An array of variables to pass to the theme template.
*/
// Override the event content type to remove the header
// function ab2014_preprocess_page(&$variables, $hook) {
// //Add custom page.tpl.php based on content type
// if (isset($variables['node']->type) && !empty($variables['node']->type) && (
// $variables['node']->type == 'homepage' ||
// $variables['node']->type == 'page')){
// // (underscores used in page__ )
// $variables['theme_hook_suggestions'][] = 'page__' . $variables['node']->type;
// }
// }
function ab2014_preprocess_page(&$vars, $hook) {
if (isset($vars['node']->type)) {
// If the content type's machine name is "my_machine_name" the file
// name will be "page--my-machine-name.tpl.php".
$vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
}
}
function ab2014_preprocess_search_results(&$variables) {
if (arg(0) == 'search') {
$variables['ab_search_count'] = (isset($variables['results'])) ? count($variables['results']) : 0;
}
}
/**
* Override or insert variables into the region templates.
*
* @param $vars
* An array of variables to pass to the theme template.
*/
/* -- Delete this line if you want to use this function
function techdrill_preprocess_region(&$vars) {
}
// */
/**
* Override or insert variables into the block templates.
*
* @param $vars
* An array of variables to pass to the theme template.
*/
/* -- Delete this line if you want to use this function
function techdrill_preprocess_block(&$vars) {
}
// */
/**
* Override or insert variables into the entity template.
*
* @param $vars
* An array of variables to pass to the theme template.
*/
/* -- Delete this line if you want to use this function
function techdrill_preprocess_entity(&$vars) {
}
// */
/**
* Override or insert variables into the node template.
*
* @param $vars
* An array of variables to pass to the theme template.
*/
function ab2014_preprocess_node(&$vars) {
$node = $vars['node'];
}
/**
* Override or insert variables into the field template.
*
* @param $vars
* An array of variables to pass to the theme template.
* @param $hook
* The name of the template being rendered ("field" in this case.)
*/
/* -- Delete this line if you want to use this function
function techdrill_preprocess_field(&$vars, $hook) {
}
// */
/**
* Override or insert variables into the comment template.
*
* @param $vars
* An array of variables to pass to the theme template.
*/
/* -- Delete this line if you want to use this function
function techdrill_preprocess_comment(&$vars) {
$comment = $vars['comment'];
}
// */
/**
* Override or insert variables into the views template.
*
* @param $vars
* An array of variables to pass to the theme template.
*/
/* -- Delete this line if you want to use this function
function techdrill_preprocess_views_view(&$vars) {
$view = $vars['view'];
}
// */
/**
* Override or insert css on the site.
*
* @param $css
* An array of all CSS items being requested on the page.
*/
function ab2014_css_alter(&$css) {
// unset($css['modules/system/system.menus.css']);
unset($css['sites/all/modules/field_collection/field_collection.theme.css']);
unset($css['sites/all/libraries/flexslider/flexslider.css']);
unset($css['sites/all/modules/flexslider/assets/css/flexslider_img.css']);
}
// */
/**
* Override or insert javascript on the site.
*
* @param $js
* An array of all JavaScript being presented on the page.
*/
/* -- Delete this line if you want to use this function
function techdrill_js_alter(&$js) {
}
// */ | xanderakafonz/portfolio | sites/all/themes/ab2014/template.php | PHP | gpl-2.0 | 7,610 |
<?php
/******************************
-Display files are included here
******************************/
include("inc/site.php"); // Css For Site
include("inc/login.php"); // Css For Login Screen
include("inc/admin.php"); // Css For Admin Dashboard
?> | wp-plugins/wpcss | display/settings.php | PHP | gpl-2.0 | 269 |
/* This file was generated by SableCC (http://www.sablecc.org/). */
package se.sics.kola.node;
public abstract class PExpression extends Node
{
// Empty body
}
| kompics/kola | src/main/java/se/sics/kola/node/PExpression.java | Java | gpl-2.0 | 166 |
using iPem.Core;
using iPem.Core.Caching;
using iPem.Core.Domain.Sc;
using iPem.Core.Enum;
using iPem.Data.Repository.Sc;
using iPem.Services.Common;
using System;
using System.Collections.Generic;
using System.Linq;
namespace iPem.Services.Sc {
public partial class RoleService : IRoleService {
#region Fields
private readonly IU_RoleRepository _repository;
private readonly ICacheManager _cacheManager;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
public RoleService(
IU_RoleRepository repository,
ICacheManager cacheManager) {
this._repository = repository;
this._cacheManager = cacheManager;
}
#endregion
#region Methods
public U_Role GetRoleById(string id) {
return _repository.GetRoleById(id);
}
public U_Role GetRoleByName(string name) {
return _repository.GetRoleByName(name);
}
public U_Role GetRoleByUid(string uid) {
return _repository.GetRoleByUid(uid);
}
public List<U_Role> GetRoles() {
return _repository.GetRoles().FindAll(r => !r.Id.Equals(U_Role.SuperId));
}
public List<U_Role> GetRolesByRole(string id) {
var roles = _repository.GetRoles();
return id.Equals(U_Role.SuperId) ? roles : roles.FindAll(r => r.Id.Equals(id));
}
public List<U_Role> GetRoleByNames(string[] names) {
var roles = _repository.GetRoles();
return roles.FindAll(r => !r.Id.Equals(U_Role.SuperId) && CommonHelper.ConditionContain(r.Name, names));
}
public IPagedList<U_Role> GetPagedRoles(int pageIndex = 0, int pageSize = int.MaxValue) {
return new PagedList<U_Role>(this.GetRoles(), pageIndex, pageSize);
}
public IPagedList<U_Role> GetPagedRoleByNames(string[] names, int pageIndex = 0, int pageSize = int.MaxValue) {
return new PagedList<U_Role>(this.GetRoleByNames(names), pageIndex, pageSize);
}
public void Add(params U_Role[] roles) {
if (roles == null || roles.Length == 0)
throw new ArgumentNullException("roles");
_repository.Insert(roles);
}
public void Update(params U_Role[] roles) {
if (roles == null || roles.Length == 0)
throw new ArgumentNullException("roles");
_repository.Update(roles);
}
public void Remove(params U_Role[] roles) {
if (roles == null || roles.Length == 0)
throw new ArgumentNullException("roles");
_repository.Delete(roles);
}
#endregion
#region Validate
public EnmLoginResults Validate(string id) {
var role = this.GetRoleById(id);
if (role == null)
return EnmLoginResults.RoleNotExist;
if (!role.Enabled)
return EnmLoginResults.RoleNotEnabled;
return EnmLoginResults.Successful;
}
#endregion
}
} | Delta-SH/iPemSystem | iPem.Services/Sc/Class/RoleService.cs | C# | gpl-2.0 | 3,268 |
<?php
/**
* @version $Id$
* @package Koowa_Template
* @subpackage Helper
* @copyright Copyright (C) 2007 - 2012 Johan Janssens. All rights reserved.
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Template Helper Class
*
* @author Johan Janssens <johan@nooku.org>
* @package Koowa_Template
* @subpackage Helper
*/
abstract class KTemplateHelperAbstract extends KObject implements KTemplateHelperInterface
{
/**
* Template object
*
* @var object
*/
protected $_template;
/**
* Constructor
*
* Prevent creating instances of this class by making the contructor private
*
* @param object An optional KConfig object with configuration options
*/
public function __construct(KConfig $config)
{
parent::__construct($config);
// Set the view indentifier
$this->setTemplate($config->template);
}
/**
* Get the template object
*
* @return object The template object
*/
public function getTemplate()
{
return $this->_template;
}
public function setTemplate($template)
{
if(!$template instanceof KTemplateAbstract)
{
if(empty($template) || (is_string($template) && strpos($template, '.') === false) )
{
$identifier = clone $this->getIdentifier();
$identifier->path = array('template');
$identifier->name = $template ? $template : 'default';
} else $identifier = $this->getIdentifier($template);
$template = $this->getService($identifier);
}
$this->_template = $template;
return $this;
}
public function translate($string, array $parameters = array())
{
return $this->getTemplate()->getHelper('translator')->translate($string, $parameters);
}
} | dwarkeshsoni/jsn_time_free_j3x | libraries/koowa/template/helper/abstract.php | PHP | gpl-2.0 | 1,898 |
/**
* Plugin to add header resizing functionality to a HeaderContainer.
* Always resizing header to the left of the splitter you are resizing.
*/
Ext.define('Ext.grid.plugin.HeaderResizer', {
extend: 'Ext.plugin.Abstract',
requires: [
'Ext.dd.DragTracker',
'Ext.util.Region'
],
alias: 'plugin.gridheaderresizer',
disabled: false,
config: {
/**
* @cfg {Boolean} dynamic
* True to resize on the fly rather than using a proxy marker.
* @accessor
*/
dynamic: false
},
colHeaderCls: Ext.baseCSSPrefix + 'column-header',
minColWidth: 40,
maxColWidth: 1000,
eResizeCursor: 'col-resize',
init: function(headerCt) {
var me = this;
me.headerCt = headerCt;
headerCt.on('render', me.afterHeaderRender, me, {single: me});
// Pull minColWidth from the minWidth in the Column prototype
if (!me.minColWidth) {
me.self.prototype.minColWidth = Ext.grid.column.Column.prototype.minWidth;
}
},
destroy: function() {
var tracker = this.tracker;
if (tracker) {
delete tracker.onBeforeStart;
delete tracker.onStart;
delete tracker.onDrag;
delete tracker.onEnd;
tracker.destroy();
this.tracker = null;
}
this.callParent();
},
afterHeaderRender: function() {
var me = this,
headerCt = me.headerCt,
el = headerCt.el;
headerCt.mon(el, 'mousemove', me.onHeaderCtMouseMove, me);
me.markerOwner = me.ownerGrid = me.headerCt.up('tablepanel');
if (me.markerOwner.ownerLockable) {
me.markerOwner = me.markerOwner.ownerLockable;
}
me.tracker = new Ext.dd.DragTracker({
disabled: me.disabled,
onBeforeStart: me.onBeforeStart.bind(me),
onStart: me.onStart.bind(me),
onDrag: me.onDrag.bind(me),
onEnd: me.onEnd.bind(me),
tolerance: 3,
autoStart: 300,
el: el
});
},
// As we mouse over individual headers, change the cursor to indicate
// that resizing is available, and cache the resize target header for use
// if/when they mousedown.
onHeaderCtMouseMove: function(e) {
var me = this;
if (me.headerCt.dragging || me.disabled) {
if (me.activeHd) {
me.activeHd.el.dom.style.cursor = '';
delete me.activeHd;
}
} else {
me.findActiveHeader(e);
}
},
findActiveHeader: function(e) {
var me = this,
headerEl = e.getTarget('.' + me.colHeaderCls, 3, true),
ownerGrid = me.ownerGrid,
ownerLockable = ownerGrid.ownerLockable,
overHeader, resizeHeader, headers, header;
if (headerEl) {
overHeader = Ext.getCmp(headerEl.id);
// If near the right edge, we're resizing the column we are over.
if (overHeader.isAtEndEdge(e)) {
// Cannot resize the only column in a forceFit grid.
if (me.headerCt.visibleColumnManager.getColumns().length === 1 && me.headerCt.forceFit) {
return;
}
resizeHeader = overHeader;
}
// Else... we might be near the right edge
else if (overHeader.isAtStartEdge(e)) {
// Extract previous visible leaf header
headers = me.headerCt.visibleColumnManager.getColumns();
header = overHeader.isGroupHeader ? overHeader.getGridColumns()[0] : overHeader;
resizeHeader = headers[Ext.Array.indexOf(headers, header) - 1];
// If there wasn't one, and we are the normal side of a lockable assembly then
// use the last visible leaf header of the locked side.
if (!resizeHeader && ownerLockable && !ownerGrid.isLocked) {
headers = ownerLockable.lockedGrid.headerCt.visibleColumnManager.getColumns();
resizeHeader = headers[headers.length - 1];
}
}
// We *are* resizing
if (resizeHeader) {
// If we're attempting to resize a group header, that cannot be resized,
// so find its last visible leaf header; Group headers are sized
// by the size of their child headers.
if (resizeHeader.isGroupHeader) {
headers = resizeHeader.getGridColumns();
resizeHeader = headers[headers.length - 1];
}
// Check if the header is resizable. Continue checking the old "fixed" property, bug also
// check whether the resizable property is set to false.
if (resizeHeader && !(resizeHeader.fixed || (resizeHeader.resizable === false))) {
me.activeHd = resizeHeader;
overHeader.el.dom.style.cursor = me.eResizeCursor;
if (overHeader.triggerEl) {
overHeader.triggerEl.dom.style.cursor = me.eResizeCursor;
}
}
// reset
} else {
overHeader.el.dom.style.cursor = '';
if (overHeader.triggerEl) {
overHeader.triggerEl.dom.style.cursor = '';
}
me.activeHd = null;
}
}
return me.activeHd;
},
// only start when there is an activeHd
onBeforeStart : function(e) {
var me = this;
// If on touch, we will have received no mouseover, so we have to
// decide whether the touch is in a resize zone, and if so, which header is to be sized.
// Cache any activeHd because it will be cleared on subsequent mousemoves outside the resize zone.
me.dragHd = Ext.supports.Touch ? me.findActiveHeader(e) : me.activeHd;
if (!!me.dragHd && !me.headerCt.dragging) {
// Calculate how far off the right marker line the mouse pointer is.
// This will be the xDelta during the following drag operation.
me.xDelta = me.dragHd.getX() + me.dragHd.getWidth() - me.tracker.getXY()[0];
me.tracker.constrainTo = me.getConstrainRegion();
return true;
} else {
me.headerCt.dragging = false;
return false;
}
},
// get the region to constrain to, takes into account max and min col widths
getConstrainRegion: function() {
var me = this,
dragHdEl = me.dragHd.el,
nextHd,
ownerGrid = me.ownerGrid,
widthModel = ownerGrid.getSizeModel().width,
maxColWidth = widthModel.shrinkWrap ? me.headerCt.getWidth() - me.headerCt.visibleColumnManager.getColumns().length * me.minColWidth : me.maxColWidth,
result;
// If forceFit, then right constraint is based upon not being able to force the next header
// beyond the minColWidth. If there is no next header, then the header may not be expanded.
if (me.headerCt.forceFit) {
nextHd = me.dragHd.nextNode('gridcolumn:not([hidden]):not([isGroupHeader])');
if (nextHd && me.headerInSameGrid(nextHd)) {
maxColWidth = dragHdEl.getWidth() + (nextHd.getWidth() - me.minColWidth);
}
}
// If resize header is in a locked grid, the maxWidth has to be 30px within the available locking grid's width
// But only if the locked grid shrinkwraps its columns
else if (ownerGrid.isLocked && widthModel.shrinkWrap) {
maxColWidth = me.dragHd.up('[scrollerOwner]').getTargetEl().getWidth(true) - ownerGrid.getWidth() - (ownerGrid.ownerLockable.normalGrid.visibleColumnManager.getColumns().length * me.minColWidth + Ext.getScrollbarSize().width);
}
result = me.adjustConstrainRegion(
dragHdEl.getRegion(),
0,
0,
0,
me.minColWidth
);
result.right = dragHdEl.getX() + maxColWidth;
return result;
},
// initialize the left and right hand side markers around
// the header that we are resizing
onStart: function(e) {
var me = this,
dragHd = me.dragHd,
width = dragHd.el.getWidth(),
headerCt = dragHd.getRootHeaderCt(),
x, y, markerOwner, lhsMarker, rhsMarker, markerHeight;
me.headerCt.dragging = true;
me.origWidth = width;
// setup marker proxies
if (!me.dynamic) {
markerOwner = me.markerOwner;
// https://sencha.jira.com/browse/EXTJSIV-11299
// In Neptune (and other themes with wide frame borders), resize handles are embedded in borders,
// *outside* of the outer element's content area, therefore the outer element is set to overflow:visible.
// During column resize, we should not see the resize markers outside the grid, so set to overflow:hidden.
if (markerOwner.frame && markerOwner.resizable) {
me.gridOverflowSetting = markerOwner.el.dom.style.overflow;
markerOwner.el.dom.style.overflow = 'hidden';
}
x = me.getLeftMarkerX(markerOwner);
lhsMarker = markerOwner.getLhsMarker();
rhsMarker = markerOwner.getRhsMarker();
markerHeight = me.ownerGrid.body.getHeight() + headerCt.getHeight();
y = headerCt.getOffsetsTo(markerOwner)[1] - markerOwner.el.getBorderWidth('t');
lhsMarker.setLocalY(y);
rhsMarker.setLocalY(y);
lhsMarker.setHeight(markerHeight);
rhsMarker.setHeight(markerHeight);
me.setMarkerX(lhsMarker, x);
me.setMarkerX(rhsMarker, x + width);
}
},
// synchronize the rhsMarker with the mouse movement
onDrag: function(e){
var me = this;
if (me.dynamic) {
me.doResize();
} else {
me.setMarkerX(me.getMovingMarker(me.markerOwner), me.calculateDragX(me.markerOwner));
}
},
getMovingMarker: function(markerOwner){
return markerOwner.getRhsMarker();
},
onEnd: function(e) {
var me = this,
markerOwner;
me.headerCt.dragging = false;
if (me.dragHd) {
if (!me.dynamic) {
markerOwner = me.headerCt.up('tablepanel');
// hide markers
if (markerOwner.ownerLockable) {
markerOwner = markerOwner.ownerLockable;
}
// If we had saved the gridOverflowSetting, restore it
if ('gridOverflowSetting' in me) {
markerOwner.el.dom.style.overflow = me.gridOverflowSetting;
}
me.setMarkerX(markerOwner.getLhsMarker(), -9999);
me.setMarkerX(markerOwner.getRhsMarker(), -9999);
}
me.doResize();
}
// If the mouse is still within the handleWidth, then we must be ready to drag again
me.onHeaderCtMouseMove(e);
},
doResize: function() {
var me = this,
dragHd = me.dragHd,
nextHd,
offset = me.tracker.getOffset('point');
// Only resize if we have dragged any distance in the X dimension...
if (dragHd && offset[0]) {
// resize the dragHd
if (dragHd.flex) {
delete dragHd.flex;
}
Ext.suspendLayouts();
// Set the new column width.
// Adjusted for the offset from the actual column border that the mousedownb too place at.
me.adjustColumnWidth(offset[0] - me.xDelta);
// In the case of forceFit, change the following Header width.
// Constraining so that neither neighbour can be sized to below minWidth is handled in getConstrainRegion
if (me.headerCt.forceFit) {
nextHd = dragHd.nextNode('gridcolumn:not([hidden]):not([isGroupHeader])');
if (nextHd && !me.headerInSameGrid(nextHd)) {
nextHd = null;
}
if (nextHd) {
delete nextHd.flex;
nextHd.setWidth(nextHd.getWidth() - offset[0]);
}
}
// Apply the two width changes by laying out the owning HeaderContainer
Ext.resumeLayouts(true);
}
},
// nextNode can traverse out of this grid, possibly to others on the page, so limit it here
headerInSameGrid: function(header) {
var grid = this.dragHd.up('tablepanel');
return !!header.up(grid);
},
disable: function() {
var tracker = this.tracker;
this.disabled = true;
if (tracker) {
tracker.disable();
}
},
enable: function() {
var tracker = this.tracker;
this.disabled = false;
if (tracker) {
tracker.enable();
}
},
calculateDragX: function(markerOwner) {
return this.tracker.getXY('point')[0] + this.xDelta - markerOwner.getX() - markerOwner.el.getBorderWidth('l');
},
getLeftMarkerX: function(markerOwner) {
return this.dragHd.getX() - markerOwner.getX() - markerOwner.el.getBorderWidth('l') - 1;
},
setMarkerX: function(marker, x) {
marker.setLocalX(x);
},
adjustConstrainRegion: function(region, t, r, b, l) {
return region.adjust(t, r, b, l);
},
adjustColumnWidth: function(offsetX) {
this.dragHd.setWidth(this.origWidth + offsetX);
}
});
| AlexeyPopovUA/Learning-ExtJS-6-Classes | ext/classic/classic/src/grid/plugin/HeaderResizer.js | JavaScript | gpl-2.0 | 13,965 |
(function ($) {
Drupal.behaviors.sbac_featured_content = {
attach: function (context, settings) {
// If JS is working, turn cursor into a pointer and redirect on click
$('.featured-content-inner').css( 'cursor', 'pointer' );
$('.featured-content-inner').click(function(){
window.location = '/' + $(this).attr('url');
});
}
};
})(jQuery); | SmarterApp/DigitalLibrary | docroot/sites/all/modules/custom/sbac_featured_content/js/sbac_featured_content.js | JavaScript | gpl-2.0 | 382 |
package com.designedpattern.abstractfactory.impl;
import com.designedpattern.abstractfactory.IMagician;
public class MagicianA implements IMagician{
public void showMagician() {
System.out.println("Magician A");
}
}
| FreeSivan/myJavaTest | src/main/java/com/designedpattern/abstractfactory/impl/MagicianA.java | Java | gpl-2.0 | 224 |
package org.tzi.use.uml.ocl.type;
import java.util.Set;
public class VoidType extends Type {
public Set<Type> allSupertypes() {
throw new UnsupportedOperationException("Call to allSupertypes is invalid on OclVoid");
}
public boolean equals(Object obj) {
return obj instanceof VoidType;
}
public int hashCode() {
return 0;
}
public boolean isVoidType() {
return true;
}
public boolean isSubtypeOf(Type t) {
return true;
}
@Override
public boolean isBag() {
return true;
}
@Override
public boolean isBoolean() {
return true;
}
@Override
public boolean isCollection(boolean excludeVoid) {
if (excludeVoid)
return false;
else
return true;
}
@Override
public boolean isDate() {
return true;
}
@Override
public boolean isEnum() {
return true;
}
@Override
public boolean isInstantiableCollection() {
return true;
}
@Override
public boolean isInteger() {
return true;
}
@Override
public boolean isNumber() {
return true;
}
@Override
public boolean isObjectType() {
return true;
}
@Override
public boolean isOrderedSet() {
return true;
}
@Override
public boolean isReal() {
return true;
}
@Override
public boolean isSequence() {
return true;
}
@Override
public boolean isSet() {
return true;
}
@Override
public boolean isString() {
return true;
}
@Override
public boolean isTupleType(boolean excludeVoid) {
return !excludeVoid;
}
@Override
public StringBuilder toString(StringBuilder sb) {
return sb.append("OclVoid");
}
@Override
public boolean isVoidOrElementTypeIsVoid() {
return true;
}
}
| vnu-dse/rtl | src/main/org/tzi/use/uml/ocl/type/VoidType.java | Java | gpl-2.0 | 1,632 |
package de.superioz.moo.api.logging;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
/**
* This is just a simple formatter for a logger
*/
public class ConciseFormatter extends Formatter {
private final DateFormat date = new SimpleDateFormat("HH:mm:ss.sss");
private boolean stripColors = false;
public ConciseFormatter(boolean stripColors) {
this.stripColors = stripColors;
}
@Override
@SuppressWarnings("ThrowableResultIgnored")
public String format(LogRecord record) {
StringBuilder formatted = new StringBuilder();
formatted.append("[");
formatted.append(date.format(record.getMillis()));
formatted.append(" ");
formatted.append(record.getLevel().getName());
formatted.append("] ");
formatted.append(stripColors ? ConsoleColor.stripColors(formatMessage(record)) : formatMessage(record));
formatted.append('\n');
if(record.getThrown() != null) {
StringWriter writer = new StringWriter();
record.getThrown().printStackTrace(new PrintWriter(writer));
formatted.append(writer);
}
return formatted.toString();
}
}
| Superioz/MooProject | api/src/main/java/de/superioz/moo/api/logging/ConciseFormatter.java | Java | gpl-2.0 | 1,332 |
<?php
include_once('include/database.php');
date_default_timezone_set(TIMEZONE);
class Site {
var $database;
var $num_active_users; //Number of active users viewing site
var $num_active_guests; //Number of active guests viewing site
var $num_members; //Number of signed-up users
var $num_trees; //Number of family trees
function Site($database) {
$this->database = $database;
/**
* Only query database to find out number of members
* when getNumMembers() is called for the first time,
* until then, default value set.
*/
$this->num_members = -1;
/* Number of trees */
$this->num_trees = -1;
if(TRACK_VISITORS){
/* Calculate number of users at site */
$this->calcNumActiveUsers();
/* Calculate number of guests at site */
$this->calcNumActiveGuests();
}
}
/**
* getNumMembers - Returns the number of signed-up users
* of the website, banned members not included. The first
* time the function is called on page load, the database
* is queried, on subsequent calls, the stored result
* is returned. This is to improve efficiency, effectively
* not querying the database when no call is made.
*/
function getNumMembers(){
if($this->num_members < 0){
$q = "SELECT * FROM ".TBL_USERS;
$result = $this->database->query($q);
$this->num_members = mysql_numrows($result);
}
return $this->num_members;
}
/**
* getNumTrees - Returns the number of family trees
* of the website. The first time the function is
* called on page load, the database is queried,
* on subsequent calls, the stored result is returned.
* This is to improve efficiency, effectively
* not querying the database when no call is made.
*/
function getNumTrees(){
if($this->num_trees < 0){
$q = "SELECT * FROM ".TBL_FAMILY;
$result = $this->database->query($q);
$this->num_trees = mysql_numrows($result);
}
return $this->num_trees;
}
/**
* calcNumActiveUsers - Finds out how many active users
* are viewing site and sets class variable accordingly.
*/
function calcNumActiveUsers(){
/* Calculate number of users at site */
$q = "SELECT * FROM ".TBL_ACTIVE_USERS;
$result = $this->database->query($q);
$this->num_active_users = mysql_numrows($result);
}
/**
* calcNumActiveGuests - Finds out how many active guests
* are viewing site and sets class variable accordingly.
*/
function calcNumActiveGuests(){
/* Calculate number of guests at site */
$q = "SELECT * FROM ".TBL_ACTIVE_GUESTS;
$result = $this->database->query($q);
$this->num_active_guests = mysql_numrows($result);
}
/*
* cleanOutput - ensures safe data entry, and accepts either strings or arrays.
* If the array is multidimensional, it will recursively loop through the array
* and make all points of data safe for entry.
*/
function cleanOutput($array) {
if(is_array($array)) {
foreach($array as $key => $value) {
if(is_array($array[$key])) {
$array[$key] = $this->filterParameters($array[$key]);
}
if(is_string($array[$key])) {
$array[$key] = mysql_real_escape_string($array[$key]);
}
}
}
if(is_string($array)) {
$array = mysql_real_escape_string($array);
}
return $array;
}
/**
* getDomainAndDir
*/
function getDomainAndDir() {
$pageURL = 'http';
if (isset($_SERVER["HTTPS"])) {
if ($_SERVER["HTTPS"] == "on") {
$pageURL .= 's';
}
}
$pageURL .= '://';
if (isset($_SERVER["SERVER_PORT"])) {
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}
else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
}
// Return the domain and directories, but exlude the filename
return substr($pageURL, 0, strripos($pageURL, '/')+1);
}
};
$site = new Site($database);
?> | monipupi/-genealogy-site-karta | giminestinklapis/site.php | PHP | gpl-2.0 | 4,042 |
/***************************************************************************
cmapview.cpp
-------------------
begin : Mon Mar 19 2001
copyright : (C) 2001 by Kmud Developer Team
(C) 2007 Tomas Mecir <kmuddy@kmuddy.net>
email : kmud-devel@kmud.de
***************************************************************************/
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include "cmapview.h"
#include <QAction>
#include <QPushButton>
#include <QScrollArea>
#include <QActionGroup>
#include "cmapmanager.h"
#include "cmapzone.h"
#include "cmapzonemanager.h"
#include "cmaplevel.h"
#include "cmappath.h"
#include "cmapview.h"
#include "cmapelement.h"
#include "cmapwidget.h"
#include "cmapviewstatusbar.h"
#include "cmaptoolbase.h"
#include "cmapclipboard.h"
#include "cmapcmdelementproperties.h"
#include <kselectaction.h>
#include <ktoggleaction.h>
#include <kactioncollection.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kstandarddirs.h>
#include <kundostack.h>
#include <kinputdialog.h>
CMapView::CMapView(CMapManager *manager,QWidget *parent) : KXmlGuiWindow(parent)
{
kDebug() << "CMapView::CMapView create view";
setCaption (i18n ("Mapper"));
setAttribute (Qt::WA_DeleteOnClose, false); // do not delete on close
mapManager = manager;
currentLevel = 0;
setFocusPolicy(Qt::StrongFocus);
setWindowFlags (Qt::Widget);
m_clipboard = new CMapClipboard(mapManager, this, actionCollection());
initMenus();
// set up the menus
setHelpMenuEnabled (false);
scroller = new QScrollArea(this);
scroller->setWidgetResizable(true);
scroller->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
scroller->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
setCentralWidget(scroller);
mapWidget = new CMapWidget(this, mapManager, scroller);
scroller->setWidget(mapWidget);
mapWidget->show();
statusbar = new CMapViewStatusbar(manager, this);
setStatusBar(statusbar);
cmdFollowMode = new QPushButton(i18n("Follow Moves"),statusbar);
cmdFollowMode->setIcon(BarIcon("kmud_follow.png"));
cmdFollowMode->setCheckable(true);
cmdFollowMode->setFocusProxy(this);
statusbar->addFollowButton(cmdFollowMode);
cmdCreateMode = new QPushButton(i18n("Auto Create"),statusbar);
cmdCreateMode->setIcon(BarIcon("kmud_create.png"));
cmdCreateMode->setCheckable(true);
cmdCreateMode->setFocusProxy(this);
statusbar->addFollowButton(cmdCreateMode);
// getMapData()->createModeActive = m_toolsCreate->isChecked();
//FIXME_jp : get settings for status bar instead of defaults
//FIXME_jp : Add proper resize instead of test size
changed();
}
CMapView::~CMapView()
{
kDebug() << "CMapView::~CMapView()";
}
void CMapView::initGUI()
{
createGUI(KStandardDirs::locate("appdata", "kmuddymapperpart.rc"));
mapWidget->initContexMenus();
enableViewControls(false);
}
void CMapView::initMenus()
{
kDebug() << "begin initMenus";
kDebug() << "Main collection is "<<actionCollection();
// Edit menu
mapManager->getCommandHistory()->createUndoAction(actionCollection(), "editUndo");
mapManager->getCommandHistory()->createRedoAction(actionCollection(), "editRedo");
// Tools menu
m_toolsGrid = new KToggleAction (this);
m_toolsGrid->setText ( i18n("&Grid"));
m_toolsGrid->setIcon (BarIcon("kmud_grid.png"));
connect (m_toolsGrid, SIGNAL (triggered()), this, SLOT(slotToolsGrid()));
actionCollection()->addAction ("toolsGrid", m_toolsGrid);
m_toolsUpLevel = new QAction (this);
m_toolsUpLevel->setText ( i18n("Display Upper Level"));
m_toolsUpLevel->setIcon (BarIcon("arrow-up"));
connect (m_toolsUpLevel, SIGNAL (triggered()), this, SLOT(slotToolsLevelUp()));
actionCollection()->addAction ("toolsLevelUp", m_toolsUpLevel);
m_toolsDownLevel = new QAction (this);
m_toolsDownLevel->setText ( i18n("Display Lower Level"));
m_toolsDownLevel->setIcon (BarIcon("arrow-down"));
connect (m_toolsDownLevel, SIGNAL (triggered()), this, SLOT(slotToolsLevelDown()));
actionCollection()->addAction ("toolsLevelDown", m_toolsDownLevel);
m_toolsDeleteLevel = new QAction (this);
m_toolsDeleteLevel->setText ( i18n("Delete Current Level"));
m_toolsDeleteLevel->setIcon (BarIcon("edit-delete"));
connect (m_toolsDeleteLevel, SIGNAL (triggered()), this, SLOT(slotToolsLevelDelete()));
actionCollection()->addAction ("toolsLevelDelete", m_toolsDeleteLevel);
m_toolsCreateZone = new QAction (this);
m_toolsCreateZone->setText ( i18n("Create New Zone"));
m_toolsCreateZone->setIcon (BarIcon("task-new"));
connect (m_toolsCreateZone, SIGNAL (triggered()), this, SLOT(slotToolsZoneCreate()));
actionCollection()->addAction ("toolsZoneCreate", m_toolsCreateZone);
m_toolsDeleteZone = new QAction (this);
m_toolsDeleteZone->setText ( i18n("Delete Current Zone"));
m_toolsDeleteZone->setIcon (BarIcon("edit-delete"));
connect (m_toolsDeleteZone, SIGNAL (triggered()), this, SLOT(slotToolsZoneDelete()));
actionCollection()->addAction ("toolsZoneDelete", m_toolsDeleteZone);
// View menu
m_viewUpperLevel = new KToggleAction (this);
m_viewUpperLevel->setText ( i18n("Map Upper Level"));
connect (m_viewUpperLevel, SIGNAL (triggered()), this, SLOT(slotViewUpperLevel()));
actionCollection()->addAction ("viewUpperLevel", m_viewUpperLevel);
m_viewLowerLevel = new KToggleAction (this);
m_viewLowerLevel->setText ( i18n("Map Lower Level"));
connect (m_viewLowerLevel, SIGNAL (triggered()), this, SLOT(slotViewLowerLevel()));
actionCollection()->addAction ("viewLowerLevel", m_viewLowerLevel);
// Room Popup Actions
QAction *action;
action = new QAction (this);
action->setText (i18n("Set &Current Position"));
connect (action, SIGNAL (triggered()), this, SLOT(slotRoomSetCurrentPos()));
actionCollection()->addAction ("roomCurrentPos", action);
action = new QAction (this);
action->setText (i18n("Set Room to &Login Point"));
connect (action, SIGNAL (triggered()), this, SLOT(slotRoomSetLogin()));
actionCollection()->addAction ("roomLoginPoint", action);
action = new QAction (this);
action->setText (i18n("&Speed walk to room"));
connect (action, SIGNAL (triggered()), this, SLOT(slotRoomSpeedwalkTo()));
actionCollection()->addAction ("roomWalkTo", action);
action = new QAction (this);
action->setText (i18n("&Delete room"));
action->setIcon (SmallIcon("edit-delete"));
connect (action, SIGNAL (triggered()), this, SLOT(slotRoomDelete()));
actionCollection()->addAction ("roomDelete", action);
action = new QAction (this);
action->setText (i18n("&Properties"));
action->setIcon (SmallIcon("document-properties"));
connect (action, SIGNAL (triggered()), this, SLOT(slotRoomProperties()));
actionCollection()->addAction ("roomProperties", action);
// Text Popup Actions
action = new QAction (this);
action->setText (i18n("&Delete Text"));
action->setIcon (SmallIcon("edit-delete"));
connect (action, SIGNAL (triggered()), this, SLOT(slotTextDelete()));
actionCollection()->addAction ("textDelete", action);
action = new QAction (this);
action->setText (i18n("&Properties"));
action->setIcon (SmallIcon("document-properties"));
connect (action, SIGNAL (triggered()), this, SLOT(slotTextProperties()));
actionCollection()->addAction ("textProperties", action);
// Path Popup Actions
action = new KToggleAction (this);
action->setText (i18n("&One way"));
connect (action, SIGNAL (triggered()), this, SLOT(slotPathOneWay()));
actionCollection()->addAction ("pathOneWay", action);
action = new KToggleAction (this);
action->setText (i18n("&Two way"));
connect (action, SIGNAL (triggered()), this, SLOT(slotPathTwoWay()));
actionCollection()->addAction ("pathTwoWay", action);
action = new QAction (this);
action->setText (i18n("&Add Bend"));
connect (action, SIGNAL (triggered()), this, SLOT(slotPathAddBend()));
actionCollection()->addAction ("pathAddBend", action);
action = new QAction (this);
action->setText (i18n("&Remove Segment"));
connect (action, SIGNAL (triggered()), this, SLOT(slotPathDelBend()));
actionCollection()->addAction ("pathDelBend", action);
action = new QAction (this);
action->setText (i18n("&Edit Bends"));
connect (action, SIGNAL (triggered()), this, SLOT(slotPathEditBends()));
actionCollection()->addAction ("pathEditBends", action);
action = new QAction (this);
action->setText (i18n("&Delete Path"));
action->setIcon (SmallIcon("edit-delete"));
connect (action, SIGNAL (triggered()), this, SLOT(slotPathDelete()));
actionCollection()->addAction ("pathDelete", action);
action = new QAction (this);
action->setText (i18n("&Properties"));
connect (action, SIGNAL (triggered()), this, SLOT(slotPathProperties()));
actionCollection()->addAction ("pathPorperties", action);
QStringList labelPos;
labelPos.append(i18n("Hide"));
labelPos.append(mapManager->directionToText(NORTH,""));
labelPos.append(mapManager->directionToText(NORTHEAST,""));
labelPos.append(mapManager->directionToText(EAST,""));
labelPos.append(mapManager->directionToText(SOUTHEAST,""));
labelPos.append(mapManager->directionToText(SOUTH,""));
labelPos.append(mapManager->directionToText(SOUTHWEST,""));
labelPos.append(mapManager->directionToText(WEST,""));
labelPos.append(mapManager->directionToText(NORTHWEST,""));
labelPos.append(i18n("Custom"));
labelMenu = new KSelectAction (this);
labelMenu->setText (i18n("&Label"));
connect (labelMenu, SIGNAL (triggered()), this, SLOT(slotChangeLabelPos()));
actionCollection()->addAction ("labelMenu", labelMenu);
labelMenu->setItems(labelPos);
// tool action group
m_toolGroup = new QActionGroup (this);
}
void CMapView::readOptions()
{
CMapData *data = mapManager->getMapData();
m_toolsGrid->setChecked(data->gridVisable);
m_viewLowerLevel->setChecked(data->showLowerLevel);
m_viewUpperLevel->setChecked(data->showUpperLevel);
}
/** Used to get the currently viewed zone */
CMapZone *CMapView::getCurrentlyViewedZone()
{
return currentLevel ? currentLevel->getZone() : 0;
}
/** Used to get the currently viewed level */
CMapLevel *CMapView::getCurrentlyViewedLevel()
{
return currentLevel;
}
/** Used to set the current level. This is for internal use */
void CMapView::setLevel(CMapLevel *level)
{
currentLevel = level;
}
void CMapView::playerPositionChanged(CMapRoom *room)
{
if (!room) return;
if (room->getLevel() != currentLevel)
showPosition(room->getLevel(), false);
}
void CMapView::setSelectedElement(CMapElement *element)
{
m_selectedElement = element;
}
void CMapView::setSelectedPos(QPoint pos)
{
m_selectedPos = pos;
}
CMapElement *CMapView::getSelectedElement()
{
return m_selectedElement;
}
/** Used to let the map manager know if it should register the focus of this widget */
bool CMapView::acceptFocus()
{
return true;
}
/** This method is called when an element is added */
void CMapView::addedElement(CMapElement *element)
{
if (isElementVisible(element))
{
checkSize(element->getHighPos());
mapWidget->update();
}
}
/** This method is called when an element is deleted */
void CMapView::deletedElement(CMapLevel *deletedFromLevel)
{
CMapLevel *upperLevel = getCurrentlyViewedLevel()->getNextLevel();
CMapLevel *lowerLevel = getCurrentlyViewedLevel()->getPrevLevel();
if (deletedFromLevel == getCurrentlyViewedLevel())
mapWidget->update();
if (upperLevel && mapManager->getMapData()->showUpperLevel)
if (deletedFromLevel == upperLevel)
mapWidget->update();
if (lowerLevel && mapManager->getMapData()->showLowerLevel)
if (deletedFromLevel == lowerLevel)
mapWidget->update();
}
/** This method is called when an element is changed */
void CMapView::changedElement(CMapElement *element)
{
if (isElementVisible(element))
{
checkSize(element->getHighPos());
mapWidget->update();
}
if (element == mapManager->getCurrentRoom())
statusbar->setRoom(mapManager->getCurrentRoom()->getLabel());
}
/** This method is called when a map level is changed */
void CMapView::changedLevel(CMapLevel *level)
{
if (!isLevelVisible(level)) return;
changed();
}
/** Used to find out if a level is visible in the view */
bool CMapView::isLevelVisible(CMapLevel *level)
{
CMapLevel *vlevel = getCurrentlyViewedLevel();
if (!vlevel) return false;
if (level == vlevel)
return true;
if (level == vlevel->getPrevLevel())
return true;
if (level == vlevel->getNextLevel())
return true;
return false;
}
/** Used to find out if a element is visiable in the view */
bool CMapView::isElementVisible(CMapElement *element)
{
return isLevelVisible(element->getLevel());
}
/**
* Used to enable/disable the view actions
* @param If true then enable the actions otherwise disable the actions
*/
void CMapView::enableViewControls(bool enabled)
{
if (!mapManager->getMapData()) return; // if we don't have mapData, we're going down
enableNonViewActions(enabled);
m_clipboard->enableActions(enabled);
m_toolsUpLevel->setEnabled(enabled);
m_toolsDownLevel->setEnabled(enabled);
m_toolsDeleteLevel->setEnabled(enabled);
m_toolsCreateZone->setEnabled(enabled);
m_toolsDeleteZone->setEnabled(enabled);
}
/**
* This method is used to disable/enable mapper actions that are not done by enableViewControls()
* @param If true then enable the actions otherwise disable the actions
*/
void CMapView::enableNonViewActions(bool enabled)
{
m_toolsGrid->setEnabled(enabled);
}
void CMapView::requestPaint()
{
mapWidget->update();
}
void CMapView::changed()
{
maxSize = QSize(0,0);
CMapLevel *level = getCurrentlyViewedLevel();
if (!level) {
mapWidget->update();
return;
}
CMapLevel *upperLevel = level->getNextLevel();
CMapLevel *lowerLevel = level->getPrevLevel();
QPoint size(0,0);
// Calc the size the widget should be
QList<CMapElement *> lst = level->getAllElements();
foreach (CMapElement *element, lst)
{
if (element->getHighX()>size.x()) size.setX(element->getHighX());
if (element->getHighY()>size.y()) size.setY(element->getHighY());
}
if (upperLevel && mapManager->getMapData()->showUpperLevel)
{
lst = upperLevel->getAllElements();
foreach (CMapElement *element, lst)
{
if (element->getHighX()>size.x()) size.setX(element->getHighX());
if (element->getHighY()>size.y()) size.setY(element->getHighY());
}
}
if (lowerLevel && mapManager->getMapData()->showLowerLevel)
{
lst = lowerLevel->getAllElements();
foreach (CMapElement *element, lst)
{
if (element->getHighX()>size.x()) size.setX(element->getHighX());
if (element->getHighY()>size.y()) size.setY(element->getHighY());
}
}
checkSize(size);
mapWidget->update();
}
/** Tell this map widget to display a different level. view wiil
* center on the first room */
void CMapView::showPosition(CMapLevel *level,bool centerView)
{
QPoint pos(0,0);
if (!level->getRoomList()->isEmpty())
{
CMapRoom *room = level->getRoomList()->first();
pos.setX(room->getX());
pos.setY(room->getY());
}
showPosition(pos,level,centerView);
}
void CMapView::showPosition(CMapRoom *room,bool centerView)
{
QPoint pos(0,0);
if (room)
{
pos.setX(room->getX());
pos.setY(room->getY());
showPosition(pos,room->getLevel(),centerView);
}
}
/** Tell this map widget to display a different zone */
void CMapView::showPosition(QPoint pos,CMapLevel *level,bool centerView)
{
if ((!centerView) && (getCurrentlyViewedLevel() == level)) return;
if (!level) { changed(); return; }
setLevel(level);
changed();
enableViewControls(true);
// Center on the position
if (centerView)
scroller->ensureVisible(pos.x(),pos.y(), width()/2, height()/2);
// Update the status bar
statusbar->setZone(mapManager->getZone());
statusbar->setLevel(level);
CMapRoom *cur = mapManager->getCurrentRoom();
statusbar->setRoom(cur ? cur->getLabel() : "");
mapManager->activeViewChanged();
}
/** This is used ensure a location is visiable for views that scroll */
void CMapView::ensureVisible(QPoint pos)
{
scroller->ensureVisible(pos.x(),pos.y(),10,10);
}
/** Used to calculate the correct size for the widget */
void CMapView::checkSize(QPoint pos)
{
if (pos.x() > maxSize.width()) maxSize.setWidth(pos.x());
if (pos.y() > maxSize.height()) maxSize.setHeight(pos.y());
int view_x = width();
int view_y = height();
if (maxSize.width() > view_x)
view_x = maxSize.width();
if (maxSize.height() > view_y)
view_y = maxSize.height();
QSize grid = mapManager->getMapData()->gridSize;
view_x += grid.width() * 3;
view_y += grid.height() * 3;
if (view_y != mapWidget->height() || view_x != mapWidget->width())
mapWidget->setFixedSize(view_x, view_y);
}
/** Get the max x cord of all elements */
int CMapView::getMaxX(void)
{
return maxSize.width();
}
/** Get the max y cord of all elements */
int CMapView::getMaxY(void)
{
return maxSize.height();
}
void CMapView::setFollowMode(bool follow)
{
cmdFollowMode->setChecked(follow);
}
bool CMapView::getFollowMode(void)
{
return cmdFollowMode->isChecked();
}
void CMapView::setCreateMode(bool follow)
{
cmdCreateMode->setChecked(follow);
}
bool CMapView::getCreateMode(void)
{
return cmdCreateMode->isChecked();
}
// Tools slots
void CMapView::slotToolsGrid()
{
mapManager->getMapData()->gridVisable = m_toolsGrid->isChecked();
mapManager->redrawAllViews();
}
void CMapView::levelShift(bool up)
{
CMapLevel *level = getCurrentlyViewedLevel();
level = up ? level->getNextLevel() : level->getPrevLevel();
if (level) {
showPosition(level, false);
return;
}
if (KMessageBox::warningYesNo (NULL, i18n("There is no level in that direction. Do you want to create a new one?"),i18n("KMuddy Mapper")) != KMessageBox::Yes) return;
mapManager->createLevel(up ? UP : DOWN);
}
void CMapView::slotToolsLevelUp()
{
levelShift(true);
}
void CMapView::slotToolsLevelDown()
{
levelShift(false);
}
void CMapView::slotToolsLevelDelete()
{
CMapLevel *level = getCurrentlyViewedLevel();
if (!level) return;
int count = mapManager->getZone()->levelCount();
if (count <= 1) return;
if (KMessageBox::warningYesNo (NULL,i18n("Are you sure that you want to delete the current level?"),i18n("KMuddy Mapper")) != KMessageBox::Yes) return;
mapManager->deleteLevel(level);
}
void CMapView::slotToolsZoneCreate()
{
bool ok;
QString name = KInputDialog::getText(i18n("KMuddy Mapper"), i18n("Please enter the name of the new zone:"), QString(), &ok);
if (!ok) return;
if (!name.length()) return;
mapManager->zoneManager()->createZone(name);
}
void CMapView::slotToolsZoneDelete()
{
CMapZoneManager *zm = mapManager->zoneManager();
if (KMessageBox::warningYesNo (NULL,i18n("Are you sure that you want to delete the current zone? This cannot be undone."),i18n("KMuddy Mapper")) != KMessageBox::Yes) return;
zm->deleteZone(zm->activeZone());
}
void CMapView::slotViewUpperLevel()
{
mapManager->getMapData()->showUpperLevel = m_viewUpperLevel->isChecked();
mapManager->redrawAllViews();
}
void CMapView::slotViewLowerLevel()
{
mapManager->getMapData()->showLowerLevel = m_viewLowerLevel->isChecked();
mapManager->redrawAllViews();
}
/** Used to room under the point the current room */
void CMapView::slotRoomSetCurrentPos(void)
{
mapManager->setCurrentRoom((CMapRoom *)m_selectedElement);
}
/** Used to room under the point the login room */
void CMapView::slotRoomSetLogin(void)
{
mapManager->setLoginRoom((CMapRoom *)m_selectedElement);
}
/** Used to set speedwalk to the room under the pointer */
void CMapView::slotRoomSpeedwalkTo(void)
{
mapManager->walkPlayerTo((CMapRoom *)m_selectedElement);
}
/** Used to delete the room under the pointer */
void CMapView::slotRoomDelete(void)
{
mapManager->deleteElement(m_selectedElement);
}
/** Used to display the properties of the room under the pointer */
void CMapView::slotRoomProperties(void)
{
mapManager->propertiesRoom((CMapRoom *)m_selectedElement);
}
/** Used to make the path under the pointer one way */
void CMapView::slotPathOneWay(void)
{
mapManager->makePathOneWay((CMapPath *)m_selectedElement);
}
/** Used to make the path under the pointer two way */
void CMapView::slotPathTwoWay(void)
{
mapManager->makePathTwoWay((CMapPath *)m_selectedElement);
}
/** Used to add a bend to the path under the pointer */
void CMapView::slotPathAddBend(void)
{
kDebug() << "CMapView::CMapManager slotPathAddBend";
mapManager->openCommandGroup(i18n("Add Bend"));
CMapPath *path = (CMapPath *)m_selectedElement;
path->addBendWithUndo(m_selectedPos);
if (path->getOpsitePath())
{
path->getOpsitePath()->addBendWithUndo(m_selectedPos);
}
m_clipboard->slotUnselectAll();
path->setEditMode(true);
changedElement(path);
mapManager->closeCommandGroup();
}
/** Used to delete the path segment under the pointer */
void CMapView::slotPathDelBend(void)
{
mapManager->openCommandGroup(i18n("Delete Path Segment"));
CMapPath *path = (CMapPath *)m_selectedElement;
int seg = path->mouseInPathSeg(m_selectedPos, getCurrentlyViewedZone());
path->deletePathSegWithUndo(seg);
if (path->getOpsitePath())
{
int seg = path->getOpsitePath()->mouseInPathSeg(m_selectedPos, getCurrentlyViewedZone());
path->getOpsitePath()->deletePathSegWithUndo(seg);
}
mapManager->changedElement(path);
mapManager->closeCommandGroup();
}
/** Used to edit the bends of the path under the pointer */
void CMapView::slotPathEditBends(void)
{
CMapPath *path = (CMapPath *)m_selectedElement;
m_clipboard->slotUnselectAll();
path->setEditMode(true);
mapManager->changedElement(path);
}
/** Used to delete the path under the pointer */
void CMapView::slotPathDelete(void)
{
mapManager->deleteElement(m_selectedElement);
}
/** Used to display the properties of the path under the pointer */
void CMapView::slotPathProperties(void)
{
mapManager->propertiesPath((CMapPath *)m_selectedElement);
}
/** Used to delete the text element under the pointer */
void CMapView::slotTextDelete(void)
{
mapManager->deleteElement(m_selectedElement);
}
/** Used to display the text properties of the text element under the pointer */
void CMapView::slotTextProperties(void)
{
mapManager->propertiesText((CMapText *)m_selectedElement);
}
/** Used to change the position of room/zone labels */
void CMapView::slotChangeLabelPos()
{
if (m_selectedElement->getElementType()==ROOM)
{
CMapRoom *room = (CMapRoom *)m_selectedElement;
CMapCmdElementProperties *command = new CMapCmdElementProperties(mapManager,i18n("Change room label position"),room);
command->getOrgProperties().writeEntry("LabelPos",(int)room->getLabelPosition());
switch(labelMenu->currentItem())
{
case 0 : command->getNewProperties().writeEntry("LabelPos",(int)CMapRoom::HIDE); break;
case 1 : command->getNewProperties().writeEntry("LabelPos",(int)CMapRoom::NORTH); break;
case 2 : command->getNewProperties().writeEntry("LabelPos",(int)CMapRoom::NORTHEAST); break;
case 3 : command->getNewProperties().writeEntry("LabelPos",(int)CMapRoom::EAST); break;
case 4 : command->getNewProperties().writeEntry("LabelPos",(int)CMapRoom::SOUTHEAST); break;
case 5 : command->getNewProperties().writeEntry("LabelPos",(int)CMapRoom::SOUTH); break;
case 6 : command->getNewProperties().writeEntry("LabelPos",(int)CMapRoom::SOUTHWEST); break;
case 7 : command->getNewProperties().writeEntry("LabelPos",(int)CMapRoom::WEST); break;
case 8 : command->getNewProperties().writeEntry("LabelPos",(int)CMapRoom::NORTHWEST); break;
case 9 : command->getNewProperties().writeEntry("LabelPos",(int)CMapRoom::CUSTOM); break;
default : command->getNewProperties().writeEntry("LabelPos",(int)CMapRoom::HIDE); break;
}
mapManager->addCommand(command);
}
if (m_selectedElement->getElementType()==ZONE)
{
CMapZone *zone = (CMapZone *)m_selectedElement;
CMapCmdElementProperties *command = new CMapCmdElementProperties(mapManager,i18n("Change zone label position"),zone);
command->getOrgProperties().writeEntry("LabelPos",(int)zone->getLabelPosition());
switch(labelMenu->currentItem())
{
case 0 : command->getNewProperties().writeEntry("LabelPos",(int)CMapZone::HIDE); break;
case 1 : command->getNewProperties().writeEntry("LabelPos",(int)CMapZone::NORTH); break;
case 2 : command->getNewProperties().writeEntry("LabelPos",(int)CMapZone::NORTHEAST); break;
case 3 : command->getNewProperties().writeEntry("LabelPos",(int)CMapZone::EAST); break;
case 4 : command->getNewProperties().writeEntry("LabelPos",(int)CMapZone::SOUTHEAST); break;
case 5 : command->getNewProperties().writeEntry("LabelPos",(int)CMapZone::SOUTH); break;
case 6 : command->getNewProperties().writeEntry("LabelPos",(int)CMapZone::SOUTHWEST); break;
case 7 : command->getNewProperties().writeEntry("LabelPos",(int)CMapZone::WEST); break;
case 8 : command->getNewProperties().writeEntry("LabelPos",(int)CMapZone::NORTHWEST); break;
case 9 : command->getNewProperties().writeEntry("LabelPos",(int)CMapZone::CUSTOM); break;
default : command->getNewProperties().writeEntry("LabelPos",(int)CMapZone::HIDE); break;
}
mapManager->addCommand(command);
}
}
int CMapView::getWidth(void)
{
if (mapWidget->width() > scroller->viewport()->width())
return mapWidget->width();
return scroller->viewport()->width();
}
int CMapView::getHeight(void)
{
if (mapWidget->height() > scroller->viewport()->height())
return mapWidget->height();
return scroller->viewport()->height();
}
void CMapView::setCursor ( const QCursor & cursor)
{
if (mapWidget)
mapWidget->setCursor(cursor);
}
void CMapView::resizeEvent (QResizeEvent *)
{
changed();
}
/** Used to set the view to active */
void CMapView::focusInEvent(QFocusEvent *)
{
}
void CMapView::closeEvent(QCloseEvent *)
{
}
void CMapView::slotWidgetBeingClosed()
{
}
void CMapView::slotDockWindowClose()
{
}
bool CMapView::queryClose()
{
emit closed();
return true;
}
| KDE/kmuddy | plugins/mapper/cmapview.cpp | C++ | gpl-2.0 | 26,945 |
<?php $unconditional_srvc1_icon = esc_html(get_theme_mod( 'unconditional_service1_icon' )); ?>
<?php $unconditional_srvc2_icon = esc_html(get_theme_mod( 'unconditional_service2_icon' )); ?>
<?php $unconditional_srvc3_icon = esc_html(get_theme_mod( 'unconditional_service3_icon' )); ?>
<?php $unconditional_srvc1_url = esc_url(get_theme_mod( 'unconditional_service1_url' )); ?>
<?php $unconditional_srvc2_url = esc_url(get_theme_mod( 'unconditional_service2_url' )); ?>
<?php $unconditional_srvc3_url = esc_url(get_theme_mod( 'unconditional_service3_url' )); ?>
<?php $unconditional_srvc1_title = esc_html(get_theme_mod( 'unconditional_service1_title' )); ?>
<?php $unconditional_srvc2_title = esc_html(get_theme_mod( 'unconditional_service2_title' )); ?>
<?php $unconditional_srvc3_title = esc_html(get_theme_mod( 'unconditional_service3_title' )); ?>
<?php $unconditional_srvc1_text = esc_html(get_theme_mod( 'unconditional_service1_text' )); ?>
<?php $unconditional_srvc2_text = esc_html(get_theme_mod( 'unconditional_service2_text' )); ?>
<?php $unconditional_srvc3_text = esc_html(get_theme_mod( 'unconditional_service3_text' )); ?>
<div class="container">
<div class="row">
<!-- Service Boxes -->
<div class="col-sm-4 col-sm-6 col-xs-12">
<div class="box">
<div class="icon">
<?php if (get_theme_mod( 'unconditional_service1_icon' )) { ?>
<div class="image"><i class="fa fa-<?php echo $unconditional_srvc1_icon ?>"></i></div>
<?php } else { ?>
<div class="image"><i class="fa fa-thumbs-o-up"></i></div>
<?php } ?>
<div class="info">
<?php if (get_theme_mod( 'unconditional_service1_title' )) { ?>
<h3 class="title"><?php echo $unconditional_srvc1_title ?></h3>
<?php } else { ?>
<h3 class="title"><?php printf( __( 'Made with Bootstrap', 'unconditional' ) ); ?></h3>
<?php } ?>
<?php if (get_theme_mod( 'unconditional_service1_text' )) { ?>
<p><?php echo $unconditional_srvc1_text ?></p>
<?php } else { ?>
<p>
<?php printf( __( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in lobortis nisl, vitae iaculis sapien. Phasellus ultrices gravida massa luctus ornare. Suspendisse blandit quam elit, eu imperdiet neque semper.', 'unconditional' ) ); ?>
</p>
<?php } ?>
<div class="more">
<?php if (get_theme_mod( 'unconditional_service1_url' )) { ?>
<a href="<?php echo $unconditional_srvc1_url ?>" title="<?php echo $unconditional_srvc1_title ?>">
<?php printf( __( 'Read More', 'unconditional' ) ); ?> <i class="fa fa-angle-double-right"></i>
</a>
<?php } else { ?>
<a href="#" title="Service Title Link">
<?php printf( __( 'Read More', 'unconditional' ) ); ?> <i class="fa fa-angle-double-right"></i>
</a>
<?php } ?>
</div>
</div>
</div>
<div class="space"></div>
</div>
</div>
<div class="col-sm-4 col-sm-6 col-xs-12">
<div class="box">
<div class="icon">
<?php if (get_theme_mod( 'unconditional_service2_icon' )) { ?>
<div class="image"><i class="fa fa-<?php echo $unconditional_srvc2_icon ?>"></i></div>
<?php } else { ?>
<div class="image"><i class="fa fa-flag"></i></div>
<?php } ?>
<div class="info">
<?php if (get_theme_mod( 'unconditional_service2_title' )) { ?>
<h3 class="title"><?php echo $unconditional_srvc2_title ?></h3>
<?php } else { ?>
<h3 class="title"><?php printf( __( 'Icons by Font Awesome', 'unconditional' ) ); ?></h3>
<?php } ?>
<?php if (get_theme_mod( 'unconditional_service2_text' )) { ?>
<p><?php echo $unconditional_srvc2_text ?></p>
<?php } else { ?>
<p>
<?php printf( __( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in lobortis nisl, vitae iaculis sapien. Phasellus ultrices gravida massa luctus ornare. Suspendisse blandit quam elit, eu imperdiet neque semper.', 'unconditional' ) ); ?>
</p>
<?php } ?>
<div class="more">
<?php if (get_theme_mod( 'unconditional_service2_url' )) { ?>
<a href="<?php echo $unconditional_srvc2_url ?>" title="<?php echo $unconditional_srvc2_title ?>">
<?php printf( __( 'Read More', 'unconditional' ) ); ?> <i class="fa fa-angle-double-right"></i>
</a>
<?php } else { ?>
<a href="#" title="Service Title Link">
<?php printf( __( 'Read More', 'unconditional' ) ); ?> <i class="fa fa-angle-double-right"></i>
</a>
<?php } ?>
</div>
</div>
</div>
<div class="space"></div>
</div>
</div>
<div class="col-sm-4 col-sm-6 col-xs-12">
<div class="box">
<div class="icon">
<?php if (get_theme_mod( 'unconditional_service3_icon' )) { ?>
<div class="image"><i class="fa fa-<?php echo $unconditional_srvc3_icon ?>"></i></div>
<?php } else { ?>
<div class="image"><i class="fa fa-desktop"></i></div>
<?php } ?>
<div class="info">
<?php if (get_theme_mod( 'unconditional_service3_title' )) { ?>
<h3 class="title"><?php echo $unconditional_srvc3_title ?></h3>
<?php } else { ?>
<h3 class="title"><?php printf( __( 'Mobile First & Desktop Friendly', 'unconditional' ) ); ?></h3>
<?php } ?>
<?php if (get_theme_mod( 'unconditional_service3_text' )) { ?>
<p><?php echo $unconditional_srvc3_text ?></p>
<?php } else { ?>
<p>
<?php printf( __( 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed in lobortis nisl, vitae iaculis sapien. Phasellus ultrices gravida massa luctus ornare. Suspendisse blandit quam elit, eu imperdiet neque semper.', 'unconditional' ) ); ?>
</p>
<?php } ?>
<div class="more">
<?php if (get_theme_mod( 'unconditional_service3_url' )) { ?>
<a href="<?php echo $unconditional_srvc3_url ?>" title="<?php echo $unconditional_srvc3_title ?>">
<?php printf( __( 'Read More', 'unconditional' ) ); ?> <i class="fa fa-angle-double-right"></i>
</a>
<?php } else { ?>
<a href="#" title="Service Title Link">
<?php printf( __( 'Read More', 'unconditional' ) ); ?> <i class="fa fa-angle-double-right"></i>
</a>
<?php } ?>
</div>
</div>
</div>
<div class="space"></div>
</div>
</div>
<!-- /Service Boxes -->
</div>
</div> | Ipstenu/dreamsiege-wp | advan/wp-content/themes/unconditional/parts/boxes.php | PHP | gpl-2.0 | 6,603 |
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using PIXTools;
namespace RacingGame.Graphics
{
class BloomPostProcess : PostProcessEffect
{
GraphicsDevice device = GraphicsManager.getDevice();
Effect bloom;
EffectTechnique tech;
EffectPass passGlare;
EffectPass passLuminance;
EffectPass passCommit;
EffectPass passDownsample;
EffectPass passAfterImage;
EffectPass passToneMap;
EffectParameter inputTexture;
EffectParameter outputTexture;
EffectParameter luminanceTexture;
EffectParameter invResolution;
EffectParameter afterImageTexture;
EffectParameter demonMode;
EffectParameter afterImage;
EffectParameter glareParams;
private RenderTarget2D intermediateBuffer;
private RenderTarget2D luminanceBuffer;
private RenderTarget2D bloomBuffer;
private RenderTarget2D toneMapBuffer;
private BlurPostProcess blurPostProcess = new BlurPostProcess();
private float afterImageRatio = 0.0f;
private Vector4 bloomParameters = new Vector4();
private bool demonModeOn = false;
private bool demonModeChanged = false;
public Texture2D Luminance
{
get { return luminanceBuffer.GetTexture(); }
}
public bool DemonMode
{
get
{
return demonModeOn;
}
set
{
if (value)
{
afterImageRatio = 0.6f;
bloomParameters = new Vector4(0.3f, 0.3f, 0.3f, 3);
}
else
{
afterImageRatio = 0.5f;
bloomParameters = new Vector4(0.4f, 0.4f, 0.4f, 2f);
}
demonModeOn = value;
demonModeChanged = true;
}
}
public BloomPostProcess()
{
bloom = RacingGame.contentManager.Load<Effect>("Shaders/bloomPostProcess");
tech = bloom.Techniques["BloomPostProcess"];
passDownsample = tech.Passes["downsample"];
passGlare = tech.Passes["glare"];
passLuminance = tech.Passes["luminance"];
passCommit = tech.Passes["commit"];
passAfterImage = tech.Passes["afterImage"];
passToneMap = tech.Passes["tonemap"];
inputTexture = bloom.Parameters["InputTexture"];
outputTexture = bloom.Parameters["OutputTexture"];
luminanceTexture = bloom.Parameters["LuminanceTexture"];
afterImageTexture = bloom.Parameters["AfterImageTexture"];
demonMode = bloom.Parameters["DemonMode"];
afterImage = bloom.Parameters["AfterImage"];
glareParams = bloom.Parameters["GlareParams"];
invResolution = bloom.Parameters["InvResolution"];
DemonMode = false;
}
public override void postProcess(RenderTarget2D input, RenderTarget2D output)
{
const int downSample = 4;
if (intermediateBuffer == null || intermediateBuffer.Height != input.Height / downSample || intermediateBuffer.Width != input.Width / downSample
|| intermediateBuffer.MultiSampleType != input.MultiSampleType)
{
bloomBuffer = new RenderTarget2D(input.GraphicsDevice, input.Width / downSample, input.Height / downSample, 1,
input.Format, input.MultiSampleType, input.MultiSampleQuality);
intermediateBuffer = new RenderTarget2D(input.GraphicsDevice, input.Width / downSample, input.Height / downSample, 1,
input.Format, input.MultiSampleType, input.MultiSampleQuality);
toneMapBuffer = new RenderTarget2D(input.GraphicsDevice, input.Width, input.Height, 1,
input.Format, input.MultiSampleType, input.MultiSampleQuality);
luminanceBuffer = new RenderTarget2D(input.GraphicsDevice, 1, 1, 1,
input.Format, input.MultiSampleType, input.MultiSampleQuality);
}
Vector2 res = new Vector2(1.0f / input.Width, 1.0f / input.Height);
invResolution.SetValue(res);
if (demonModeChanged)
{
demonMode.SetValue(demonModeOn);
afterImage.SetValue(afterImageRatio);
glareParams.SetValue(bloomParameters);
demonModeChanged = false;
}
device.SetRenderTarget(0, bloomBuffer);
inputTexture.SetValue(input.GetTexture());
bloom.Begin();
// downsample pass
PIXTools.PIXTools.BeginEvent("downsample pass");
passDownsample.Begin();
drawQuad();
passDownsample.End();
PIXTools.PIXTools.EndEvent();
// luminance pass
device.SetRenderTarget(0, luminanceBuffer);
inputTexture.SetValue(bloomBuffer.GetTexture());
Vector2 dsRes = res * downSample;
invResolution.SetValue(dsRes);
PIXTools.PIXTools.BeginEvent("luminance pass");
passLuminance.Begin();
drawQuad();
passLuminance.End();
PIXTools.PIXTools.EndEvent();
// glare pass
device.SetRenderTarget(0, bloomBuffer);
luminanceTexture.SetValue(luminanceBuffer.GetTexture());
PIXTools.PIXTools.BeginEvent("bloom pass");
passGlare.Begin();
drawQuad();
passGlare.End();
PIXTools.PIXTools.EndEvent();
bloom.End();
// blur
PIXTools.PIXTools.BeginEvent("blur pass");
blurPostProcess.postProcess(bloomBuffer, bloomBuffer);
PIXTools.PIXTools.EndEvent();
bloom.Begin();
// afterimage pass
device.SetRenderTarget(0, intermediateBuffer);
inputTexture.SetValue(bloomBuffer.GetTexture());
PIXTools.PIXTools.BeginEvent("afterimage pass");
passAfterImage.Begin();
drawQuad();
passAfterImage.End();
PIXTools.PIXTools.EndEvent();
// tone map pass
device.SetRenderTarget(0, toneMapBuffer);
inputTexture.SetValue(input.GetTexture());
PIXTools.PIXTools.BeginEvent("tonemap pass");
passToneMap.Begin();
drawQuad();
passToneMap.End();
PIXTools.PIXTools.EndEvent();
// commit pass
device.SetRenderTarget(0, output);
inputTexture.SetValue(intermediateBuffer.GetTexture());
outputTexture.SetValue(toneMapBuffer.GetTexture());
PIXTools.PIXTools.BeginEvent("commit glare pass");
passCommit.Begin();
drawQuad();
passCommit.End();
PIXTools.PIXTools.EndEvent();
bloom.End();
afterImageTexture.SetValue(intermediateBuffer.GetTexture());
inputTexture.SetValue((Texture)null);
}
}
}
| davidsundelius/SLERP3D | Graphics/Effect/BloomPostProcess.cs | C# | gpl-2.0 | 7,197 |
/* Publish module for wikiEditor */
( function ( $ ) {
$.wikiEditor.modules.publish = {
/**
* Compatability map
*/
browsers: {
// Left-to-right languages
ltr: {
msie: [['>=', 7]],
firefox: [['>=', 3]],
opera: [['>=', 9.6]],
safari: [['>=', 4]]
},
// Right-to-left languages
rtl: {
msie: [['>=', 8]],
firefox: [['>=', 3]],
opera: [['>=', 9.6]],
safari: [['>=', 4]]
}
},
/**
* Internally used functions
*/
fn: {
/**
* Creates a publish module within a wikiEditor
* @param context Context object of editor to create module in
* @param config Configuration object to create module from
*/
create: function ( context, config ) {
// Build the dialog behind the Publish button
var dialogID = 'wikiEditor-' + context.instance + '-dialog';
$.wikiEditor.modules.dialogs.fn.create(
context,
{
previewsave: {
id: dialogID,
titleMsg: 'wikieditor-publish-dialog-title',
html: '\
<div class="wikiEditor-publish-dialog-copywarn"></div>\
<div class="wikiEditor-publish-dialog-editoptions">\
<form id="wikieditor-' + context.instance + '-publish-dialog-form">\
<div class="wikiEditor-publish-dialog-summary">\
<label for="wikiEditor-' + context.instance + '-dialog-summary"\
rel="wikieditor-publish-dialog-summary"></label>\
<br />\
<input type="text" id="wikiEditor-' + context.instance + '-dialog-summary"\
style="width: 100%;" />\
</div>\
<div class="wikiEditor-publish-dialog-options">\
<input type="checkbox"\
id="wikiEditor-' + context.instance + '-dialog-minor" />\
<label for="wikiEditor-' + context.instance + '-dialog-minor"\
rel="wikieditor-publish-dialog-minor"></label>\
<input type="checkbox"\
id="wikiEditor-' + context.instance + '-dialog-watch" />\
<label for="wikiEditor-' + context.instance + '-dialog-watch"\
rel="wikieditor-publish-dialog-watch"></label>\
</div>\
</form>\
</div>',
init: function () {
var i;
$(this).find( '[rel]' ).each( function () {
$(this).text( mediaWiki.msg( $(this).attr( 'rel' ) ) );
});
/* REALLY DIRTY HACK! */
// Reformat the copyright warning stuff
var copyWarnHTML = $( '#editpage-copywarn p' ).html();
// TODO: internationalize by splitting on other characters that end statements
var copyWarnStatements = copyWarnHTML.split( '. ' );
var newCopyWarnHTML = '<ul>';
for ( i = 0; i < copyWarnStatements.length; i++ ) {
if ( copyWarnStatements[i] !== '' ) {
var copyWarnStatement = $.trim( copyWarnStatements[i] ).replace( /\.*$/, '' );
newCopyWarnHTML += '<li>' + copyWarnStatement + '.</li>';
}
}
newCopyWarnHTML += '</ul>';
// No list if there's only one element
$(this).find( '.wikiEditor-publish-dialog-copywarn' ).html(
copyWarnStatements.length > 1 ? newCopyWarnHTML : copyWarnHTML
);
/* END OF REALLY DIRTY HACK */
if ( $( '#wpMinoredit' ).length === 0 )
$( '#wikiEditor-' + context.instance + '-dialog-minor' ).hide();
else if ( $( '#wpMinoredit' ).is( ':checked' ) )
$( '#wikiEditor-' + context.instance + '-dialog-minor' )
.prop( 'checked', true );
if ( $( '#wpWatchthis' ).length === 0 )
$( '#wikiEditor-' + context.instance + '-dialog-watch' ).hide();
else if ( $( '#wpWatchthis' ).is( ':checked' ) )
$( '#wikiEditor-' + context.instance + '-dialog-watch' )
.prop( 'checked', true );
$(this).find( 'form' ).submit( function ( e ) {
$(this).closest( '.ui-dialog' ).find( 'button:first' ).click();
e.preventDefault();
});
},
dialog: {
buttons: {
'wikieditor-publish-dialog-publish': function () {
var minorChecked = $( '#wikiEditor-' + context.instance +
'-dialog-minor' ).is( ':checked' ) ?
'checked' : '';
var watchChecked = $( '#wikiEditor-' + context.instance +
'-dialog-watch' ).is( ':checked' ) ?
'checked' : '';
$( '#wpMinoredit' ).prop( 'checked', minorChecked );
$( '#wpWatchthis' ).prop( 'checked', watchChecked );
$( '#wpSummary' ).val( $( '#wikiEditor-' + context.instance +
'-dialog-summary' ).val() );
$( '#editform' ).submit();
},
'wikieditor-publish-dialog-goback': function () {
$(this).dialog( 'close' );
}
},
open: function () {
$( '#wikiEditor-' + context.instance + '-dialog-summary' ).focus();
},
width: 500
},
resizeme: false
}
}
);
context.fn.addButton( {
'captionMsg': 'wikieditor-publish-button-publish',
'action': function () {
$( '#' + dialogID ).dialog( 'open' );
return false;
}
} );
context.fn.addButton( {
'captionMsg': 'wikieditor-publish-button-cancel',
'action': function () { }
} );
}
}
};
}( jQuery ) );
| libis/schatkamer-mediawiki | extensions/WikiEditor/modules/jquery.wikiEditor.publish.js | JavaScript | gpl-2.0 | 5,169 |
/***********************************************************************************
* *
* Voreen - The Volume Rendering Engine *
* *
* Copyright (C) 2005-2013 University of Muenster, Germany. *
* Visualization and Computer Graphics Group <http://viscg.uni-muenster.de> *
* For a list of authors please refer to the file "CREDITS.txt". *
* *
* This file is part of the Voreen software package. Voreen is free software: *
* you can redistribute it and/or modify it under the terms of the GNU General *
* Public License version 2 as published by the Free Software Foundation. *
* *
* Voreen 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 in the file *
* "LICENSE.txt" along with this file. If not, see <http://www.gnu.org/licenses/>. *
* *
* For non-commercial academic use see the license exception specified in the file *
* "LICENSE-academic.txt". To get information about commercial licensing please *
* contact the authors. *
* *
***********************************************************************************/
#include "quadview.h"
namespace voreen {
QuadView::QuadView()
: RenderProcessor()
, showGrid_("showGrid", "Show grid", true)
, gridColor_("gridColor", "Grid color", tgt::vec4(1.0f, 1.0f, 1.0f, 1.0f))
, maximized_("maximized", "Maximized sub-view", 0, 0, 4)
, maximizeOnDoubleClick_("maximizeOnDoubleClick", "Maximize on double click", true)
, maximizeEventProp_("mouseEvent.maximize", "Maximize Event", this, &QuadView::toggleMaximization,
tgt::MouseEvent::MOUSE_BUTTON_LEFT, tgt::MouseEvent::DOUBLECLICK, tgt::MouseEvent::MODIFIER_NONE)
, mouseMoveEventProp_("mouseEvent.move", "Move Event", this, &QuadView::mouseMove,
tgt::MouseEvent::MOUSE_BUTTON_NONE, tgt::MouseEvent::MOTION | tgt::MouseEvent::CLICK | tgt::MouseEvent::ENTER_EXIT, tgt::MouseEvent::MODIFIER_NONE)
, outport_(Port::OUTPORT, "outport", "Image Output", true, Processor::INVALID_RESULT, RenderPort::RENDERSIZE_RECEIVER)
, inport1_(Port::INPORT, "inport1", "Image1 Input", false, Processor::INVALID_RESULT, RenderPort::RENDERSIZE_ORIGIN)
, inport2_(Port::INPORT, "inport2", "Image2 Input", false, Processor::INVALID_RESULT, RenderPort::RENDERSIZE_ORIGIN)
, inport3_(Port::INPORT, "inport3", "Image3 Input", false, Processor::INVALID_RESULT, RenderPort::RENDERSIZE_ORIGIN)
, inport4_(Port::INPORT, "inport4", "Image4 Input", false, Processor::INVALID_RESULT, RenderPort::RENDERSIZE_ORIGIN)
, currentPort_(-1)
, isDragging_(false)
{
gridColor_.setViews(Property::COLOR);
addProperty(showGrid_);
addProperty(gridColor_);
addProperty(maximized_);
maximized_.setVisible(false);
addProperty(maximizeOnDoubleClick_);
addEventProperty(maximizeEventProp_);
addEventProperty(mouseMoveEventProp_);
addPort(outport_);
addPort(inport1_);
addPort(inport2_);
addPort(inport3_);
addPort(inport4_);
outport_.onSizeReceiveChange<QuadView>(this, &QuadView::portSizeReceiveChanged);
}
QuadView::~QuadView() {
}
Processor* QuadView::create() const {
return new QuadView();
}
bool QuadView::isReady() const {
if (!outport_.isReady())
return false;
if (!inport1_.isReady() && !inport2_.isReady() && !inport3_.isReady() && !inport4_.isReady())
return false;
if(maximized_.get() != 0) {
switch(maximized_.get()) {
case 1: if(!inport1_.isReady())
return false;
break;
case 2: if(!inport2_.isReady())
return false;
break;
case 3: if(!inport3_.isReady())
return false;
break;
case 4: if(!inport4_.isReady())
return false;
break;
}
}
return true;
}
void QuadView::process() {
if (maximized_.get() == 0) {
MatStack.matrixMode(tgt::MatrixStack::MODELVIEW);
outport_.activateTarget();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (inport1_.isReady()) {
inport1_.bindColorTexture(GL_TEXTURE0);
inport1_.getColorTexture()->enable();
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
MatStack.translate(-0.5f, 0.5f, 0.0f);
MatStack.scale(0.5f, 0.5f, 1.0f);
glDepthFunc(GL_ALWAYS);
renderQuad();
glDepthFunc(GL_LESS);
MatStack.loadIdentity();
inport1_.getColorTexture()->disable();
}
if (inport2_.isReady()) {
inport2_.bindColorTexture(GL_TEXTURE0);
inport2_.getColorTexture()->enable();
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
MatStack.translate(0.5f, 0.5f, 0.0f);
MatStack.scale(0.5f, 0.5f, 1.0f);
glDepthFunc(GL_ALWAYS);
renderQuad();
glDepthFunc(GL_LESS);
MatStack.loadIdentity();
inport2_.getColorTexture()->disable();
}
if (inport3_.isReady()) {
inport3_.bindColorTexture(GL_TEXTURE0);
inport3_.getColorTexture()->enable();
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
MatStack.translate(-0.5f, -0.5f, 0.0f);
MatStack.scale(0.5f, 0.5f, 1.0f);
glDepthFunc(GL_ALWAYS);
renderQuad();
glDepthFunc(GL_LESS);
MatStack.loadIdentity();
inport3_.getColorTexture()->disable();
}
if (inport4_.isReady()) {
inport4_.bindColorTexture(GL_TEXTURE0);
inport4_.getColorTexture()->enable();
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
MatStack.translate(0.5f, -0.5f, 0.0f);
MatStack.scale(0.5f, 0.5f, 1.0f);
glDepthFunc(GL_ALWAYS);
renderQuad();
glDepthFunc(GL_LESS);
MatStack.loadIdentity();
inport4_.getColorTexture()->disable();
}
glActiveTexture(GL_TEXTURE0);
if(showGrid_.get()) {
glDepthFunc(GL_ALWAYS);
glColor4f(gridColor_.get().r, gridColor_.get().g, gridColor_.get().b, gridColor_.get().a);
glBegin(GL_LINES);
glVertex2f(-1.0f, 0.0f);
glVertex2f(1.0f, 0.0f);
glVertex2f(0.0f, 1.0f);
glVertex2f(0.0f, -1.0f);
glEnd();
glDepthFunc(GL_LESS);
}
outport_.deactivateTarget();
MatStack.matrixMode(tgt::MatrixStack::MODELVIEW);
MatStack.loadIdentity();
LGL_ERROR;
}
else {
//maximized:
switch(maximized_.get()) {
case 1: if(!inport1_.isReady())
return;
outport_.activateTarget();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
inport1_.bindColorTexture(GL_TEXTURE0);
inport1_.getColorTexture()->enable();
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glDepthFunc(GL_ALWAYS);
renderQuad();
glDepthFunc(GL_LESS);
MatStack.loadIdentity();
inport1_.getColorTexture()->disable();
outport_.deactivateTarget();
break;
case 2: if(!inport2_.isReady())
return;
outport_.activateTarget();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
inport2_.bindColorTexture(GL_TEXTURE0);
inport2_.getColorTexture()->enable();
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glDepthFunc(GL_ALWAYS);
renderQuad();
glDepthFunc(GL_LESS);
MatStack.loadIdentity();
inport2_.getColorTexture()->disable();
outport_.deactivateTarget();
break;
case 3: if(!inport3_.isReady())
return;
outport_.activateTarget();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
inport3_.bindColorTexture(GL_TEXTURE0);
inport3_.getColorTexture()->enable();
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glDepthFunc(GL_ALWAYS);
renderQuad();
glDepthFunc(GL_LESS);
MatStack.loadIdentity();
inport3_.getColorTexture()->disable();
outport_.deactivateTarget();
break;
case 4: if(!inport4_.isReady())
return;
outport_.activateTarget();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
inport4_.bindColorTexture(GL_TEXTURE0);
inport4_.getColorTexture()->enable();
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glDepthFunc(GL_ALWAYS);
renderQuad();
glDepthFunc(GL_LESS);
MatStack.loadIdentity();
inport4_.getColorTexture()->disable();
outport_.deactivateTarget();
break;
}
}
}
void QuadView::initialize() throw (tgt::Exception) {
RenderProcessor::initialize();
updateSizes();
}
void QuadView::portSizeReceiveChanged() {
updateSizes();
}
void QuadView::updateSizes() {
if (outport_.getSize() == tgt::ivec2(0))
return;
if(maximized_.get() == 0) {
tgt::ivec2 subsize = outport_.getReceivedSize() / 2;
inport1_.requestSize(subsize);
inport2_.requestSize(subsize);
inport3_.requestSize(subsize);
inport4_.requestSize(subsize);
}
else {
switch(maximized_.get()) {
case 1: inport1_.requestSize(outport_.getReceivedSize());
break;
case 2: inport2_.requestSize(outport_.getReceivedSize());
break;
case 3: inport3_.requestSize(outport_.getReceivedSize());
break;
case 4: inport4_.requestSize(outport_.getReceivedSize());
break;
default:;
}
}
}
void QuadView::mouseMove(tgt::MouseEvent* e) {
e->accept();
int prevCurrenPort = currentPort_;
if (maximized_.get() == 0) {
if ((e->action() & tgt::MouseEvent::EXIT) == tgt::MouseEvent::EXIT)
currentPort_ = -1;
if ((e->action() & tgt::MouseEvent::PRESSED) == tgt::MouseEvent::PRESSED)
isDragging_ = true;
if ((e->action() & tgt::MouseEvent::RELEASED) == tgt::MouseEvent::RELEASED)
isDragging_ = false;
if (!isDragging_) {
if (e->y() < (e->viewport().y/2)) {
if(e->x() < (e->viewport().x/2)) {
currentPort_ = 1;
}
else {
currentPort_ = 2;
}
}
else {
if(e->x() < (e->viewport().x/2)) {
currentPort_ = 3;
}
else {
currentPort_ = 4;
}
}
}
if (currentPort_ != prevCurrenPort) {
tgt::MouseEvent leaveEvent(1, 1, tgt::MouseEvent::EXIT, e->modifiers(), e->button(), e->viewport() / 2);
tgt::MouseEvent enterEvent(1, 1, tgt::MouseEvent::ENTER, e->modifiers(), e->button(), e->viewport() / 2);
leaveEvent.ignore();
enterEvent.ignore();
switch(prevCurrenPort) {
case 1:
inport1_.distributeEvent(&leaveEvent);
break;
case 2:
inport2_.distributeEvent(&leaveEvent);
break;
case 3:
inport3_.distributeEvent(&leaveEvent);
break;
case 4:
inport4_.distributeEvent(&leaveEvent);
break;
}
switch(currentPort_) {
case 1:
inport1_.distributeEvent(&enterEvent);
break;
case 2:
inport2_.distributeEvent(&enterEvent);
break;
case 3:
inport3_.distributeEvent(&enterEvent);
break;
case 4:
inport4_.distributeEvent(&enterEvent);
break;
}
}
tgt::MouseEvent moveEvent(e->x() % (e->viewport().x/2), e->y() % (e->viewport().y/2), tgt::MouseEvent::MOTION, e->modifiers(), e->button(), e->viewport() / 2);
moveEvent.ignore();
switch(currentPort_) {
case 1:
inport1_.distributeEvent(&moveEvent);
break;
case 2:
inport2_.distributeEvent(&moveEvent);
break;
case 3:
inport3_.distributeEvent(&moveEvent);
break;
case 4:
inport4_.distributeEvent(&moveEvent);
break;
}
}
else {
switch(maximized_.get()) {
case 1: inport1_.distributeEvent(e);
break;
case 2: inport2_.distributeEvent(e);
break;
case 3: inport3_.distributeEvent(e);
break;
case 4: inport4_.distributeEvent(e);
break;
default:;
}
}
}
void QuadView::invalidate(int inv) {
RenderProcessor::invalidate(inv);
}
void QuadView::onEvent(tgt::Event* e) {
tgt::TouchEvent* te = dynamic_cast<tgt::TouchEvent*>(e);
if(te) {
distributeTouchEvent(te);
return;
}
tgt::MouseEvent* me = dynamic_cast<tgt::MouseEvent*>(e);
if (me && !(maximized_.get() == 0 && mouseMoveEventProp_.accepts(me)) && !(maximizeEventProp_.accepts(me) && maximizeOnDoubleClick_.get())) {
distributeMouseEvent(me);
return;
}
RenderProcessor::onEvent(e);
}
// TODO For now, Touch Events are sent to inports only if all touchpoints are located within a single subsection of the viewport
void QuadView::distributeTouchEvent(tgt::TouchEvent* te) {
if (maximized_.get() == 0) {
const std::deque<tgt::TouchPoint>& tps = te->touchPoints();
const tgt::TouchPoint& first = tps.front();
tgt::vec2 outSize = outport_.getSize();
int section = first.pos().y < outSize.y / 2 ? (first.pos().x < outSize.x / 2 ? 0 : 1) : (first.pos().x < outSize.x / 2 ? 2 : 3);
for(std::deque<tgt::TouchPoint>::const_iterator it = tps.begin() + 1; it != tps.end(); it++) {
const tgt::TouchPoint& tp = *it;
// TODO different sections -> handle instead of doing nothing
if(section != (tp.pos().y < outSize.y / 2 ? (tp.pos().x < outSize.x / 2 ? 0 : 1) : (tp.pos().x < outSize.x / 2 ? 2 : 3)))
return;
}
RenderPort* inport = (section == 0 ? &inport1_ : (section == 1 ? &inport2_ : (section == 2 ? &inport3_ : &inport4_)));
tgt::vec2 offset = section == 0 ? tgt::vec2(0.f) : (section == 1 ? tgt::vec2(-outSize.x / 2.f, 0.f) : (section == 2 ? tgt::vec2(0.f, -outSize.y / 2.f) : -outSize / 2.f));
std::deque<tgt::TouchPoint> tpsTrafo;
for(std::deque<tgt::TouchPoint>::const_iterator it = tps.begin(); it != tps.end(); it++) {
const tgt::TouchPoint& tp = *it;
tgt::TouchPoint newTP = tp;
newTP.setPos(tp.pos() + offset);
tpsTrafo.push_back(newTP);
}
tgt::TouchEvent nte = tgt::TouchEvent(tgt::Event::MODIFIER_NONE, te->touchPointStates(), te->deviceType(), tpsTrafo);
nte.ignore(); // accepted is set to true by default
inport->distributeEvent(&nte);
if(nte.isAccepted())
te->accept();
}
else {
switch(maximized_.get()) {
case 1: inport1_.distributeEvent(te);
break;
case 2: inport2_.distributeEvent(te);
break;
case 3: inport3_.distributeEvent(te);
break;
case 4: inport4_.distributeEvent(te);
break;
default:;
}
}
}
void QuadView::distributeMouseEvent(tgt::MouseEvent* me) {
if (maximized_.get() == 0) {
if (me->y() < (me->viewport().y / 2)) {
if (me->x() < (me->viewport().x / 2)) {
tgt::MouseEvent newme(me->x(), me->y(), me->action(), me->modifiers(), me->button(), me->viewport() / 2);
newme.ignore(); // accepted is set to true by default
inport1_.distributeEvent(&newme);
if (newme.isAccepted())
me->accept();
}
else {
tgt::MouseEvent newme(me->x() - (me->viewport().x / 2), me->y(), me->action(), me->modifiers(), me->button(), me->viewport() / 2);
newme.ignore();
inport2_.distributeEvent(&newme);
if (newme.isAccepted())
me->accept();
}
}
else {
if (me->x() < (me->viewport().x / 2)) {
tgt::MouseEvent newme(me->x(), me->y() - (me->viewport().y / 2), me->action(), me->modifiers(), me->button(), me->viewport() / 2);
newme.ignore();
inport3_.distributeEvent(&newme);
if (newme.isAccepted())
me->accept();
}
else {
tgt::MouseEvent newme(me->x() - (me->viewport().x / 2), me->y() - (me->viewport().y / 2), me->action(), me->modifiers(), me->button(), me->viewport() / 2);
newme.ignore();
inport4_.distributeEvent(&newme);
if (newme.isAccepted())
me->accept();
}
}
}
else {
switch(maximized_.get()) {
case 1: inport1_.distributeEvent(me);
break;
case 2: inport2_.distributeEvent(me);
break;
case 3: inport3_.distributeEvent(me);
break;
case 4: inport4_.distributeEvent(me);
break;
default:;
}
}
}
void QuadView::toggleMaximization(tgt::MouseEvent* me) {
if (maximizeOnDoubleClick_.get()) {
if (maximized_.get() == 0) {
if (me->y() < (me->viewport().y / 2)) {
if (me->x() < (me->viewport().x / 2)) {
maximized_.set(1);
}
else {
maximized_.set(2);
}
}
else {
if (me->x() < (me->viewport().x / 2)) {
maximized_.set(3);
}
else {
maximized_.set(4);
}
}
}
else {
maximized_.set(0);
}
updateSizes();
me->accept();
}
}
} // namespace voreen
| bilgili/Voreen | modules/base/processors/image/quadview.cpp | C++ | gpl-2.0 | 20,440 |
package com.dental.provider;
import com.dental.persistence.entity.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.Collection;
/**
* Created by admin on 27.05.2015.
*/
public class DentalUserDetails implements UserDetails {
private Collection<? extends GrantedAuthority> grantedAuthorities;
private String password;
private String username;
// private boolean isAccountNonLocked;
// private boolean isAccountNonExpired;
private User user;
public DentalUserDetails(String username, String password,
Collection<? extends GrantedAuthority> grantedAuthorities, User user) {
this.username = username;
this.password = password;
// this.isAccountNonExpired = isAccountNonExpired;
// this.isAccountNonLocked = isAccountNonLocked;
this.grantedAuthorities = grantedAuthorities;
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return this.grantedAuthorities;
}
@Override
public String getPassword() {
return this.password;
}
@Override
public String getUsername() {
return this.username;
}
@Override
public boolean isAccountNonExpired() {
return false;
}
@Override
public boolean isAccountNonLocked() {
return false;
}
@Override
public boolean isCredentialsNonExpired() {
return false;
}
@Override
public boolean isEnabled() {
return true;
}
public User getUser() {
return this.user;
}
} | light88/dental-spring | web/src/main/java/com/dental/provider/DentalUserDetails.java | Java | gpl-2.0 | 1,589 |
class AddSpecificsToResponses < ActiveRecord::Migration
def change
add_column :responses, :liked, :text
add_column :responses, :disliked, :text
end
end
| atyndall/feedback | db/migrate/20140224144514_add_specifics_to_responses.rb | Ruby | gpl-2.0 | 164 |
<?php
header("Content-type: application/json");
if(isset($_POST['submit'])){
// For delay effect
sleep(1);
// For storing the error fields' name
$errorFields = array();
// Validate fields
if($_POST['name']==""){
// Array key must be the same like input name.
$errorFields['name'] = "Please fill name!";
}
if($_POST['address']==""){
// Array key must be the same like input name.
$errorFields['address'] = "Please fill address!";
}
// Check error fields count
if(count($errorFields)==0){
// Success message
$result['status'] = "success";
$result['message'] = "Your data has been saved.";
// Form will be cleared
$result['clearForm'] = true;
}
else{
// Failed message
$result['status'] = "failed";
$result['message'] = "Please fill all fields correctly!";
// Form will not be cleared
$result['clearForm'] = false;
}
// Error fields list
$result['errorFields'] = $errorFields;
// Return message and error fields is JSON format
echo json_encode($result);
}
| w3shaman/jquery-ajax-validation | action.php | PHP | gpl-2.0 | 1,050 |
/* global kirkiL10n */
var kirki = kirki || {};
kirki = jQuery.extend( kirki, {
/**
* An object containing definitions for input fields.
*
* @since 3.0.16
*/
input: {
/**
* Radio input fields.
*
* @since 3.0.17
*/
radio: {
/**
* Init the control.
*
* @since 3.0.17
* @param {Object} control - The control object.
* @param {Object} control.id - The setting.
* @returns {null}
*/
init: function( control ) {
var input = jQuery( 'input[data-id="' + control.id + '"]' );
// Save the value
input.on( 'change keyup paste click', function() {
kirki.setting.set( control.id, jQuery( this ).val() );
} );
}
},
/**
* Color input fields.
*
* @since 3.0.16
*/
color: {
/**
* Init the control.
*
* @since 3.0.16
* @param {Object} control - The control object.
* @param {Object} control.id - The setting.
* @param {Object} control.choices - Additional options for the colorpickers.
* @param {Object} control.params - Control parameters.
* @param {Object} control.params.choices - alias for control.choices.
* @returns {null}
*/
init: function( control ) {
var picker = jQuery( '.kirki-color-control[data-id="' + control.id + '"]' ),
clear;
control.choices = control.choices || {};
if ( _.isEmpty( control.choices ) && control.params.choices ) {
control.choices = control.params.choices;
}
// If we have defined any extra choices, make sure they are passed-on to Iris.
if ( ! _.isEmpty( control.choices ) ) {
picker.wpColorPicker( control.choices );
}
// Tweaks to make the "clear" buttons work.
setTimeout( function() {
clear = jQuery( '.kirki-input-container[data-id="' + control.id + '"] .wp-picker-clear' );
if ( clear.length ) {
clear.click( function() {
kirki.setting.set( control.id, '' );
} );
}
}, 200 );
// Saves our settings to the WP API
picker.wpColorPicker( {
change: function() {
// Small hack: the picker needs a small delay
setTimeout( function() {
kirki.setting.set( control.id, picker.val() );
}, 20 );
}
} );
}
},
/**
* Generic input fields.
*
* @since 3.0.17
*/
genericInput: {
/**
* Init the control.
*
* @since 3.0.17
* @param {Object} control - The control object.
* @param {Object} control.id - The setting.
* @returns {null}
*/
init: function( control ) {
var input = jQuery( 'input[data-id="' + control.id + '"]' );
// Save the value
input.on( 'change keyup paste click', function() {
kirki.setting.set( control.id, jQuery( this ).val() );
} );
}
},
/**
* Generic input fields.
*
* @since 3.0.17
*/
textarea: {
/**
* Init the control.
*
* @since 3.0.17
* @param {Object} control - The control object.
* @param {Object} control.id - The setting.
* @returns {null}
*/
init: function( control ) {
var textarea = jQuery( 'textarea[data-id="' + control.id + '"]' );
// Save the value
textarea.on( 'change keyup paste click', function() {
kirki.setting.set( control.id, jQuery( this ).val() );
} );
}
},
select: {
/**
* Init the control.
*
* @since 3.0.17
* @param {Object} control - The control object.
* @param {Object} control.id - The setting.
* @returns {null}
*/
init: function( control ) {
var element = jQuery( 'select[data-id="' + control.id + '"]' ),
multiple = parseInt( element.data( 'multiple' ), 10 ),
selectValue,
selectWooOptions = {
escapeMarkup: function( markup ) {
return markup;
}
};
if ( control.params.placeholder ) {
selectWooOptions.placeholder = control.params.placeholder;
selectWooOptions.allowClear = true;
}
if ( 1 < multiple ) {
selectWooOptions.maximumSelectionLength = multiple;
}
jQuery( element ).selectWoo( selectWooOptions ).on( 'change', function() {
selectValue = jQuery( this ).val();
selectValue = ( null === selectValue && 1 < multiple ) ? [] : selectValue;
kirki.setting.set( control.id, selectValue );
} );
}
},
/**
* Number fields.
*
* @since 3.0.26
*/
number: {
/**
* Init the control.
*
* @since 3.0.17
* @param {Object} control - The control object.
* @param {Object} control.id - The setting.
* @returns {null}
*/
init: function( control ) {
var element = jQuery( 'input[data-id="' + control.id + '"]' ),
value = control.setting._value,
up,
down;
// Make sure we use default values if none are define for some arguments.
control.params.choices = _.defaults( control.params.choices, {
min: 0,
max: 100,
step: 1
} );
// Make sure we have a valid value.
if ( isNaN( value ) || '' === value ) {
value = ( 0 > control.params.choices.min && 0 < control.params.choices.max ) ? 0 : control.params.choices.min;
}
value = parseFloat( value );
// If step is 'any', set to 0.001.
control.params.choices.step = ( 'any' === control.params.choices.step ) ? 0.001 : control.params.choices.step;
// Make sure choices are properly formtted as numbers.
control.params.choices.min = parseFloat( control.params.choices.min );
control.params.choices.max = parseFloat( control.params.choices.max );
control.params.choices.step = parseFloat( control.params.choices.step );
up = jQuery( '.kirki-input-container[data-id="' + control.id + '"] .plus' );
down = jQuery( '.kirki-input-container[data-id="' + control.id + '"] .minus' );
up.click( function() {
var oldVal = parseFloat( element.val() ),
newVal;
newVal = ( oldVal >= control.params.choices.max ) ? oldVal : oldVal + control.params.choices.step;
element.val( newVal );
element.trigger( 'change' );
} );
down.click( function() {
var oldVal = parseFloat( element.val() ),
newVal;
newVal = ( oldVal <= control.params.choices.min ) ? oldVal : oldVal - control.params.choices.step;
element.val( newVal );
element.trigger( 'change' );
} );
element.on( 'change keyup paste click', function() {
var val = jQuery( this ).val();
if ( isNaN( val ) ) {
val = parseFloat( val, 10 );
val = ( isNaN( val ) ) ? 0 : val;
jQuery( this ).attr( 'value', val );
}
kirki.setting.set( control.id, val );
} );
}
},
/**
* Image fields.
*
* @since 3.0.34
*/
image: {
/**
* Init the control.
*
* @since 3.0.34
* @param {Object} control - The control object.
* @returns {null}
*/
init: function( control ) {
var value = kirki.setting.get( control.id ),
saveAs = ( ! _.isUndefined( control.params.choices ) && ! _.isUndefined( control.params.choices.save_as ) ) ? control.params.choices.save_as : 'url',
preview = control.container.find( '.placeholder, .thumbnail' ),
previewImage = ( 'array' === saveAs ) ? value.url : value,
removeButton = control.container.find( '.image-upload-remove-button' ),
defaultButton = control.container.find( '.image-default-button' );
// Make sure value is properly formatted.
value = ( 'array' === saveAs && _.isString( value ) ) ? { url: value } : value;
// Tweaks for save_as = id.
if ( ( 'id' === saveAs || 'ID' === saveAs ) && '' !== value ) {
wp.media.attachment( value ).fetch().then( function() {
setTimeout( function() {
var url = wp.media.attachment( value ).get( 'url' );
preview.removeClass().addClass( 'thumbnail thumbnail-image' ).html( '<img src="' + url + '" alt="" />' );
}, 700 );
} );
}
// If value is not empty, hide the "default" button.
if ( ( 'url' === saveAs && '' !== value ) || ( 'array' === saveAs && ! _.isUndefined( value.url ) && '' !== value.url ) ) {
control.container.find( 'image-default-button' ).hide();
}
// If value is empty, hide the "remove" button.
if ( ( 'url' === saveAs && '' === value ) || ( 'array' === saveAs && ( _.isUndefined( value.url ) || '' === value.url ) ) ) {
removeButton.hide();
}
// If value is default, hide the default button.
if ( value === control.params.default ) {
control.container.find( 'image-default-button' ).hide();
}
if ( '' !== previewImage ) {
preview.removeClass().addClass( 'thumbnail thumbnail-image' ).html( '<img src="' + previewImage + '" alt="" />' );
}
control.container.on( 'click', '.image-upload-button', function( e ) {
var image = wp.media( { multiple: false } ).open().on( 'select', function() {
// This will return the selected image from the Media Uploader, the result is an object.
var uploadedImage = image.state().get( 'selection' ).first(),
jsonImg = uploadedImage.toJSON(),
previewImage = jsonImg.url;
if ( ! _.isUndefined( jsonImg.sizes ) ) {
previewImage = jsonImg.sizes.full.url;
if ( ! _.isUndefined( jsonImg.sizes.medium ) ) {
previewImage = jsonImg.sizes.medium.url;
} else if ( ! _.isUndefined( jsonImg.sizes.thumbnail ) ) {
previewImage = jsonImg.sizes.thumbnail.url;
}
}
if ( 'array' === saveAs ) {
kirki.setting.set( control.id, {
id: jsonImg.id,
url: jsonImg.sizes.full.url,
width: jsonImg.width,
height: jsonImg.height
} );
} else if ( 'id' === saveAs ) {
kirki.setting.set( control.id, jsonImg.id );
} else {
kirki.setting.set( control.id, ( ( ! _.isUndefined( jsonImg.sizes ) ) ? jsonImg.sizes.full.url : jsonImg.url ) );
}
if ( preview.length ) {
preview.removeClass().addClass( 'thumbnail thumbnail-image' ).html( '<img src="' + previewImage + '" alt="" />' );
}
if ( removeButton.length ) {
removeButton.show();
defaultButton.hide();
}
} );
e.preventDefault();
} );
control.container.on( 'click', '.image-upload-remove-button', function( e ) {
var preview,
removeButton,
defaultButton;
e.preventDefault();
kirki.setting.set( control.id, '' );
preview = control.container.find( '.placeholder, .thumbnail' );
removeButton = control.container.find( '.image-upload-remove-button' );
defaultButton = control.container.find( '.image-default-button' );
if ( preview.length ) {
preview.removeClass().addClass( 'placeholder' ).html( kirkiL10n.noFileSelected );
}
if ( removeButton.length ) {
removeButton.hide();
if ( jQuery( defaultButton ).hasClass( 'button' ) ) {
defaultButton.show();
}
}
} );
control.container.on( 'click', '.image-default-button', function( e ) {
var preview,
removeButton,
defaultButton;
e.preventDefault();
kirki.setting.set( control.id, control.params.default );
preview = control.container.find( '.placeholder, .thumbnail' );
removeButton = control.container.find( '.image-upload-remove-button' );
defaultButton = control.container.find( '.image-default-button' );
if ( preview.length ) {
preview.removeClass().addClass( 'thumbnail thumbnail-image' ).html( '<img src="' + control.params.default + '" alt="" />' );
}
if ( removeButton.length ) {
removeButton.show();
defaultButton.hide();
}
} );
}
}
}
} );
| reduxframework/kirki | controls/js/src/kirki.input.js | JavaScript | gpl-2.0 | 11,614 |
using ApiApp.Data.Racetrack.Models;
namespace ApiApp.Data.Racetrack
{
public interface IRacetrackRepository
{
RacetrackDaoList GetRacetrackList(int? pageNumber, int? pageSize);
RacetrackDao GetRacetrack(string name);
RacetrackDao GetRacetrack(int id);
RacetrackDao CreateRacetrack(RacetrackDaoCreate payload);
bool DeleteRacetrack(string name);
bool DeleteRacetrack(int id);
}
}
| fannaroh/AkkaMachineLearning | ApiApp.Data/Racetrack/IRacetrackRepository.cs | C# | gpl-2.0 | 443 |
#include "stdafx.h"
#include "cellGem.h"
#include "cellCamera.h"
#include "Emu/Cell/PPUModule.h"
#include "Emu/Io/MouseHandler.h"
#include "Emu/RSX/GSRender.h"
#include "Utilities/Timer.h"
#include "Input/pad_thread.h"
LOG_CHANNEL(cellGem);
template <>
void fmt_class_string<CellGemError>::format(std::string& out, u64 arg)
{
format_enum(out, arg, [](auto error)
{
switch (error)
{
STR_CASE(CELL_GEM_ERROR_RESOURCE_ALLOCATION_FAILED);
STR_CASE(CELL_GEM_ERROR_ALREADY_INITIALIZED);
STR_CASE(CELL_GEM_ERROR_UNINITIALIZED);
STR_CASE(CELL_GEM_ERROR_INVALID_PARAMETER);
STR_CASE(CELL_GEM_ERROR_INVALID_ALIGNMENT);
STR_CASE(CELL_GEM_ERROR_UPDATE_NOT_FINISHED);
STR_CASE(CELL_GEM_ERROR_UPDATE_NOT_STARTED);
STR_CASE(CELL_GEM_ERROR_CONVERT_NOT_FINISHED);
STR_CASE(CELL_GEM_ERROR_CONVERT_NOT_STARTED);
STR_CASE(CELL_GEM_ERROR_WRITE_NOT_FINISHED);
STR_CASE(CELL_GEM_ERROR_NOT_A_HUE);
}
return unknown;
});
}
template <>
void fmt_class_string<CellGemStatus>::format(std::string& out, u64 arg)
{
format_enum(out, arg, [](auto error)
{
switch (error)
{
STR_CASE(CELL_GEM_NOT_CONNECTED);
STR_CASE(CELL_GEM_SPHERE_NOT_CALIBRATED);
STR_CASE(CELL_GEM_SPHERE_CALIBRATING);
STR_CASE(CELL_GEM_COMPUTING_AVAILABLE_COLORS);
STR_CASE(CELL_GEM_HUE_NOT_SET);
STR_CASE(CELL_GEM_NO_VIDEO);
STR_CASE(CELL_GEM_TIME_OUT_OF_RANGE);
STR_CASE(CELL_GEM_NOT_CALIBRATED);
STR_CASE(CELL_GEM_NO_EXTERNAL_PORT_DEVICE);
}
return unknown;
});
}
// **********************
// * HLE helper structs *
// **********************
struct gem_config
{
atomic_t<u32> state = 0;
struct gem_color
{
float r, g, b;
gem_color() : r(0.0f), g(0.0f), b(0.0f) {}
gem_color(float r_, float g_, float b_)
{
r = std::clamp(r_, 0.0f, 1.0f);
g = std::clamp(g_, 0.0f, 1.0f);
b = std::clamp(b_, 0.0f, 1.0f);
}
};
struct gem_controller
{
u32 status = CELL_GEM_STATUS_DISCONNECTED; // Connection status (CELL_GEM_STATUS_DISCONNECTED or CELL_GEM_STATUS_READY)
u32 ext_status = CELL_GEM_NO_EXTERNAL_PORT_DEVICE; // External port connection status
u32 port = 0; // Assigned port
bool enabled_magnetometer = false; // Whether the magnetometer is enabled (probably used for additional rotational precision)
bool calibrated_magnetometer = false; // Whether the magnetometer is calibrated
bool enabled_filtering = false; // Whether filtering is enabled
bool enabled_tracking = false; // Whether tracking is enabled
bool enabled_LED = false; // Whether the LED is enabled
u8 rumble = 0; // Rumble intensity
gem_color sphere_rgb = {}; // RGB color of the sphere LED
u32 hue = 0; // Tracking hue of the motion controller
};
CellGemAttribute attribute = {};
CellGemVideoConvertAttribute vc_attribute = {};
u64 status_flags = CELL_GEM_NOT_CALIBRATED;
bool enable_pitch_correction = false;
u32 inertial_counter = 0;
std::array<gem_controller, CELL_GEM_MAX_NUM> controllers;
u32 connected_controllers = 0;
bool update_started{};
u32 camera_frame{};
u32 memory_ptr{};
shared_mutex mtx;
Timer timer;
// helper functions
bool is_controller_ready(u32 gem_num) const
{
return controllers[gem_num].status == CELL_GEM_STATUS_READY;
}
void reset_controller(u32 gem_num)
{
switch (g_cfg.io.move)
{
case move_handler::fake:
case move_handler::mouse:
{
connected_controllers = 1;
break;
}
default: break;
}
// Assign status and port number
if (gem_num < connected_controllers)
{
controllers[gem_num].status = CELL_GEM_STATUS_READY;
controllers[gem_num].port = 7u - gem_num;
}
}
};
/**
* \brief Verifies that a Move controller id is valid
* \param gem_num Move controler ID to verify
* \return True if the ID is valid, false otherwise
*/
static bool check_gem_num(const u32 gem_num)
{
return gem_num >= 0 && gem_num < CELL_GEM_MAX_NUM;
}
/**
* \brief Maps Move controller data (digital buttons, and analog Trigger data) to DS3 pad input.
* Unavoidably buttons conflict with DS3 mappings, which is problematic for some games.
* \param port_no DS3 port number to use
* \param digital_buttons Bitmask filled with CELL_GEM_CTRL_* values
* \param analog_t Analog value of Move's Trigger. Currently mapped to R2.
* \return true on success, false if port_no controller is invalid
*/
static bool ds3_input_to_pad(const u32 port_no, be_t<u16>& digital_buttons, be_t<u16>& analog_t)
{
std::scoped_lock lock(pad::g_pad_mutex);
const auto handler = pad::get_current_handler();
auto& pads = handler->GetPads();
auto pad = pads[port_no];
if (!(pad->m_port_status & CELL_PAD_STATUS_CONNECTED))
return false;
for (Button& button : pad->m_buttons)
{
// here we check btns, and set pad accordingly
if (button.m_offset == CELL_PAD_BTN_OFFSET_DIGITAL2)
{
if (button.m_pressed) pad->m_digital_2 |= button.m_outKeyCode;
else pad->m_digital_2 &= ~button.m_outKeyCode;
switch (button.m_outKeyCode)
{
case CELL_PAD_CTRL_SQUARE:
pad->m_press_square = button.m_value;
break;
case CELL_PAD_CTRL_CROSS:
pad->m_press_cross = button.m_value;
break;
case CELL_PAD_CTRL_CIRCLE:
pad->m_press_circle = button.m_value;
break;
case CELL_PAD_CTRL_TRIANGLE:
pad->m_press_triangle = button.m_value;
break;
case CELL_PAD_CTRL_R1:
pad->m_press_R1 = button.m_value;
break;
case CELL_PAD_CTRL_L1:
pad->m_press_L1 = button.m_value;
break;
case CELL_PAD_CTRL_R2:
pad->m_press_R2 = button.m_value;
break;
case CELL_PAD_CTRL_L2:
pad->m_press_L2 = button.m_value;
break;
default: break;
}
}
}
digital_buttons = 0;
// map the Move key to R1 and the Trigger to R2
if (pad->m_press_R1)
digital_buttons |= CELL_GEM_CTRL_MOVE;
if (pad->m_press_R2)
digital_buttons |= CELL_GEM_CTRL_T;
if (pad->m_press_cross)
digital_buttons |= CELL_GEM_CTRL_CROSS;
if (pad->m_press_circle)
digital_buttons |= CELL_GEM_CTRL_CIRCLE;
if (pad->m_press_square)
digital_buttons |= CELL_GEM_CTRL_SQUARE;
if (pad->m_press_triangle)
digital_buttons |= CELL_GEM_CTRL_TRIANGLE;
if (pad->m_digital_1)
digital_buttons |= CELL_GEM_CTRL_SELECT;
if (pad->m_digital_2)
digital_buttons |= CELL_GEM_CTRL_START;
analog_t = pad->m_press_R2;
return true;
}
/**
* \brief Maps external Move controller data to DS3 input
* Implementation detail: CellGemExtPortData's digital/analog fields map the same way as
* libPad, so no translation is needed.
* \param port_no DS3 port number to use
* \param ext External data to modify
* \return true on success, false if port_no controller is invalid
*/
static bool ds3_input_to_ext(const u32 port_no, CellGemExtPortData& ext)
{
std::scoped_lock lock(pad::g_pad_mutex);
const auto handler = pad::get_current_handler();
auto& pads = handler->GetPads();
auto pad = pads[port_no];
if (!(pad->m_port_status & CELL_PAD_STATUS_CONNECTED))
return false;
ext.status = 0; // CELL_GEM_EXT_CONNECTED | CELL_GEM_EXT_EXT0 | CELL_GEM_EXT_EXT1
ext.analog_left_x = pad->m_analog_left_x;
ext.analog_left_y = pad->m_analog_left_y;
ext.analog_right_x = pad->m_analog_right_x;
ext.analog_right_y = pad->m_analog_right_y;
ext.digital1 = pad->m_digital_1;
ext.digital2 = pad->m_digital_2;
return true;
}
/**
* \brief Maps Move controller data (digital buttons, and analog Trigger data) to mouse input.
* Move Button: Mouse1
* Trigger: Mouse2
* \param mouse_no Mouse index number to use
* \param digital_buttons Bitmask filled with CELL_GEM_CTRL_* values
* \param analog_t Analog value of Move's Trigger.
* \return true on success, false if mouse_no is invalid
*/
static bool mouse_input_to_pad(const u32 mouse_no, be_t<u16>& digital_buttons, be_t<u16>& analog_t)
{
const auto handler = g_fxo->get<MouseHandlerBase>();
std::scoped_lock lock(handler->mutex);
if (mouse_no >= handler->GetMice().size())
{
return false;
}
const auto& mouse_data = handler->GetMice().at(0);
digital_buttons = 0;
if ((mouse_data.buttons & CELL_MOUSE_BUTTON_1) && (mouse_data.buttons & CELL_MOUSE_BUTTON_2))
digital_buttons |= CELL_GEM_CTRL_CIRCLE;
if (mouse_data.buttons & CELL_MOUSE_BUTTON_3)
digital_buttons |= CELL_GEM_CTRL_CROSS;
if (mouse_data.buttons & CELL_MOUSE_BUTTON_2)
digital_buttons |= CELL_GEM_CTRL_MOVE;
if ((mouse_data.buttons & CELL_MOUSE_BUTTON_1) && (mouse_data.buttons & CELL_MOUSE_BUTTON_3))
digital_buttons |= CELL_GEM_CTRL_START;
if (mouse_data.buttons & CELL_MOUSE_BUTTON_1)
digital_buttons |= CELL_GEM_CTRL_T;
if ((mouse_data.buttons & CELL_MOUSE_BUTTON_2) && (mouse_data.buttons & CELL_MOUSE_BUTTON_3))
digital_buttons |= CELL_GEM_CTRL_TRIANGLE;
analog_t = (mouse_data.buttons & CELL_MOUSE_BUTTON_1) ? 0xFFFF : 0;
return true;
}
static bool mouse_pos_to_gem_image_state(const u32 mouse_no, vm::ptr<CellGemImageState>& gem_image_state)
{
const auto handler = g_fxo->get<MouseHandlerBase>();
std::scoped_lock lock(handler->mutex);
if (!gem_image_state || mouse_no >= handler->GetMice().size())
{
return false;
}
const auto& mouse = handler->GetMice().at(0);
const auto renderer = static_cast<GSRender*>(rsx::get_current_renderer());
const auto width = renderer->get_frame()->client_width();
const auto hight = renderer->get_frame()->client_height();
const f32 scaling_width = width / 640.f;
const f32 scaling_hight = hight / 480.f;
const f32 x = static_cast<f32>(mouse.x_pos) / scaling_width;
const f32 y = static_cast<f32>(mouse.y_pos) / scaling_hight;
gem_image_state->u = 133.f + (x / 1.50f);
gem_image_state->v = 160.f + (y / 1.67f);
gem_image_state->projectionx = x - 320.f;
gem_image_state->projectiony = 240.f - y;
return true;
}
static bool mouse_pos_to_gem_state(const u32 mouse_no, vm::ptr<CellGemState>& gem_state)
{
const auto handler = g_fxo->get<MouseHandlerBase>();
std::scoped_lock lock(handler->mutex);
if (!gem_state || mouse_no >= handler->GetMice().size())
{
return false;
}
const auto& mouse = handler->GetMice().at(0);
const auto renderer = static_cast<GSRender*>(rsx::get_current_renderer());
const auto width = renderer->get_frame()->client_width();
const auto hight = renderer->get_frame()->client_height();
const f32 scaling_width = width / 640.f;
const f32 scaling_hight = hight / 480.f;
const f32 x = static_cast<f32>(mouse.x_pos) / scaling_width;
const f32 y = static_cast<f32>(mouse.y_pos) / scaling_hight;
gem_state->pos[0] = x;
gem_state->pos[1] = -y;
gem_state->pos[2] = 1500.f;
gem_state->pos[3] = 0.f;
gem_state->quat[0] = 320.f - x;
gem_state->quat[1] = (mouse.y_pos / scaling_width) - 180.f;
gem_state->quat[2] = 1200.f;
gem_state->handle_pos[0] = x;
gem_state->handle_pos[1] = y;
gem_state->handle_pos[2] = 1500.f;
gem_state->handle_pos[3] = 0.f;
return true;
}
// *********************
// * cellGem functions *
// *********************
error_code cellGemCalibrate(u32 gem_num)
{
cellGem.todo("cellGemCalibrate(gem_num=%d)", gem_num);
const auto gem = g_fxo->get<gem_config>();
std::scoped_lock lock(gem->mtx);
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!check_gem_num(gem_num))
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
if (g_cfg.io.move == move_handler::fake || g_cfg.io.move == move_handler::mouse)
{
gem->controllers[gem_num].calibrated_magnetometer = true;
gem->controllers[gem_num].enabled_tracking = true;
gem->controllers[gem_num].hue = 1;
gem->status_flags = CELL_GEM_FLAG_CALIBRATION_OCCURRED | CELL_GEM_FLAG_CALIBRATION_SUCCEEDED;
}
return CELL_OK;
}
error_code cellGemClearStatusFlags(u32 gem_num, u64 mask)
{
cellGem.todo("cellGemClearStatusFlags(gem_num=%d, mask=0x%x)", gem_num, mask);
const auto gem = g_fxo->get<gem_config>();
std::scoped_lock lock(gem->mtx);
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!check_gem_num(gem_num))
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
gem->status_flags &= ~mask;
return CELL_OK;
}
error_code cellGemConvertVideoFinish()
{
cellGem.todo("cellGemConvertVideoFinish()");
const auto gem = g_fxo->get<gem_config>();
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
return CELL_OK;
}
error_code cellGemConvertVideoStart(vm::cptr<void> video_frame)
{
cellGem.todo("cellGemConvertVideoStart(video_frame=*0x%x)", video_frame);
const auto gem = g_fxo->get<gem_config>();
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
return CELL_OK;
}
error_code cellGemEnableCameraPitchAngleCorrection(u32 enable_flag)
{
cellGem.todo("cellGemEnableCameraPitchAngleCorrection(enable_flag=%d)", enable_flag);
const auto gem = g_fxo->get<gem_config>();
std::scoped_lock lock(gem->mtx);
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
gem->enable_pitch_correction = !!enable_flag;
return CELL_OK;
}
error_code cellGemEnableMagnetometer(u32 gem_num, u32 enable)
{
cellGem.todo("cellGemEnableMagnetometer(gem_num=%d, enable=0x%x)", gem_num, enable);
const auto gem = g_fxo->get<gem_config>();
std::scoped_lock lock(gem->mtx);
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!gem->is_controller_ready(gem_num))
{
return CELL_GEM_NOT_CONNECTED;
}
gem->controllers[gem_num].enabled_magnetometer = !!enable;
return CELL_OK;
}
error_code cellGemEnableMagnetometer2()
{
UNIMPLEMENTED_FUNC(cellGem);
return CELL_OK;
}
error_code cellGemEnd(ppu_thread& ppu)
{
cellGem.warning("cellGemEnd()");
const auto gem = g_fxo->get<gem_config>();
std::scoped_lock lock(gem->mtx);
if (gem->state.compare_and_swap_test(1, 0))
{
if (u32 addr = gem->memory_ptr)
{
sys_memory_free(ppu, addr);
}
return CELL_OK;
}
return CELL_GEM_ERROR_UNINITIALIZED;
}
error_code cellGemFilterState(u32 gem_num, u32 enable)
{
cellGem.warning("cellGemFilterState(gem_num=%d, enable=%d)", gem_num, enable);
const auto gem = g_fxo->get<gem_config>();
std::scoped_lock lock(gem->mtx);
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!check_gem_num(gem_num))
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
gem->controllers[gem_num].enabled_filtering = !!enable;
return CELL_OK;
}
error_code cellGemForceRGB(u32 gem_num, float r, float g, float b)
{
cellGem.todo("cellGemForceRGB(gem_num=%d, r=%f, g=%f, b=%f)", gem_num, r, g, b);
const auto gem = g_fxo->get<gem_config>();
std::scoped_lock lock(gem->mtx);
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!check_gem_num(gem_num))
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
gem->controllers[gem_num].sphere_rgb = gem_config::gem_color(r, g, b);
return CELL_OK;
}
error_code cellGemGetAccelerometerPositionInDevice()
{
UNIMPLEMENTED_FUNC(cellGem);
return CELL_OK;
}
error_code cellGemGetAllTrackableHues(vm::ptr<u8> hues)
{
cellGem.todo("cellGemGetAllTrackableHues(hues=*0x%x)");
const auto gem = g_fxo->get<gem_config>();
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
for (u32 i = 0; i < 360; i++)
{
hues[i] = true;
}
return CELL_OK;
}
error_code cellGemGetCameraState(vm::ptr<CellGemCameraState> camera_state)
{
cellGem.todo("cellGemGetCameraState(camera_state=0x%x)", camera_state);
const auto gem = g_fxo->get<gem_config>();
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!camera_state)
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
camera_state->exposure_time = 1.0f / 60.0f; // TODO: use correct framerate
camera_state->gain = 1.0;
return CELL_OK;
}
error_code cellGemGetEnvironmentLightingColor(vm::ptr<f32> r, vm::ptr<f32> g, vm::ptr<f32> b)
{
cellGem.todo("cellGemGetEnvironmentLightingColor(r=*0x%x, g=*0x%x, b=*0x%x)", r, g, b);
const auto gem = g_fxo->get<gem_config>();
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!r || !g || !b)
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
// default to 128
*r = 128;
*g = 128;
*b = 128;
return CELL_OK;
}
error_code cellGemGetHuePixels(vm::cptr<void> camera_frame, u32 hue, vm::ptr<u8> pixels)
{
cellGem.todo("cellGemGetHuePixels(camera_frame=*0x%x, hue=%d, pixels=*0x%x)", camera_frame, hue, pixels);
const auto gem = g_fxo->get<gem_config>();
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!camera_frame || !pixels || hue > 359)
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
return CELL_OK;
}
error_code cellGemGetImageState(u32 gem_num, vm::ptr<CellGemImageState> gem_image_state)
{
cellGem.todo("cellGemGetImageState(gem_num=%d, image_state=&0x%x)", gem_num, gem_image_state);
const auto gem = g_fxo->get<gem_config>();
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!check_gem_num(gem_num) || !gem_image_state)
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
auto shared_data = g_fxo->get<gem_camera_shared>();
if (g_cfg.io.move == move_handler::fake)
{
gem_image_state->u = 0;
gem_image_state->v = 0;
gem_image_state->projectionx = 1;
gem_image_state->projectiony = 1;
}
else if (g_cfg.io.move == move_handler::mouse)
{
mouse_pos_to_gem_image_state(gem_num, gem_image_state);
}
if (g_cfg.io.move == move_handler::fake || g_cfg.io.move == move_handler::mouse)
{
gem_image_state->frame_timestamp = shared_data->frame_timestamp.load();
gem_image_state->timestamp = gem_image_state->frame_timestamp + 10;
gem_image_state->r = 10;
gem_image_state->distance = 2 * 1000; // 2 meters away from camera
gem_image_state->visible = true;
gem_image_state->r_valid = true;
}
return CELL_OK;
}
error_code cellGemGetInertialState(u32 gem_num, u32 state_flag, u64 timestamp, vm::ptr<CellGemInertialState> inertial_state)
{
cellGem.warning("cellGemGetInertialState(gem_num=%d, state_flag=%d, timestamp=0x%x, inertial_state=0x%x)", gem_num, state_flag, timestamp, inertial_state);
const auto gem = g_fxo->get<gem_config>();
std::scoped_lock lock(gem->mtx);
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!check_gem_num(gem_num) || state_flag > CELL_GEM_INERTIAL_STATE_FLAG_NEXT || !inertial_state || !gem->is_controller_ready(gem_num))
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
if (g_cfg.io.move == move_handler::fake)
{
ds3_input_to_pad(gem_num, inertial_state->pad.digitalbuttons, inertial_state->pad.analog_T);
}
else if (g_cfg.io.move == move_handler::mouse)
{
mouse_input_to_pad(gem_num, inertial_state->pad.digitalbuttons, inertial_state->pad.analog_T);
}
if (g_cfg.io.move == move_handler::fake || g_cfg.io.move == move_handler::mouse)
{
ds3_input_to_ext(gem_num, inertial_state->ext);
inertial_state->timestamp = gem->timer.GetElapsedTimeInMicroSec();
inertial_state->counter = gem->inertial_counter++;
inertial_state->accelerometer[0] = 10;
}
return CELL_OK;
}
error_code cellGemGetInfo(vm::ptr<CellGemInfo> info)
{
cellGem.warning("cellGemGetInfo(info=*0x%x)", info);
const auto gem = g_fxo->get<gem_config>();
reader_lock lock(gem->mtx);
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!info)
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
// TODO: Support connecting PlayStation Move controllers
info->max_connect = gem->attribute.max_connect;
info->now_connect = gem->connected_controllers;
for (int i = 0; i < CELL_GEM_MAX_NUM; i++)
{
info->status[i] = gem->controllers[i].status;
info->port[i] = gem->controllers[i].port;
}
return CELL_OK;
}
u32 GemGetMemorySize(s32 max_connect)
{
return max_connect <= 2 ? 0x120000 : 0x140000;
}
error_code cellGemGetMemorySize(s32 max_connect)
{
cellGem.warning("cellGemGetMemorySize(max_connect=%d)", max_connect);
if (max_connect > CELL_GEM_MAX_NUM || max_connect <= 0)
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
return not_an_error(GemGetMemorySize(max_connect));
}
error_code cellGemGetRGB(u32 gem_num, vm::ptr<float> r, vm::ptr<float> g, vm::ptr<float> b)
{
cellGem.todo("cellGemGetRGB(gem_num=%d, r=*0x%x, g=*0x%x, b=*0x%x)", gem_num, r, g, b);
const auto gem = g_fxo->get<gem_config>();
reader_lock lock(gem->mtx);
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!check_gem_num(gem_num) || !r || !g || !b)
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
auto& sphere_color = gem->controllers[gem_num].sphere_rgb;
*r = sphere_color.r;
*g = sphere_color.g;
*b = sphere_color.b;
return CELL_OK;
}
error_code cellGemGetRumble(u32 gem_num, vm::ptr<u8> rumble)
{
cellGem.todo("cellGemGetRumble(gem_num=%d, rumble=*0x%x)", gem_num, rumble);
const auto gem = g_fxo->get<gem_config>();
reader_lock lock(gem->mtx);
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!check_gem_num(gem_num) || !rumble)
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
*rumble = gem->controllers[gem_num].rumble;
return CELL_OK;
}
error_code cellGemGetState(u32 gem_num, u32 flag, u64 time_parameter, vm::ptr<CellGemState> gem_state)
{
cellGem.warning("cellGemGetState(gem_num=%d, flag=0x%x, time=0x%llx, gem_state=*0x%x)", gem_num, flag, time_parameter, gem_state);
const auto gem = g_fxo->get<gem_config>();
reader_lock lock(gem->mtx);
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!check_gem_num(gem_num) || flag > CELL_GEM_STATE_FLAG_TIMESTAMP || !gem_state)
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
if (g_cfg.io.move == move_handler::fake)
{
ds3_input_to_pad(gem_num, gem_state->pad.digitalbuttons, gem_state->pad.analog_T);
}
else if (g_cfg.io.move == move_handler::mouse)
{
mouse_input_to_pad(gem_num, gem_state->pad.digitalbuttons, gem_state->pad.analog_T);
mouse_pos_to_gem_state(gem_num, gem_state);
}
if (g_cfg.io.move == move_handler::fake || g_cfg.io.move == move_handler::mouse)
{
ds3_input_to_ext(gem_num, gem_state->ext);
gem_state->tracking_flags = CELL_GEM_TRACKING_FLAG_POSITION_TRACKED | CELL_GEM_TRACKING_FLAG_VISIBLE;
gem_state->timestamp = gem->timer.GetElapsedTimeInMicroSec();
gem_state->quat[3] = 1.f;
return CELL_OK;
}
return CELL_GEM_NOT_CONNECTED;
}
error_code cellGemGetStatusFlags(u32 gem_num, vm::ptr<u64> flags)
{
cellGem.todo("cellGemGetStatusFlags(gem_num=%d, flags=*0x%x)", gem_num, flags);
const auto gem = g_fxo->get<gem_config>();
reader_lock lock(gem->mtx);
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!check_gem_num(gem_num) || !flags)
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
*flags = gem->status_flags;
return CELL_OK;
}
error_code cellGemGetTrackerHue(u32 gem_num, vm::ptr<u32> hue)
{
cellGem.warning("cellGemGetTrackerHue(gem_num=%d, hue=*0x%x)", gem_num, hue);
const auto gem = g_fxo->get<gem_config>();
reader_lock lock(gem->mtx);
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!check_gem_num(gem_num) || !hue)
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
if (!gem->controllers[gem_num].enabled_tracking || gem->controllers[gem_num].hue > 359)
{
return CELL_GEM_ERROR_NOT_A_HUE;
}
*hue = gem->controllers[gem_num].hue;
return CELL_OK;
}
error_code cellGemHSVtoRGB(f32 h, f32 s, f32 v, vm::ptr<f32> r, vm::ptr<f32> g, vm::ptr<f32> b)
{
cellGem.todo("cellGemHSVtoRGB(h=%f, s=%f, v=%f, r=*0x%x, g=*0x%x, b=*0x%x)", h, s, v, r, g, b);
if (s < 0.0f || s > 1.0f || v < 0.0f || v > 1.0f || !r || !g || !b)
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
h = std::clamp(h, 0.0f, 360.0f);
// TODO: convert
return CELL_OK;
}
error_code cellGemInit(ppu_thread& ppu, vm::cptr<CellGemAttribute> attribute)
{
cellGem.warning("cellGemInit(attribute=*0x%x)", attribute);
const auto gem = g_fxo->get<gem_config>();
if (!attribute || !attribute->spurs_addr || !attribute->max_connect || attribute->max_connect > CELL_GEM_MAX_NUM)
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
std::scoped_lock lock(gem->mtx);
if (!gem->state.compare_and_swap_test(0, 1))
{
return CELL_GEM_ERROR_ALREADY_INITIALIZED;
}
if (!attribute->memory_ptr)
{
vm::var<u32> addr(0);
// Decrease memory stats
if (sys_memory_allocate(ppu, GemGetMemorySize(attribute->max_connect), SYS_MEMORY_PAGE_SIZE_64K, +addr) != CELL_OK)
{
return CELL_GEM_ERROR_RESOURCE_ALLOCATION_FAILED;
}
gem->memory_ptr = *addr;
}
else
{
gem->memory_ptr = 0;
}
gem->update_started = false;
gem->camera_frame = 0;
gem->status_flags = 0;
gem->attribute = *attribute;
if (g_cfg.io.move == move_handler::mouse)
{
// init mouse handler
const auto handler = g_fxo->get<MouseHandlerBase>();
handler->Init(std::min<u32>(attribute->max_connect, CELL_GEM_MAX_NUM));
}
for (int gem_num = 0; gem_num < CELL_GEM_MAX_NUM; gem_num++)
{
gem->reset_controller(gem_num);
}
// TODO: is this correct?
gem->timer.Start();
return CELL_OK;
}
error_code cellGemInvalidateCalibration(s32 gem_num)
{
cellGem.todo("cellGemInvalidateCalibration(gem_num=%d)", gem_num);
const auto gem = g_fxo->get<gem_config>();
std::scoped_lock lock(gem->mtx);
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!check_gem_num(gem_num))
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
if (g_cfg.io.move == move_handler::fake || g_cfg.io.move == move_handler::mouse)
{
gem->controllers[gem_num].calibrated_magnetometer = false;
// TODO: gem->status_flags
}
return CELL_OK;
}
s32 cellGemIsTrackableHue(u32 hue)
{
cellGem.todo("cellGemIsTrackableHue(hue=%d)", hue);
const auto gem = g_fxo->get<gem_config>();
if (!gem->state || hue > 359)
{
return false;
}
return true;
}
error_code cellGemPrepareCamera(s32 max_exposure, f32 image_quality)
{
cellGem.todo("cellGemPrepareCamera(max_exposure=%d, image_quality=%f)", max_exposure, image_quality);
const auto gem = g_fxo->get<gem_config>();
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
max_exposure = std::clamp(max_exposure, static_cast<s32>(CELL_GEM_MIN_CAMERA_EXPOSURE), static_cast<s32>(CELL_GEM_MAX_CAMERA_EXPOSURE));
image_quality = std::clamp(image_quality, 0.0f, 1.0f);
// TODO: prepare camera
return CELL_OK;
}
error_code cellGemPrepareVideoConvert(vm::cptr<CellGemVideoConvertAttribute> vc_attribute)
{
cellGem.todo("cellGemPrepareVideoConvert(vc_attribute=*0x%x)", vc_attribute);
const auto gem = g_fxo->get<gem_config>();
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!vc_attribute)
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
const auto vc = *vc_attribute;
if (!vc_attribute || vc.version == 0 || vc.output_format == 0 ||
(vc.conversion_flags & CELL_GEM_COMBINE_PREVIOUS_INPUT_FRAME && !vc.buffer_memory))
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
if (vc.video_data_out & 0x1f || vc.buffer_memory & 0xff)
{
return CELL_GEM_ERROR_INVALID_ALIGNMENT;
}
gem->vc_attribute = vc;
return CELL_OK;
}
error_code cellGemReadExternalPortDeviceInfo(u32 gem_num, vm::ptr<u32> ext_id, vm::ptr<u8[CELL_GEM_EXTERNAL_PORT_DEVICE_INFO_SIZE]> ext_info)
{
cellGem.todo("cellGemReadExternalPortDeviceInfo(gem_num=%d, ext_id=*0x%x, ext_info=%s)", gem_num, ext_id, ext_info);
const auto gem = g_fxo->get<gem_config>();
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!check_gem_num(gem_num) || !ext_id)
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
if (gem->controllers[gem_num].status & CELL_GEM_STATUS_DISCONNECTED)
{
return CELL_GEM_NOT_CONNECTED;
}
if (!(gem->controllers[gem_num].ext_status & CELL_GEM_EXT_CONNECTED))
{
return CELL_GEM_NO_EXTERNAL_PORT_DEVICE;
}
return CELL_OK;
}
error_code cellGemReset(u32 gem_num)
{
cellGem.todo("cellGemReset(gem_num=%d)", gem_num);
const auto gem = g_fxo->get<gem_config>();
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!check_gem_num(gem_num))
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
gem->reset_controller(gem_num);
// TODO: is this correct?
gem->timer.Start();
return CELL_OK;
}
error_code cellGemSetRumble(u32 gem_num, u8 rumble)
{
cellGem.todo("cellGemSetRumble(gem_num=%d, rumble=0x%x)", gem_num, rumble);
const auto gem = g_fxo->get<gem_config>();
std::scoped_lock lock(gem->mtx);
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!check_gem_num(gem_num))
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
gem->controllers[gem_num].rumble = rumble;
return CELL_OK;
}
error_code cellGemSetYaw()
{
UNIMPLEMENTED_FUNC(cellGem);
return CELL_OK;
}
error_code cellGemTrackHues(vm::cptr<u32> req_hues, vm::ptr<u32> res_hues)
{
cellGem.todo("cellGemTrackHues(req_hues=*0x%x, res_hues=*0x%x)", req_hues, res_hues);
const auto gem = g_fxo->get<gem_config>();
std::scoped_lock lock(gem->mtx);
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!req_hues)
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
for (u32 i = 0; i < CELL_GEM_MAX_NUM; i++)
{
if (req_hues[i] == u32{CELL_GEM_DONT_CARE_HUE})
{
}
else if (req_hues[i] == u32{CELL_GEM_DONT_TRACK_HUE})
{
gem->controllers[i].enabled_tracking = false;
gem->controllers[i].enabled_LED = false;
}
else
{
if (req_hues[i] > 359)
{
cellGem.warning("cellGemTrackHues: req_hues[%d]=%d -> this can lead to unexpected behavior", i, req_hues[i]);
}
}
}
return CELL_OK;
}
error_code cellGemUpdateFinish()
{
cellGem.warning("cellGemUpdateFinish()");
const auto gem = g_fxo->get<gem_config>();
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
std::scoped_lock lock(gem->mtx);
if (!std::exchange(gem->update_started, false))
{
return CELL_GEM_ERROR_UPDATE_NOT_STARTED;
}
if (!gem->camera_frame)
{
return not_an_error(CELL_GEM_NO_VIDEO);
}
return CELL_OK;
}
error_code cellGemUpdateStart(vm::cptr<void> camera_frame, u64 timestamp)
{
cellGem.warning("cellGemUpdateStart(camera_frame=*0x%x, timestamp=%d)", camera_frame, timestamp);
const auto gem = g_fxo->get<gem_config>();
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
std::scoped_lock lock(gem->mtx);
// Update is starting even when camera_frame is null
if (std::exchange(gem->update_started, true))
{
return CELL_GEM_ERROR_UPDATE_NOT_FINISHED;
}
gem->camera_frame = camera_frame.addr();
if (!camera_frame)
{
return not_an_error(CELL_GEM_NO_VIDEO);
}
return CELL_OK;
}
error_code cellGemWriteExternalPort(u32 gem_num, vm::ptr<u8[CELL_GEM_EXTERNAL_PORT_OUTPUT_SIZE]> data)
{
cellGem.todo("cellGemWriteExternalPort(gem_num=%d, data=%s)", gem_num, data);
const auto gem = g_fxo->get<gem_config>();
if (!gem->state)
{
return CELL_GEM_ERROR_UNINITIALIZED;
}
if (!check_gem_num(gem_num))
{
return CELL_GEM_ERROR_INVALID_PARAMETER;
}
return CELL_OK;
}
DECLARE(ppu_module_manager::cellGem)("libgem", []()
{
REG_FUNC(libgem, cellGemCalibrate);
REG_FUNC(libgem, cellGemClearStatusFlags);
REG_FUNC(libgem, cellGemConvertVideoFinish);
REG_FUNC(libgem, cellGemConvertVideoStart);
REG_FUNC(libgem, cellGemEnableCameraPitchAngleCorrection);
REG_FUNC(libgem, cellGemEnableMagnetometer);
REG_FUNC(libgem, cellGemEnableMagnetometer2);
REG_FUNC(libgem, cellGemEnd);
REG_FUNC(libgem, cellGemFilterState);
REG_FUNC(libgem, cellGemForceRGB);
REG_FUNC(libgem, cellGemGetAccelerometerPositionInDevice);
REG_FUNC(libgem, cellGemGetAllTrackableHues);
REG_FUNC(libgem, cellGemGetCameraState);
REG_FUNC(libgem, cellGemGetEnvironmentLightingColor);
REG_FUNC(libgem, cellGemGetHuePixels);
REG_FUNC(libgem, cellGemGetImageState);
REG_FUNC(libgem, cellGemGetInertialState);
REG_FUNC(libgem, cellGemGetInfo);
REG_FUNC(libgem, cellGemGetMemorySize);
REG_FUNC(libgem, cellGemGetRGB);
REG_FUNC(libgem, cellGemGetRumble);
REG_FUNC(libgem, cellGemGetState);
REG_FUNC(libgem, cellGemGetStatusFlags);
REG_FUNC(libgem, cellGemGetTrackerHue);
REG_FUNC(libgem, cellGemHSVtoRGB);
REG_FUNC(libgem, cellGemInit);
REG_FUNC(libgem, cellGemInvalidateCalibration);
REG_FUNC(libgem, cellGemIsTrackableHue);
REG_FUNC(libgem, cellGemPrepareCamera);
REG_FUNC(libgem, cellGemPrepareVideoConvert);
REG_FUNC(libgem, cellGemReadExternalPortDeviceInfo);
REG_FUNC(libgem, cellGemReset);
REG_FUNC(libgem, cellGemSetRumble);
REG_FUNC(libgem, cellGemSetYaw);
REG_FUNC(libgem, cellGemTrackHues);
REG_FUNC(libgem, cellGemUpdateFinish);
REG_FUNC(libgem, cellGemUpdateStart);
REG_FUNC(libgem, cellGemWriteExternalPort);
});
| mpm11011/rpcs3 | rpcs3/Emu/Cell/Modules/cellGem.cpp | C++ | gpl-2.0 | 32,387 |
// ---------------------------------------------------------------------------
// This file is part of reSID, a MOS6581 SID emulator engine.
// Copyright (C) 2004 Dag Lem <resid@nimrod.no>
//
// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// ---------------------------------------------------------------------------
#define __VOICE_CC__
#include "voice.h"
// ----------------------------------------------------------------------------
// Constructor.
// ----------------------------------------------------------------------------
Voice::Voice()
{
set_chip_model(MOS6581);
}
// ----------------------------------------------------------------------------
// Set chip model.
// ----------------------------------------------------------------------------
void Voice::set_chip_model(chip_model model)
{
wave.set_chip_model(model);
if (model == MOS6581) {
// The waveform D/A converter introduces a DC offset in the signal
// to the envelope multiplying D/A converter. The "zero" level of
// the waveform D/A converter can be found as follows:
//
// Measure the "zero" voltage of voice 3 on the SID audio output
// pin, routing only voice 3 to the mixer ($d417 = $0b, $d418 =
// $0f, all other registers zeroed).
//
// Then set the sustain level for voice 3 to maximum and search for
// the waveform output value yielding the same voltage as found
// above. This is done by trying out different waveform output
// values until the correct value is found, e.g. with the following
// program:
//
// lda #$08
// sta $d412
// lda #$0b
// sta $d417
// lda #$0f
// sta $d418
// lda #$f0
// sta $d414
// lda #$21
// sta $d412
// lda #$01
// sta $d40e
//
// ldx #$00
// lda #$38 ; Tweak this to find the "zero" level
//l cmp $d41b
// bne l
// stx $d40e ; Stop frequency counter - freeze waveform output
// brk
//
// The waveform output range is 0x000 to 0xfff, so the "zero"
// level should ideally have been 0x800. In the measured chip, the
// waveform output "zero" level was found to be 0x380 (i.e. $d41b
// = 0x38) at 5.94V.
wave_zero = 0x380;
// The envelope multiplying D/A converter introduces another DC
// offset. This is isolated by the following measurements:
//
// * The "zero" output level of the mixer at full volume is 5.44V.
// * Routing one voice to the mixer at full volume yields
// 6.75V at maximum voice output (wave = 0xfff, sustain = 0xf)
// 5.94V at "zero" voice output (wave = any, sustain = 0x0)
// 5.70V at minimum voice output (wave = 0x000, sustain = 0xf)
// * The DC offset of one voice is (5.94V - 5.44V) = 0.50V
// * The dynamic range of one voice is |6.75V - 5.70V| = 1.05V
// * The DC offset is thus 0.50V/1.05V ~ 1/2 of the dynamic range.
//
// Note that by removing the DC offset, we get the following ranges for
// one voice:
// y > 0: (6.75V - 5.44V) - 0.50V = 0.81V
// y < 0: (5.70V - 5.44V) - 0.50V = -0.24V
// The scaling of the voice amplitude is not symmetric about y = 0;
// this follows from the DC level in the waveform output.
voice_DC = 0x800*0xff;
}
else {
// No DC offsets in the MOS8580.
wave_zero = 0x800;
voice_DC = 0;
}
}
// ----------------------------------------------------------------------------
// Set sync source.
// ----------------------------------------------------------------------------
void Voice::set_sync_source(Voice* source)
{
wave.set_sync_source(&source->wave);
}
// ----------------------------------------------------------------------------
// Register functions.
// ----------------------------------------------------------------------------
void Voice::writeCONTROL_REG(reg8 control)
{
wave.writeCONTROL_REG(control);
envelope.writeCONTROL_REG(control);
}
// ----------------------------------------------------------------------------
// SID reset.
// ----------------------------------------------------------------------------
void Voice::reset()
{
wave.reset();
envelope.reset();
}
| leafo/goattracker2 | src/resid/voice.cpp | C++ | gpl-2.0 | 4,860 |
<?php
/**
* The main template file.
*
* This is the most generic template file in a WordPress theme and one of the
* two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* For example, it puts together the home page when no home.php file exists.
*
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
*/
get_header(); ?>
<?php global $invert_shortname; ?>
<div class="main-wrapper-item">
<div class="bread-title-holder">
<div class="bread-title-bg-image full-bg-breadimage-fixed"></div>
<div class="container">
<div class="row-fluid">
<div class="container_inner clearfix">
<h1 class="title"><?php if(sketch_get_option($invert_shortname.'_blogpage_heading')) { echo sketch_get_option($invert_shortname.'_blogpage_heading'); } ?></h1>
</div>
</div>
</div>
</div>
<div class="container post-wrap">
<div class="row-fluid">
<div id="container" class="span8">
<div id="content">
<?php if(have_posts()) : ?>
<?php /* The loop */ ?>
<?php while(have_posts()) : the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
<div class="navigation">
<?php if (function_exists("invert_paginate") && sketch_get_option($invert_shortname.'_show_pagination')) { invert_paginate(); } else {?>
<div class="alignleft"><?php previous_posts_link(__('←Previous','invert'),0) ?></div>
<div class="alignright"><?php next_posts_link(__('Next→','invert'),0) ?></div>
<?php } ?>
</div>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif; ?>
</div>
<!-- content -->
</div>
<!-- container -->
<!-- Sidebar -->
<div id="sidebar" class="span3">
<?php get_sidebar(); ?>
</div>
<!-- Sidebar -->
</div>
<!-- row-fluid -->
</div><!-- container -->
</div>
<?php get_footer(); ?> | nadin90/wordpress | wp-content/themes/invert-lite/index.php | PHP | gpl-2.0 | 1,991 |
<?php // $Revision: 2.0 $
/************************************************************************/
/* phpAdsNew 2 */
/* =========== */
/* */
/* Copyright (c) 2000-2002 by the phpAdsNew developers */
/* For more information visit: http://www.phpadsnew.com */
/* */
/* 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. */
/************************************************************************/
// Main strings
$GLOBALS['strChooseSection'] = "Ñ¡Ôñ²¿·Ö";
// Priority
$GLOBALS['strRecalculatePriority'] = "ÖØÐ¼ÆËãÓÅÏÈȨ";
$GLOBALS['strHighPriorityCampaigns'] = "¸ßÓÅÏÈȨÏîÄ¿";
$GLOBALS['strAdViewsAssigned'] = "·ÖÅäµÄ¹ã¸æ·ÃÎÊÊý";
$GLOBALS['strLowPriorityCampaigns'] = "µÍÓÅÏÈȨÏîÄ¿";
$GLOBALS['strPredictedAdViews'] = "Ô¤¶¨µÄ¹ã¸æ·ÃÎÊÊý";
$GLOBALS['strPriorityDaysRunning'] = $phpAds_productname."¿ÉÒÔÔÚÏÖÔÚÓÐ{days}ÌìÊý¾ÝµÄ»ù´¡ÉÏÔ¤¹ÀÿÌìµÄÓÅÏÈȨ.";
$GLOBALS['strPriorityBasedLastWeek'] = "ÔÚÉÏÖܺͱ¾ÖÜÊý¾Ý»ù´¡ÉϵÄÔ¤¹ÀÖµ.";
$GLOBALS['strPriorityBasedLastDays'] = "TÔÚǰ¼¸ÌìÊý¾ÝµÄ»ù´¡ÉϵÄÔ¤¹ÀÖµ.";
$GLOBALS['strPriorityBasedYesterday'] = "ÔÚ×òÌìÊý¾ÝµÄ»ù´¡ÉϵÄÔ¤¹ÀÖµ";
$GLOBALS['strPriorityNoData'] = "ÏÖÔÚûÓÐ×ã¹»µÄÊý¾ÝÀ´¾«È·¹ÀËã´Ë¹ã¸æ·þÎñÆ÷½ñÌìµã»÷ÊýµÄÔ¤¼ÆÖµ¡£ËùÒÔÖ»ÔÚʵʱÊý¾ÝµÄ»ù´¡ÉÏ·ÖÅäÓÅÏÈȨ.";
$GLOBALS['strPriorityEnoughAdViews'] = "ÓÐ×ã¹»µÄ·ÃÎÊÊýÀ´ÍêÈ«Âú×ãÔ¤¶¨µÄËùÓиßÓÅÏÈȨµÄ·½°¸.";
$GLOBALS['strPriorityNotEnoughAdViews'] = "»¹²»ÖªµÀÊÇ·ñÓÐ×ã¹»µÄÍÆ²¥ÊýÀ´ÍêÈ«Âú×ãÔ¤¶¨µÄËùÓиßÓÅÏÈȨµÄ·½°¸,ËùÒÔËùÓеÍÓÅÏÈȨµÄ·½°¸ÒѾÔÝʱͣÓÃÁË.";
// Banner cache
$GLOBALS['strRebuildBannerCache'] = "ÖØ½¨¹ã¸æ»º´æÇø";
$GLOBALS['strBannerCacheExplaination'] = "¹ã¸æ»º´æÇø°üº¬ÁËÓÃÀ´ÏÔʾ¹ã¸æµÄHTML´úÂëµÄÒ»¸ö¸±±¾.ʹÓÃ¹ã¸æ»º´æÇø¿ÉÒÔÌá¸ß¹ã¸æ·¢·ÅµÄËÙ¶È,ÒòΪ²»ÔÙÐèҪÿ´Î·¢·ÅµÄʱºò¶¼ÒªÉú³öÄǸöÒ»´ÎHTML´úÂë.ÒòΪ´Ë¹ã¸æ»º´æÇø°üº¬ÁË".$phpAds_productname."ºÍ¹ã¸æµÄURLµØÖ·,ËùÒÔ»º´æÇøÐèÒªÔÚÿ´Î".$phpAds_productname."ÒÆ¶¯µ½ÍøÒ³·þÎñÆ÷µÄÁíÒ»¸öλÖõÄʱºòÖØ½¨.";
// Cache
$GLOBALS['strCache'] = "·¢ËÍ»º´æÇø";
$GLOBALS['strAge'] = "ÊÙÃü";
$GLOBALS['strRebuildDeliveryCache'] = "ÖØ½¨·¢ËÍ»º´æÇø";
$GLOBALS['strDeliveryCacheExplaination'] = "·¢ËÍ»º´æÇø¿ÉÒÔÌá¸ß¹ã¸æµÄ·¢·ÅËÙ¶È.·¢ËÍ»º´æÇø°üº¬Á¬½Óµ½´Ë°æÎ»µÄËùÓÐ¹ã¸æµÄÒ»¸ö¸±±¾,µ±¹ã¸æÊµ¼Ê·¢·Å¸øÓû§µÄʱºò¼õÉÙÁËһЩÊý¾Ý¿âµÄ²éѯ.´Ë»º´æÇøÍ¨³£ÔÚÒ»¸ö°æÎ»»òÕß°æÎ»µÄÒ»¸ö¹ã¸æ¸Ä¶¯µÄʱºòÖØ½¨,Ëü¿ÉÄÜ»á¹ýÆÚ.ËùÒÔ»º´æÇø»áÿ¸öСʱ×Ô¶¯Öؽ¨Ò»´Î,µ«ÄúÒ²¿ÉÒÔÊÖ¹¤Öؽ¨.";
$GLOBALS['strDeliveryCacheSharedMem'] = "ÏÖÔÚʹÓù²ÏíÄÚ´æÀ´´æ·Å·¢ËÍ»º´æÇø.";
$GLOBALS['strDeliveryCacheDatabase'] = "ÏÖÔÚʹÓÃÊý¾Ý¿âÀ´´æ·Å·¢ËÍ»º´æÇø.";
$GLOBALS['strDeliveryCacheFiles'] = "ÏÖÔÚʹÓÃÄú·þÎñÆ÷ÉϵĶà¸öÎļþÀ´´æ·Å·¢ËÍ»º´æÇø.";
// Storage
$GLOBALS['strStorage'] = "´æ´¢";
$GLOBALS['strMoveToDirectory'] = "°Ñ´æ´¢ÔÚÊý¾Ý¿âÖеÄÍ¼Æ¬ÒÆ¶¯µ½Ò»¸öĿ¼";
$GLOBALS['strStorageExplaination'] = "±¾µØ¹ã¸æÊ¹ÓõÄͼƬ´æ´¢ÔÚÊý¾Ý¿â»òÕßÒ»¸öĿ¼ÖÐ.Èç¹ûÄú°ÑͼƬ´æ´¢µ½Ò»¸öĿ¼,¼õСÁËÊý¾Ý¿âµÄ¸ºÔØ»áÌá¸ßÔËÐÐËÙ¶È.";
// Storage
$GLOBALS['strStatisticsExplaination'] = "ÄúÒѾÆôÓÃÁË<i>¼ò½à±¨±í</i>,µ«ÊÇÀϵı¨±í»¹ÊÇÏêϸ¸ñʽ.ÄúÏë°ÑÏêϸ¸ñʽµÄ±¨±íת»»³Éеļò½à¸ñʽÂð?";
// Product Updates
$GLOBALS['strSearchingUpdates'] = "²é¿´Éý¼¶. ÇëÉÔºò...";
$GLOBALS['strAvailableUpdates'] = "¿ÉÓÃÉý¼¶";
$GLOBALS['strDownloadZip'] = "ÏÂÔØ(.zip)";
$GLOBALS['strDownloadGZip'] = "ÏÂÔØ(.tar.gz)";
$GLOBALS['strUpdateAlert'] = $phpAds_productname."ÓÐеİ汾¿ÉÓÃ\\n\\nÄúÏëÖªµÀ¸ü¶à¹ØÓÚ´Ë´ÎÉý¼¶µÄÏûÏ¢Âð?";
$GLOBALS['strUpdateAlertSecurity'] = $phpAds_productname."ÓÐеİ汾¿ÉÓÃ\\n\\nÇ¿ÁÒÍÆ¼öÄú¾¡¿ìÉý¼¶,\\nÒòΪ´Ë´Îа汾°üº¬ÁËÒ»¸ö»ò¶à¸ö°²È«²¹¶¡!";
$GLOBALS['strUpdateServerDown'] = "ÒòΪδ֪ÔÒò²»Äܵõ½Éý¼¶ÐÅÏ¢,ÇëÉÔºòÔÙÊÔ.";
$GLOBALS['strNoNewVersionAvailable'] = "ÄúµÄ".$phpAds_productname."ÊÇ×îаæµÄ.ÏÖÔÚûÓпÉÓõÄÉý¼¶°æ±¾.";
$GLOBALS['strNewVersionAvailable'] = "<b>Ò»¸öа汾".$phpAds_productname."¿ÉÓÃ</b><br>ÍÆ¼öÄú°²×°´Ë´Î¸üÐÂ,ÒòΪ¿ÉÄÜÐÞ²¹ÁËһЩ´æÔÚµÄÎÊÌâºÍÔö¼ÓÁËһЩÐµĹ¦ÄÜ.¸ü¶àµÄÓйØÉý¼¶µÄÐÅÏ¢Çë²Î¿¼ÏÂÃæµÄÏà¹ØÎĵµ.";
$GLOBALS['strSecurityUpdate'] = "<b>Ç¿ÁÒÍÆ¼öÄú¾¡¿ì°²×°´Ë´Î¸üУ¬ÒòΪ°üº¬ÁËһЩ°²È«²¹¶¡</b>ÄúÏÖÔÚʹÓõÄ".$phpAds_productname."µÄ°æ±¾µÄ©¶´¿ÉÄܱ»¹¥»÷ºÍ²»°²È«.¸ü¶àµÄÓйØÉý¼¶µÄÐÅÏ¢Çë²Î¿¼ÏÂÃæµÄÏà¹ØÎĵµ.";
$GLOBALS['strNotAbleToCheck'] = "<b>ÒòΪÄúµÄ·þÎñÆ÷XMLÀ©Õ¹¹¦Äܲ»ÄÜʹÓÃ,".$phpAds_productname."ÎÞ·¨¼ì²éÊÇ·ñÓÐеİ汾¿ÉÒÔʹÓÃ.</b>";
$GLOBALS['strForUpdatesLookOnWebsite'] = "Èç¹ûÄúÏëÖªµÀÊÇ·ñÓÐеİ汾¿ÉÓÃ,Çë·ÃÎÊÎÒÃǵÄÍøÕ¾.";
$GLOBALS['strClickToVisitWebsite'] = "Çëµã»÷ÕâÀïÀ´·ÃÎÊÎÒÃǵÄÍøÕ¾.";
$GLOBALS['strCurrentlyUsing'] = "ÄúÏÖÔÚʹÓõÄÊÇ";
$GLOBALS['strRunningOn'] = "ÔËÐÐÔÚ";
$GLOBALS['strAndPlain'] = "ºÍ";
// Stats conversion
$GLOBALS['strConverting'] = "ת»»ÖÐ";
$GLOBALS['strConvertingStats'] = "ͳ¼ÆÊý¾Ýת»»ÖÐ...";
$GLOBALS['strConvertStats'] = "ת»»Í³¼ÆÊý¾Ý";
$GLOBALS['strConvertAdViews'] = "·ÃÎÊÊýÒѾת»»Íê±Ï,";
$GLOBALS['strConvertAdClicks'] = "µã»÷ÊýÒѾת»»Íê±Ï...";
$GLOBALS['strConvertNothing'] = "ûÓÐÊý¾Ý¿ÉÒÔת»»...";
$GLOBALS['strConvertFinished'] = "Íê±Ï...";
$GLOBALS['strConvertExplaination'] = "ÄúÏÖÔÚʹÓüò½à¸ñʽÀ´±£´æ±¨±í,µ«ÊÇ»¹ÓÐһЩ±¨±íÊÇÏêϸ¸ñʽ.<br>Ïêϸ¸ñʽµÄ±¨±íûÓÐת»»³É¼ò½à¸ñʽ½«²»ÄÜÔÚÒ³ÃæÉÏÖ±½ÓʹÓÃ.<br>ÔÚת»»ÄúµÄ±¨±í֮ǰ,±£´æÊý¾Ý¿âµÄÒ»¸ö±¸·Ý!<br>ÊÇ·ñÈ·ÈÏÒª°ÑÏêϸ¸ñʽµÄ±¨±íת»»³Éеļò½à¸ñʽ?<br>";
$GLOBALS['strConvertingExplaination'] = "ËùÓÐÊ£ÓàµÄÏêϸ¸ñʽµÄ±¨±íÕýÔÚת»»³É¼ò½à¸ñʽ<br>¸ù¾ÝÏêϸ¸ñʽµÄÊýÄ¿¶øÐèҪʱ¼ä²»Í¬£¬¿ÉÄÜÐèÒª¼¸·ÖÖÓ¡£ÔÚä¯ÀÀÆäËûÒ³ÃæÖ®Ç°Ò»¶¨ÒªµÈµ½×ª»»Íê³É¡£<br>ÏÂÃæÄú½«¿´µ½Êý¾Ý¿âÐ޸ĵļǼ.<br>";
$GLOBALS['strConvertFinishedExplaination'] = "Ê£ÓàµÄÏêϸ¸ñʽµÄ±¨±íÒѾת»»³É¹¦¡£Êý¾ÝÏÖÔÚÒªÔÙ´ÎʹÓã¬ÏÂÃæÄú½«¿´µ½Êý¾Ý¿âÐ޸ĵļǼ<br>";
?>
| miller-tamil/openads-plus | language/chinese_gb2312/maintenance.lang.php | PHP | gpl-2.0 | 5,999 |
#! /usr/bin/env python
#Written by Kjetil Matheussen: k.s.matheussen@notam02.no
import sys
import os
import urllib2
import readline
executable_path = os.path.split(os.path.abspath(os.path.realpath(sys.argv[0])))[0]
# TODO: Use bin/packages/s7/s7webserver instead, and delete the local s7webserver directory.
sys.path += [os.path.join(executable_path,os.path.pardir,"s7webserver")]
import s7webserver_repl
portnum = "5080"
if len(sys.argv)>1:
portnum = sys.argv[1]
s7webserver_repl.start("radium>", "http://localhost:"+portnum)
| kmatheussen/radium | bin/scheme/repl.py | Python | gpl-2.0 | 543 |
namespace KanbanWpf.Persistence
{
/// <summary>
/// Represents the persistency data of a note to store or retrieve.
/// </summary>
public struct PersistantNote : INote
{
/// <summary>
/// Gets/sets the X-coordinate of this note.
/// </summary>
public double X { get; set; }
/// <summary>
/// Gets/sets the Y-coordinate of this note.
/// </summary>
public double Y { get; set; }
/// <summary>
/// Gets/sets the unique id of this note.
/// </summary>
public string Uid { get; set; }
/// <summary>
/// Gets/sets the note text.
/// </summary>
public string Text { get; set; }
}
}
| chrishensel/SimpleKanbanWpf | KanbanWpf/Persistence/PersistantNote.cs | C# | gpl-2.0 | 732 |
<?php
// namespace administrator\components\com_jmap\views\cpanel;
/**
* @package JMAP::CPANEL::administrator::components::com_jmap
* @subpackage views
* @subpackage cpanel
* @author Joomla! Extensions Store
* @copyright (C) 2014 - Joomla! Extensions Store
* @license GNU/GPLv2 http://www.gnu.org/licenses/gpl-2.0.html
*/
defined ( '_JEXEC' ) or die ( 'Restricted access' );
/**
* CPanel view
*
* @package JMAP::CPANEL::administrator::components::com_jmap
* @subpackage views
* @subpackage cpanel
* @since 1.0
*/
class JMapViewCpanel extends JMapView {
/**
* Render iconset for cpanel
*
* @param $link string
* @param $image string
* @access private
* @return string
*/
private function getIcon($link, $image, $text, $target = '', $title = null, $class = null) {
$mainframe = JFactory::getApplication ();
$lang = JFactory::getLanguage ();
?>
<div style="float:<?php echo ($lang->isRTL()) ? 'right' : 'left'; ?>;">
<div class="icon">
<a <?php echo $title . $class;?> <?php echo $target;?> href="<?php echo $link; ?>">
<img src="components/com_jmap/images/<?php echo $image;?>" />
<span><?php echo $text; ?></span>
</a>
</div>
</div>
<?php
}
/**
* Add the page title and toolbar.
*
* @since 1.6
*/
protected function addDisplayToolbar() {
$doc = JFactory::getDocument();
$doc->addStyleDeclaration('.icon-48-jmap{background-image:url("components/com_jmap/images/jmap-48x48.png")}');
JToolBarHelper::title( JText::_('COM_JMAP_CPANEL_TOOLBAR' ), 'jmap' );
JToolBarHelper::custom('cpanel.display', 'home', 'home', 'COM_JMAP_CPANEL', false);
}
/**
* Control panel display
*
* @access public
* @param string $tpl
* @return void
*/
public function display($tpl = null) {
$doc = $this->document;
$componentParams = $this->getModel()->getState('cparams');
$this->loadJQuery($doc);
$this->loadBootstrap($doc);
$doc->addStylesheet ( JURI::root ( true ) . '/administrator/components/com_jmap/css/cpanel.css' );
$doc->addStylesheet ( JURI::root ( true ) . '/administrator/components/com_jmap/css/jquery.fancybox.css' );
$doc->addScript ( JURI::root ( true ) . '/administrator/components/com_jmap/js/chart.js' );
$doc->addScript ( JURI::root ( true ) . '/administrator/components/com_jmap/js/cpanel.js' );
$doc->addScript ( JURI::root ( true ) . '/administrator/components/com_jmap/js/analyzer.js' );
if($componentParams->get('enable_precaching', 0)) {
$doc->addScript ( JURI::root ( true ) . '/administrator/components/com_jmap/js/xmlprecaching.js' );
}
$doc->addCustomTag ('<script type="text/javascript" src="' . JURI::root ( true ) . '/administrator/components/com_jmap/js/jquery.fancybox.pack.js' . '"></script>');
// Inject js translations
$translations = array ( 'COM_JMAP_ROBOTSPROGRESSTITLE',
'COM_JMAP_ROBOTSPROGRESSSUBTITLE',
'COM_JMAP_ROBOTSPROGRESSSUBTITLESUCCESS',
'COM_JMAP_ROBOTSPROGRESSSUBTITLEERROR',
'COM_JMAP_PRECACHING_TITLE',
'COM_JMAP_START_PRECACHING_PROCESS',
'COM_JMAP_PRECACHING_NO_DATASOURCES_FOUND',
'COM_JMAP_PRECACHING_PROCESS_RUNNING',
'COM_JMAP_PRECACHING_PROCESS_COMPLETED',
'COM_JMAP_PRECACHING_REPORT_DATASOURCE',
'COM_JMAP_PRECACHING_REPORT_DATASOURCE_TYPE',
'COM_JMAP_PRECACHING_REPORT_LINKS',
'COM_JMAP_PRECACHING_DATA_SOURCE_COMPLETED',
'COM_JMAP_PRECACHING_DATASOURCES_RETRIEVED',
'COM_JMAP_PRECACHING_PROCESS_FINALIZING',
'COM_JMAP_PRECACHING_INTERRUPT',
'COM_JMAP_PRECACHING_CACHED',
'COM_JMAP_PRECACHING_NOT_CACHED',
'COM_JMAP_PRECACHING_CLEARING',
'COM_JMAP_PRECACHING_CLEAR_CACHE',
'COM_JMAP_PUBLISHED_DATA_SOURCE_CHART',
'COM_JMAP_TOTAL_DATA_SOURCE_CHART',
'COM_JMAP_MENU_DATA_SOURCE_CHART',
'COM_JMAP_USER_DATA_SOURCE_CHART',
'COM_JMAP_ANALYZER_TITLE',
'COM_JMAP_ANALYZER_PROCESS_RUNNING',
'COM_JMAP_ANALYZER_STARTED_SITEMAP_GENERATION',
'COM_JMAP_ANALYZER_ERROR_STORING_FILE',
'COM_JMAP_ANALYZER_GENERATION_COMPLETE'
);
$this->injectJsTranslations($translations, $doc);
$livesite = substr_replace(JURI::root(), "", -1, 1);
$user = JFactory::getUser();
$lists = $this->get('Lists');
$infoData = $this->get('Data');
$doc->addScriptDeclaration('var jmapChartData = ' . json_encode($infoData));
// Buffer delle icons
ob_start ();
$this->getIcon ( 'index.php?option=com_jmap&task=sources.display', 'icon-48-data.png', JText::_('COM_JMAP_SITEMAP_SOURCES' ), '', 'title="' . JText::_('COM_JMAP_SITEMAP_SOURCES' ) . '"');
$this->getIcon ( 'index.php?option=com_jmap&task=wizard.display', 'icon-48-wizard.png', JText::_('COM_JMAP_NEW_WIZARD_DATASOURCE' ), '', 'title="' . JText::_('COM_JMAP_NEW_WIZARD_DATASOURCE' ) . '"');
$this->getIcon ( $livesite . '/index.php?option=com_jmap&view=sitemap', 'icon-48-html_sitemap.png', JText::_('COM_JMAP_SHOW_HTML_MAP' ), 'target="_blank"', 'title="' . JText::_('COM_JMAP_SHOW_HTML_MAP' ) . '"', 'data-role="torefresh"' );
$this->getIcon ( '#xmlsitemap', 'icon-48-xml_sitemap.png', JText::_('COM_JMAP_SHOW_XML_MAP' ), '', 'title="' . JText::_('COM_JMAP_SHOW_XML_MAP' ) . '"', 'class="fancybox"' );
$this->getIcon ( '#xmlsitemap_xslt', 'icon-48-xsl_sitemap.png', JText::_('COM_JMAP_SHOW_XML_MAP_XSLT' ), '', 'title="' . JText::_('COM_JMAP_SHOW_XML_MAP_XSLT' ) . '"', 'class="fancybox"' );
$this->getIcon ( '#xmlsitemap_export', 'icon-48-xml_export.png', JText::_('COM_JMAP_EXPORT_XML_SITEMAP' ), '', 'title="' . JText::_('COM_JMAP_EXPORT_XML_SITEMAP' ) . '"', 'class="fancybox"' );
$this->getIcon ( $livesite . '/index.php?option=com_jmap&task=sitemap.exportxml&format=xml', 'icon-48-analyze.png', JText::_('COM_JMAP_ANALYZE_MAP' ), '', 'title="' . JText::_('COM_JMAP_ANALYZE_MAP' ) . '"', 'class="jmap_analyzer"' );
if($user->authorise('core.edit', 'com_jmap')) {
$this->getIcon ( 'index.php?option=com_jmap&task=cpanel.editEntity', 'icon-48-robots.png', JText::_('COM_JMAP_ROBOTS_EDITOR' ), '', 'title="' . JText::_('COM_JMAP_ROBOTS_EDITOR' ) . '"', 'class="fancybox_iframe"' );
}
$this->getIcon ( 'index.php?option=com_jmap&task=pingomatic.display', 'icon-48-pingomatic.png', JText::_('COM_JMAP_PINGOMATIC_LINKS' ), '', 'title="' . JText::_('COM_JMAP_PINGOMATIC_LINKS' ) . '"');
// Access check.
if ($user->authorise('core.admin', 'com_jmap')) {
$this->getIcon ( 'index.php?option=com_jmap&task=config.display', 'icon-48-config.png', JText::_('COM_JMAP_CONFIG' ), '', 'title="' . JText::_('COM_JMAP_CONFIG' ) . '"' );
}
$this->getIcon ( 'http://storejextensions.org/jsitemap_professional_documentation.html', 'icon-48-help.png', JText::_('COM_JMAP_HELPTITLE' ), '', 'title="' . JText::_('COM_JMAP_HELPTITLE' ) . '"' );
echo '<div style="display:none" id="xmlsitemap">';
$this->getIcon ( $livesite . '/index.php?option=com_jmap&view=sitemap&format=xml', 'icon-48-xml_sitemap_standard.png', JText::_('COM_JMAP_SHOW_XML_STANDARD_MAP' ), 'target="_blank"' );
$this->getIcon ( $livesite . '/index.php?option=com_jmap&view=sitemap&format=images', 'icon-48-xml_sitemap_images.png', JText::_('COM_JMAP_SHOW_XML_IMAGES_MAP' ), 'target="_blank"' );
$this->getIcon ( $livesite . '/index.php?option=com_jmap&view=sitemap&format=gnews', 'icon-48-xml_sitemap_gnews.png', JText::_('COM_JMAP_SHOW_XML_GNEWS_MAP' ), 'target="_blank"' );
$this->getIcon ( $livesite . '/index.php?option=com_jmap&view=sitemap&format=mobile', 'icon-48-xml_sitemap_mobile.png', JText::_('COM_JMAP_SHOW_XML_MOBILE_MAP' ), 'target="_blank"' );
echo '</div>';
echo '<div style="display:none" id="xmlsitemap_xslt">';
$this->getIcon ( $livesite . '/index.php?option=com_jmap&view=sitemap&format=xml&xslt=1', 'icon-48-xml_sitemap_standard.png', JText::_('COM_JMAP_SHOW_XML_STANDARD_MAP' ), 'target="_blank"' );
$this->getIcon ( $livesite . '/index.php?option=com_jmap&view=sitemap&format=images&xslt=1', 'icon-48-xml_sitemap_images.png', JText::_('COM_JMAP_SHOW_XML_IMAGES_MAP' ), 'target="_blank"' );
$this->getIcon ( $livesite . '/index.php?option=com_jmap&view=sitemap&format=gnews&xslt=1', 'icon-48-xml_sitemap_gnews.png', JText::_('COM_JMAP_SHOW_XML_GNEWS_MAP' ), 'target="_blank"' );
$this->getIcon ( $livesite . '/index.php?option=com_jmap&view=sitemap&format=mobile&xslt=1', 'icon-48-xml_sitemap_mobile.png', JText::_('COM_JMAP_SHOW_XML_MOBILE_MAP' ), 'target="_blank"' );
echo '</div>';
echo '<div style="display:none" id="xmlsitemap_export">';
$this->getIcon ( $livesite . '/index.php?option=com_jmap&task=sitemap.exportxml&format=xml', 'icon-48-xml_sitemap_standard.png', JText::_('COM_JMAP_EXPORT_XML_STANDARD_MAP' ));
$this->getIcon ( $livesite . '/index.php?option=com_jmap&task=sitemap.exportxml&format=images', 'icon-48-xml_sitemap_images.png', JText::_('COM_JMAP_EXPORT_XML_IMAGES_MAP' ));
$this->getIcon ( $livesite . '/index.php?option=com_jmap&task=sitemap.exportxml&format=gnews', 'icon-48-xml_sitemap_gnews.png', JText::_('COM_JMAP_EXPORT_XML_GNEWS_MAP' ));
$this->getIcon ( $livesite . '/index.php?option=com_jmap&task=sitemap.exportxml&format=mobile', 'icon-48-xml_sitemap_mobile.png', JText::_('COM_JMAP_EXPORT_XML_MOBILE_MAP' ));
echo '</div>';
$contents = ob_get_clean ();
// Assign reference variables
$this->icons = $contents;
$this->livesite = $livesite;
$this->componentParams = $componentParams;
$this->infodata = $infoData;
$this->lists = $lists;
$this->updatesData = $this->getModel()->getUpdates($this->get('httpclient'));
$this->siteRouter = JRouterSite::getInstance('site', array('mode'=>JROUTER_MODE_SEF));
$this->showSefLinks = $this->componentParams->get('sitemap_links_sef', false);
$this->joomlaSefLinks = JFactory::getConfig()->get('sef', true);
$this->currentVersion = strval(simplexml_load_file(JPATH_COMPONENT_ADMINISTRATOR . '/jmap.xml')->version);
// Aggiunta toolbar
$this->addDisplayToolbar();
// Output del template
parent::display ();
}
/**
* Edit entity view
*
* @access public
* @param Object& $row the item to edit
* @return void
*/
public function editEntity(&$row) {
// Load JS Client App dependencies
$doc = JFactory::getDocument();
$this->loadJQuery($doc);
$this->loadBootstrap($doc);
// Load specific JS App
$doc->addStylesheet ( JURI::root ( true ) . '/administrator/components/com_jmap/css/cpanel.css' );
$doc->addScript ( JURI::root ( true ) . '/administrator/components/com_jmap/js/cpanel.js' );
$this->option = $this->option;
$this->robotsVersion = $this->getModel ()->getState ( 'robots_version' );
$this->record = $row;
parent::display ( 'edit' );
}
/**
* Rendering for installer APP that runs on JSitemap installation iframe
* @access public
* @return void
*/
public function showInstallerApp() {
$doc = JFactory::getDocument();
$this->loadJQuery($doc);
$this->loadBootstrap($doc);
$doc->addStylesheet ( JURI::root ( true ) . '/administrator/components/com_jmap/css/cpanel.css' );
$doc->addScript ( JURI::root ( true ) . '/administrator/components/com_jmap/js/installer.js' );
// Set layout
$this->setLayout('default');
// Format data
parent::display ('installer');
}
} | neoandrew1000/crao_journal | administrator/components/com_jmap/views/cpanel/view.html.php | PHP | gpl-2.0 | 11,282 |
/**
* $Id$
* <p>
* Title: tn5250J
* Copyright: Copyright (c) 2001,2009
* Company:
*
* @author: master_jaf
* <p>
* Description:
* Tab component for displaying title text and icons.
* <p>
* <p>
* 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, or (at your option)
* any later version.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU General Public License
* along with this software; see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307 USA
*/
package org.tn5250j.gui;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingConstants;
import javax.swing.plaf.basic.BasicButtonUI;
import org.tn5250j.TN5250jConstants;
import org.tn5250j.event.SessionChangeEvent;
import org.tn5250j.event.SessionListener;
import org.tn5250j.event.TabClosedListener;
import org.tn5250j.tools.LangTool;
/**
* Component to be used as tabComponent; Contains a JLabel to show the text and
* a JButton to close the tab it belongs to.<br>
* <br>
* This class based on the ButtonTabComponent example from
* Sun Microsystems, Inc. and was modified to use tool tips, other layout and stuff.
*/
public final class ButtonTabComponent extends JPanel implements SessionListener {
private static final long serialVersionUID = 1L;
private final JTabbedPane pane;
private List<TabClosedListener> closeListeners;
private final JLabel label;
public ButtonTabComponent(final JTabbedPane pane) {
super(new BorderLayout(0, 0));
if (pane == null) {
throw new NullPointerException("TabbedPane is null");
}
this.pane = pane;
setOpaque(false);
this.label = new TabLabel(); // {
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setVerticalAlignment(SwingConstants.CENTER);
add(label, BorderLayout.CENTER);
// add more space between the label and the button
label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
// tab button
JButton button = new TabButton();
button.setHorizontalAlignment(SwingConstants.TRAILING);
add(button, BorderLayout.EAST);
// add more space to the top of the component
setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
pane.addPropertyChangeListener(new PropertyChangeListener() {
// triggers repaint, so size is recalculated, when title text changes
@Override
public void propertyChange(PropertyChangeEvent evt) {
if ("indexForTitle".equals(evt.getPropertyName())) {
label.revalidate();
label.repaint();
}
}
});
}
@Override
public void onSessionChanged(SessionChangeEvent changeEvent) {
if (changeEvent.getState() == TN5250jConstants.STATE_CONNECTED) {
this.label.setEnabled(true);
this.label.setToolTipText(LangTool.getString("ss.state.connected"));
this.setToolTipText(LangTool.getString("ss.state.connected"));
} else {
this.label.setEnabled(false);
this.label.setToolTipText(LangTool.getString("ss.state.disconnected"));
this.setToolTipText(LangTool.getString("ss.state.disconnected"));
}
}
/**
* Add a TabClosedListener to the listener list.
*
* @param listener The TabClosedListener to be added
*/
public synchronized void addTabCloseListener(TabClosedListener listener) {
if (closeListeners == null) {
closeListeners = new ArrayList<TabClosedListener>(3);
}
closeListeners.add(listener);
}
/**
* Remove a TabClosedListener from the listener list.
*
* @param listener The TabClosedListener to be removed
*/
public synchronized void removeTabCloseListener(TabClosedListener listener) {
if (closeListeners == null) {
return;
}
closeListeners.remove(listener);
}
/**
* Notify all the tab listeners that this specific tab was selected to close.
*
* @param tabToClose
*/
protected void fireTabClosed(int tabToClose) {
if (closeListeners != null) {
int size = closeListeners.size();
for (int i = 0; i < size; i++) {
TabClosedListener target = closeListeners.get(i);
target.onTabClosed(tabToClose);
}
}
}
// =======================================================================
/**
* Label delegating icon and text to the corresponding tab.
* Implementing MouseListener is a workaround, cause when applying
* a tool tip to the JLabel, clicking the tabs doesn't work
* (tested on Tn5250j0.6.2; WinXP+WinVista+Win7; JRE 1.6.0_20+).
*/
private final class TabLabel extends JLabel implements MouseListener {
private static final long serialVersionUID = 1L;
public TabLabel() {
addMouseListener(this);
}
public String getText() {
final int i = pane.indexOfTabComponent(ButtonTabComponent.this);
if (i != -1) {
return pane.getTitleAt(i);
}
return null;
}
public Icon getIcon() {
final int i = pane.indexOfTabComponent(ButtonTabComponent.this);
if (i != -1) {
return pane.getIconAt(i);
}
return null;
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent)
*/
@Override
public void mouseClicked(MouseEvent e) {
actionSelectTab();
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent)
*/
@Override
public void mousePressed(MouseEvent e) {
// not needed
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent)
*/
@Override
public void mouseReleased(MouseEvent e) {
actionSelectTab();
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent)
*/
@Override
public void mouseEntered(MouseEvent e) {
// not needed
}
/* (non-Javadoc)
* @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent)
*/
@Override
public void mouseExited(MouseEvent e) {
// not needed
}
private void actionSelectTab() {
final int i = pane.indexOfTabComponent(ButtonTabComponent.this);
if (i != -1) {
pane.setSelectedIndex(i);
}
}
}
/**
* Special button displaying an X as close icon.
*/
private final class TabButton extends JButton implements ActionListener {
private static final long serialVersionUID = 1L;
public TabButton() {
int size = 17;
setPreferredSize(new Dimension(size, size));
setToolTipText(LangTool.getString("popup.close"));
// Make the button looks the same for all Laf's
setUI(new BasicButtonUI());
// Make it transparent
setContentAreaFilled(false);
// No need to be focusable
setFocusable(false);
setBorder(BorderFactory.createEtchedBorder());
setBorderPainted(false);
// Making nice rollover effect
// we use the same listener for all buttons
addMouseListener(buttonMouseListener);
setRolloverEnabled(true);
// Close the proper tab by clicking the button
addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
int i = pane.indexOfTabComponent(ButtonTabComponent.this);
if (i != -1) {
fireTabClosed(i);
// hint: the actual close will be done within the TabbedPane Container
}
}
// we don't want to update UI for this button
public void updateUI() {
}
// paint the cross
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g.create();
// shift the image for pressed buttons
if (getModel().isPressed()) {
g2.translate(1, 1);
}
g2.setStroke(new BasicStroke(2));
g2.setColor(Color.BLACK);
if (getModel().isRollover()) {
g2.setColor(Color.MAGENTA);
}
int delta = 6;
g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1);
g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1);
g2.dispose();
}
}
private final static MouseListener buttonMouseListener = new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
Component component = e.getComponent();
if (component instanceof AbstractButton) {
AbstractButton button = (AbstractButton) component;
button.setBorderPainted(true);
}
}
public void mouseExited(MouseEvent e) {
Component component = e.getComponent();
if (component instanceof AbstractButton) {
AbstractButton button = (AbstractButton) component;
button.setBorderPainted(false);
}
}
};
}
| tn5250j/tn5250j | src/org/tn5250j/gui/ButtonTabComponent.java | Java | gpl-2.0 | 11,125 |
/*
* Copyright (C) 2006 The Android Open Source Project
* Copyright (C) 2012 YIXIA.COM
* Copyright (C) 2013 Zhang Rui <bbcallen@gmail.com>
* 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 tv.danmaku.ijk.media.widget;
import java.io.IOException;
import java.util.List;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IMediaPlayer.OnBufferingUpdateListener;
import tv.danmaku.ijk.media.player.IMediaPlayer.OnCompletionListener;
import tv.danmaku.ijk.media.player.IMediaPlayer.OnErrorListener;
import tv.danmaku.ijk.media.player.IMediaPlayer.OnInfoListener;
import tv.danmaku.ijk.media.player.IMediaPlayer.OnPreparedListener;
import tv.danmaku.ijk.media.player.IMediaPlayer.OnSeekCompleteListener;
import tv.danmaku.ijk.media.player.IMediaPlayer.OnVideoSizeChangedListener;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;
import tv.danmaku.ijk.media.player.option.AvFourCC;
import tv.danmaku.ijk.media.player.option.format.AvFormatOption_HttpDetectRangeSupport;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import android.util.AttributeSet;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
/**
* Displays a video file. The VideoView class can load images from various
* sources (such as resources or content providers), takes care of computing its
* measurement from the video so that it can be used in any layout manager, and
* provides various display options such as scaling and tinting.
*
* VideoView also provide many wrapper methods for
* {@link io.vov.vitamio.MediaPlayer}, such as {@link #getVideoWidth()},
* {@link #setSubShown(boolean)}
*/
public class VideoView extends SurfaceView implements
MediaController.MediaPlayerControl {
private static final String TAG = VideoView.class.getName();
private Uri mUri;
private long mDuration;
private static final int STATE_ERROR = -1;
private static final int STATE_IDLE = 0;
private static final int STATE_PREPARING = 1;
private static final int STATE_PREPARED = 2;
private static final int STATE_PLAYING = 3;
private static final int STATE_PAUSED = 4;
private static final int STATE_PLAYBACK_COMPLETED = 5;
private static final int STATE_SUSPEND = 6;
private static final int STATE_RESUME = 7;
private static final int STATE_SUSPEND_UNSUPPORTED = 8;
private int mCurrentState = STATE_IDLE;
private int mTargetState = STATE_IDLE;
private int mVideoLayout = VIDEO_LAYOUT_SCALE;
public static final int VIDEO_LAYOUT_ORIGIN = 0;
public static final int VIDEO_LAYOUT_SCALE = 1;
public static final int VIDEO_LAYOUT_STRETCH = 2;
public static final int VIDEO_LAYOUT_ZOOM = 3;
private SurfaceHolder mSurfaceHolder = null;
private IMediaPlayer mMediaPlayer = null;
private int mVideoWidth;
private int mVideoHeight;
private int mVideoSarNum;
private int mVideoSarDen;
private int mSurfaceWidth;
private int mSurfaceHeight;
private MediaController mMediaController;
private View mMediaBufferingIndicator;
private OnCompletionListener mOnCompletionListener;
private OnPreparedListener mOnPreparedListener;
private OnErrorListener mOnErrorListener;
private OnSeekCompleteListener mOnSeekCompleteListener;
private OnInfoListener mOnInfoListener;
private OnBufferingUpdateListener mOnBufferingUpdateListener;
private int mCurrentBufferPercentage;
private long mSeekWhenPrepared;
private boolean mCanPause = true;
private boolean mCanSeekBack = true;
private boolean mCanSeekForward = true;
private Context mContext;
public VideoView(Context context) {
super(context);
initVideoView(context);
}
public VideoView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public VideoView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initVideoView(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = getDefaultSize(mVideoWidth, widthMeasureSpec);
int height = getDefaultSize(mVideoHeight, heightMeasureSpec);
setMeasuredDimension(width, height);
}
/**
* Set the display options
*
* @param layout
* <ul>
* <li>{@link #VIDEO_LAYOUT_ORIGIN}
* <li>{@link #VIDEO_LAYOUT_SCALE}
* <li>{@link #VIDEO_LAYOUT_STRETCH}
* <li>{@link #VIDEO_LAYOUT_ZOOM}
* </ul>
* @param aspectRatio
* video aspect ratio, will audo detect if 0.
*/
public void setVideoLayout(int layout) {
LayoutParams lp = getLayoutParams();
Pair<Integer, Integer> res = ScreenResolution.getResolution(mContext);
int windowWidth = res.first.intValue(), windowHeight = res.second.intValue();
float windowRatio = windowWidth / (float) windowHeight;
int sarNum = mVideoSarNum;
int sarDen = mVideoSarDen;
if (mVideoHeight > 0 && mVideoWidth > 0) {
float videoRatio = ((float) (mVideoWidth)) / mVideoHeight;
if (sarNum > 0 && sarDen > 0)
videoRatio = videoRatio * sarNum / sarDen;
mSurfaceHeight = mVideoHeight;
mSurfaceWidth = mVideoWidth;
if (VIDEO_LAYOUT_ORIGIN == layout && mSurfaceWidth < windowWidth
&& mSurfaceHeight < windowHeight) {
lp.width = (int) (mSurfaceHeight * videoRatio);
lp.height = mSurfaceHeight;
} else if (layout == VIDEO_LAYOUT_ZOOM) {
lp.width = windowRatio > videoRatio ? windowWidth
: (int) (videoRatio * windowHeight);
lp.height = windowRatio < videoRatio ? windowHeight
: (int) (windowWidth / videoRatio);
} else {
boolean full = layout == VIDEO_LAYOUT_STRETCH;
lp.width = (full || windowRatio < videoRatio) ? windowWidth
: (int) (videoRatio * windowHeight);
lp.height = (full || windowRatio > videoRatio) ? windowHeight
: (int) (windowWidth / videoRatio);
}
setLayoutParams(lp);
getHolder().setFixedSize(mSurfaceWidth, mSurfaceHeight);
DebugLog.dfmt(
TAG,
"VIDEO: %dx%dx%f[SAR:%d:%d], Surface: %dx%d, LP: %dx%d, Window: %dx%dx%f",
mVideoWidth, mVideoHeight, videoRatio, mVideoSarNum,
mVideoSarDen, mSurfaceWidth, mSurfaceHeight, lp.width,
lp.height, windowWidth, windowHeight, windowRatio);
}
mVideoLayout = layout;
}
private void initVideoView(Context ctx) {
mContext = ctx;
mVideoWidth = 0;
mVideoHeight = 0;
mVideoSarNum = 0;
mVideoSarDen = 0;
getHolder().addCallback(mSHCallback);
setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
if (ctx instanceof Activity)
((Activity) ctx).setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
public boolean isValid() {
return (mSurfaceHolder != null && mSurfaceHolder.getSurface().isValid());
}
public void setVideoPath(String path) {
setVideoURI(Uri.parse(path));
}
public void setVideoURI(Uri uri) {
mUri = uri;
mSeekWhenPrepared = 0;
openVideo();
requestLayout();
invalidate();
}
public void stopPlayback() {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
}
}
private void openVideo() {
if (mUri == null || mSurfaceHolder == null)
return;
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause");
mContext.sendBroadcast(i);
release(false);
try {
mDuration = -1;
mCurrentBufferPercentage = 0;
// mMediaPlayer = new AndroidMediaPlayer();
IjkMediaPlayer ijkMediaPlayer = null;
if (mUri != null) {
ijkMediaPlayer = new IjkMediaPlayer();
ijkMediaPlayer.setAvOption(AvFormatOption_HttpDetectRangeSupport.Disable);
ijkMediaPlayer.setOverlayFormat(AvFourCC.SDL_FCC_RV32);
ijkMediaPlayer.setAvCodecOption("skip_loop_filter", "48");
ijkMediaPlayer.setFrameDrop(12);
}
mMediaPlayer = ijkMediaPlayer;
mMediaPlayer.setOnPreparedListener(mPreparedListener);
mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
mMediaPlayer.setOnCompletionListener(mCompletionListener);
mMediaPlayer.setOnErrorListener(mErrorListener);
mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
mMediaPlayer.setOnInfoListener(mInfoListener);
mMediaPlayer.setOnSeekCompleteListener(mSeekCompleteListener);
if (mUri != null)
mMediaPlayer.setDataSource(mUri.toString());
mMediaPlayer.setDisplay(mSurfaceHolder);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.prepareAsync();
mCurrentState = STATE_PREPARING;
attachMediaController();
} catch (IOException ex) {
DebugLog.e(TAG, "Unable to open content: " + mUri, ex);
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
mErrorListener.onError(mMediaPlayer,
IMediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
return;
} catch (IllegalArgumentException ex) {
DebugLog.e(TAG, "Unable to open content: " + mUri, ex);
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
mErrorListener.onError(mMediaPlayer,
IMediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
return;
}
}
public void setMediaController(MediaController controller) {
if (mMediaController != null)
mMediaController.hide();
mMediaController = controller;
attachMediaController();
}
public void setMediaBufferingIndicator(View mediaBufferingIndicator) {
if (mMediaBufferingIndicator != null)
mMediaBufferingIndicator.setVisibility(View.GONE);
mMediaBufferingIndicator = mediaBufferingIndicator;
}
private void attachMediaController() {
if (mMediaPlayer != null && mMediaController != null) {
mMediaController.setMediaPlayer(this);
View anchorView = this.getParent() instanceof View ? (View) this
.getParent() : this;
mMediaController.setAnchorView(anchorView);
mMediaController.setEnabled(isInPlaybackState());
if (mUri != null) {
List<String> paths = mUri.getPathSegments();
String name = paths == null || paths.isEmpty() ? "null" : paths
.get(paths.size() - 1);
mMediaController.setFileName(name);
}
}
}
OnVideoSizeChangedListener mSizeChangedListener = new OnVideoSizeChangedListener() {
public void onVideoSizeChanged(IMediaPlayer mp, int width, int height,
int sarNum, int sarDen) {
DebugLog.dfmt(TAG, "onVideoSizeChanged: (%dx%d)", width, height);
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
mVideoSarNum = sarNum;
mVideoSarDen = sarDen;
if (mVideoWidth != 0 && mVideoHeight != 0)
setVideoLayout(mVideoLayout);
}
};
OnPreparedListener mPreparedListener = new OnPreparedListener() {
public void onPrepared(IMediaPlayer mp) {
DebugLog.d(TAG, "onPrepared");
mCurrentState = STATE_PREPARED;
mTargetState = STATE_PLAYING;
if (mOnPreparedListener != null)
mOnPreparedListener.onPrepared(mMediaPlayer);
if (mMediaController != null)
mMediaController.setEnabled(true);
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
long seekToPosition = mSeekWhenPrepared;
if (seekToPosition != 0)
seekTo(seekToPosition);
if (mVideoWidth != 0 && mVideoHeight != 0) {
setVideoLayout(mVideoLayout);
if (mSurfaceWidth == mVideoWidth
&& mSurfaceHeight == mVideoHeight) {
if (mTargetState == STATE_PLAYING) {
start();
if (mMediaController != null)
mMediaController.show();
} else if (!isPlaying()
&& (seekToPosition != 0 || getCurrentPosition() > 0)) {
if (mMediaController != null)
mMediaController.show(0);
}
}
} else if (mTargetState == STATE_PLAYING) {
start();
}
}
};
private OnCompletionListener mCompletionListener = new OnCompletionListener() {
public void onCompletion(IMediaPlayer mp) {
DebugLog.d(TAG, "onCompletion");
mCurrentState = STATE_PLAYBACK_COMPLETED;
mTargetState = STATE_PLAYBACK_COMPLETED;
if (mMediaController != null)
mMediaController.hide();
if (mOnCompletionListener != null)
mOnCompletionListener.onCompletion(mMediaPlayer);
}
};
private OnErrorListener mErrorListener = new OnErrorListener() {
public boolean onError(IMediaPlayer mp, int framework_err, int impl_err) {
DebugLog.dfmt(TAG, "Error: %d, %d", framework_err, impl_err);
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
if (mMediaController != null)
mMediaController.hide();
if (mOnErrorListener != null) {
if (mOnErrorListener.onError(mMediaPlayer, framework_err,
impl_err))
return true;
}
if (getWindowToken() != null) {
int message = framework_err == IMediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK ? R.string.vitamio_videoview_error_text_invalid_progressive_playback
: R.string.vitamio_videoview_error_text_unknown;
new AlertDialog.Builder(mContext)
.setTitle(R.string.vitamio_videoview_error_title)
.setMessage(message)
.setPositiveButton(
R.string.vitamio_videoview_error_button,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
if (mOnCompletionListener != null)
mOnCompletionListener
.onCompletion(mMediaPlayer);
}
}).setCancelable(false).show();
}
return true;
}
};
private OnBufferingUpdateListener mBufferingUpdateListener = new OnBufferingUpdateListener() {
public void onBufferingUpdate(IMediaPlayer mp, int percent) {
mCurrentBufferPercentage = percent;
if (mOnBufferingUpdateListener != null)
mOnBufferingUpdateListener.onBufferingUpdate(mp, percent);
}
};
private OnInfoListener mInfoListener = new OnInfoListener() {
@Override
public boolean onInfo(IMediaPlayer mp, int what, int extra) {
DebugLog.dfmt(TAG, "onInfo: (%d, %d)", what, extra);
if (mOnInfoListener != null) {
mOnInfoListener.onInfo(mp, what, extra);
} else if (mMediaPlayer != null) {
if (what == IMediaPlayer.MEDIA_INFO_BUFFERING_START) {
DebugLog.dfmt(TAG, "onInfo: (MEDIA_INFO_BUFFERING_START)");
if (mMediaBufferingIndicator != null)
mMediaBufferingIndicator.setVisibility(View.VISIBLE);
} else if (what == IMediaPlayer.MEDIA_INFO_BUFFERING_END) {
DebugLog.dfmt(TAG, "onInfo: (MEDIA_INFO_BUFFERING_END)");
if (mMediaBufferingIndicator != null)
mMediaBufferingIndicator.setVisibility(View.GONE);
}
}
return true;
}
};
private OnSeekCompleteListener mSeekCompleteListener = new OnSeekCompleteListener() {
@Override
public void onSeekComplete(IMediaPlayer mp) {
DebugLog.d(TAG, "onSeekComplete");
if (mOnSeekCompleteListener != null)
mOnSeekCompleteListener.onSeekComplete(mp);
}
};
public void setOnPreparedListener(OnPreparedListener l) {
mOnPreparedListener = l;
}
public void setOnCompletionListener(OnCompletionListener l) {
mOnCompletionListener = l;
}
public void setOnErrorListener(OnErrorListener l) {
mOnErrorListener = l;
}
public void setOnBufferingUpdateListener(OnBufferingUpdateListener l) {
mOnBufferingUpdateListener = l;
}
public void setOnSeekCompleteListener(OnSeekCompleteListener l) {
mOnSeekCompleteListener = l;
}
public void setOnInfoListener(OnInfoListener l) {
mOnInfoListener = l;
}
SurfaceHolder.Callback mSHCallback = new SurfaceHolder.Callback() {
public void surfaceChanged(SurfaceHolder holder, int format, int w,
int h) {
mSurfaceHolder = holder;
if (mMediaPlayer != null) {
mMediaPlayer.setDisplay(mSurfaceHolder);
}
mSurfaceWidth = w;
mSurfaceHeight = h;
boolean isValidState = (mTargetState == STATE_PLAYING);
boolean hasValidSize = (mVideoWidth == w && mVideoHeight == h);
if (mMediaPlayer != null && isValidState && hasValidSize) {
if (mSeekWhenPrepared != 0)
seekTo(mSeekWhenPrepared);
start();
if (mMediaController != null) {
if (mMediaController.isShowing())
mMediaController.hide();
mMediaController.show();
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
mSurfaceHolder = holder;
if (mMediaPlayer != null && mCurrentState == STATE_SUSPEND
&& mTargetState == STATE_RESUME) {
mMediaPlayer.setDisplay(mSurfaceHolder);
resume();
} else {
openVideo();
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
mSurfaceHolder = null;
if (mMediaController != null)
mMediaController.hide();
if (mCurrentState != STATE_SUSPEND)
release(true);
}
};
private void release(boolean cleartargetstate) {
if (mMediaPlayer != null) {
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
mCurrentState = STATE_IDLE;
if (cleartargetstate)
mTargetState = STATE_IDLE;
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (isInPlaybackState() && mMediaController != null)
toggleMediaControlsVisiblity();
return false;
}
@Override
public boolean onTrackballEvent(MotionEvent ev) {
if (isInPlaybackState() && mMediaController != null)
toggleMediaControlsVisiblity();
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean isKeyCodeSupported = keyCode != KeyEvent.KEYCODE_BACK
&& keyCode != KeyEvent.KEYCODE_VOLUME_UP
&& keyCode != KeyEvent.KEYCODE_VOLUME_DOWN
&& keyCode != KeyEvent.KEYCODE_MENU
&& keyCode != KeyEvent.KEYCODE_CALL
&& keyCode != KeyEvent.KEYCODE_ENDCALL;
if (isInPlaybackState() && isKeyCodeSupported
&& mMediaController != null) {
if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK
|| keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE
|| keyCode == KeyEvent.KEYCODE_SPACE) {
if (mMediaPlayer.isPlaying()) {
pause();
mMediaController.show();
} else {
start();
mMediaController.hide();
}
return true;
} else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP
&& mMediaPlayer.isPlaying()) {
pause();
mMediaController.show();
} else {
toggleMediaControlsVisiblity();
}
}
return super.onKeyDown(keyCode, event);
}
private void toggleMediaControlsVisiblity() {
if (mMediaController.isShowing()) {
mMediaController.hide();
} else {
mMediaController.show();
}
}
@Override
public void start() {
if (isInPlaybackState()) {
mMediaPlayer.start();
mCurrentState = STATE_PLAYING;
}
mTargetState = STATE_PLAYING;
}
@Override
public void pause() {
if (isInPlaybackState()) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
mCurrentState = STATE_PAUSED;
}
}
mTargetState = STATE_PAUSED;
}
public void resume() {
if (mSurfaceHolder == null && mCurrentState == STATE_SUSPEND) {
mTargetState = STATE_RESUME;
} else if (mCurrentState == STATE_SUSPEND_UNSUPPORTED) {
openVideo();
}
}
@Override
public int getDuration() {
if (isInPlaybackState()) {
if (mDuration > 0)
return (int) mDuration;
mDuration = mMediaPlayer.getDuration();
return (int) mDuration;
}
mDuration = -1;
return (int) mDuration;
}
@Override
public int getCurrentPosition() {
if (isInPlaybackState()) {
long position = mMediaPlayer.getCurrentPosition();
return (int) position;
}
return 0;
}
@Override
public void seekTo(long msec) {
if (isInPlaybackState()) {
mMediaPlayer.seekTo(msec);
mSeekWhenPrepared = 0;
} else {
mSeekWhenPrepared = msec;
}
}
@Override
public boolean isPlaying() {
return isInPlaybackState() && mMediaPlayer.isPlaying();
}
@Override
public int getBufferPercentage() {
if (mMediaPlayer != null)
return mCurrentBufferPercentage;
return 0;
}
public int getVideoWidth() {
return mVideoWidth;
}
public int getVideoHeight() {
return mVideoHeight;
}
protected boolean isInPlaybackState() {
return (mMediaPlayer != null && mCurrentState != STATE_ERROR
&& mCurrentState != STATE_IDLE && mCurrentState != STATE_PREPARING);
}
public boolean canPause() {
return mCanPause;
}
public boolean canSeekBackward() {
return mCanSeekBack;
}
public boolean canSeekForward() {
return mCanSeekForward;
}
}
| jgfntu/ijkplayer | android/ijkmediawidget/src/tv/danmaku/ijk/media/widget/VideoView.java | Java | gpl-2.0 | 25,159 |
<?php
defined('JPATH_PLATFORM') or die;
class CAdminactivity
{
public static function getTitle($activities)
{
foreach($activities as $key=>$activity)
{
$param = new CParameter($activity->params);
switch ($activity->app) {
case 'users.featured':
$user = CFactory::getUser($param->get('userid'));
$activities[$key]->title = JText::sprintf('COM_COMMUNITY_MEMBER_IS_FEATURED','<a href="'.CRoute::_(JUri::root().$param->get('owner_url')).'" class="cStream-Author">'.$user->getDisplayName().'</a>');
break;
case 'events.wall':
case 'groups.wall':
case 'profile':
//$user = CFactory::getUser($activity->actor);
$html = '';
if($activity->eventid)
{
$event = JTable::getInstance('Event','cTable');
$event->load($activity->eventid);
$html .= '<a class="cStream-Reference" target="_blank" href="'.JUri::root().'index.php?option=com_community&view=events&task=viewevent&eventid='.$event->id.'">'. $event->title .'</a>';
}
elseif($activity->groupid)
{
$group = JTable::getInstance('Group','cTable');
$group->load($activity->groupid);
$html .= '<a class="cStream-Reference" target="_blank" href="'.JUri::root().'index.php?option=com_community&view=groups&task=viewgroup&groupid='.$group->id.'">'.$group->name.'</a>';
}
elseif( !empty($activity->target) && $activity->target != $activity->actor)
{
$target = CFactory::getUser($activity->target);
$html .= '<a class="cStream-Author" target="_blank" href="'.JUri::root().'index.php?option=com_community&view=profile&userid='.$target->id.'">'.$target->getDisplayName().'</a> ';
$html .= CActivities::format($activity->title);
}
else
{
$html .= ' posted: "'.CActivities::format($activity->title).'"';
}
$activities[$key]->title = $html;
break;
case 'profile.avatar.upload':
//$user = CFactory::getUser($activity->actor);
//$html = '<a class="cStream-Author" target="_blank" href="'.JUri::root().'index.php?option=com_community&view=profile&userid='.$user->id.'">'.$user->getDisplayName().'</a> ';
$html = JText::_('COM_COMMUNITY_ACTIVITIES_NEW_AVATAR');
$activities[$key]->title = $html;
break;
case 'albums.comment':
case 'albums':
$album = JTable::getInstance( 'Album' , 'CTable' );
$album->load( $activity->cid );
$user = CFactory::getUser($activity->actor);
//$html = '<a class="cStream-Author" target="_blank" href="'.JUri::root().'index.php?option=com_community&view=profile&userid='.$user->id.'">'.$user->getDisplayName().'</a> ';
$html = JText::sprintf('COM_COMMUNITY_ACTIVITIES_WALL_POST_ALBUM', CRoute::_($album->getURI()), CStringHelper::escape($album->name) );
$activities[$key]->title = $html;
break;
case 'profile.like':
case 'groups.like':
case 'events.like':
case 'photo.like':
case 'videos.like':
case 'album.like':
$actors = $param->get('actors');
$user = CFactory::getUser($activity->actor);
$users = explode(',', $actors);
$userCount = count($users);
switch($activity->app){
case 'profile.like':
$cid = CFactory::getUser($activity->cid);
$urlLink = JUri::root().'index.php?option=com_community&view=profile&userid='.$cid->id;
$name = $cid->getDisplayName();
$element = 'COM_COMMUNITY_STREAM_LIKES_ELEMENT_PROFILE';
break;
case 'groups.like':
$cid = JTable::getInstance('Group', 'CTable');
$cid->load($activity->groupid);
$urlLink = JUri::root().'index.php?option=com_community&view=groups&task=viewgroup&groupid='.$cid->id;
$name = $cid->name;
$element = 'COM_COMMUNITY_STREAM_LIKES_ELEMENT_GROUP';
break;
case 'events.like':
$cid = JTable::getInstance('Event','CTable');
$cid->load($activity->eventid);
$urlLink = JUri::root().'index.php?option=com_community&view=events&task=viewevent&eventid='.$cid->id;
$name = $cid->title;
$element = 'COM_COMMUNITY_STREAM_LIKES_ELEMENT_EVENT';
break;
case 'photo.like':
$cid = JTable::getInstance('Photo','CTable');
$cid->load($activity->cid);
$urlLink = JUri::root().'index.php?option=com_community&view=photos&task=photo&albumid='.$cid->albumid.'&userid='.$cid->creator.'&photoid='.$cid->id;
$name = $cid->caption;
$element = 'COM_COMMUNITY_STREAM_LIKES_ELEMENT_PHOTO';
break;
case 'videos.like':
$cid = JTable::getInstance('Video','CTable');
$cid->load($activity->cid);
$urlLink = JURI::root().'index.php?option=com_community&view=videos&task=video&userid='.$cid->creator.'&videoid='.$cid->id;
$name = $cid->getTitle();
$element = 'COM_COMMUNITY_STREAM_LIKES_ELEMENT_VIDEO';
break;
case 'album.like':
$cid = JTable::getInstance('Album','CTable');
$cid->load($activity->cid);
$urlLink = Juri::root().'index.php?option=com_community&view=photos&task=album&albumid='.$cid->id.'&userid='.$cid->creator;
$name = $cid->name;
$element = 'COM_COMMUNITY_STREAM_LIKES_ELEMENT_ALBUM';
break;
}
$slice = 2;
if($userCount > 2)
{
$slice = 1;
}
$users = array_slice($users,0,$slice);
$actorsHTML = array();
foreach($users as $actor)
{
$user = CFactory::getUser($actor);
$actorsHTML[] = '<a class="cStream-Author" target="_blank" href="'. JUri::root().'index.php?option=com_community&view=profile&userid='.$user->id.'">'. $user->getDisplayName().'</a>';
}
$others = '';
if($userCount > 2)
{
$others = JText::sprintf('COM_COMMUNITY_STREAM_OTHERS_JOIN_GROUP' , $userCount-1);
}
$jtext =($userCount>1) ? 'COM_COMMUNITY_STREAM_LIKES_PLURAL' : 'COM_COMMUNITY_STREAM_LIKES_SINGULAR';
$activities[$key]->title = implode( ' '. JText::_('COM_COMMUNITY_AND') . ' ' , $actorsHTML).$others.JText::sprintf($jtext,$urlLink,$name,JText::_($element)) ;
break;
case 'cover.upload':
$user = CFactory::getUser($activity->actor);
$type = $param->get('type');
$extraMessage = '';
if(strtolower($type) !=='profile')
{
$id = strtolower($type.'id');
$cTable = JTable::getInstance(ucfirst($type),'CTable');
$cTable->load($activity->$id);
if($type == 'group')
{
$extraMessage = ', <a target="_blank" href="'.JUri::root().'index.php?option=com_community&view=groups&task=viewgroup&groupid='.$cTable->id.'">'.$cTable->name.'</a>';
}
if($type == 'event')
{
$extraMessage = ', <a target="_blank" href="'.JUri::root().'index.php?option=com_community&view=events&task=viewevent&eventid='.$cTable->id.'">'.$cTable->title.'</a>';
}
}
//$html = '<a class="cStream-Author" target="_blank" href="'.JUri::root().'index.php?option=com_community&view=profile&userid='.$user->id.'">'.$user->getDisplayName().'</a> ';
$html = JText::sprintf('COM_COMMUNITY_PHOTOS_COVER_UPLOAD',Jtext::_('COM_COMMUNITY_COVER_'.strtoupper($type))).$extraMessage;
$activities[$key]->title = $html;
break;
case 'events.attend':
case 'events':
$user = CFactory::getUser($activity->actor);
$action = $param->get('action');
$event = JTable::getInstance('Event', 'CTable');
$event->load($activity->eventid);
switch ($action) {
case 'events.create':
//$html = '<a class="cStream-Author" target="_blank" href="'.JUri::root().'index.php?option=com_community&view=profile&userid='.$user->id.'">'.$user->getDisplayName().'</a> -';
$html = JText::sprintf('COM_COMMUNITY_EVENTS_ACTIVITIES_NEW_EVENT' , JUri::root().'index.php?option=com_community&view=events&task=viewevent&eventid='.$event->id, $event->title);
$activities[$key]->title = $html;
break;
case 'events.attendence.attend':
$users = explode(',',$param->get('actors'));
$actorsHTML = array();
foreach($users as $actor)
{
if (!$actor)
{
$actor = $activity->actor;
}
$user = CFactory::getUser($actor);
$actorsHTML[] = '<a class="cStream-Author" href="'. JUri::root().'index.php?option=com_community&view=profile&userid='.$user->id.'">'. $user->getDisplayName().'</a>';
}
$activities[$key]->title = implode(', ', $actorsHTML) .' - '. JText::sprintf('COM_COMMUNITY_ACTIVITIES_EVENT_ATTEND' , JUri::root().'index.php?option=com_community&view=events&task=viewevent&eventid='.$event->id, $event->title);
break;
}
break;
case 'friends.connect':
$user1 = CFactory::getUser($activity->actor);
$user2 = CFactory::getUser($activity->target);
$html =JText::sprintf('COM_COMMUNITY_STREAM_OTHER_FRIENDS', $user1->getDisplayName(),$user2->getDisplayName(), JUri::root().'index.php?option=com_community&view=profile&userid='.$user1->id, JUri::root().'index.php?option=com_community&view=profile&userid='.$user2->id);
$activities[$key]->title =$html;
break;
case 'groups.bulletin':
$user = CFactory::getUser($activity->actor);
$bulletin = JTable::getInstance('Bulletin', 'CTable');
$bulletin->load($activity->cid);
$group = JTable::getInstance('Group','CTable');
$group->load($bulletin->groupid);
$html = '<a class="cStream-Author" target="_blank" href="' .JUri::root().'index.php?option=com_community&view=profile&userid='.$user->id.'">'.$user->getDisplayName().'</a>'
. JText::sprintf('COM_COMMUNITY_GROUPS_NEW_GROUP_NEWS' , CRoute::_(JUri::root().'index.php?option=com_community&view=groups&task=viewbulletin&groupid=' . $group->id . '&bulletinid=' . $bulletin->id ), $bulletin->title );
$activities[$key]->title =$html;
break;
case 'groups.discussion':
$user = CFactory::getUser($activity->actor);
$discussion = JTable::getInstance('Discussion' , 'CTable' );
$discussion->load($activity->cid);
$discussionLink = CRoute::_(JUri::root().'index.php?option=com_community&view=groups&task=viewdiscussion&groupid=' . $discussion->groupid . '&topicid=' . $discussion->id );
$html = JText::sprintf('COM_COMMUNITY_GROUPS_NEW_GROUP_DISCUSSION' , $discussionLink, $discussion->title ) ;
$activities[$key]->title =$html;
break;
case 'groups.discussion.reply':
$user = CFactory::getUser($activity->actor);
$discussion = JTable::getInstance('Discussion' , 'CTable' );
$discussion->load($activity->cid);
$html = JText::sprintf('COM_COMMUNITY_GROUPS_REPLY_DISCUSSION' , CRoute::_(JUri::root().'index.php?option=com_community&view=groups&task=viewdiscussion&groupid='.$discussion->groupid.'&topicid='.$discussion->id), $discussion->title );
$activities[$key]->title =$html;
break;
case 'groups.join':
$user = CFactory::getUser($activity->actor);
$users = explode(',', $param->get('actors'));
$userCount = count($users);
$group = JTable::getInstance('Group','CTable');
$group->load($activity->cid);
$slice = 2;
if($userCount > 2)
{
$slice = 1;
}
$users = array_slice($users,0,$slice);
$actorsHTML = array();
foreach($users as $actor)
{
$user = CFactory::getUser($actor);
$actorsHTML[] = '<a class="cStream-Author" target="_blank" href="'. JUri::root().'index.php?option=com_community&view=profile&userid='.$user->id.'">'. $user->getDisplayName().'</a>';
}
$others = '';
if($userCount > 2)
{
$others = JText::sprintf('COM_COMMUNITY_STREAM_OTHERS_JOIN_GROUP' , $userCount-1);
}
$html = implode( ' '. JText::_('COM_COMMUNITY_AND') . ' ' , $actorsHTML) . $others . JText::sprintf('COM_COMMUNITY_GROUPS_GROUP_JOIN' , JUri::root().'index.php?option=com_community&view=groups&task=viewgroup&groupid='.$group->id, $group->name);
$activities[$key]->title =$html;
break;
case 'groups.update':
$user = CFactory::getUser($activity->actor);
$group = JTable::getInstance('Group','CTable');
$group->load($activity->cid);
$html = JText::sprintf('COM_COMMUNITY_GROUPS_GROUP_UPDATED' , JUri::root().'index.php?option=com_community&view=groups&task=viewgroup&groupid='.$group->id , $group->name );
$activities[$key]->title =$html;
break;
case 'photos':
$user = CFactory::getUser($activity->actor);
$album = JTable::getInstance( 'Album' , 'CTable' );
$album->load( $activity->cid );
$html = '';
if($activity->groupid)
{
$group = JTable::getInstance( 'Group' , 'CTable' );
$group->load($activity->groupid);
$html .= '<a class="cStream-Reference" target="_blank" href="'.JUri::root().'index.php?option=com_community&view=groups&task=viewgroup&groupid='.$group->id.'">'.$group->name .'</a> -';
}
//$html .= ' <a class="cStream-Author" target="_blank" href="'.JUri::root().'index.php?option=com_community&view=profile&userid='.$user->id.'">'.$user->getDisplayName().'</a>';
$count = $param->get('count', 1);
$url = Juri::root().'index.php?option=com_community&view=photos&task=album&albumid='.$album->id.'&userid='.$user->id;
if(CStringHelper::isPlural($count))
{
$html .= JText::sprintf( 'COM_COMMUNITY_ACTIVITY_PHOTO_UPLOAD_TITLE_MANY' , $count, $url, CStringHelper::escape($album->name) );
}else
{
$html .= JText::sprintf( 'COM_COMMUNITY_ACTIVITY_PHOTO_UPLOAD_TITLE' , $url, CStringHelper::escape($album->name) );;
}
$activities[$key]->title =$html;
break;
case 'photos.comment':
$user = CFactory::getUser($activity->actor);
$wall = JTable::getInstance('Wall', 'CTable');
$wall->load($param->get('wallid'));
$photo = JTable::getInstance('Photo','CTable');
$photo->load($activity->cid);
$url = JUri::root().'index.php?option=com_community&view=photos&task=photo&albumid='.$photo->albumid.'&userid='.$photo->creator.'&photoid='.$photo->id;
$html = JText::sprintf('COM_COMMUNITY_ACTIVITIES_WALL_POST_PHOTO', $url, CStringHelper::escape($photo->caption) );
$activities[$key]->title =$html;
break;
case 'system.message':
case 'system.videos.popular':
case 'system.photos.popular':
case 'system.members.popular':
case 'system.photos.total':
case 'system.groups.popular':
case 'system.members.registered':
$action = $param->get('action');
switch ($action) {
case 'registered_users':
$usersModel = CFactory::getModel( 'user' );
$now = new JDate();
$date = CTimeHelper::getDate();
$users = $usersModel->getLatestMember(10);
$totalRegistered = count($users);
$title = JText::sprintf('COM_COMMUNITY_TOTAL_USERS_REGISTERED_THIS_MONTH_ACTIVITY_TITLE', $totalRegistered , $date->monthToString($now->format('%m')));
$activities[$key]->title = $title;
break;
case 'total_photos':
$photosModel = CFactory::getModel( 'photos' );
$total = $photosModel->getTotalSitePhotos();
$activities[$key]->title = JText::sprintf('COM_COMMUNITY_TOTAL_PHOTOS_ACTIVITY_TITLE', CRoute::_(JURI::root().'index.php?option=com_community&view=photos') ,$total);
break;
case 'top_videos':
$activities[$key]->title = JText::_('COM_COMMUNITY_ACTIVITIES_TOP_VIDEOS');
break;
case 'top_photos':
$activities[$key]->title = JText::_('COM_COMMUNITY_ACTIVITIES_TOP_PHOTOS');
break;
case 'top_users':
$activities[$key]->title = JText::_('COM_COMMUNITY_ACTIVITIES_TOP_MEMBERS');
break;
case 'top_groups':
$groupsModel = $this->getModel('groups');
$activeGroup = $groupsModel->getMostActiveGroup();
if( is_null($activeGroup)) {
$title = JText::_('COM_COMMUNITY_GROUPS_NONE_CREATED');
} else {
$title = JText::sprintf('COM_COMMUNITY_MOST_POPULAR_GROUP_ACTIVITY_TITLE', CRoute::_(JUri::root().'index.php?option=com_community&view=groups&task=viewgroup&groupid='.$activeGroup->id), $activeGroup->name);
}
$activities[$key]->title = $title;
break;
case 'message':
break;
}
break;
case 'videos':
$video = JTable::getInstance('Video','CTable');
$video->load($activity->cid);
$actor = CFactory::getUser($activity->actor);
//$html = self::_getUserLink($activity->actor);
$html = JText::sprintf('COM_COMMUNITY_ACTIVITY_VIDEO_SHARE_TITLE',JUri::root().$video->getViewURI(false),$video->title);
$activities[$key]->title = $html;
break;
case 'videos.featured':
$video = JTable::getInstance('Video','CTable');
$video->load($activity->cid);
$activities[$key]->title =JText::sprintf('COM_COMMUNITY_VIDEOS_IS_FEATURED',''.CStringHelper::escape($video->title).'</a>');
break;
case 'albums.featured':
$album = JTable::getInstance('Album','CTable');
$album->load($activity->cid);
$activities[$key]->title = JText::sprintf('COM_COMMUNITY_ALBUM_IS_FEATURED',''.CStringHelper::escape($album->name).'</a>');
break;
}
$activities[$key]->title = CString::str_ireplace('{target}', self::_getUserLink( $activities[$key]->target ) , $activities[$key]->title);
$activities[$key]->title = preg_replace('/\{multiple\}(.*)\{\/multiple\}/i', '', $activities[$key]->title);
$search = array('{single}','{/single}');
$activities[$key]->title = CString::str_ireplace($search, '', $activities[$key]->title);
$activities[$key]->title = CString::str_ireplace('{actor}', self::_getUserLink( $activities[$key]->actor ) , $activities[$key]->title);
$activities[$key]->title = CString::str_ireplace('{app}', $activities[$key]->app, $activities[$key]->title);
//strip out _QQQ_
$activities[$key]->title = CString::str_ireplace('_QQQ_','', $activities[$key]->title);
preg_match_all("/{(.*?)}/", $activities[$key]->title, $matches, PREG_SET_ORDER);
if(!empty( $matches ))
{
//$params = new CParameter( $row->params );
foreach ($matches as $val)
{
$replaceWith = $param->get($val[1], null);
//if the replacement start with 'index.php', we can CRoute it
if( strpos($replaceWith, 'index.php') === 0){
$replaceWith = JURI::root().$replaceWith;
}
if( !is_null( $replaceWith ) )
{
$activities[$key]->title = CString::str_ireplace($val[0], $replaceWith, $activities[$key]->title);
}
}
}
$activities[$key]->title = preg_replace('/(<a href[^<>]+)>/is', '\\1 target="_blank">', $activities[$key]->title);
}
return $activities;
}
private static function _getUserLink( $id )
{
$user = CFactory::getUser( $id );
return '<a href="' . JURI::root() . 'index.php?option=com_community&view=profile&userid=' . $user->id . '" target="_blank">' . $user->getDisplayName() . '</a>';
}
} | rodrigonegretep/trdv | administrator/components/com_community/libraries/cadminactivity.php | PHP | gpl-2.0 | 19,590 |
/***************************************************************************
* Copyright (C) 2011-2012 by Virginia Tech Real-Time Systems Lab *
* *
* Author(s): *
* - Aaron Lindsay (aaron.lindsay@vt.edu) *
* *
* 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., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
package edu.vt.realtime;
public class ChronosUtil{
/* Make sure libjchronos is loaded so we can access the native methods */
static{
System.loadLibrary("jchronos");
}
public static native void burnCpu(long exec_usec, double slope);
public static native void usleep(long usec);
public static final native void printAbortTime(int tid);
public static final native int gettid();
public static native int getPriority();
/* These set/get the "nice" values */
public static native boolean setPriority(int priority);
public static boolean setLinuxScheduler(LinuxSchedulerType sched, int priority){
return ChronosUtil.setLinuxScheduler(sched.getNativeId(), priority);
}
public static boolean setLinuxScheduler(LinuxSchedulerType sched){
return ChronosUtil.setLinuxScheduler(sched.getNativeId(), sched==LinuxSchedulerType.SCHED_NORMAL?1:0);
}
private static native boolean setLinuxScheduler(int sched, int priority);
public static LinuxSchedulerType getLinuxScheduler() {
return LinuxSchedulerType.typeFromInt(ChronosUtil.chronos_getLinuxScheduler());
}
private static native int chronos_getLinuxScheduler();
public static native boolean setAffinity(int pid, long mask);
public static boolean setAffinity(long mask) {return ChronosUtil.setAffinity(0, mask); }
public static native boolean memoryLock();
public static native boolean memoryUnlock();
}
| longqzh/chronOS_test | libjchronos/source/java/edu/vt/realtime/ChronosUtil.java | Java | gpl-2.0 | 3,005 |
<?php
namespace App\Shell;
//use Cake\Mailer\Email;
use Cake\Network\Email\Email;
use Cake\Console\Shell;
class EmailerShell extends Shell {
public function main() {
$this->loadModel('Comms');
$comms = $this->Comms->find('all')
->select(['Comms.id', 'Comms.dest', 'Comms.subject', 'Comms.body', 'Users.email'])
->contain('Users')
->where([
'OR' =>[
['comms_status_id' => COMM_NEW],
['comms_status_id' => 0] //awkward way to catch incorrect status
]
])
->limit(10)
->toArray();
foreach ($comms as $comm) {
//TODO: correct this unreliable and inflexible way to send emails
Email::deliver(COMPANY_EMAIL, $comm->subject, $comm->body, [
'from' => $comm->user->email,
'transport' => 'default',
'domain' => WEBSITE_DOMAIN
]);
$this->Comms->patchEntity($comm, ['comms_status_id' => COMM_COMPLETED]);
$this->Comms->save($comm);
}
}
}
| esaul314/norn-cms | src/Shell/EmailerShell.php | PHP | gpl-2.0 | 904 |
# encoding: utf-8
from yast import import_module
import_module('UI')
from yast import *
class Heading2Client:
def main(self):
UI.OpenDialog(
VBox(
Heading("This Is a Heading."),
Label("This is a Label."),
PushButton("&OK")
)
)
UI.UserInput()
UI.CloseDialog()
Heading2Client().main()
| yast/yast-python-bindings | examples/Heading2.py | Python | gpl-2.0 | 361 |
<?php
include('../../../config.php');
header('Location: '.$FANNIE_URL.'modules/plugins2.0/WfcHoursTracking/WfcHtSalaryUploadPage.php');
exit;
/*
include('db.php');
$sql = hours_dbconnect();
if (isset($_POST["month"])){
$ids = $_POST['ids'];
$days = $_POST['days'];
$datestamp = $_POST['year']."-".str_pad($_POST['month'],2,'0',STR_PAD_LEFT)."-01";
for ($i=0; $i < count($ids); $i++){
$insQ = "INSERT INTO salaryHours VALUES ($ids[$i],'$datestamp',$days[$i])";
echo $insQ."<br />";
$sql->query($insQ);
}
echo "Salary PTO added";
}
else {
echo "<form action=salaryPTO.php method=post>";
$fetchQ = "select empID,name from employees where department IN (999 ,998)
and deleted=0 order by name";
$fetchR = $sql->query($fetchQ);
echo "<table cellpadding=4 cellspacing=0 border=1>";
echo "<tr><th>Employee</th><th>Days taken</th></tr>";
while($fetchW = $sql->fetch_row($fetchR)){
echo "<tr><td>$fetchW[1]</td>";
echo "<td><input type=text name=days[] size=4 value=0 /></td>";
echo "<input type=hidden name=ids[] value=$fetchW[0] /></tr>";
}
echo "<tr><th>Month</th><th>Year</th></tr>";
echo "<tr><td><select name=month>";
for ($i=1;$i<=12;$i++){
$stamp = mktime(0,0,0,$i,1);
$mname = date('F',$stamp);
echo "<option value=$i>$mname</option>";
}
echo "</select></td><td>";
echo "<input type=text size=4 name=year value=".date("Y")." /></td></tr>";
echo "</table>";
echo "<br />";
echo "<input type=submit value=Submit />";
echo "</form>";
}
?>
*/
| joelbrock/PFC_CORE | fannie/legacy/it/hours/salaryPTO.php | PHP | gpl-2.0 | 1,482 |
/*
* Player - One Hell of a Robot Server
* Copyright (C) 2007
* Radu Bogdan Rusu (rusu@cs.tum.edu)
*
* This library 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 2.1 of the License, or (at your option) any later version.
*
* This library 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 library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/*
Desc: Driver for the SICK RFI341 (Radio Frequency Interrogator) unit
Author: Nico Blodow and Radu Bogdan Rusu
Date: 9 Mar 2007
CVS: $Id: sickrfi341.cc 7204 2008-12-18 19:09:01Z thjc $
*/
/** @ingroup drivers */
/** @{ */
/** @defgroup driver_sickrfi341 sickrfi341
* @brief SICK RFI341 RFID reader
The sickrfi341 driver controls the SICK RFI341 RFID reader (13.56Mhz).
@par Compile-time dependencies
- none
@par Provides
- @ref interface_rfid
@par Requires
- none
@par Configuration requests
- none
@par Configuration file options
- port (string)
- Default: "/dev/ttyS0"
- Serial port to which the SICK RFI341 reader is attached. If you are
using a USB/232 or USB/422 converter, this will be "/dev/ttyUSBx".
- connect_rate (integer)
- Default: 9600.
- Rate at which we connect to the RFID unit. Valid values are 1200, 2400,
4800, 9600, 19200, 38400, 57600 and 115200.
- transfer_rate (integer)
- Default: 9600.
- Rate at which we want to transfer data from the RFID unit. Valid values
are 1200, 2400, 4800, 9600, 19200, 38400, 57600 and 115200.
- debug (integer)
- Default: 0
- Print additional debug informations on screen. Valid values are 0 and 1.
@par Example
@verbatim
driver
(
name "skyetekM1"
provides ["rfid:0"]
port "/dev/ttyS0"
connect_rate 9600
transfer_rate 38400
)
@endverbatim
@author Radu Bogdan Rusu
*/
/** @} */
#include "rfi341_protocol.h"
#include <libplayercore/playercore.h>
#include <libplayerxdr/playerxdr.h>
#define DEFAULT_RFI341_PORT "/dev/ttyS0"
#define DEFAULT_RFI341_RATE 9600
// The SICK RFI 341 device class.
class SickRFI341 : public Driver
{
public:
// Constructor/Destructor
SickRFI341 (ConfigFile* cf, int section);
~SickRFI341 ();
int Setup ();
int Shutdown ();
// MessageHandler
int ProcessMessage (QueuePointer &resp_queue,
player_msghdr* hdr,
void* data);
private:
// Main function for device thread.
virtual void Main ();
// Reference to rfi341_protocol
rfi341_protocol* rfi341;
// connection parameters
const char* portName;
int connect_rate;
int transfer_rate;
int current_rate;
int debug;
};
////////////////////////////////////////////////////////////////////////////////
// Constructor. Retrieve options from the configuration file and do any
// pre-Setup() setup.
SickRFI341::SickRFI341 (ConfigFile* cf, int section)
: Driver (cf, section, true,
PLAYER_MSGQUEUE_DEFAULT_MAXLEN, PLAYER_RFID_CODE)
{
// Read connection settings
portName = cf->ReadString (section, "port", DEFAULT_RFI341_PORT);
connect_rate = cf->ReadInt (section, "connect_rate", DEFAULT_RFI341_RATE);
transfer_rate = cf->ReadInt (section, "transfer_rate", DEFAULT_RFI341_RATE);
current_rate = 0;
debug = cf->ReadInt (section, "debug", 0);
}
////////////////////////////////////////////////////////////////////////////////
// Destructor.
SickRFI341::~SickRFI341 ()
{
}
////////////////////////////////////////////////////////////////////////////////
// Set up the device. Return 0 if things go well, and -1 otherwise.
int
SickRFI341::Setup ()
{
// Create a rfi341_protocol object
rfi341 = new rfi341_protocol (portName, debug);
// Attempt to connect to the rfid unit
if (rfi341->Connect (connect_rate) != 0)
return (-1);
current_rate = connect_rate;
if (connect_rate != transfer_rate)
{
// Attempt to connect to the rfid unit
if (rfi341->SetupSensor (transfer_rate) != 0)
return (-1);
else
current_rate = transfer_rate;
}
// Start the device thread
StartThread ();
return (0);
}
////////////////////////////////////////////////////////////////////////////////
// Shutdown the device
int
SickRFI341::Shutdown ()
{
// shutdown rfid device
StopThread ();
// Change back to the original speed
if (current_rate != connect_rate)
rfi341->SetupSensor (connect_rate);
// Disconnect from the rfid unit
rfi341->Disconnect ();
PLAYER_MSG0 (1, "> SICK RFI341 driver shutting down... [done]");
return (0);
}
////////////////////////////////////////////////////////////////////////////////
// ProcessMessage
int
SickRFI341::ProcessMessage (QueuePointer &resp_queue,
player_msghdr* hdr,
void* data)
{
return (-1);
}
////////////////////////////////////////////////////////////////////////////////
// Main function for device thread
void
SickRFI341::Main ()
{
timespec sleepTime = {0, 0};
while (true)
{
// test if we are supposed to cancel
pthread_testcancel ();
// Request/replies handler
ProcessMessages ();
player_rfid_data_t data = rfi341->ReadTags ();
// Make data available
Publish (device_addr, PLAYER_MSGTYPE_DATA, PLAYER_RFID_DATA_TAGS,
&data, sizeof (data), NULL);
player_rfid_data_t_cleanup(&data);
nanosleep (&sleepTime, NULL);
}
}
////////////////////////////////////////////////////////////////////////////////
// Factory creation function. This functions is given as an argument when the
// driver is added to the driver table
Driver*
SickRFI341_Init (ConfigFile* cf, int section)
{
return ((Driver*)(new SickRFI341 (cf, section)));
}
////////////////////////////////////////////////////////////////////////////////
// Registers the driver in the driver table. Called from the player_driver_init
// function that the loader looks for
void
SickRFI341_Register (DriverTable* table)
{
table->AddDriver ("sickrfi341", SickRFI341_Init);
}
| uml-robotics/player-2.1.3 | server/drivers/rfid/sickrfi341.cc | C++ | gpl-2.0 | 6,461 |
package starrealmssimulator.cards.ships.machinecult;
import starrealmssimulator.model.*;
public class PatrolBot extends Ship implements AlliableCard
{
public PatrolBot()
{
name = "Patrol Bot";
faction = Faction.MACHINE_CULT;
cost = 2;
set = CardSet.CRISIS_FLEETS_AND_FORTRESSES;
text = "Add 2 Trade OR Add 4 Combat; Ally: You may scrap a card in your hand or discard pile";
}
@Override
public void cardPlayed(Player player) {
Choice choice1 = new Choice(1, "Add 2 Trade");
Choice choice2 = new Choice(2, "Add 4 Combat");
player.makeChoice(this, choice1, choice2);
}
@Override
public void choiceMade(int choice, Player player) {
player.getGame().gameLog("Chose Add 2 Trade");
if (choice == 1) {
player.addTrade(2);
} else if (choice == 2) {
player.getGame().gameLog("Chose Add 4 Combat");
player.addCombat(4);
}
}
@Override
public void cardAllied(Player player) {
player.scrapCardFromHandOrDiscard();
}
}
| icesphere/star-realms-simulator | src/starrealmssimulator/cards/ships/machinecult/PatrolBot.java | Java | gpl-2.0 | 1,098 |
package es.javiergarciaescobedo.addressbookdroid.models;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Persons {
public static List<Person> personList = new ArrayList();
public static Map<String, Person> ITEM_MAP = new HashMap<String, Person>();
/**
* Load a little number of persons in the list, with only a few properties filled
*/
public static void loadSimpleSamples() {
Person person = new Person();
person = new Person();
person.setId(1);
person.setName("EVA MARIA");
person.setSurnames("HURTADO REQUENA");
person.setAlias("EVA");
person.setPhoneNumber("956290949");
person.setFavorite(true);
person.setEmail("eva.hurtado@server.com");
person.setAddress("CLAVILEÑO , CALLE");
person.setPostCode("11659");
person.setCity("PUERTO SERRANO");
person.setProvince("CÁDIZ");
personList.add(person);
ITEM_MAP.put(String.valueOf(person.getId()), person);
person = new Person();
person.setId(2);
person.setName("CARLOS DOMINGO DE GUZMAN");
person.setSurnames("BLANCO PEREZ");
person.setAlias("CARLOS");
person.setPhoneNumber("956125889");
person.setFavorite(false);
person.setEmail("carlos.blanco@server.com");
person.setAddress("PERU , CALLE");
person.setPostCode("11611");
person.setCity("VILLALUENGA DEL ROSARIO");
person.setProvince("CÁDIZ");
personList.add(person);
ITEM_MAP.put(String.valueOf(person.getId()), person);
person = new Person();
person.setId(3);
person.setName("ANTONIO ENRIQUE");
person.setSurnames("FUENTE DE LA SANDE\n");
person.setAlias("ANTONIO");
person.setPhoneNumber("956222472");
person.setFavorite(true);
person.setEmail("antonio.fuente@server.com");
person.setAddress("PORTERIA DE STO.DOMINGO , CALLE");
person.setPostCode("11600");
person.setCity("UBRIQUE");
person.setProvince("CÁDIZ");
personList.add(person);
ITEM_MAP.put(String.valueOf(person.getId()), person);
}
}
| javiergarciaescobedo/AddressBookDroid | app/src/main/java/es/javiergarciaescobedo/addressbookdroid/models/Persons.java | Java | gpl-2.0 | 2,252 |
<?php
/**
* @file
* Handles all FB integration to Authorize and to Post
*/
_load_facebook_sdk();
/**
* API class to handle common actions when autoposting
* This class uses ErrorException for error handling. Severity is
* passed resusing watchdog severity (See: http://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/watchdog/7)
* @see https://developers.facebook.com/docs/howtos/login/server-side-login
*/
class FBAutopost extends Facebook {
/**
* Constant indicating error code for a missing parameter
*/
const missing_param = 0;
/**
* Constant indicating error code for an icorrect parameter
*/
const incorrect_param = 1;
/**
* Constant indicating error code for a missing dependency
*/
const missing_dependency = 2;
/**
* Constant indicating error code for a SDK thrown error
*/
const sdk_error = 3;
/**
* Publication types as defined in Facebook documentation
* Contains the name of the publication and the endpoint keyed by the machine name of the publication.
* @see https://developers.facebook.com/docs/reference/api/page
*/
private $publication_types = array(
'event' => array(
'name' => 'Event',
'endpoint' => 'events',
),
'link' => array(
'name' => 'Links',
'endpoint' => 'feed',
),
'note' => array(
'name' => 'Note',
'endpoint' => 'notes',
),
'photo' => array(
'name' => 'Photo',
'endpoint' => 'photos',
),
'post' => array(
'name' => 'Post',
'endpoint' => 'feed',
),
'question' => array(
'name' => 'Question',
'endpoint' => 'questions',
),
'milestone' => array(
'name' => 'Milestone',
'endpoint' => 'milestones',
),
'offer' => array(
'name' => 'Offer',
'endpoint' => 'offers',
),
'message' => array(
'name' => 'Message',
'endpoint' => 'conversations',
),
'status' => array(
'name' => 'Status',
'endpoint' => 'feed',
),
'video' => array(
'name' => 'Video',
'endpoint' => 'videos',
),
'tab' => array(
'name' => 'Tab',
'endpoint' => 'tabs',
),
);
/**
* Gets the endpoint of a publication
*
* @return string
* String containing the endpoint
*/
protected function getEndpoint() {
return $this->publication_types[$this->getType()]['endpoint'];
}
/**
* Destination for the publication. An string with the page ID or 'me'.
*/
private $destination;
/**
* Privacy setting for the publications. This property is made public because
* the getter method will give some formatting along with the property.
*/
public $privacy;
/**
* Stored publication type.
*/
private $type;
/**
* Boolean indicating wether to retry the publication or not when publishing
* on the user's timeline if the acting user does not have a valid access
* token.
*/
private $retry;
function __construct($conf = array()) {
if (!isset($conf['appId'])) {
$conf['appId'] = variable_get('fb_autopost_app_id', '');
}
if (!isset($conf['secret'])) {
$conf['secret'] = variable_get('fb_autopost_app_secret', '');
}
$this->destination = NULL;
$this->retry = TRUE;
// Delete any previously saved publication in the session.
$this->getSession()->removePublication();
parent::__construct($conf);
}
/**
* Publishes content in the selected pages
* @param $publication
* Keyed array containing the info for the publication. Must contain the
* keys:
* - 'type': The publication type as defined in $publication_types
* - 'params': Associative array with the necessary params for a
* successful FB publication
* @param string $page_id
* Page id (among those already selected via UI).
* If this is present it will override the parameter destination.
* Use 'me' to publish to the user's timeline
* @return
* Facebook id string for the publication. Needed to edit, or delete the publication.
* @throws ErrorException
*/
function publish($publication, string $page_id = NULL) {
// $page_id parameter for backwards compatibility
if (!is_null($page_id)) {
$this->setDestination($page_id);
}
$page_id = $this->getDestination();
// Override publication type if it's present in th$e publication array.
if (!empty($publication['type'])) {
try {
$this->setType($publication['type']);
}
catch (ErrorException $e) {}
}
if (empty($this->type)) {
throw new ErrorException(t('The publication array must contain publication type.'), FBAutopost::missing_param, WATCHDOG_ERROR);;
}
// Error generation
if (!isset($publication['params'])) {
throw new ErrorException(t('The publication array must contain publication parameters.'), FBAutopost::missing_param, WATCHDOG_ERROR);
}
$this->checkPagesAvailability();
// Now we can start the publication.
try {
return $this->publishOn($publication);
}
catch (FacebookApiException $e) {
if ($this->getRetry()) {
$session = $this->getSession();
// If trying to publish on timeline for the first time
if ($page_id == 'me' && !$session->isStored()) {
// Here we can handle the unauthorized user error
// To do so we save the relevant data in $_SESSION, then redirect to
// Facebook athorization URL. This URL redirects back to a fixed
// location that handles the publishing and redirects back to the
// original location
$publication['type'] = $this->getType();
$session->storePublication($publication);
$login_url = $this->getLoginUrl(array(
'scope' => 'publish_stream',
'redirect_uri' => url('fbautopost/authorization/retry', array('absolute' => TRUE)),
));
// Redirect the user token the login URL that will redirect back to
// the retry URI.
// Remove the destination parameter, this is bad for redirections
// outside Drupal.
if (isset($_GET['destination'])) {
unset($_GET['destination']);
}
drupal_goto($login_url);
// Since there is a redirection the return statement is never
// executed. Its presence is only for code clarity.
return NULL;
}
}
// Throw an exception
throw new ErrorException(t('Facebook SDK threw an error: %error', array('%error' => $e)), FBAutopost::sdk_error, WATCHDOG_ERROR);
}
}
/**
* Publishes on a single destination.
*
* @param string $publication
* The publication as described in FBAutopost::publish()
*
* @see FBAutopost::publish()
* @throws FacebookApiException
*/
protected function publishOn($publication) {
$this->publishParameterPrepare(&$publication);
// Call api method from ancestor.
return $this->api(
// Post to destination on the selected endpoint.
'/' . $this->getDestination() . '/' . $this->getEndpoint(),
// This is fixed.
'POST',
// Add access token to the params.
$publication['params']
);
}
/**
* Prepares the parameters to publish to Facebook, this means settings any
* field or destination dependent configuration.
*/
protected function publishParameterPrepare(&$publication) {
$destination = $this->getDestination();
if ($destination != 'me') {
$pages = self::getPagesAccessTokens(variable_get('fb_autopost_account_id', 'me'), variable_get('fb_autopost_token', ''));
$publication['params'] += array('access_token' => $pages[$destination]['access_token']);
}
else {
// Privacy only makes sense when publishing to timeline
if ($p = $this->getPrivacy()) {
$publication['params'] += array('privacy' => $p);
}
}
}
/**
* Get access tokens for publishing to several Facebook Pages
*
* @param $account_id
* User account asked for
* @param $account_access_token
* Server side access token stored from the admin form.
* @return
* A keyed array indexed by page id and containing the values:
* - 'id': Facebook page id
* - 'access_token': Access token for publishing to the page
* @throws ErrorException
*/
private static function getPagesAccessTokens($account_id, $account_access_token) {
$pages = array();
foreach (variable_get('fb_autopost_pages_access_tokens', array()) as $page_id => $page_access_token) {
$pages[$page_id] = array(
'id' => $page_id,
'access_token' => $page_access_token,
);
}
return $pages;
}
/**
* Gets the reply given from Facebook when asking for user account.
* @param $account_id
* User account asked for
* @param $account_access_token
* Server side access token stored from the admin form.
* @return
* The array from the Graph API call
* @throws ErrorException
*/
public function getPagesData($account_id, $account_access_token) {
// Check if there is an access_token available.
if (empty($account_access_token)) {
throw new ErrorException(t('Cannot ask for user accounts without an access token.'), FBAutopost::missing_param, WATCHDOG_ERROR);
}
try {
return $this->api('/' . $account_id . '/accounts', 'GET', array(
'limit' => 999,
));
} catch (FacebookApiException $e) {
// Get the FacebookApiException and throw an ordinary ErrorException
throw new ErrorException(t('Facebook SDK threw an error: %error It is possible that your Facebook account cannot access the configured pages, if so please log in again in !url.', array('%error' => $e, '!url' => l(t('Facebook autopost configuration page'), 'admin/config/services/fbautopost'))), FBAutopost::sdk_error, WATCHDOG_ERROR);
}
}
/**
* Set the destination to publish to
*
* @param $destination
* @return
* Returns itsef for chainable code.
*/
public function setDestination($destination) {
$this->destination = $destination;
return $this;
}
/**
* Gets the destination to publish to
*
* @return
* The destination parameter
*/
public function getDestination() {
return $this->destination;
}
/**
* Deletes a publication from Facebook
*
* @param $publication_id
* The id that identifies the publication in Facebook
* @throws FacebookApiException
*/
public function remoteDelete($publication_id) {
// TODO: Add a remoetDelete callback to the entity delete (optional)
$this->api('/' . $publication_id, 'DELETE');
// If request fails then an exception is thrown and there is no return value
return TRUE;
}
/**
* Edits a publication from Facebook
*
* @param $publication
* Keyed array containing the info for the publication. Must contain the
* keys:
* - 'type': The publication type as defined in $publication_types
* - 'params': Associative array with the necessary params for a
* successful FB publication
* @param $publication_id
* The id that identifies the publication in Facebook
*/
public function remoteEdit($publication, $publication_id) {
// In this case, edit means delete + publish. This has the side effect that
// the ID is not preserved.
if ($this->remoteDelete($publication)) {
return $this->publish($publication);
}
}
/**
* Gets the session object for sugar syntax. Factory method.
*
* @return FBSession
*/
public function getSession() {
return new FBSession();
}
/**
* Sets the privacy.
*
* @param string $privacy_code
* Privacy string as defined in Facebook documentation. Allowed values are:
* - EVERYONE
* - ALL_FRIENDS
* - FRIENDS_OF_FRIENDS
* - SELF
* @return
* Returns itself.
* @throws ErrorException
* @see https://developers.facebook.com/docs/reference/api/privacy-parameter
*/
public function setPrivacy($privacy_code) {
if (!in_array($privacy_code, array('ALL_FRIENDS', 'EVERYONE', 'SELF', 'FRIENDS_OF_FRIENDS'))) {
throw new ErrorException(t('The privacy code you specified is invalid.'), FBAutopost::incorrect_param, WATCHDOG_ERROR);
}
$this->privacy = $privacy_code;
return $this;
}
/**
* Gets the privacy value.
*
* @return string
* The privacy array formatted as array('value' => 'ALL_FRIENDS') …
* @see https://developers.facebook.com/docs/reference/api/privacy-parameter/
* @todo Better handling of the privacy
*/
public function getPrivacy() {
return isset($this->privacy) ? array('value' => $this->privacy) : NULL;
}
/**
* Sets the type value.
*
* @param string $type
* The type as defined in FBAutopost::types.
*
* @return FBAutopost
* Returns itself
*/
public function setType($type) {
if (!in_array($type, array_keys($this->publication_types))) {
throw new ErrorException(t('The publication type you specified is invalid.'), FBAutopost::incorrect_param, WATCHDOG_ERROR);
}
$this->type = $type;
return $this;
}
/**
* Gets the publication type.
*
* @return string
* The publication type.
*/
protected function getType() {
return $this->type;
}
/**
* Throws an exception if the selected page id is not among the authorized
* ones.
*/
private function checkPagesAvailability() {
$page_id = $this->getDestination();
// Get fresh access tokens for the pages. We use the server side access
// token and the account ID to retrieve them
$pages = self::getPagesAccessTokens(variable_get('fb_autopost_account_id', 'me'), variable_get('fb_autopost_token', ''));
// Check that the selected page is in the available list.
if (!in_array($page_id, array_keys($pages)) && $page_id != 'me') {
throw new ErrorException(t('Insufficient permissions to publish on page with id @id. Please check !config.', array('@id' => $page_id, '!config' => l(t('your configuration'), 'admin/config/services/fbautopost'))), FBAutopost::incorrect_param, WATCHDOG_ERROR);
}
}
/**
* Checks if a user has an active access token.
*
* @return boolean
* TRUE if the user may publish to the timeline.
*/
public function hasActiveAccessToken() {
$access_token = FALSE;
foreach ($_SESSION as $key => $value) {
if (preg_match("/fb_\d+_access_token/", $key)) {
$access_token = $value;
break;
}
}
// This is to make sure the access token is not gotten from the app.
return $this->getAccessToken() == $access_token;
}
/**
* Sets the retry value.
*
* @param boolean $retry
* Boolean indicating if the publication in the timeline must be retried.
*
* @return FBAutopost
* Returns itself
*/
public function setRetry($retry) {
$this->retry = $retry;
return $this;
}
/**
* Gets the publication type.
*
* @return boolean
* The retry settings.
*/
protected function getRetry() {
return $this->retry;
}
}
| joshbg2k/shoofly-web | sites/all/modules/fb_autopost/class/FBAutopost.php | PHP | gpl-2.0 | 15,239 |
package org.dei.perla.lang.executor;
import org.dei.perla.lang.executor.statement.QueryHandler;
/**
* @author Guido Rota 13/04/15.
*/
public class NoopQueryHandler
implements QueryHandler<Object, Object[]> {
@Override
public void error(Object source, Throwable error) { }
@Override
public void data(Object source, Object[] value) { }
}
| perlawsn/language | src/test/java/org/dei/perla/lang/executor/NoopQueryHandler.java | Java | gpl-2.0 | 367 |
###############################################################################
# #
# Copyright 2019. Triad National Security, LLC. All rights reserved. #
# This program was produced under U.S. Government contract 89233218CNA000001 #
# for Los Alamos National Laboratory (LANL), which is operated by Triad #
# National Security, LLC for the U.S. Department of Energy/National Nuclear #
# Security Administration. #
# #
# All rights in the program are reserved by Triad National Security, LLC, and #
# the U.S. Department of Energy/National Nuclear Security Administration. The #
# Government is granted for itself and others acting on its behalf a #
# nonexclusive, paid-up, irrevocable worldwide license in this material to #
# reproduce, prepare derivative works, distribute copies to the public, #
# perform publicly and display publicly, and to permit others to do so. #
# #
###############################################################################
'''
Created on 2015/07/01
@author: Eric Ball
@change: 2015/12/07 eball Added information about REMOVEX CI to help text
@change: 2016/07/06 eball Separated fix into discrete methods
@change: 2017/06/02 bgonz12 - Change a conditional in reportUbuntu to search for
"manual" using regex instead of direct comparison
@change 2017/08/28 rsn Fixing to use new help text methods
@change: 2017/10/23 rsn - change to new service helper interface
@change: 2017/11/14 bgonz12 - Fix removeX dependency issue for deb systems
'''
import os
import re
import traceback
from KVEditorStonix import KVEditorStonix
from logdispatcher import LogPriority
from pkghelper import Pkghelper
from rule import Rule
from CommandHelper import CommandHelper
from ServiceHelper import ServiceHelper
from stonixutilityfunctions import iterate, readFile, writeFile, createFile
from stonixutilityfunctions import resetsecon
class DisableGUILogon(Rule):
def __init__(self, config, environ, logger, statechglogger):
Rule.__init__(self, config, environ, logger, statechglogger)
self.logger = logger
self.rulenumber = 105
self.rulename = "DisableGUILogon"
self.formatDetailedResults("initialize")
self.mandatory = False
self.applicable = {'type': 'white',
'family': ['linux']}
# Configuration item instantiation
datatype = "bool"
key = "DISABLEX"
instructions = "To enable this item, set the value of DISABLEX " + \
"to True. When enabled, this rule will disable the automatic " + \
"GUI login, and the system will instead boot to the console " + \
"(runlevel 3). This will not remove any GUI components, and the " + \
"GUI can still be started using the \"startx\" command."
default = False
self.ci1 = self.initCi(datatype, key, instructions, default)
datatype = "bool"
key = "LOCKDOWNX"
instructions = "To enable this item, set the value of LOCKDOWNX " + \
"to True. When enabled, this item will help secure X Windows by " + \
"disabling the X Font Server (xfs) service and disabling X " + \
"Window System Listening. This item should be enabled if X " + \
"Windows is disabled but will be occasionally started via " + \
"startx, unless there is a mission-critical need for xfs or " + \
"a remote display."
default = False
self.ci2 = self.initCi(datatype, key, instructions, default)
datatype = "bool"
key = "REMOVEX"
instructions = "To enable this item, set the value of REMOVEX " + \
"to True. When enabled, this item will COMPLETELY remove X " + \
"Windows from the system, and on most platforms will disable " + \
"any currently running display manager. It is therefore " + \
"recommended that this rule be run from a console session " + \
"rather than from the GUI.\nREMOVEX cannot be undone."
default = False
self.ci3 = self.initCi(datatype, key, instructions, default)
self.guidance = ["NSA 3.6.1.1", "NSA 3.6.1.2", "NSA 3.6.1.3",
"CCE 4462-8", "CCE 4422-2", "CCE 4448-7",
"CCE 4074-1"]
self.iditerator = 0
self.ph = Pkghelper(self.logger, self.environ)
self.ch = CommandHelper(self.logger)
self.sh = ServiceHelper(self.environ, self.logger)
self.myos = self.environ.getostype().lower()
self.sethelptext()
def report(self):
'''@author: Eric Ball
:param self: essential if you override this definition
:returns: bool - True if system is compliant, False if it isn't
'''
try:
compliant = True
results = ""
if os.path.exists("/bin/systemctl"):
self.initver = "systemd"
compliant, results = self.reportSystemd()
elif re.search("debian", self.myos):
self.initver = "debian"
compliant, results = self.reportDebian()
elif re.search("ubuntu", self.myos):
self.initver = "ubuntu"
compliant, results = self.reportUbuntu()
else:
self.initver = "inittab"
compliant, results = self.reportInittab()
# NSA guidance specifies disabling of X Font Server (xfs),
# however, this guidance seems to be obsolete as of RHEL 6,
# and does not apply to the Debian family.
if self.sh.auditService("xfs", _="_"):
compliant = False
results += "xfs is currently enabled\n"
xremoved = True
self.xservSecure = True
if re.search("debian|ubuntu", self.myos):
if self.ph.check("xserver-xorg-core"):
compliant = False
xremoved = False
results += "Core X11 components are present\n"
elif re.search("opensuse", self.myos):
if self.ph.check("xorg-x11-server"):
compliant = False
xremoved = False
results += "Core X11 components are present\n"
else:
if self.ph.check("xorg-x11-server-Xorg"):
compliant = False
xremoved = False
results += "Core X11 components are present\n"
# Removing X will take xserverrc with it. If X is not present, we
# do not need to check for xserverrc
if not xremoved:
self.serverrc = "/etc/X11/xinit/xserverrc"
self.xservSecure = False
if os.path.exists(self.serverrc):
serverrcText = readFile(self.serverrc, self.logger)
if re.search("opensuse", self.myos):
for line in serverrcText:
reSearch = r'exec (/usr/bin/)?X \$dspnum.*\$args'
if re.search(reSearch, line):
self.xservSecure = True
break
else:
for line in serverrcText:
reSearch = r'^exec (/usr/bin/)?X (:0 )?-nolisten tcp ("$@"|.?\$@)'
if re.search(reSearch, line):
self.xservSecure = True
break
if not self.xservSecure:
compliant = False
results += self.serverrc + " does not contain proper " \
+ "settings to disable X Window System " + \
"Listening/remote display\n"
else:
compliant = False
results += self.serverrc + " does not exist; X Window " + \
"System Listening/remote display has not " + \
"been disabled\n"
self.detailedresults = results
self.compliant = compliant
except (KeyboardInterrupt, SystemExit):
raise
except Exception:
self.rulesuccess = False
self.detailedresults = "\n" + traceback.format_exc()
self.logger.log(LogPriority.ERROR, self.detailedresults)
self.formatDetailedResults("report", self.compliant,
self.detailedresults)
self.logger.log(LogPriority.INFO, self.detailedresults)
return self.compliant
def reportInittab(self):
compliant = False
results = ""
inittab = "/etc/inittab"
if os.path.exists(inittab):
initData = readFile(inittab, self.logger)
for line in initData:
if line.strip() == "id:3:initdefault:":
compliant = True
break
else:
self.logger.log(LogPriority.ERROR, inittab + " not found, init " +
"system unknown")
if not compliant:
results = "inittab not set to runlevel 3; GUI logon is enabled\n"
return compliant, results
def reportSystemd(self):
compliant = True
results = ""
cmd = ["/bin/systemctl", "get-default"]
self.ch.executeCommand(cmd)
defaultTarget = self.ch.getOutputString()
if not re.search("multi-user.target", defaultTarget):
compliant = False
results = "systemd default target is not multi-user.target; " + \
"GUI logon is enabled\n"
return compliant, results
def reportDebian(self):
compliant = True
results = ""
dmlist = ["gdm", "gdm3", "lightdm", "xdm", "kdm"]
for dm in dmlist:
if self.sh.auditService(dm, _="_"):
compliant = False
results = dm + \
" is still in init folders; GUI logon is enabled\n"
return compliant, results
def reportUbuntu(self):
compliant = True
results = ""
ldmover = "/etc/init/lightdm.override"
grub = "/etc/default/grub"
if os.path.exists(ldmover):
lightdmText = readFile(ldmover, self.logger)
if not re.search("manual", lightdmText[0], re.IGNORECASE):
compliant = False
results += ldmover + ' exists, but does not contain text ' + \
'"manual". GUI logon is still enabled\n'
else:
compliant = False
results += ldmover + " does not exist; GUI logon is enabled\n"
if os.path.exists(grub):
tmppath = grub + ".tmp"
data = {"GRUB_CMDLINE_LINUX_DEFAULT": '"quiet"'}
editor = KVEditorStonix(self.statechglogger, self.logger, "conf",
grub, tmppath, data, "present", "closedeq")
if not editor.report():
compliant = False
results += grub + " does not contain the correct values: " + \
str(data)
else:
compliant = False
results += "Cannot find file " + grub
if not compliant:
results += "/etc/init does not contain proper override file " + \
"for lightdm; GUI logon is enabled\n"
return compliant, results
def fix(self):
'''@author: Eric Ball
:param self: essential if you override this definition
:returns: bool - True if fix is successful, False if it isn't
'''
try:
if not self.ci1.getcurrvalue() and not self.ci2.getcurrvalue() \
and not self.ci3.getcurrvalue():
return
success = True
self.detailedresults = ""
# Delete past state change records from previous fix
self.iditerator = 0
eventlist = self.statechglogger.findrulechanges(self.rulenumber)
for event in eventlist:
self.statechglogger.deleteentry(event)
# If we are doing DISABLEX or REMOVEX, we want to boot to
# non-graphical multi-user mode.
if self.ci1.getcurrvalue() or self.ci3.getcurrvalue():
success &= self.fixBootMode()
# Since LOCKDOWNX depends on having X installed, and REMOVEX
# completely removes X from the system, LOCKDOWNX fix will only be
# executed if REMOVEX is not.
if self.ci3.getcurrvalue():
success &= self.fixRemoveX()
elif self.ci2.getcurrvalue():
success &= self.fixLockdownX()
self.rulesuccess = success
except (KeyboardInterrupt, SystemExit):
# User initiated exit
raise
except Exception:
self.rulesuccess = False
self.detailedresults += "\n" + traceback.format_exc()
self.logdispatch.log(LogPriority.ERROR, self.detailedresults)
self.formatDetailedResults("fix", self.rulesuccess,
self.detailedresults)
self.logdispatch.log(LogPriority.INFO, self.detailedresults)
return self.rulesuccess
def fixBootMode(self):
success = True
if self.initver == "systemd":
cmd = ["/bin/systemctl", "set-default",
"multi-user.target"]
if not self.ch.executeCommand(cmd):
success = False
self.detailedresults += '"systemctl set-default ' \
+ 'multi-user.target" did not succeed\n'
else:
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
commandstring = "/bin/systemctl set-default " + \
"graphical.target"
event = {"eventtype": "commandstring",
"command": commandstring}
self.statechglogger.recordchgevent(myid, event)
elif self.initver == "debian":
dmlist = ["gdm", "gdm3", "lightdm", "xdm", "kdm"]
for dm in dmlist:
cmd = ["update-rc.d", "-f", dm, "disable"]
if not self.ch.executeCommand(cmd):
self.detailedresults += "Failed to disable desktop " + \
"manager " + dm
else:
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
event = {"eventtype": "servicehelper",
"servicename": dm,
"startstate": "enabled",
"endstate": "disabled"}
self.statechglogger.recordchgevent(myid, event)
elif self.initver == "ubuntu":
ldmover = "/etc/init/lightdm.override"
tmpfile = ldmover + ".tmp"
created = False
if not os.path.exists(ldmover):
createFile(ldmover, self.logger)
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
event = {"eventtype": "creation", "filepath": ldmover}
self.statechglogger.recordchgevent(myid, event)
created = True
writeFile(tmpfile, "manual\n", self.logger)
if not created:
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
event = {"eventtype": "conf", "filepath": ldmover}
self.statechglogger.recordchgevent(myid, event)
self.statechglogger.recordfilechange(ldmover, tmpfile, myid)
os.rename(tmpfile, ldmover)
resetsecon(ldmover)
grub = "/etc/default/grub"
if not os.path.exists(grub):
createFile(grub, self.logger)
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
event = {"eventtype": "creation", "filepath": grub}
self.statechglogger.recordchgevent(myid, event)
tmppath = grub + ".tmp"
data = {"GRUB_CMDLINE_LINUX_DEFAULT": '"quiet"'}
editor = KVEditorStonix(self.statechglogger, self.logger,
"conf", grub, tmppath, data,
"present", "closedeq")
editor.report()
if editor.fixables:
if editor.fix():
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
editor.setEventID(myid)
debug = "kveditor fix ran successfully\n"
self.logger.log(LogPriority.DEBUG, debug)
if editor.commit():
debug = "kveditor commit ran successfully\n"
self.logger.log(LogPriority.DEBUG, debug)
else:
error = "kveditor commit did not run " + \
"successfully\n"
self.logger.log(LogPriority.ERROR, error)
success = False
else:
error = "kveditor fix did not run successfully\n"
self.logger.log(LogPriority.ERROR, error)
success = False
cmd = "update-grub"
self.ch.executeCommand(cmd)
else:
inittab = "/etc/inittab"
tmpfile = inittab + ".tmp"
if os.path.exists(inittab):
initText = open(inittab, "r").read()
initre = r"id:\d:initdefault:"
if re.search(initre, initText):
initText = re.sub(initre, "id:3:initdefault:",
initText)
writeFile(tmpfile, initText, self.logger)
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
event = {"eventtype": "conf", "filepath": inittab}
self.statechglogger.recordchgevent(myid, event)
self.statechglogger.recordfilechange(inittab,
tmpfile, myid)
os.rename(tmpfile, inittab)
resetsecon(inittab)
else:
initText += "\nid:3:initdefault:\n"
writeFile(tmpfile, initText, self.logger)
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
event = {"eventtype": "conf", "filepath": inittab}
self.statechglogger.recordchgevent(myid, event)
self.statechglogger.recordfilechange(inittab,
tmpfile, myid)
os.rename(tmpfile, inittab)
resetsecon(inittab)
else:
self.detailedresults += inittab + " not found, no other " + \
"init system found. If you are using a supported " + \
"Linux OS, please report this as a bug\n"
return success
def fixRemoveX(self):
success = True
# Due to automatic removal of dependent packages, the full
# removal of X and related packages cannot be undone
if re.search("opensuse", self.myos):
cmd = ["zypper", "-n", "rm", "-u", "xorg-x11*", "kde*",
"xinit*"]
self.ch.executeCommand(cmd)
elif re.search("debian|ubuntu", self.myos):
xpkgs = ["unity.*", "xserver-xorg-video-ati",
"xserver-xorg-input-synaptics",
"xserver-xorg-input-wacom", "xserver-xorg-core",
"xserver-xorg", "lightdm.*", "libx11-data"]
for xpkg in xpkgs:
self.ph.remove(xpkg)
elif re.search("fedora", self.myos):
# Fedora does not use the same group packages as other
# RHEL-based OSs. Removing this package will remove the X
# Windows system, just less efficiently than using a group
self.ph.remove("xorg-x11-server-Xorg")
self.ph.remove("xorg-x11-xinit*")
else:
cmd = ["yum", "groups", "mark", "convert"]
self.ch.executeCommand(cmd)
self.ph.remove("xorg-x11-xinit")
self.ph.remove("xorg-x11-server-Xorg")
cmd2 = ["yum", "groupremove", "-y", "X Window System"]
if not self.ch.executeCommand(cmd2):
success = False
self.detailedresults += '"yum groupremove -y X Window System" command failed\n'
return success
def fixLockdownX(self):
success = True
if self.sh.disableService("xfs", _="_"):
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
event = {"eventtype": "servicehelper",
"servicename": "xfs",
"startstate": "enabled",
"endstate": "disabled"}
self.statechglogger.recordchgevent(myid, event)
else:
success = False
self.detailedresults += "STONIX was unable to disable the " + \
"xfs service\n"
if not self.xservSecure:
serverrcString = "exec X :0 -nolisten tcp $@"
if not os.path.exists(self.serverrc):
createFile(self.serverrc, self.logger)
self.iditerator += 1
myid = iterate(self.iditerator, self.rulenumber)
event = {"eventtype": "creation",
"filepath": self.serverrc}
self.statechglogger.recordchgevent(myid, event)
writeFile(self.serverrc, serverrcString, self.logger)
else:
open(self.serverrc, "a").write(serverrcString)
return success
| CSD-Public/stonix | src/stonix_resources/rules/DisableGUILogon.py | Python | gpl-2.0 | 22,537 |
<?php
/**
* @package Joomla.Site
* @subpackage Templates.beez3
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access.
defined('_JEXEC') or die;
JLoader::import('joomla.filesystem.file');
// Check modules
$showRightColumn = ($this->countModules('position-3') or $this->countModules('position-6') or $this->countModules('position-8'));
$showbottom = ($this->countModules('position-9') or $this->countModules('position-10') or $this->countModules('position-11'));
$showleft = ($this->countModules('position-4') or $this->countModules('position-7') or $this->countModules('position-5'));
if ($showRightColumn == 0 and $showleft == 0)
{
$showno = 0;
}
JHtml::_('behavior.framework', true);
// Get params
$color = $this->params->get('templatecolor');
$logo = $this->params->get('logo');
$navposition = $this->params->get('navposition');
$headerImage = $this->params->get('headerImage');
$app = JFactory::getApplication();
$doc = JFactory::getDocument();
$templateparams = $app->getTemplate(true)->params;
$config = JFactory::getConfig();
$bootstrap = explode(',', $templateparams->get('bootstrap'));
$jinput = JFactory::getApplication()->input;
$option = $jinput->get('option', '', 'cmd');
if (in_array($option, $bootstrap))
{
// Load optional rtl Bootstrap css and Bootstrap bugfixes
JHtmlBootstrap::loadCss($includeMaincss = true, $this->direction);
}
$doc->addStyleSheet(JURI::base() . 'templates/system/css/system.css');
$doc->addStyleSheet(JURI::base() . 'templates/' . $this->template . '/css/position.css', $type = 'text/css', $media = 'screen,projection');
$doc->addStyleSheet(JURI::base() . 'templates/' . $this->template . '/css/layout.css', $type = 'text/css', $media = 'screen,projection');
$doc->addStyleSheet(JURI::base() . 'templates/' . $this->template . '/css/print.css', $type = 'text/css', $media = 'print');
$doc->addStyleSheet(JURI::base() . 'templates/' . $this->template . '/css/general.css', $type = 'text/css', $media = 'screen,projection');
$doc->addStyleSheet(JURI::base() . 'templates/' . $this->template . '/css/' . htmlspecialchars($color) . '.css', $type = 'text/css', $media = 'screen,projection');
if ($this->direction == 'rtl')
{
$doc->addStyleSheet($this->baseurl . '/templates/' . $this->template . '/css/template_rtl.css');
if (file_exists(JPATH_SITE . '/templates/' . $this->template . '/css/' . $color . '_rtl.css'))
{
$doc->addStyleSheet($this->baseurl . '/templates/' . $this->template . '/css/' . htmlspecialchars($color) . '_rtl.css');
}
}
JHtml::_('bootstrap.framework');
$doc->addScript($this->baseurl . '/templates/' . $this->template . '/javascript/md_stylechanger.js', 'text/javascript');
$doc->addScript($this->baseurl . '/templates/' . $this->template . '/javascript/hide.js', 'text/javascript');
$doc->addScript($this->baseurl . '/templates/' . $this->template . '/javascript/respond.src.js', 'text/javascript');
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language; ?>" dir="<?php echo $this->direction; ?>" >
<head>
<?php require __DIR__ . '/jsstrings.php';?>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=3.0, user-scalable=yes"/>
<meta name="HandheldFriendly" content="true" />
<meta name="apple-mobile-web-app-capable" content="YES" />
<jdoc:include type="head" />
<!--[if IE 7]>
<link href="<?php echo $this->baseurl ?>/templates/<?php echo $this->template; ?>/css/ie7only.css" rel="stylesheet" type="text/css" />
<![endif]-->
</head>
<body id="shadow">
<?php if ($color == 'image'):?>
<style type="text/css">
.logoheader
{
background:url('<?php echo $this->baseurl . '/' . htmlspecialchars($headerImage); ?>') no-repeat right;
}
body
{
background: <?php echo $templateparams->get('backgroundcolor'); ?>;
}
</style>
<?php endif; ?>
<div id="all">
<div id="back">
<header id="header">
<div class="logoheader">
<h1 id="logo">
<?php if ($logo): ?>
<img src="<?php echo $this->baseurl ?>/<?php echo htmlspecialchars($logo); ?>" alt="<?php echo htmlspecialchars($templateparams->get('sitetitle'));?>" />
<?php endif;?>
<?php if (!$logo AND $templateparams->get('sitetitle')): ?>
<?php echo htmlspecialchars($templateparams->get('sitetitle'));?>
<?php elseif (!$logo AND $config->get('sitename')): ?>
<?php echo htmlspecialchars($config->get('sitename'));?>
<?php endif; ?>
<span class="header1">
<?php echo htmlspecialchars($templateparams->get('sitedescription'));?>
</span></h1>
</div><!-- end logoheader -->
<ul class="skiplinks">
<li><a href="#main" class="u2"><?php echo JText::_('TPL_BEEZ3_SKIP_TO_CONTENT'); ?></a></li>
<li><a href="#nav" class="u2"><?php echo JText::_('TPL_BEEZ3_JUMP_TO_NAV'); ?></a></li>
<?php if($showRightColumn ):?>
<li><a href="#additional" class="u2"><?php echo JText::_('TPL_BEEZ3_JUMP_TO_INFO'); ?></a></li>
<?php endif; ?>
</ul>
<h2 class="unseen"><?php echo JText::_('TPL_BEEZ3_NAV_VIEW_SEARCH'); ?></h2>
<h3 class="unseen"><?php echo JText::_('TPL_BEEZ3_NAVIGATION'); ?></h3>
<jdoc:include type="modules" name="position-1" />
<div id="line">
<div id="fontsize"></div>
<h3 class="unseen"><?php echo JText::_('TPL_BEEZ3_SEARCH'); ?></h3>
<jdoc:include type="modules" name="position-0" />
</div> <!-- end line -->
</header><!-- end header -->
<div id="<?php echo $showRightColumn ? 'contentarea2' : 'contentarea'; ?>">
<div id="breadcrumbs">
<jdoc:include type="modules" name="position-2" />
</div>
<?php if ($navposition == 'left' and $showleft) : ?>
<nav class="left1 <?php if ($showRightColumn == null){ echo 'leftbigger';} ?>" id="nav">
<jdoc:include type="modules" name="position-7" style="beezDivision" headerLevel="3" />
<jdoc:include type="modules" name="position-4" style="beezHide" headerLevel="3" state="0 " />
<jdoc:include type="modules" name="position-5" style="beezTabs" headerLevel="2" id="3" />
</nav><!-- end navi -->
<?php endif; ?>
<div id="<?php echo $showRightColumn ? 'wrapper' : 'wrapper2'; ?>" <?php if (isset($showno)){echo 'class="shownocolumns"';}?>>
<div id="main">
<?php if ($this->countModules('position-12')): ?>
<div id="top"><jdoc:include type="modules" name="position-12" />
</div>
<?php endif; ?>
<jdoc:include type="message" />
<jdoc:include type="component" />
</div><!-- end main -->
</div><!-- end wrapper -->
<?php if ($showRightColumn) : ?>
<h2 class="unseen">
<?php echo JText::_('TPL_BEEZ3_ADDITIONAL_INFORMATION'); ?>
</h2>
<div id="close">
<a href="#" onclick="auf('right')">
<span id="bild">
<?php echo JText::_('TPL_BEEZ3_TEXTRIGHTCLOSE'); ?>
</span></a>
</div>
<aside id="right">
<a id="additional"></a>
<jdoc:include type="modules" name="position-6" style="beezDivision" headerLevel="3"/>
<jdoc:include type="modules" name="position-8" style="beezDivision" headerLevel="3" />
<jdoc:include type="modules" name="position-3" style="beezDivision" headerLevel="3" />
</aside><!-- end right -->
<?php endif; ?>
<?php if ($navposition == 'center' and $showleft) : ?>
<nav class="left <?php if ($showRightColumn == null){ echo 'leftbigger';} ?>" id="nav" >
<jdoc:include type="modules" name="position-7" style="beezDivision" headerLevel="3" />
<jdoc:include type="modules" name="position-4" style="beezHide" headerLevel="3" state="0 " />
<jdoc:include type="modules" name="position-5" style="beezTabs" headerLevel="2" id="3" />
</nav><!-- end navi -->
<?php endif; ?>
<div class="wrap"></div>
</div> <!-- end contentarea -->
</div><!-- back -->
</div><!-- all -->
<div id="footer-outer">
<?php if ($showbottom) : ?>
<div id="footer-inner" >
<div id="bottom">
<div class="box box1"> <jdoc:include type="modules" name="position-9" style="beezDivision" headerlevel="3" /></div>
<div class="box box2"> <jdoc:include type="modules" name="position-10" style="beezDivision" headerlevel="3" /></div>
<div class="box box3"> <jdoc:include type="modules" name="position-11" style="beezDivision" headerlevel="3" /></div>
</div>
</div>
<?php endif; ?>
<div id="footer-sub">
<footer id="footer">
<jdoc:include type="modules" name="position-14" />
</footer><!-- end footer -->
</div>
</div>
<jdoc:include type="modules" name="debug" />
</body>
</html>
| irina-hychka/Joomla | templates/geekhub/index_old.php | PHP | gpl-2.0 | 8,949 |
jQuery(document).ready(function ($) {
const $resourcesTable = $('#resources-table');
$resourcesTable.find('tbody tr:not(.sub-table-header)').hide();
$resourcesTable.find('.sub-table-header').click(function () {
$(this).nextUntil('tr.sub-table-header').toggle();
const visibleLength = $resourcesTable.find('tbody tr:has(:checkbox):visible').length,
allVisibleChecked = visibleLength > 0 && visibleLength === $resourcesTable.find('tbody tr.selected:visible').length;
$('#mark-all').prop('checked', allVisibleChecked);
});
});
| ACP3/module-permissions | Resources/Assets/js/admin/resources.index.js | JavaScript | gpl-2.0 | 579 |
/* $Id: jquery.pngFix.js,v 1.1.1.5 2009/02/04 19:23:30 gibbozer Exp $ */
/**
* --------------------------------------------------------------------
* jQuery-Plugin "pngFix"
* Version: 1.1, 11.09.2007
* by Andreas Eberhard, andreas.eberhard@gmail.com
* http://jquery.andreaseberhard.de/
*
* Copyright (c) 2007 Andreas Eberhard
* Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
*
* Changelog:
* 11.09.2007 Version 1.1
* - removed noConflict
* - added png-support for input type=image
* - 01.08.2007 CSS background-image support extension added by Scott Jehl, scott@filamentgroup.com, http://www.filamentgroup.com
* 31.05.2007 initial Version 1.0
* --------------------------------------------------------------------
* @example $(function(){$(document).pngFix();});
* @desc Fixes all PNG's in the document on document.ready
*
* jQuery(function(){jQuery(document).pngFix();});
* @desc Fixes all PNG's in the document on document.ready when using noConflict
*
* @example $(function(){$('div.examples').pngFix();});
* @desc Fixes all PNG's within div with class examples
*
* @example $(function(){$('div.examples').pngFix( { blankgif:'ext.gif' } );});
* @desc Fixes all PNG's within div with class examples, provides blank gif for input with png
* --------------------------------------------------------------------
*/
(function($) {
jQuery.fn.pngFix = function(settings) {
// Settings
settings = jQuery.extend({
blankgif: 'blank.gif'
}, settings);
var ie55 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 5.5") != -1);
var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);
if (jQuery.browser.msie && (ie55 || ie6)) {
//fix images with png-source
jQuery(this).find("img[@src$=.png]").each(function() {
jQuery(this).attr('width',jQuery(this).width());
jQuery(this).attr('height',jQuery(this).height());
var prevStyle = '';
var strNewHTML = '';
var imgId = (jQuery(this).attr('id')) ? 'id="' + jQuery(this).attr('id') + '" ' : '';
var imgClass = (jQuery(this).attr('class')) ? 'class="' + jQuery(this).attr('class') + '" ' : '';
var imgTitle = (jQuery(this).attr('title')) ? 'title="' + jQuery(this).attr('title') + '" ' : '';
var imgAlt = (jQuery(this).attr('alt')) ? 'alt="' + jQuery(this).attr('alt') + '" ' : '';
var imgAlign = (jQuery(this).attr('align')) ? 'float:' + jQuery(this).attr('align') + ';' : '';
var imgHand = (jQuery(this).parent().attr('href')) ? 'cursor:hand;' : '';
if (this.style.border) {
prevStyle += 'border:'+this.style.border+';';
this.style.border = '';
}
if (this.style.padding) {
prevStyle += 'padding:'+this.style.padding+';';
this.style.padding = '';
}
if (this.style.margin) {
prevStyle += 'margin:'+this.style.margin+';';
this.style.margin = '';
}
var imgStyle = (this.style.cssText);
strNewHTML += '<span '+imgId+imgClass+imgTitle+imgAlt;
strNewHTML += 'style="position:relative;white-space:pre-line;display:inline-block;background:transparent;'+imgAlign+imgHand;
strNewHTML += 'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;';
strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + jQuery(this).attr('src') + '\', sizingMethod=\'scale\');';
strNewHTML += imgStyle+'"></span>';
if (prevStyle != ''){
strNewHTML = '<span style="position:relative;display:inline-block;'+prevStyle+imgHand+'width:' + jQuery(this).width() + 'px;' + 'height:' + jQuery(this).height() + 'px;'+'">' + strNewHTML + '</span>';
}
jQuery(this).hide();
jQuery(this).after(strNewHTML);
});
// fix css background pngs
jQuery(this).find("*").each(function(){
var bgIMG = jQuery(this).css('background-image');
if(bgIMG.indexOf(".png")!=-1){
var iebg = bgIMG.split('url("')[1].split('")')[0];
jQuery(this).css('background-image', 'none');
jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='scale')";
}
});
//fix input with png-source
jQuery(this).find("input[@src$=.png]").each(function() {
var bgIMG = jQuery(this).attr('src');
jQuery(this).get(0).runtimeStyle.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + bgIMG + '\', sizingMethod=\'scale\');';
jQuery(this).attr('src', settings.blankgif)
});
}
return jQuery;
};
})(jQuery);
| rmontero/dla_ecommerce_site | sites/all/modules/contrib/colourise/js/jquery.pngFix.js | JavaScript | gpl-2.0 | 4,655 |
<?php
/**
* @file
* class WdTaxonomyTermWrapperQuery
*/
class WdTaxonomyTermWrapperQueryResults extends WdWrapperQueryResults {
/**
* @return WdTaxonomyTermWrapper
*/
public function current() {
return parent::current();
}
}
class WdTaxonomyTermWrapperQuery extends WdWrapperQuery {
/**
* Construct a WdTaxonomyTermWrapperQuery
*/
public function __construct() {
parent::__construct('taxonomy_term');
}
/**
* Construct a WdTaxonomyTermWrapperQuery
*
* @return WdTaxonomyTermWrapperQuery
*/
public static function find() {
return new self();
}
/**
* @return WdTaxonomyTermWrapperQueryResults
*/
public function execute() {
return new WdTaxonomyTermWrapperQueryResults($this->entityType, $this->query->execute());
}
/**
* Query by tid
*
* @param int $tid
* @param string $operator
*
* @return $this
*/
public function byTid($tid, $operator = NULL) {
return parent::byId($tid, $operator);
}
/**
* Order by tid
*
* @param string $direction
*
* @return $this
*/
public function orderByTid($direction = 'ASC') {
return $this->orderByProperty('tid.value', $direction);
}
/**
* Query by name
*
* @param string $name
* @param string $operator
*
* @return $this
*/
public function byName($name, $operator = NULL) {
return $this->byPropertyConditions(array('name' => array($name, $operator)));
}
/**
* Order by name
*
* @param string $direction
*
* @return $this
*/
public function orderByName($direction = 'ASC') {
return $this->orderByProperty('name', $direction);
}
/**
* Query by description
*
* @param string $description
* @param string $operator
*
* @return $this
*/
public function byDescription($description, $operator = NULL) {
return $this->byPropertyConditions(array('description' => array($description, $operator)));
}
/**
* Order by description
*
* @param string $direction
*
* @return $this
*/
public function orderByDescription($direction = 'ASC') {
return $this->orderByProperty('description', $direction);
}
/**
* Query by weight
*
* @param int $weight
* @param string $operator
*
* @return $this
*/
public function byWeight($weight, $operator = NULL) {
return $this->byPropertyConditions(array('weight' => array($weight, $operator)));
}
/**
* Order by weight
*
* @param string $direction
*
* @return $this
*/
public function orderByWeight($direction = 'ASC') {
return $this->orderByProperty('weight', $direction);
}
/**
* Query by vid
*
* @param int|object|WdTaxonomyVocabularyWrapper $vid
* @param string $operator
*
* @return $this
*/
public function byVocabulary($vid, $operator = NULL) {
if ($vid instanceof WdEntityWrapper) {
$id = $vid->getId();
}
elseif (is_object($vid)) {
$wrapper = new WdTaxonomyVocabularyWrapper($vid);
$id = $wrapper->getId();
}
else {
$id = $vid;
}
return $this->byPropertyConditions(array('vid' => array($id, $operator)));
}
/**
* Order by vid
*
* @param string $direction
*
* @return $this
*/
public function orderByVocabulary($direction = 'ASC') {
return $this->orderByProperty('vid', $direction);
}
}
| ilDeposito/drupal-site | sites/all/modules/contrib/wrappers_delight/modules/wrappers_delight_query/includes/WdTaxonomyTermWrapperQuery.php | PHP | gpl-2.0 | 3,376 |
/*
* TuxCourser
* Copyright (C) 2003-2004 Adam Elliott
*
* 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package net.ovres.tuxcourser.itemtypes;
public class Finish extends ItemType {
public Finish( String baseObj ) {
this.initialize( "finish", baseObj, 255, 255, 0 );
this.setScale( 1.2 );
}
}
| aelliott2000/tuxcourser | src/main/java/net/ovres/tuxcourser/itemtypes/Finish.java | Java | gpl-2.0 | 991 |
<?php
global $has_this_got_widgets;
$has_this_got_widgets = 'yes';
global $childishlysimple_is_the_theme_activated;
global $childishlysimple_miscellaneous_stuff;
global $childishlysimple_site_details;
global $childishlysimple_footer_items;
?>
<div class="long-right-sidebar-background">
</div>
<div class="sidebar right-sidebar">
<?php
$childishlysimple_right_sidebar_items = array( );
if( ! isset( $childishlysimple_site_details[ 'selected_right_sidebar_items' ] ) ) {
$childishlysimple_right_sidebar_items = array( 1,2 );
echo '<div class="sidebar-item right-sidebar-item right-sidebar-home-item">';
echo '<h2 class="right-sidebar-item right-sidebar-home">Home</h2>';
echo '<ul class="right-sidebar-item right-sidebar-home">';
echo '<li class="right-sidebar-home">';
echo '<a class="right-sidebar-home" href="' . home_url('/'). '">Home</a>';
echo '</li>';
echo '</ul>';
echo '</div><!--End right-sidebar-item-->';
echo '<div class="sidebar-item right-sidebar-item right-sidebar-all-categories-item">';
echo '<h2 class="right-sidebar-item right-sidebar-all-categories">All categories</h2>';
echo '<ul class="right-sidebar-item right-sidebar-all-categories">';
wp_list_categories( 'title_li=' );
echo '</ul>';
echo '</div><!--End right-sidebar-item-->';
echo '<div class="sidebar-item right-sidebar-item right-sidebar-pages-item">';
echo '<h2 class="right-sidebar-item pages"> All pages</h2>';
echo '<ul class="right-sidebar-item right-sidebar-pages">';
wp_list_pages( 'title_li=' );
echo '</ul>';
echo '</div><!--End right-sidebar-item-->';
echo '<div class="sidebar-item right-sidebar-item right-sidebar-widget right-sidebar-widget-13-item">';
if ( is_active_sidebar( 'right_sidebar_widget_13' ) ) :
dynamic_sidebar( 'right_sidebar_widget_13' );
else : ?>
<h2 class="widgettitle right-sidebar-item right-sidebar-widget-13">Right Sidebar Widget 13</h2>
<ul class="right-sidebar-item right-sidebar-widget-13">
<li class="explanation">This is the right Sidebar Widget 13 container in sidebar-right.php. This text disappears and the title changes when you add a widget and give it a title in Admin / Appearance / Widgets. <br /><br />To remove this widget click on Appearance / Childishly Simple Options / Choose your sidebar items<br /><br />
</li>
</ul>
<?php endif;
echo '</div><!--End right-sidebar-item-->';
} elseif ( $childishlysimple_site_details['errors'] == 'errors' ) {
$childishlysimple_right_sidebar_items = array_flip( $childishlysimple_site_details['right_sidebar_items_default'] );
} else {
$childishlysimple_right_sidebar_items = $childishlysimple_site_details['selected_right_sidebar_items'];
}
?>
<?php
if( in_array( 'right_sidebar_home', $childishlysimple_right_sidebar_items ) ) { ?>
<div class="sidebar-item right-sidebar-item right-sidebar-home-item">
<h2 class="right-sidebar-item right-sidebar-home">Home</h2>
<ul class="right-sidebar-item right-sidebar-home">
<li class="right-sidebar-home">
<?php echo '<a class="right-sidebar-home" href="' . home_url('/'). '">Home</a>'; ?>
</li>
</ul>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_widget_01', $childishlysimple_right_sidebar_items ) ){ ?>
<div class="sidebar-item right-sidebar-item right-sidebar-widget right-sidebar-widget-01-item">
<?php if ( is_active_sidebar( 'right_sidebar_widget_01' ) ) :
dynamic_sidebar( 'right_sidebar_widget_01' );
else : ?>
<h2 class="widgettitle right-sidebar-item right-sidebar-widget-01">Right Sidebar Widget 01</h2>
<ul class="right-sidebar-item right-sidebar-widget-01">
<li class="explanation">This is the Right Sidebar Widget 01 container in sidebar-right.php. This text disappears and the title changes when you add a widget and give it a title in Admin / Appearance / Widgets.<br /><br />
</li>
</ul>
<?php endif; ?>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_most_recent', $childishlysimple_right_sidebar_items ) ) { ?>
<div class="sidebar-item right-sidebar-item right-sidebar-most-recent-posts-item">
<h2 class="right-sidebar-item right-sidebar-most-recent-posts">Most recent posts</h2>
<ul class="right-sidebar-item most-recent-posts right-sidebar-most-recent-posts">
<?php wp_get_archives( 'type=postbypost&limit=10' ); ?>
</ul>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_widget_02', $childishlysimple_right_sidebar_items ) ){ ?>
<div class="sidebar-item right-sidebar-item right-sidebar-widget right-sidebar-widget-02-item">
<?php
if ( is_active_sidebar( 'right_sidebar_widget_02' ) ) :
dynamic_sidebar( 'right_sidebar_widget_02' );
else :
?>
<h2 class="widgettitle right-sidebar-item right-sidebar-widget-02">Right Sidebar Widget 02</h2>
<ul class="right-sidebar-item right-sidebar-widget-02">
<li class="explanation">This is the Right Sidebar Widget 02 container in sidebar-right.php. This text disappears and the title changes when you add a widget and give it a title in Admin / Appearance / Widgets.<br /><br />
</li>
</ul>
<?php endif; ?>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_most_popular', $childishlysimple_right_sidebar_items ) ) { ?>
<div class="sidebar-item right-sidebar-item right-sidebar-popular-item">
<h2 class="right-sidebar-item right-sidebar-popular">Most popular posts</h2>
<ul class="right-sidebar-item right-sidebar-popular">
<?php
$loop_most_popular2 = new WP_Query( 'orderby=comment_count&posts_per_page=10&ignore_sticky_posts=1' );?>
<?php
if ( $loop_most_popular2->have_posts( ) ) : while ( $loop_most_popular2->have_posts( ) ) : $loop_most_popular2->the_post( ); ?>
<li class="right-sidebar-popular">
<?php
$shortened_title = '';
$limit = "25";
$ending="...";
$shortened_title = the_title_attribute (array('echo' => 0) );
if( strlen( $shortened_title ) >= ( $limit ) ) {
$shortened_title = substr( $shortened_title, 0, $limit ) . $ending;
} ?>
<a class="right-sidebar-popular" href="<?php the_permalink( ) ?>" rel="bookmark" title="Permanent Link to <?php echo $shortened_title; ?>"><?php echo $shortened_title; ?>(<?php comments_number('0','1','%'); ?>)</a>
</li>
<?php endwhile; ?>
</ul>
<?php
else :
endif;
wp_reset_query( );
?>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_widget_03', $childishlysimple_right_sidebar_items ) ){ ?>
<div class="sidebar-item right-sidebar-item right-sidebar-widget right-sidebar-widget-03-item">
<?php
if ( is_active_sidebar( 'right_sidebar_widget_03' ) ) :
dynamic_sidebar( 'right_sidebar_widget_03' );
else :
?>
<h2 class="widgettitle right-sidebar-item right-sidebar-widget-03">Right Sidebar Widget 03</h2>
<ul class="right-sidebar-item right-sidebar-widget-03">
<li class="explanation">This is the Right Sidebar Widget 03 container in sidebar-right.php. This text disappears and the title changes when you add a widget and give it a title in Admin / Appearance / Widgets.<br /><br />
</li>
</ul>
<?php endif; ?>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_latest_comments', $childishlysimple_right_sidebar_items ) ) { ?>
<div class="sidebar-item right-sidebar-item right-sidebar-latest-comments-item">
<h2 class="right-sidebar-item right-sidebar-latest-comments"> Latest Comments</h2>
<ul class="right-sidebar-item right-sidebar-latest-comments">
<?php
$recent_comments = get_comments( 'status=approve&number=5' );
foreach( $recent_comments as $comment ) :
$random = rand( 1,3 );
$images_url = get_template_directory_uri();
$default_avatar_url = $images_url.'/images/gravatar'.$random.'.gif';
$avatar_alt ='';
?>
<li class="right-sidebar-latest-comments">
<?php echo get_avatar( $comment->comment_author_email, 32, $default_avatar_url , $avatar_alt ); // Output the gravatar ?>
<span class="right-sidebar-latest-comments-author">By <?php echo ( get_comment_author_link( ) ) ?> on </span>
<span class="right-sidebar-latest-comments-date"><?php echo mysql2date( 'j-m-y', $comment->comment_date ); ?></span>
<p class="latest-comments-excerpt right-sidebar-latest-comments-excerpt">
<?php
$latest_posts_post_ID = $comment->comment_post_ID ; $post_info = get_post( $latest_posts_post_ID ); $title = $post_info->post_title;
$excerpt = wp_html_excerpt( $comment->comment_content, 70 );
$excerpt = $excerpt .'...'; // Add some dots after the excerpt
echo $excerpt;
?>
<a class="sidebar-latest-comments-more right-sidebar-latest-comments-more" href="<?php echo get_permalink( $comment->comment_post_ID ); ?>#comment-<?php echo $comment->comment_ID?>" title="Comment on <?php echo $title; ?>">Read more</a>
</p>
</li>
<?php endforeach; ?>
</ul>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_widget_04', $childishlysimple_right_sidebar_items ) ) { ?>
<div class="sidebar-item right-sidebar-item right-sidebar-widget right-sidebar-widget-04-item">
<?php if ( is_active_sidebar( 'right_sidebar_widget_04' ) ) :
dynamic_sidebar( 'right_sidebar_widget_04' );
else : ?>
<h2 class="widgettitle right-sidebar-item right-sidebar-widget-04">Right Sidebar Widget 04</h2>
<ul class="right-sidebar-item right-sidebar-widget-04">
<li class="explanation">This is the Right Sidebar Widget 04 container in sidebar-right.php. This text disappears and the title changes when you add a widget and give it a title in Admin / Appearance / Widgets.<br /><br />
</li>
</ul>
<?php endif; ?>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_calendar', $childishlysimple_right_sidebar_items ) ){ ?>
<div class="sidebar-item right-sidebar-item right-sidebar-calendar-item">
<h2 class="right-sidebar-item calendar"> Calendar</h2>
<?php get_calendar( true ); ?>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_widget_05', $childishlysimple_right_sidebar_items ) ){ ?>
<div class="sidebar-item right-sidebar-item right-sidebar-widget right-sidebar-widget-05-item">
<?php if ( is_active_sidebar( 'right_sidebar_widget_05' ) ) :
dynamic_sidebar( 'right_sidebar_widget_05' );
else : ?>
<h2 class="widgettitle right-sidebar-item right-sidebar-widget-05">Right Sidebar Widget 05</h2>
<ul class="right-sidebar-item right-sidebar-widget-05">
<li class="explanation">This is the Right Sidebar Widget 05 container in sidebar-right.php. This text disappears and the title changes when you add a widget and give it a title in Admin / Appearance / Widgets.<br /><br />
</li>
</ul>
<?php endif; ?>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_all_categories', $childishlysimple_right_sidebar_items ) ) { ?>
<div class="sidebar-item right-sidebar-item right-sidebar-all-categories-item">
<h2 class="right-sidebar-item right-sidebar-all-categories">All categories</h2>
<ul class="right-sidebar-item right-sidebar-all-categories">
<?php wp_list_categories( 'title_li=' ); ?>
</ul>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_widget_06', $childishlysimple_right_sidebar_items ) ) { ?>
<div class="sidebar-item right-sidebar-item right-sidebar-widget right-sidebar-widget-06-item">
<?php if ( is_active_sidebar( 'right_sidebar_widget_06' ) ) :
dynamic_sidebar( 'right_sidebar_widget_06' );
else : ?>
<h2 class="widgettitle right-sidebar-item right-sidebar-widget-06">Right Sidebar Widget 06</h2>
<ul class="right-sidebar-item right-sidebar-widget-06">
<li class="explanation">This is the Right Sidebar Widget 06 container in sidebar-right.php. This text disappears and the title changes when you add a widget and give it a title in Admin / Appearance / Widgets.<br /><br />
</li>
</ul>
<?php endif; ?>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_child_categories', $childishlysimple_right_sidebar_items ) ) { ?>
<div class="sidebar-item right-sidebar-item right-sidebar-child-categories-item">
<h2 class="right-sidebar-item right-sidebar-child-categories">Child Categories</h2>
<ul class="right-sidebar-item right-sidebar-child-categories">
<?php wp_list_categories( 'child_of=4&title_li=' ); ?>
</ul>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_widget_07', $childishlysimple_right_sidebar_items ) ){ ?>
<div class="sidebar-item right-sidebar-item right-sidebar-widget right-sidebar-widget-07-item">
<?php if ( is_active_sidebar( 'right_sidebar_widget_07' ) ) :
dynamic_sidebar( 'right_sidebar_widget_07' );
else : ?>
<h2 class="widgettitle right-sidebar-item right-sidebar-widget-07">Right Sidebar Widget 07</h2>
<ul class="right-sidebar-item right-sidebar-widget-07">
<li class="explanation">This is the Right Sidebar Widget 07 container in sidebar-right.php. This text disappears and the title changes when you add a widget and give it a title in Admin / Appearance / Widgets.<br /><br />
</li>
</ul>
<?php endif; ?>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_pages', $childishlysimple_right_sidebar_items ) ){ ?>
<div class="sidebar-item right-sidebar-item right-sidebar-pages-item">
<h2 class="right-sidebar-item pages"> All pages</h2>
<ul class="right-sidebar-item right-sidebar-pages">
<?php wp_list_pages( 'title_li=' );?>
</ul>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_widget_08', $childishlysimple_right_sidebar_items ) ) { ?>
<div class="sidebar-item right-sidebar-item right-sidebar-widget right-sidebar-widget-08-item">
<?php if ( is_active_sidebar( 'right_sidebar_widget_08' ) ) :
dynamic_sidebar( 'right_sidebar_widget_08' );
else : ?>
<h2 class="widgettitle right-sidebar-item right-sidebar-widget-08">Right Sidebar Widget 08</h2>
<ul class="right-sidebar-item right-sidebar-widget-08">
<li class="explanation">This is the Right Sidebar Widget 08 container in sidebar-right.php. This text disappears and the title changes when you add a widget and give it a title in Admin / Appearance / Widgets.<br /><br />
</li>
</ul>
<?php endif; ?>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_archives', $childishlysimple_right_sidebar_items ) ) { ?>
<div class="sidebar-item right-sidebar-item right-sidebar-archives-item">
<h2 class="right-sidebar-item archives">Archives</h2>
<ul class="right-sidebar-item right-sidebar-archives">
<?php wp_get_archives( 'type=monthly' ); ?>
</ul>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_widget_09', $childishlysimple_right_sidebar_items ) ){ ?>
<div class="sidebar-item right-sidebar-item right-sidebar-widget right-sidebar-widget-09-item">
<?php if ( is_active_sidebar( 'right_sidebar_widget_09' ) ) :
dynamic_sidebar( 'right_sidebar_widget_09' );
else : ?>
<h2 class="widgettitle right-sidebar-item right-sidebar-widget-09">Right Sidebar Widget 09</h2>
<ul class="right-sidebar-item right-sidebar-widget-09">
<li class="explanation">This is the Right Sidebar Widget 09 container in sidebar-right.php. This text disappears and the title changes when you add a widget and give it a title in Admin / Appearance / Widgets.<br /><br />
</li>
</ul>
<?php endif; ?>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_bookmarks', $childishlysimple_right_sidebar_items ) ) { ?>
<div class="sidebar-item right-sidebar-item right-sidebar-bookmarks-item">
<h2 class="right-sidebar-item right-sidebar-bookmarks">Bookmarks</h2>
<ul class="right-sidebar-item right-sidebar-bookmarks">
<?php wp_list_bookmarks( 'categorize=0&title_li=' ); ?>
</ul>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_widget_10', $childishlysimple_right_sidebar_items ) ){ ?>
<div class="sidebar-item right-sidebar-item right-sidebar-widget right-sidebar-widget-10-item">
<?php if ( is_active_sidebar( 'right_sidebar_widget_10' ) ) :
dynamic_sidebar( 'right_sidebar_widget_10' );
else : ?>
<h2 class="widgettitle right-sidebar-item right-sidebar-widget-10">Right Sidebar Widget 10</h2>
<ul class="right-sidebar-item right-sidebar-widget-10">
<li class="explanation">This is the Right Sidebar Widget 10 container in sidebar-right.php. This text disappears and the title changes when you add a widget and give it a title in Admin / Appearance / Widgets.<br /><br />
</li>
</ul>
<?php endif; ?>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_authors', $childishlysimple_right_sidebar_items ) ) { ?>
<div class="sidebar-item right-sidebar-item right-sidebar-authors-item">
<h2 class="right-sidebar-item authors">Authors</h2>
<ul class="right-sidebar-item right-sidebar-authors">
<?php wp_list_authors( 'exclude_admin=0' ); ?>
</ul>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_widget_11', $childishlysimple_right_sidebar_items ) ){ ?>
<div class="sidebar-item right-sidebar-item right-sidebar-widget right-sidebar-widget-11-item">
<?php if ( is_active_sidebar( 'right_sidebar_widget_11' ) ) :
dynamic_sidebar( 'right_sidebar_widget_11' );
else : ?>
<h2 class="widgettitle right-sidebar-item right-sidebar-widget-11">Right Sidebar Widget 11</h2>
<ul class="right-sidebar-item right-sidebar-widget-11">
<li class="explanation">This is the Right Sidebar Widget 11 container in sidebar-right.php. This text disappears and the title changes when you add a widget and give it a title in Admin / Appearance / Widgets.<br /><br />
</li>
</ul>
<?php endif; ?>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_tag_cloud', $childishlysimple_right_sidebar_items ) ) { ?>
<div class="sidebar-item right-sidebar-item right-sidebar-tag-cloud-item">
<h2 class="right-sidebar-item right-sidebar-tag-cloud"> Tag cloud</h2>
<?php if ( function_exists( 'wp_tag_cloud' ) ) : ?>
<ul>
<li>
<?php wp_tag_cloud( 'smallest=8&largest=22&unit=pt&number=30' ); ?>
</li>
</ul>
<?php endif; ?>
<?php
$tag = array( );
$tag = get_tags( );
if ( ! $tag ) echo '<ul><li>You need to add tags</li></ul>';
?>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_widget_12', $childishlysimple_right_sidebar_items ) ){ ?>
<div class="sidebar-item right-sidebar-item right-sidebar-widget right-sidebar-widget-12-item">
<?php if ( is_active_sidebar( 'right_sidebar_widget_12' ) ) :
dynamic_sidebar( 'right_sidebar_widget_12' );
else : ?>
<h2 class="widgettitle right-sidebar-item right-sidebar-widget-12">Right Sidebar Widget 12</h2>
<ul class="right-sidebar-item right-sidebar-widget-12">
<li class="explanation">This is the Right Sidebar Widget 12 container in sidebar-right.php. This text disappears and the title changes when you add a widget and give it a title in Admin / Appearance / Widgets.<br /><br />
</li>
</ul>
<?php endif; ?>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_register_or_login', $childishlysimple_right_sidebar_items ) ) { ?>
<div class="sidebar-item right-sidebar-item right-sidebar-register-item">
<h2 class="right-sidebar-item right-sidebar-register">Register or Log in</h2>
<ul class="right-sidebar-item right-sidebar-register">
<?php wp_register( ); ?>
<li><?php wp_loginout( ); ?></li>
<?php wp_meta( ); // A hook for plugins ?>
</ul>
</div><!--End right-sidebar-item-->
<?php } ?>
<?php
if( in_array( 'right_sidebar_widget_13', $childishlysimple_right_sidebar_items ) ){ ?>
<div class="sidebar-item right-sidebar-item right-sidebar-widget right-sidebar-widget-13-item">
<?php if ( is_active_sidebar( 'right_sidebar_widget_13' ) ) :
dynamic_sidebar( 'right_sidebar_widget_13' );
else : ?>
<h2 class="widgettitle right-sidebar-item right-sidebar-widget-13">Right Sidebar Widget 13</h2>
<ul class="right-sidebar-item right-sidebar-widget-13">
<li class="explanation">This is the Right Sidebar Widget 13 container in sidebar-right.php. This text disappears and the title changes when you add a widget and give it a title in Admin / Appearance / Widgets.<br /><br />
</li>
</ul>
<?php endif; ?>
</div><!--End right-sidebar-item-->
<?php } ?>
</div><!--End right-sidebar-->
<?php $has_this_got_widgets = 'no'; ?> | MrGreeny/FMITutorials | wp-content/themes/childishlysimple/sidebar-right.php | PHP | gpl-2.0 | 20,944 |
package de.asideas.crowdsource.controller;
import de.asideas.crowdsource.presentation.DateTimeWrapper;
import de.asideas.crowdsource.security.Roles;
import org.joda.time.DateTime;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/datetime")
public class DateTimeController {
@Secured({Roles.ROLE_USER})
@RequestMapping(method = RequestMethod.GET)
public DateTimeWrapper getDatetime() {
return new DateTimeWrapper(DateTime.now());
}
}
| as-ideas/crowdsource | crowdsource-core/src/main/java/de/asideas/crowdsource/controller/DateTimeController.java | Java | gpl-2.0 | 697 |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'FormPlugin'
db.create_table(u'cmsplugin_formplugin', (
(u'cmsplugin_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['cms.CMSPlugin'], unique=True, primary_key=True)),
('form_class', self.gf('django.db.models.fields.CharField')(max_length=200)),
('success_url', self.gf('django.db.models.fields.URLField')(max_length=200, null=True)),
('post_to_url', self.gf('django.db.models.fields.URLField')(max_length=200)),
))
db.send_create_signal(u'cms_form_plugin', ['FormPlugin'])
def backwards(self, orm):
# Deleting model 'FormPlugin'
db.delete_table(u'cmsplugin_formplugin')
models = {
'cms.cmsplugin': {
'Meta': {'object_name': 'CMSPlugin'},
'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}),
'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}),
'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}),
'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
},
'cms.placeholder': {
'Meta': {'object_name': 'Placeholder'},
'default_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'slot': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'})
},
u'cms_form_plugin.formplugin': {
'Meta': {'object_name': 'FormPlugin', 'db_table': "u'cmsplugin_formplugin'", '_ormbases': ['cms.CMSPlugin']},
u'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}),
'form_class': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
'post_to_url': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
'success_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True'})
}
}
complete_apps = ['cms_form_plugin'] | metzlar/cms-form-plugin | cms_form_plugin/migrations/0001_initial.py | Python | gpl-2.0 | 3,411 |
/*
* Web service utility functions for managing hibernate, json, etc.
*
* Copyright (C) 2010 Regents of the University of Colorado.
*
* 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 Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
package edu.ucdenver.bios.webservice.common.domain;
import java.util.ArrayList;
import java.util.List;
// TODO: Auto-generated Javadoc
// TO-DO: Auto-generated Javadoc
/**
* List of beta scale objects to work around Jackson serializaiton issues.
*
* @author Uttara Sakhadeo
*
*/
public class BetaScaleList {
/** The Constant serialVersionUID. */
private static final long serialVersionUID = 1L;
/** The uuid. */
private byte[] uuid = null;
/** The beta scale list. */
private List<BetaScale> betaScaleList = null;
/*--------------------
* Constructors
*--------------------*/
/**
* Instantiates a new beta scale list.
*/
public BetaScaleList() {
}
/**
* Instantiates a new beta scale list.
*
* @param uuid
* the uuid
*/
public BetaScaleList(final byte[] uuid) {
this.uuid = uuid;
}
/**
* Instantiates a new beta scale list.
*
* @param uuid the uuid
* @param list the list
*/
public BetaScaleList(final byte[] uuid,
final List<BetaScale> list) {
this.betaScaleList = list;
this.uuid = uuid;
}
/**
* Instantiates a new beta scale list.
*
* @param list
* the list
*/
public BetaScaleList(final List<BetaScale> list) {
this.betaScaleList = list;
}
/**
* Instantiates a new beta scale list.
*
* @param size
* the size
*/
public BetaScaleList(final int size) {
this.betaScaleList = new ArrayList<BetaScale>(size);
}
/*--------------------
* Getter/Setter Methods
*--------------------*/
/**
* Gets the uuid.
*
* @return the uuid
*/
public final byte[] getUuid() {
return uuid;
}
/**
* Sets the uuid.
*
* @param uuid
* the new uuid
*/
public final void setUuid(final byte[] uuid) {
this.uuid = uuid;
}
/**
* Gets the beta scale list.
*
* @return the beta scale list
*/
public final List<BetaScale> getBetaScaleList() {
return betaScaleList;
}
/**
* Sets the beta scale list.
*
* @param betaScaleList
* the new beta scale list
*/
public void setBetaScaleList(final List<BetaScale> betaScaleList) {
this.betaScaleList = betaScaleList;
}
}
| SampleSizeShop/WebServiceCommon | src/edu/ucdenver/bios/webservice/common/domain/BetaScaleList.java | Java | gpl-2.0 | 3,456 |
<?php
/**
* @package AdminTools
* @copyright Copyright (c)2010-2015 Nicholas K. Dionysopoulos
* @license GNU General Public License version 3, or later
*/
// Protection against direct access
defined('AKEEBAENGINE') or die();
/**
* Add site's root to the backup set.
*/
class AEFilterPlatformSiteroot extends AEAbstractFilter
{
public function __construct()
{
// This is a directory inclusion filter.
$this->object = 'dir';
$this->subtype = 'inclusion';
$this->method = 'direct';
$this->filter_name = 'PlatformSiteroot';
// Directory inclusion format:
// array(real_directory, add_path)
$add_path = null; // A null add_path means that we dump this dir's contents in the archive's root
// We take advantage of the filter class magic to inject our custom filters
$configuration = AEFactory::getConfiguration();
$this->filter_data[] = array(
'[SITEROOT]',
$add_path
);
parent::__construct();
}
private function get_site_path()
{
// FIX 1.1.0 $mosConfig_absolute_path may contain trailing slashes or backslashes incompatible with exclusion filters
// FIX 1.2.2 Some hosts yield an empty string on realpath(JPATH_SITE)
// FIX 2.2 On Windows, realpath might fail
// FIX 2.4: Make an assumption (wild guess...)
if ((JPATH_BASE == '/administrator') || (JPATH_ROOT == ''))
{
$this->setWarning("Your site's root is an empty string. I am trying a workaround.");
$jpath_site_real = '/';
}
else
{
// Fix 2.4: Make sure that $jpath_site_real contains something even if realpath fails
$jpath_site_real = @realpath(trim(JPATH_SITE));
$jpath_site_real = ($jpath_site_real === false) ? trim(JPATH_SITE) : $jpath_site_real;
$jpath_site_real = AEUtilFilesystem::TranslateWinPath($jpath_site_real);
}
if ($jpath_site_real == '')
{
// The JPATH_SITE is resolved to an empty string; attempt a workaround
// Windows hosts
if (DIRECTORY_SEPARATOR == '\\')
{
if ((trim(JPATH_SITE) != '') && (trim(JPATH_SITE) != '\\') && (trim(JPATH_SITE) != '/'))
{
$this->setWarning("The site's root couldn't be normalized on a Windows host. Attempting workaround (filters might not work)");
$jpath_site_real = JPATH_SITE; // Forcibly use the configured JPATH_SITE
}
else
{
$this->setWarning("The normalized path to your site's root seems to be an empty string; I will attempt a workaround (Windows host)");
$jpath_site_real = '/'; // Start scanning from filesystem root (workaround mode)
}
}
// *NIX hosts
else
{
$this->setWarning("The normalized path to your site's root seems to be an empty string; I will attempt a workaround (*NIX host)");
# Fix 2.1 Since JPATH_SITE is an empty string, shouldn't I begin scanning from the FS root, for crying out loud? What was I thinking putting JPATH_SITE there?
$jpath_site_real = '/'; // Start scanning from filesystem root (workaround mode)
}
}
// Fix 2.4.b1 : Add the trailing slash
if ((substr($jpath_site_real, -1) != '/') && !empty($jpath_site_real))
{
$jpath_site_real .= '/';
}
return $jpath_site_real;
}
} | jug-berlin/joomla.berlin | administrator/components/com_admintools/akeeba/platform/jfscan/filters/siteroot.php | PHP | gpl-2.0 | 3,113 |
package com.medavox.distribackup.connections;
import java.io.*;
import java.net.*;
import com.medavox.distribackup.peers.Peer;
/**Assigns new Sockets to incoming connections. The first point of contact for new connections.
* Further new connection set up is handled via a callback: Peer.setupNewSocket(Socket)*/
public class Listener extends Thread
{
static PrintStream o = System.out;
Peer owner;
private int port = 1210;//default value
private final int MAX_BACKLOG = 50;
public Listener(int port, Peer owner)
{
this.port = port;
this.owner = owner;
}
public void run()
{
ServerSocket svr;
//get open port to listen on
while(true)
{
try
{
System.out.println("Opening listening port: "+port+"...");
svr = new ServerSocket(port, MAX_BACKLOG);
break;
}
catch(BindException be)
{
System.err.println(be.getMessage());
port++;
continue;
}
catch(IOException ioe)
{
ioe.printStackTrace();
System.exit(1);
}
}
while(owner.threadsEnabled)
{//on a new socket connection:
try
{
Socket s = svr.accept();
owner.setupNewSocket(s);//callback: pass new Socket back to main thread
}
catch(Exception e)
{
System.err.println("CRASHED on connection NODATA");
e.printStackTrace();
System.exit(1);
}
//o.println("connection "+connectionNumber+" established");
}
}
}
| medavox/distribackup | src/main/java/com/medavox/distribackup/connections/Listener.java | Java | gpl-2.0 | 1,383 |
/*------------------------------------------------------------------------
# Full Name of JSN UniForm
# ------------------------------------------------------------------------
# author JoomlaShine.com Team
# copyright Copyright (C) 2012 JoomlaShine.com. All Rights Reserved.
# Websites: http://www.joomlashine.com
# Technical Support: Feedback - http://www.joomlashine.com/contact-us/get-support.html
# @license - GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
# @version $Id: forms.js 19013 2012-11-28 04:48:47Z thailv $
-------------------------------------------------------------------------*/
define([
'jquery',
'uniform/help',
'uniform/dialogedition',
'jquery.ui'],
function($, JSNHelp, JSNUniformDialogEdition) {
function JSNUniformForms(params) {
this.params = params;
this.lang = params.language;
this.init();
}
JSNUniformForms.prototype = {
//Create modal box email list select
init: function() {
this.JSNHelp = new JSNHelp();
var self = this;
this.JSNUniformDialogEdition = new JSNUniformDialogEdition(this.params);
$(".jsn-popup-upgrade").click(function() {
JSNUniformDialogEdition.createDialogLimitation($(this), self.lang["JSN_UNIFORM_YOU_HAVE_REACHED_THE_LIMITATION_OF_3_FORM_IN_FREE_EDITION_0"]);
})
}
}
return JSNUniformForms;
}); | ducdongmg/joomla_tut25 | administrator/components/com_uniform/assets/js/forms.js | JavaScript | gpl-2.0 | 1,317 |
package net.blaklizt.streets.android.location.navigation;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* User: tkaviya
* Date: 7/1/14
* Time: 7:49 PM
*/
public class Legs {
private ArrayList<Steps> steps;
private String totalDistance;
private String totalDuration;
public Legs(JSONObject leg){
steps = new ArrayList<Steps>();
parseSteps(leg);
}
public ArrayList<Steps> getSteps(){
return steps;
}
private void parseSteps(JSONObject leg){
try{
if(!leg.isNull("steps")){
JSONArray step = leg.getJSONArray("steps");
for(int i=0; i<step.length();i++){
JSONObject obj = step.getJSONObject(i);
steps.add(new Steps(obj));
}
}
if(!leg.isNull("distance")){
JSONObject obj = leg.getJSONObject("distance");
totalDistance = obj.getString("text");
}
if(!leg.isNull("duration")){
JSONObject obj = leg.getJSONObject("duration");
totalDuration = obj.getString("text");
}
}catch (JSONException e) {
e.printStackTrace();
}
}
public String getLegDistance(){
return totalDistance;
}
public String getLegDuration(){
return totalDuration;
}
}
| tkaviya/streets | src/main/java/net/blaklizt/streets/android/location/navigation/Legs.java | Java | gpl-2.0 | 1,464 |
/*
* *************************************************************************************
* Copyright (C) 2008 EsperTech, Inc. All rights reserved. *
* http://esper.codehaus.org *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
* *************************************************************************************
*/
package com.espertech.esper.support.xml;
import javax.xml.xpath.XPathVariableResolver;
import javax.xml.xpath.XPathFunctionResolver;
import javax.xml.xpath.XPathFunction;
import javax.xml.namespace.QName;
public class SupportXPathFunctionResolver implements XPathFunctionResolver
{
public XPathFunction resolveFunction(QName functionName, int arity) {
return null;
}
} | mobile-event-processing/Asper | source/test/com/espertech/esper/support/xml/SupportXPathFunctionResolver.java | Java | gpl-2.0 | 1,106 |
<?php
/**
* @copyright Copyright (C) 1999-2012 eZ Systems AS. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
* @version 2012.5
* @package kernel
*/
$Module = $Params['Module'];
$http = eZHTTPTool::instance();
$hash = trim( $http->hasPostVariable( 'Hash' ) ? $http->postVariable( 'Hash' ) : $Params['Hash'] );
$mainNodeID = (int) $http->hasPostVariable( 'MainNodeID' ) ? $http->postVariable( 'MainNodeID' ) : $Params['MainNodeID'];
// Prepend or append the hash string with a salt, and md5 the resulting hash
// Example: use is login name as salt, and a 'secret password' as hash sent to the user
if ( $http->hasPostVariable( 'HashSaltPrepend' ) )
$hash = md5( trim( $http->postVariable( 'HashSaltPrepend' ) ) . $hash );
else if ( $http->hasPostVariable( 'HashSaltAppend' ) )
$hash = md5( $hash . trim( $http->postVariable( 'HashSaltAppend' ) ) );
// Check if key exists
$accountActivated = false;
$alreadyActive = false;
$isPending = false;
$accountKey = $hash ? eZUserAccountKey::fetchByKey( $hash ) : false;
if ( $accountKey )
{
$accountActivated = true;
$userID = $accountKey->attribute( 'user_id' );
$userContentObject = eZContentObject::fetch( $userID );
if ( !$userContentObject instanceof eZContentObject )
{
return $Module->handleError( eZError::KERNEL_NOT_FOUND, 'kernel' );
}
if ( $userContentObject->attribute('main_node_id') != $mainNodeID )
{
return $Module->handleError( eZError::KERNEL_ACCESS_DENIED, 'kernel' );
}
// Enable user account
if ( eZOperationHandler::operationIsAvailable( 'user_activation' ) )
{
$operationResult = eZOperationHandler::execute( 'user',
'activation', array( 'user_id' => $userID,
'user_hash' => $hash,
'is_enabled' => true ) );
}
else
{
eZUserOperationCollection::activation( $userID, $hash, true );
}
// execute operation to publish the user object
$publishResult = eZOperationHandler::execute( 'user' , 'register', array( 'user_id'=> $userID ) );
if( $publishResult['status'] === eZModuleOperationInfo::STATUS_HALTED )
{
$isPending = true;
}
else
{
// Log in user
$user = eZUser::fetch( $userID );
if ( $user === null )
return $Module->handleError( eZError::KERNEL_NOT_FOUND, 'kernel' );
$user->loginCurrent();
}
}
elseif( $mainNodeID )
{
$userContentObject = eZContentObject::fetchByNodeID( $mainNodeID );
if ( $userContentObject instanceof eZContentObject )
{
$userSetting = eZUserSetting::fetch( $userContentObject->attribute( 'id' ) );
if ( $userSetting !== null && $userSetting->attribute( 'is_enabled' ) )
{
$alreadyActive = true;
}
}
}
// Template handling
$tpl = eZTemplate::factory();
$tpl->setVariable( 'module', $Module );
$tpl->setVariable( 'account_activated', $accountActivated );
$tpl->setVariable( 'already_active', $alreadyActive );
$tpl->setVariable( 'is_pending' , $isPending );
// This line is deprecated, the correct name of the variable should
// be 'account_activated' as shown above.
// However it is kept for backwards compatibility.
$tpl->setVariable( 'account_avtivated', $accountActivated );
$Result = array();
$Result['content'] = $tpl->fetch( 'design:user/activate.tpl' );
$Result['path'] = array( array( 'text' => ezpI18n::tr( 'kernel/user', 'User' ),
'url' => false ),
array( 'text' => ezpI18n::tr( 'kernel/user', 'Activate' ),
'url' => false ) );
$ini = eZINI::instance();
if ( $ini->variable( 'SiteSettings', 'LoginPage' ) == 'custom' )
$Result['pagelayout'] = 'loginpagelayout.tpl';
?>
| pauletienney/siliconnexion | kernel/user/activate.php | PHP | gpl-2.0 | 4,003 |
<?php
/**
* Template part for displaying page content in page.php.
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package Alex_Apostolides_Portfolio
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
</header><!-- .entry-header -->
<div class="entry-content">
<?php
the_content();
wp_link_pages( array(
'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'alex_apostolides_portfolio' ),
'after' => '</div>',
) );
?>
</div><!-- .entry-content -->
<footer class="entry-footer">
<?php
edit_post_link(
sprintf(
/* translators: %s: Name of current post */
esc_html__( 'Edit %s', 'alex_apostolides_portfolio' ),
the_title( '<span class="screen-reader-text">"', '"</span>', false )
),
'<span class="edit-link">',
'</span>'
);
?>
</footer><!-- .entry-footer -->
</article><!-- #post-## -->
| alexapostolides/alex_apostolides_portfolio | wp-content/themes/alex_apostolides_portfolio/template-parts/content-page.php | PHP | gpl-2.0 | 996 |
/********************************************************************
* Copyright (C) 2015-2017 Antoine Aflalo
*
* 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.
********************************************************************/
using System;
using System.Collections.Generic;
using NAudio.CoreAudioApi;
using SoundSwitch.Common.Framework.Audio.Device;
using SoundSwitch.Localization;
using SoundSwitch.Model;
namespace SoundSwitch.Framework.DeviceCyclerManager.DeviceCycler
{
public class DeviceCyclerAvailable : ADeviceCycler
{
public override DeviceCyclerTypeEnum TypeEnum => DeviceCyclerTypeEnum.Available;
public override string Label => SettingsStrings.cycleThroughOptionOnlySelectedAudioDevices;
protected override IEnumerable<DeviceFullInfo> GetDevices(DataFlow type)
{
return type switch
{
DataFlow.Render => AppModel.Instance.AvailablePlaybackDevices,
DataFlow.Capture => AppModel.Instance.AvailableRecordingDevices,
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null)
};
}
}
} | Belphemur/SoundSwitch | SoundSwitch/Framework/DeviceCyclerManager/DeviceCycler/DeviceCyclerAvailable.cs | C# | gpl-2.0 | 1,608 |
using System.Collections.Generic;
namespace com.espertech.esper.compat.collections.bound
{
public static class BoundExtensions
{
public static bool IsLessThan<TK>(
Bound<TK> bound,
TK value,
IComparer<TK> comparer)
{
if (bound == null)
return true;
return bound.IsInclusive
? comparer.Compare(value, bound.Value) <= 0
: comparer.Compare(value, bound.Value) < 0;
}
public static bool IsGreaterThan<TK>(
Bound<TK> bound,
TK value,
IComparer<TK> comparer)
{
if (bound == null)
return true;
return bound.IsInclusive
? comparer.Compare(value, bound.Value) >= 0
: comparer.Compare(value, bound.Value) > 0;
}
public static Bound<TV> MergeLower<TV>(
this Bound<TV> bound,
Bound<TV> other,
IComparer<TV> comparer)
{
if (other == null) {
return bound;
}
return MergeLower(bound, other.Value, other.IsInclusive, comparer);
}
public static Bound<TV> MergeLower<TV>(
this Bound<TV> bound,
TV value,
bool isInclusive,
IComparer<TV> comparer)
{
if (bound == null)
return new Bound<TV>(value, isInclusive);
var comp = comparer.Compare(value, bound.Value);
if (comp == 0) {
return new Bound<TV>(value, isInclusive & bound.IsInclusive);
} else if (comp < 0) {
return bound;
}
return new Bound<TV>(value, isInclusive);
}
public static Bound<TV> MergeUpper<TV>(
this Bound<TV> bound,
Bound<TV> other,
IComparer<TV> comparer)
{
if (other == null) {
return bound;
}
return MergeUpper(bound, other.Value, other.IsInclusive, comparer);
}
public static Bound<TV> MergeUpper<TV>(
this Bound<TV> bound,
TV value,
bool isInclusive,
IComparer<TV> comparer)
{
if (bound == null)
return new Bound<TV>(value, isInclusive);
var comp = comparer.Compare(value, bound.Value);
if (comp == 0) {
return new Bound<TV>(value, isInclusive & bound.IsInclusive);
} else if (comp > 0) {
return bound;
}
return new Bound<TV>(value, isInclusive);
}
}
} | espertechinc/nesper | src/NEsper.Compat/compat/collections/bound/BoundExtensions.cs | C# | gpl-2.0 | 2,814 |
package utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import Constants.DataBaseConstants;
public class projectNameEncoder {
public Connection createConnection() throws SQLException {
Connection conn = null;
conn = DriverManager.getConnection(
"jdbc:postgresql://" + DataBaseConstants.host + "/"
+ DataBaseConstants.databaseName,
DataBaseConstants.userName,
DataBaseConstants.password
);
return conn;
}
public String encode(String projectName) {
String projectId = projectName.replace(" ", "_");
String requestStr = "SELECT count(*) as c FROM projects p where p.name = '" + projectName + "';";
int count = 0;
try {
Statement s = this.createConnection().createStatement();
final ResultSet res = s.executeQuery(requestStr);
if (res.next()) {
count = res.getInt("c");
}
} catch (SQLException e) {
e.printStackTrace();
}
projectId = projectId.concat("_" + count);
return projectId;
}
public void main(String[] args) {
System.out.println("Trying to encode 'SR03 project'...");
System.out.println("The encoded id is: " + encode("SR03 project"));
}
}
| hkaj/CoFITS | server/src/utils/projectNameEncoder.java | Java | gpl-2.0 | 1,231 |
// ====================================================================================================================
// Copyright (C) 2015 Lukas Georgieff
// Last modified: 06/04/2015
// Description: Declares a class for an HTTP GET request to the translation service.
// ====================================================================================================================
// ====================================================================================================================
// 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 in version 2.
//
// 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
// ====================================================================================================================
#ifndef HTTP_GET_REQUEST_HPP_
#define HTTP_GET_REQUEST_HPP_
#include "http_request.hpp"
#include <string>
namespace lgeorgieff {
namespace translate {
namespace client {
class HttpGetRequest : public HttpRequest {
public:
// === Constructors and destructor ==================================================================================
explicit HttpGetRequest(const std::string &);
virtual ~HttpGetRequest();
// The actual method that handles the curl HTTP request and must be implemented in each derived class from
// HttpRequest
std::string operator()() override;
}; // HttpGetRequest
} // client
} // translate
} // lgeorgieff
#endif // HTTP_GET_REQUEST_HPP_
| lgeorgieff/translate | src/client/http_get_request.hpp | C++ | gpl-2.0 | 1,971 |
<?php
require_once '../../csrest_clients.php';
$wrap = new CS_REST_Clients('Your clients ID', 'Your API Key');
$result = $wrap->set_basics(array(
'CompanyName' => 'Clients company name',
'ContactName' => 'Clients contact name',
'EmailAddress' => 'Clients email',
'Country' => 'Clients country',
'Timezone' => 'Clients timezone'
));
echo "Result of PUT /api/v3/clients/{id}/setbasics\n<br />";
if($result->was_successful()) {
echo "Updated with Code ".$result->http_status_code;
} else {
echo 'Failed with code '.$result->http_status_code."\n<br /><pre>";
var_dump($result->response);
echo '</pre>';
} | ashray-velapanur/grind-members | cm/samples/client/set_basics.php | PHP | gpl-2.0 | 661 |