code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="Author" content="Made by 'tree'">
<meta name="GENERATOR" content="$Version: $ tree v1.6.0 (c) 1996 - 2011 by Steve Baker, Thomas Moore, Francesc Rocher, Kyosuke Tokoro $">
<title>Directory Tree</title>
<style type="text/css">
<!--
BODY { font-family : ariel, monospace, sans-serif; }
P { font-weight: normal; font-family : ariel, monospace, sans-serif; color: black; background-color: transparent;}
B { font-weight: normal; color: black; background-color: transparent;}
A:visited { font-weight : normal; text-decoration : none; background-color : transparent; margin : 0px 0px 0px 0px; padding : 0px 0px 0px 0px; display: inline; }
A:link { font-weight : normal; text-decoration : none; margin : 0px 0px 0px 0px; padding : 0px 0px 0px 0px; display: inline; }
A:hover { color : #000000; font-weight : normal; text-decoration : underline; background-color : yellow; margin : 0px 0px 0px 0px; padding : 0px 0px 0px 0px; display: inline; }
A:active { color : #000000; font-weight: normal; background-color : transparent; margin : 0px 0px 0px 0px; padding : 0px 0px 0px 0px; display: inline; }
.VERSION { font-size: small; font-family : arial, sans-serif; }
.NORM { color: black; background-color: transparent;}
.FIFO { color: purple; background-color: transparent;}
.CHAR { color: yellow; background-color: transparent;}
.DIR { color: blue; background-color: transparent;}
.BLOCK { color: yellow; background-color: transparent;}
.LINK { color: aqua; background-color: transparent;}
.SOCK { color: fuchsia;background-color: transparent;}
.EXEC { color: green; background-color: transparent;}
-->
</style>
</head>
<body>
<h1>Directory Tree</h1><p>
<a href="http://localhost">http://localhost</a><br>
├── <a href="http://localhost/1">1</a><br>
├── <a href="http://localhost/2">2</a><br>
├── <a href="http://localhost/a.out">a.out</a><br>
├── <a href="http://localhost/a.txt">a.txt</a><br>
├── <a href="http://localhost/b.txt">b.txt</a><br>
├── <a href="http://localhost/file">file</a><br>
├── <a href="http://localhost/filestat.sh">filestat.sh</a><br>
├── <a href="http://localhost/helloworld.c">helloworld.c</a><br>
├── <a href="http://localhost/image2.iso">image2.iso</a><br>
├── <a href="http://localhost/image.iso">image.iso</a><br>
├── <a href="http://localhost/loopback/">loopback</a><br>
│ └── <a href="http://localhost/loopback/file">file</a><br>
├── <a href="http://localhost/loopbackfile.img">loopbackfile.img</a><br>
├── <a href="http://localhost/other">other</a><br>
├── <a href="http://localhost/out.html">out.html</a><br>
├── <a href="http://localhost/remove">remove</a><br>
├── <a href="http://localhost/remove_duplicates.sh">remove_duplicates.sh</a><br>
├── <a href="http://localhost/test9.txt">test9.txt</a><br>
├── <a href="http://localhost/version12.patch">version12.patch</a><br>
├── <a href="http://localhost/version1.txt">version1.txt</a><br>
├── <a href="http://localhost/version1.txt.orig">version1.txt.orig</a><br>
├── <a href="http://localhost/version2.txt">version2.txt</a><br>
└── <a href="http://localhost/version.patch">version.patch</a><br>
<br><br>
</p>
<p>
1 directory, 22 files
<br><br>
</p>
<hr>
<p class="VERSION">
tree v1.6.0 © 1996 - 2011 by Steve Baker and Thomas Moore <br>
HTML output hacked and copyleft © 1998 by Francesc Rocher <br>
Charsets / OS/2 support © 2001 by Kyosuke Tokoro
</p>
</body>
</html>
| sczzq/symmetrical-spoon | base-usage/shell/FileInFileOut/out.html | HTML | unlicense | 3,778 |
#ifndef __NETWORKBALANCER_HPP
#define __NETWORKBALANCER_HPP
#include <stdlib.h>
namespace Network
{
class NetworkBalancer
{
public:
/**
* @brief NetworkBalancer Class constructor
*/
NetworkBalancer();
/**
* @brief sendTroughBalancer Sends a buffer through an automatically chosen output channel,
* trying to balance the output
* @param Buffer Reference to buffer to be sent
* @param length Length of buffer
* @return Output channel chosen
*/
int sendTroughBalancer( const char *Buffer, int length );
/* @brief Total number of output channels */
const static int MAX_OUTPUTS = 4;
private:
/**
* @brief calculateOutputChannel Calculates an output channel following the strategy
* stated in this class
* @return Calculated output channel, a number between 1 and 4
*/
int calculateOutputChannel();
private:
/**
* @brief The BALANCE_STRATEGY enum Enumerated class containing the strategies that can be
* chosen for this class to produce the output
*/
enum class BALANCE_STRATEGY { ROUNDROBIN4, RANDOM };
/* @brief theLastOutput Contains the last chosen channel */
int theLastOutput;
/* @brief theChosenStrategy Currently chosen strategy */
BALANCE_STRATEGY theChosenStrategy;
};
}
#endif // __NETWORKBALANCER_HPP
| magfernandez/TIDTest | src/Network/NetworkBalancer.hpp | C++ | unlicense | 1,492 |
from djangosanetesting.cases import HttpTestCase
from django.conf import settings
from django.core.urlresolvers import reverse
from django.core import mail
from accounts.tests import testdata
class TestResetPassword(HttpTestCase):
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.host = 'localhost'
self.port = 8000
def setUp(self):
testdata.run()
def test_reset_password(self):
res = self.client.post(reverse('password_reset'),
{'register_number' : settings.TEST_USERNAME,
},
follow=True)
assert reverse('password_reset_done') in res.request['PATH_INFO']
assert len(mail.outbox) == 1
reset_url = [word for word in mail.outbox[0].body.split() if word.startswith('http')][0]
res = self.client.get(reset_url, follow=True)
assert res.status_code == 200
assert 'unsuccessful' not in res.content.lower()
assert 'change my password' in res.content.lower()
# I've to stop here, because next step is to change password at Google Apps.
# Can't mess up production database.
| sramana/pysis | apps/passwords/tests/test_reset_password.py | Python | unlicense | 1,236 |
/**
* This is a demo class
*
* @author Ravi
*/
public class Demo
{
/**
* This is the main method
*
* @param args
*/
public static void main(String[] args)
{
System.out.println("This is a demo.");
}
}
| PatchRowcester/LearningJava | Demo/src/Demo.java | Java | unlicense | 239 |
# 00Text
[3ds Homebrew] Open Source text editor with an old mobile phone like keyboard. To use it just take the 00Text folder and put it with your other homebrews (3ds folder in your sd).
# Instructions
Use the different buttons to select the letters
| BUTTON | USE |
|---|---|
| UP | A B C |
| RIGHT | D E F |
| DOWN | G H I |
| LEFT | J K L |
| X | M N Q |
| A | P Q R S |
| B | T U V |
| Y | W X Y Z |
| SELECT | DEBUG |
| START | EXIT |
| L | **PRINT SELECTED LETTER** |
| R | DELETE |
| ZL | SPACE |
| ZR | PRINT EVERYTHING WRITTEN |
| k0ryan/00Text | README.md | Markdown | unlicense | 627 |
package com.github.alkedr.matchers.reporting.reporters;
import org.junit.Test;
import static com.github.alkedr.matchers.reporting.reporters.Reporters.noOpSafeTreeReporter;
import static com.github.alkedr.matchers.reporting.reporters.Reporters.noOpSimpleTreeReporter;
public class NoOpReportersTest {
@Test
public void noOpSafeTreeReporter_methodsShouldNotUseArgumentsOrThrow() {
SafeTreeReporter reporter = noOpSafeTreeReporter();
reporter.presentNode(null, null, null);
reporter.absentNode(null, null);
reporter.brokenNode(null, null, null);
callAllFlatReporterMethods(reporter);
}
@Test
public void noOpSimpleTreeReporter_methodsShouldNotUseArgumentsOrThrow() {
SimpleTreeReporter reporter = noOpSimpleTreeReporter();
reporter.beginPresentNode(null, null);
reporter.beginAbsentNode(null);
reporter.beginBrokenNode(null, null);
reporter.endNode();
callAllFlatReporterMethods(reporter);
}
private static void callAllFlatReporterMethods(FlatReporter reporter) {
reporter.correctlyPresent();
reporter.correctlyAbsent();
reporter.incorrectlyPresent();
reporter.incorrectlyAbsent();
reporter.passedCheck(null);
reporter.failedCheck(null, null);
reporter.checkForAbsentItem(null);
reporter.brokenCheck(null, null);
}
}
| alkedr/reporting-matchers | src/test/java/com/github/alkedr/matchers/reporting/reporters/NoOpReportersTest.java | Java | unlicense | 1,403 |
energies = dict()
energies[81] = -3.17 # Ammoniadimer.xyz
energies[82] = -5.02 # Waterdimer.xyz
energies[83] = -1.50 # BenzeneMethanecomplex.xyz
energies[84] = -18.61 # Formicaciddimer.xyz
energies[85] = -15.96 # Formamidedimer.xyz
energies[86] = -20.65 # Uracildimerhbonded.xyz
energies[87] = -16.71 # 2pyridoxine2aminopyridinecomplex.xyz
energies[88] = -16.37 # AdeninethymineWatsonCrickcomplex.xyz
energies[89] = -0.53 # Methanedimer.xyz
energies[90] = -1.51 # Ethenedimer.xyz
energies[91] = -2.73 # Benzenedimerparalleldisplaced.xyz
energies[92] = -4.42 # Pyrazinedimer.xyz
energies[93] = -10.12 # Uracildimerstack.xyz
energies[94] = -5.22 # Indolebenzenecomplexstack.xyz
energies[95] = -12.23 # Adeninethyminecomplexstack.xyz
energies[96] = -1.53 # Etheneethynecomplex.xyz
energies[97] = -3.28 # Benzenewatercomplex.xyz
energies[98] = -2.35 # Benzeneammoniacomplex.xyz
energies[99] = -4.46 # BenzeneHCNcomplex.xyz
energies[100] = -2.74 # BenzenedimerTshaped.xyz
energies[101] = -5.73 # IndolebenzeneTshapecomplex.xyz
energies[102] = -7.05 # Phenoldimer.xyz
names = dict()
names[81] = "Ammoniadimer.xyz"
names[82] = "Waterdimer.xyz"
names[83] = "BenzeneMethanecomplex.xyz"
names[84] = "Formicaciddimer.xyz"
names[85] = "Formamidedimer.xyz"
names[86] = "Uracildimerhbonded.xyz"
names[87] = "2pyridoxine2aminopyridinecomplex.xyz"
names[88] = "AdeninethymineWatsonCrickcomplex.xyz"
names[89] = "Methanedimer.xyz"
names[90] = "Ethenedimer.xyz"
names[91] = "Benzenedimerparalleldisplaced.xyz"
names[92] = "Pyrazinedimer.xyz"
names[93] = "Uracildimerstack.xyz"
names[94] = "Indolebenzenecomplexstack.xyz"
names[95] = "Adeninethyminecomplexstack.xyz"
names[96] = "Etheneethynecomplex.xyz"
names[97] = "Benzenewatercomplex.xyz"
names[98] = "Benzeneammoniacomplex.xyz"
names[99] = "BenzeneHCNcomplex.xyz"
names[100] = "BenzenedimerTshaped.xyz"
names[101] = "IndolebenzeneTshapecomplex.xyz"
names[102] = "Phenoldimer.xyz"
| andersx/s22-charmm | structures/ref.py | Python | unlicense | 2,038 |
// --------------------------------------------------------------------------
// Citadel: CfgFiles.h
//
// For figuring out how to configure ourselves.
#ifdef MAIN
char *citfiles[] =
{
"GRPDATA.CIT", "EXTERNAL.CIT", "CONFIG.CIT",
"CRON.CIT", "ROUTE.CIT", "HARDWARE.CIT",
"NODES.CIT", "FILEQTMP.CIT", "DEFUSER.CIT",
"CRASH.CIT", "MAILLIST.CIT", "PROTOCOL.CIT",
"MDMRESLT.CIT", "NETID.CIT", "MCI.CIT",
"TERMCAP.CIT", "COMMANDS.CIT",
NULL
};
#else
extern char *citfiles[];
#endif
enum
{
C_GRPDATA_CIT, C_EXTERNAL_CIT, C_CONFIG_CIT,
C_CRON_CIT, C_ROUTE_CIT, C_HARDWARE_CIT,
C_NODES_CIT, C_FILEQTMP_CIT, C_DEFUSER_CIT,
C_CRASH_CIT, C_MAILLIST_CIT, C_PROTOCOL_CIT,
C_MDMRESLT_CIT, C_NETID_CIT, C_MCI_CIT,
C_TERMCAP_CIT, C_COMMANDS_CIT,
MAXCIT,
};
enum
{
GRK_DAYS, GRK_GROUP, GRK_HOURS,
GRK_DAYINC, GRK_SPECIAL, GRK_PRIORITY,
GRK_MAXBAL, GRK_DLMULT, GRK_ULMULT,
GRK_NUM
};
enum
{
EC_EDITOR, EC_USERAPP, EC_AUTO_EDITOR,
EC_REPLACE, EC_DOOR, EC_C_AUTHOR,
EC_C_NODE, EC_C_TEXT, EC_HOLIDAY,
EC_HOLIDAYWITHYEAR, EC_EVENT, EC_ARCHIVER,
EC_DIRECTORY, EC_RLM, EC_REFUSER,
EC_NETCOMMAND, EC_BANPORT,
EC_NUM
};
enum
{
PR_PROTOCOL, PR_MENU_NAME, PR_COMMAND_KEY,
PR_BATCH, PR_BLOCK_SIZE, PR_RECEIVE,
PR_SEND, PR_AUTO_UPLOAD, PR_RESPONSE_SEND,
PR_NET_ONLY, PR_CHECK_TRANSFER,
PR_NUM
};
enum
{
DUK_FORWARD, DUK_SURNAME, DUK_TITLE,
DUK_BOLD, DUK_NULLS, DUK_WIDTH,
DUK_CREDITS, DUK_INVERSE, DUK_BLINK,
DUK_UNDERLINE, DUK_PROTOCOL, DUK_PROMPT,
DUK_DSTAMP, DUK_VDSTAMP, DUK_SIGNATURE,
DUK_NETPREFIX, DUK_ADDR2, DUK_ADDR3,
DUK_POOP, DUK_UCMASK, DUK_EXPERT,
DUK_AIDE, DUK_TABS, DUK_OLDTOO,
DUK_UNLISTED, DUK_PERMANENT, DUK_SYSOP,
DUK_NODE, DUK_NOACCOUNT, DUK_NOMAIL,
DUK_ROOMTELL, DUK_BORDERS, DUK_VERIFIED,
DUK_SURNAMLOK, DUK_LOCKHALL, DUK_DISPLAYTS,
DUK_SUBJECTS, DUK_SIGNATURES, DUK_DEFAULTHALL,
DUK_LINESSCREEN, DUK_FORWARDNODE, DUK_ADDR1,
DUK_LFMASK, DUK_PROBLEM, DUK_NETUSER,
DUK_NEXTHALL, DUK_PSYCHO, DUK_TWIRLY,
DUK_VERBOSE, DUK_MSGPAUSE, DUK_MINIBIN,
DUK_MSGCLS, DUK_ROOMINFO, DUK_HALLTELL,
DUK_VERBOSECONT, DUK_VIEWCENSOR, DUK_SEEBORDERS,
DUK_OUT300, DUK_LOCKUSIG, DUK_HIDEEXCL,
DUK_NODOWNLOAD, DUK_NOUPLOAD, DUK_NOCHAT,
DUK_PRINTFILE, DUK_REALNAME, DUK_PHONENUM,
DUK_SPELLCHECK, DUK_NOMAKEROOM, DUK_VERBOSELO,
DUK_CONFSAVE, DUK_CONFABORT, DUK_CONFEOABORT,
DUK_USEPERSONAL, DUK_YOUAREHERE, DUK_IBMROOM,
DUK_WIDEROOM, DUK_MUSIC, DUK_MOREPROMPT,
DUK_NUMUSERSHOW, DUK_CALLLIMIT, DUK_CHECKAPS,
DUK_CHECKALLCAPS, DUK_CHECKDIGITS, DUK_EXCLUDEENCRYPTED,
DUK_SHOWCOMMAS, DUK_PUNPAUSES, DUK_KUSER,
DUK_KTEXT, DUK_KNODE, DUK_KREG,
DUK_TUSER, DUK_DICTWORD, DUK_FINGER,
DUK_USERDEF, DUK_REPLACE, DUK_NORMAL,
DUK_ROMAN, DUK_TERMTYPE, DUK_SUPERSYSOP,
DUK_BUNNY, DUK_SSE_LOGONOFF, DUK_SSE_NEWMSG,
DUK_SSE_EXCLMSG, DUK_SSE_CHATALL, DUK_SSE_CHATROOM,
DUK_SSE_CHATGROUP, DUK_SSE_CHATUSER, DUK_SSE_RMINOUT,
DUK_BANNED, DUK_KILLOWN, DUK_SEEOWNCHATS,
DUK_ERASEPROMPT, DUK_AUTOIDLESECONDS, DUK_SSE_MSGSOMEWHERE,
DUK_NUM
};
enum TermCapCitE
{
TCK_TERMINAL, TCK_IBMUPPER, TCK_COLOR,
TCK_TERMTYPE, TCK_CLS, TCK_FORECOLOR,
TCK_BACKCOLOR, TCK_FULLCOLOR, TCK_HIGHFORECOLOR,
TCK_HIGHBOTHCOLOR, TCK_UNDERLINE, TCK_BLINK,
TCK_NORMAL, TCK_REVERSE, TCK_BOLD,
TCK_DELEOL, TCK_SAVECURS, TCK_RESTORECURS,
TCK_BLANKFOR1CURS, TCK_CURSUP, TCK_CURSDOWN,
TCK_CURSLEFT, TCK_CURSRIGHT, TCK_ROWSTART,
TCK_COLSTART, TCK_BLANKFORTLCUR, TCK_ABSCURSPOS,
TCK_NUM
};
#define CONFIGDDSTART 1
#define CONFIGDDEND 7
#define GRPDATADDSTART 8
#define GRPDATADDEND 8
#define EXTERNALDDSTART 9
#define EXTERNALDDEND 10
#define PROTOCOLDDSTART 11
#define PROTOCOLDDEND 11
#define MDMRESLTDDSTART 12
#define MDMRESLTDDEND 12
#define MCIDDSTART 13
#define MCIDDEND 13
#define COMMANDSDDSTART 14
#define COMMANDSDDEND 14
| dylancarlson/citplus | cfgfiles.h | C | unlicense | 4,118 |
<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<link href="layout.css" charset="utf-8" type="text/css" rel="stylesheet"></link>
<TITLE>SDL_CreateWindow</TITLE>
</HEAD>
<BODY>
<script src="menu.js"></script>
<div id=pagecontent>
<h1>SDL_CreateWindow</h1>
<p>Use this function to create a window with the specified position, dimensions, and flags.
<h2>Syntax</h2>
<div style=codearea>
<pre>
SDL_Window* SDL_CreateWindow(const char* title,
int x,
int y,
int w,
int h,
Uint32 flags)
</pre></div>
<h2>Function Parameters</h2>
<table>
<tr><td><strong>title</strong></td><td>the title of the window, in UTF-8 encoding
<tr><td><strong>x</strong></td><td>the x position of the window, SDL_WINDOWPOS_CENTERED, or SDL_WINDOWPOS_UNDEFINED</td></tr>
<tr><td><strong>y</strong></td><td>the y position of the window, SDL_WINDOWPOS_CENTERED, or SDL_WINDOWPOS_UNDEFINED</td></tr>
<tr><td><strong>w</strong></td><td>the width of the window</td></tr>
<tr><td><strong>h</strong></td><td>the height of the window</td></tr>
<tr><td><strong>flags</strong></td><td>0, or one or more <a href="SDL_WindowFlags.html">SDL_WindowFlags</a> OR'd together; see <a href="#Remarks">Remarks</a> for details</td></tr>
</table>
<h2>Return Value</h2>
<p>Returns the window that was created or NULL on failure; call <a href="SDL_GetError.html">SDL_GetError</a>() for more information.
<h2>Code Examples</h2>
<div style=codearea>
<pre>
// Example program:
// Using SDL2 to create an application window
#include "SDL.h"
#include <stdio.h>
int main(int argc, char* argv[]) {
SDL_Window *window; // Declare a pointer
SDL_Init(SDL_INIT_VIDEO); // Initialize SDL2
// Create an application window with the following settings:
window = SDL_CreateWindow(
"An SDL2 window", // window title
SDL_WINDOWPOS_UNDEFINED, // initial x position
SDL_WINDOWPOS_UNDEFINED, // initial y position
640, // width, in pixels
480, // height, in pixels
SDL_WINDOW_OPENGL // flags - see below
);
// Check that the window was successfully made
if (window == NULL) {
// In the event that the window could not be made...
printf("Could not create window: %s\n", SDL_GetError());
return 1;
}
// The window is open: enter program loop (see SDL_PollEvent)
SDL_Delay(3000); // Pause execution for 3000 milliseconds, for example
// Close and destroy the window
SDL_DestroyWindow(window);
// Clean up
SDL_Quit();
return 0;
}
</pre></div>
<h2 id="Remarks">Remarks</h2>
<p><strong>flags</strong> may be any of the following OR'd together:
<table>
<tr><td>SDL_WINDOW_FULLSCREEN</td><td>fullscreen window</td></tr>
<tr><td>SDL_WINDOW_FULLSCREEN_DESKTOP</td><td>fullscreen window at the current desktop resolution</td></tr>
<tr><td>SDL_WINDOW_OPENGL</td><td>window usable with OpenGL context</td></tr>
<tr><td>SDL_WINDOW_HIDDEN</td><td>window is not visible</td></tr>
<tr><td>SDL_WINDOW_BORDERLESS</td><td>no window decoration</td></tr>
<tr><td>SDL_WINDOW_RESIZABLE</td><td>window can be resized</td></tr>
<tr><td>SDL_WINDOW_MINIMIZED</td><td>window is minimized</td></tr>
<tr><td>SDL_WINDOW_MAXIMIZED</td><td>window is maximized</td></tr>
<tr><td>SDL_WINDOW_INPUT_GRABBED</td><td>window has grabbed input focus</td></tr>
<tr><td>SDL_WINDOW_ALLOW_HIGHDPI</td><td>window should be created in high-DPI mode if supported (>= SDL 2.0.1)</td></tr>
</table>
<h2>Related Functions</h2>
<ul style="list-style-type:none"><li><a href="SDL_DestroyWindow.html">SDL_DestroyWindow</a></li></ul>
</div>
</BODY>
</HTML> | d0n3val/programacio_2 | Motor2D_1er/Docs/SDL2/SDL_CreateWindow.html | HTML | unlicense | 3,925 |
<!DOCTYPE html>
<html lang="en-US">
<head>
<base href="http://localhost/wordpress" />
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bulfinch-1827 Report of Charles Bulfinch on the Subject of Penitentiaries, | Communicating with Prisoners</title>
<link rel='stylesheet' id='ortext-fonts-css' href='//fonts.googleapis.com/css?family=Lato%3A300%2C400%2C700%2C900%2C300italic%2C400italic%2C700italic' type='text/css' media='all' />
<link rel='stylesheet' id='ortext-style-css' href='http://cwpc.github.io/wp-content/themes/ortext/style.css?ver=4.1' type='text/css' media='all' />
<link rel='stylesheet' id='ortext-layout-style-css' href='http://cwpc.github.io/wp-content/themes/ortext/layouts/content.css?ver=4.1' type='text/css' media='all' />
<link rel='stylesheet' id='ortext_fontawesome-css' href='http://cwpc.github.io/wp-content/themes/ortext/fonts/font-awesome/css/font-awesome.min.css?ver=4.1' type='text/css' media='all' />
<link rel='stylesheet' id='tablepress-default-css' href='http://cwpc.github.io/wp-content/plugins/tablepress/css/default.min.css?ver=1.5.1' type='text/css' media='all' />
<style id='tablepress-default-inline-css' type='text/css'>
.tablepress{width:auto;border:2px solid;margin:0 auto 1em}.tablepress td,.tablepress thead th{text-align:center}.tablepress .column-1{text-align:left}.tablepress-table-name{font-weight:900;text-align:center;font-size:20px;line-height:1.3em}.tablepress tfoot th{font-size:14px}.tablepress-table-description{font-weight:900;text-align:center}
</style>
<script type='text/javascript' src='http://cwpc.github.io/wp-includes/js/jquery/jquery.js?ver=1.11.1'></script>
<script type='text/javascript' src='http://cwpc.github.io/wp-includes/js/jquery/jquery-migrate.min.js?ver=1.2.1'></script>
<link rel='next' title='Burke-1790 Reflections on the Revolution in France' href='http://cwpc.github.io/refs/burke-1790-reflections-on-the-revolution-in-france/' />
<link rel='canonical' href='http://cwpc.github.io/refs/bulfinch-1827-report-of-charles-bulfinch-on-the-subject-of-penitentiaries/' />
<link rel='shortlink' href='http://cwpc.github.io/?p=29901' />
</head>
<body class="single single-refs postid-29901 custom-background">
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-56314084-1', 'auto');
ga('send', 'pageview');
</script><div id="page" class="hfeed site">
<a class="skip-link screen-reader-text" href="#content">Skip to content</a>
<header id="masthead" class="site-header" role="banner">
<div class="site-branding">
<div class="title-box">
<h1 class="site-title"><a href="http://cwpc.github.io/" rel="home">Communicating with Prisoners</a></h1>
<h2 class="site-description">Public Interest Analysis</h2>
</div>
</div>
<div id="scroller-anchor"></div>
<nav id="site-navigation" class="main-navigation clear" role="navigation">
<span class="menu-toggle"><a href="#">menu</a></span>
<div class="menu-left-nav-container"><ul id="menu-left-nav" class="menu"><li id="menu-item-10830" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-10830"><a title="outline of sections" href="http://cwpc.github.io/outline-post/">Outline</a></li>
<li id="menu-item-11571" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-11571"><a title="context-sensitive notes link" href="http://cwpc.github.io/outline-notes/">Notes</a></li>
<li id="menu-item-11570" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-11570"><a title="context-sensitive data link" href="http://cwpc.github.io/list-datasets/">Data</a></li>
</ul></div>
<div id="rng">
<div id="menu-secondary" class="menu-secondary"><ul id="menu-secondary-items" class="menu-items"><li id="menu-item-10840" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-10840"><a title="about this ortext" href="http://cwpc.github.io/about/">About</a></li>
</ul></div> <div class="search-toggle">
<span class="fa fa-search"></span>
<a href="#search-container" class="screen-reader-text">search</a>
</div>
</div>
</nav><!-- #site-navigation -->
<div id="header-search-container" class="search-box-wrapper clear hide">
<div class="search-box clear">
<form role="search" method="get" class="search-form" action="http://cwpc.github.io/">
<label>
<span class="screen-reader-text">Search for:</span>
<input type="search" class="search-field" placeholder="Search …" value="" name="s" title="Search for:" />
</label>
<input type="submit" class="search-submit" value="Search" />
</form> </div>
</div>
</header><!-- #masthead -->
<div id="content" class="site-content">
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<div class="section-label"></div>
<article id="post-29901" class="post-29901 refs type-refs status-publish hentry">
<header class="entry-header">
<h1 class="entry-title">Bulfinch-1827 Report of Charles Bulfinch on the Subject of Penitentiaries,</h1>
</header><!-- .entry-header -->
<div class="entry-content">
<img class="aligncenter otx-face" alt="face of a prisoner" src="http://cwpc.github.io/wp-content/uploads/faces/prisoner-117.jpg"></br><p>reference-type: Book <br />author: Bulfinch <br />year: 1826 <br />title: Report of Charles Bulfinch on the Subject of Penitentiaries, Feb. 13, 1827 <br />series: 19th Congress, 2d Session, Rep. No. 98, House of Representatives <br />place-published: Washington <br />otx-key: Bulfinch-1827 </p>
</div><!-- .entry-content -->
<footer class="entry-footer">
<div class="tags-footer">
</div>
</footer><!-- .entry-footer -->
</article><!-- #post-## -->
<nav class="navigation post-navigation" role="navigation">
<h1 class="screen-reader-text">Post navigation</h1>
<div class="nav-links-nd"><div class="nav-nd-title">In Series of References</div><div class="nav-previous"><a href="http://cwpc.github.io/refs/buel-2004-voire-dire-in-domesti-violence-cases-adapted-from/" rel="prev">Buel-2004 Voire Dire in Domesti Violence Cases, Adapted from</a></div><div class="nav-next"><a href="http://cwpc.github.io/refs/burke-1790-reflections-on-the-revolution-in-france/" rel="next">Burke-1790 Reflections on the Revolution in France</a></div> </div><!-- .nav-links -->
</nav><!-- .navigation -->
</main><!-- #main -->
</div><!-- #primary -->
</div><!-- #content -->
<footer id="colophon" class="site-footer" role="contentinfo">
<div class="site-info">
<nav id="site-navigation" class="main-navigation clear" role="navigation">
<span class="menu-toggle"><a href="#">menu</a></span>
<div class="menu-left-nav-container"><ul id="menu-left-nav-1" class="menu"><li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-10830"><a title="outline of sections" href="http://cwpc.github.io/outline-post/">Outline</a></li>
<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-11571"><a title="context-sensitive notes link" href="http://cwpc.github.io/outline-notes/">Notes</a></li>
<li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-11570"><a title="context-sensitive data link" href="http://cwpc.github.io/list-datasets/">Data</a></li>
</ul></div>
<div id="rng">
<div id="menu-secondary" class="menu-secondary"><ul id="menu-secondary-items" class="menu-items"><li class="menu-item menu-item-type-post_type menu-item-object-page menu-item-10840"><a title="about this ortext" href="http://cwpc.github.io/about/">About</a></li>
</ul></div> <div class="search-toggle-bottom">
<span class="fa fa-search"></span>
<a href="#search-container" class="screen-reader-text">search</a>
</div>
</div>
<div id="header-search-container" class="search-box-wrapper-bottom clear hide">
<div class="search-box clear">
<form role="search" method="get" class="search-form" action="http://cwpc.github.io/">
<label>
<span class="screen-reader-text">Search for:</span>
<input type="search" class="search-field" placeholder="Search …" value="" name="s" title="Search for:" />
</label>
<input type="submit" class="search-submit" value="Search" />
</form> </div>
</div>
<div id="footer-tagline">
<a href="http://cwpc.github.io/">Communicating with Prisoners</a>
</div>
</nav><!-- #site-navigation -->
</div><!-- .site-info -->
</footer><!-- #colophon -->
</div><!-- #page -->
<script type='text/javascript' src='http://cwpc.github.io/wp-content/themes/ortext/js/superfish.min.js?ver=1.7.4'></script>
<script type='text/javascript' src='http://cwpc.github.io/wp-content/themes/ortext/js/superfish-settings.js?ver=1.7.4'></script>
<script type='text/javascript' src='http://cwpc.github.io/wp-content/themes/ortext/js/navigation.js?ver=20120206'></script>
<script type='text/javascript' src='http://cwpc.github.io/wp-content/themes/ortext/js/skip-link-focus-fix.js?ver=20130115'></script>
<script type='text/javascript' src='http://cwpc.github.io/wp-content/themes/ortext/js/hide-search.js?ver=20120206'></script>
<script type='text/javascript' src='http://cwpc.github.io/wp-content/themes/ortext/js/show-hide-comments.js?ver=1.0'></script>
</body>
</html>
<!-- Dynamic page generated in 0.213 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2015-01-27 23:56:19 -->
<!-- super cache --> | cwpc/cwpc.github.io | refs/bulfinch-1827-report-of-charles-bulfinch-on-the-subject-of-penitentiaries/index.html | HTML | unlicense | 9,819 |
export class InvalidTimeValueError extends Error {
constructor(unit: string, providedValue: number) {
super(`Cannot create a valid time with provided ${unit} value: ${providedValue}`);
}
}
| rizadh/scheduler | src/InvalidTimeValueError.ts | TypeScript | unlicense | 197 |
avatar = function(x){
this.x = x;
this.y = 0;
this.prevY = 0;
this.velocity_x = 0;
this.velocity_y = 0;
this.img = loadImage("stickman.png");
this.crouch = loadImage("crouch.png");
this.width = 16;
this.standingHeight=64;
this.crouchHeight=44;
this.height = this.standingHeight;
this.collisionCheck = [];
};
avatar.prototype.addCollisionCheck = function(item){
this.collisionCheck.push(item);
//console.log("add "+item);
}
avatar.prototype.removeCollisionCheck = function(item){
this.collisionCheck.splice(
this.collisionCheck.indexOf(item), 1);
//console.log("remove mushroom");
}
avatar.prototype.platformCheck = function(){
this.talajon=false;
if(this.y<=0){
this.y=0; this.velocity_y=0; this.talajon=true;
}
for(var i in elements.es){
if(elements.es[i] instanceof platform){
var p=elements.es[i];
if(p.x<this.x +this.width && p.x+p.width > this.x){
if(this.prevY>=p.y && this.y<=p.y){
this.y=p.y;
this.velocity_y=0;
this.talajon=true;
}
}
}
}
}
avatar.prototype.death = function(){
new Audio(explosionSound.src).play();
life--;
lifeText.text = "Life: "+life;
if(life <= 0)
gameOver();
this.x = 0;
this.y = 0;
}
avatar.prototype.spikeCheck = function(){
for(var i in elements.es){
if(elements.es[i] instanceof spike){
var p=elements.es[i];
if(p.x<this.x +this.width && p.x+p.width > this.x){
/*console.log("player.y = "+this.y);
console.log("spike.y = "+p.y);
console.log("spike.height = "+p.height);
console.log("player.height = "+this.height);*/
if(p.y<this.y+this.height && p.y+p.height-3 > this.y){
this.death();
}
}
}
}
}
avatar.prototype.mushroomCheck = function(){
for(var i in elements.es){
if(elements.es[i] instanceof mushroom){
var p=elements.es[i];
if(p.x<=this.x +this.width && p.x+p.width >= this.x){
/*console.log("player.y = "+this.y);
console.log("spike.y = "+p.y);
console.log("spike.height = "+p.height);
console.log("player.height = "+this.height);*/
if(p.y<=this.y+this.height && p.y+p.height >= this.y){
if(this.prevY>p.y+p.height) {
p.death();
}else {
this.death();
}
}
}
}
}
}
avatar.prototype.logic = function(){
var speedX = 5;
if(keys[KEY_RIGHT]){
this.x += speedX;
}if(keys[KEY_LEFT]){
this.x -= speedX;
}
this.prevY = this.y;
this.y += this.velocity_y;
if(keys[KEY_UP] && this.talajon){
this.velocity_y = 14;
this.y += 0.001;
}
this.platformCheck();
//this.spikeCheck();
//this.mushroomCheck();
//collision Test
for(var i in this.collisionCheck){
var p = this.collisionCheck[i];
if(p.x<this.x +this.width &&
p.x+p.width > this.x){
if(p.y<this.y+this.height &&
p.y+p.height > this.y){
p.collide(this);
}
}
}
if(!this.talajon){
this.velocity_y-=1;
}
if(keys[KEY_DOWN]){
this.currentImg=this.crouch;
this.height=this.crouchHeight;
}else{
this.currentImg=this.img;
this.height=this.standingHeight;
}
};
avatar.prototype.draw=function(context, t){
context.drawImage(this.currentImg, t.tX(this.x), t.tY(this.y)-this.standingHeight);
};
| rizsi/szakkor2014 | orak/sa-23/avatar.js | JavaScript | unlicense | 3,166 |
/* * * * * * * * * * * * * * * * * * * * * * * * * * *
* SYSTEM/FS/FAT.H *
* * * * * * * * * * * * * * * * * * * * * * * * * * */
#ifndef FAT_H_INCLUDED
#define FAT_H_INCLUDED
#include <FORMATTING.H>
typedef struct _FAT121632_BPB {
uint8_t OEMName[8];
uint16_t BytesPerSector;
uint8_t SectorsPerCluster;
uint16_t ReservedSectors;
uint8_t NumberOfFats;
uint16_t NumDirEntries;
uint16_t NumSectors;
uint8_t Media;
uint16_t SectorsPerFat;
uint16_t SectorsPerTrack;
uint16_t HeadsPerCyl;
uint32_t HiddenSectors;
uint32_t LongSectors;
}__attribute__((packed)) FATBPB, *PFATBPB;
typedef struct _FAT1216_BPB_EXT {
uint8_t DriveNumber;
uint8_t Flags;
uint8_t Signiture;
uint32_t Serial;
char VolumeLable[11];
char SysIDString[8];
}__attribute__((packed)) FAT1216BPBEXT, *PFAT1216BPBEXT;
typedef struct _FAT32_BPB_EXT {
uint32_t SectorsPerFat32;
uint16_t Flags;
uint16_t Version;
uint32_t RootCluster;
uint16_t InfoCluster;
uint16_t BackupBoot;
uint16_t Reserved[6];
uint8_t DriveNumber;
uint8_t flag;
uint8_t Signiture;
uint32_t Serial;
char VolumeLable[11];
char SysIDString[8];
}__attribute__((packed)) FAT32BPBEXT, *PFAT32BPBEXT;
typedef struct _FAT1216_BS {
uint8_t Ignore[3]; //first 3 bytes are ignored
FATBPB Bpb;
FAT1216BPBEXT BpbExt;
uint8_t Filler[448]; //needed to make struct 512 bytes
uint16_t BootSig;
}__attribute__((packed)) FAT1216BS, *PFAT1216BS;
typedef struct _FAT32_BS {
uint8_t Ignore[3]; //first 3 bytes are ignored
FATBPB Bpb;
FAT32BPBEXT BpbExt;
uint8_t Filler[420]; //needed to make struct 512 bytes
uint16_t BootSig;
}__attribute__((packed)) FAT32BS, *PFAT32BS;
typedef struct _FAT_DIRECTORY {
uint8_t Filename[11];
uint8_t Attrib;
uint8_t Reserved;
uint8_t TimeCreatedMs;
uint16_t TimeCreated;
uint16_t DateCreated;
uint16_t DateLastAccessed;
uint16_t FirstClusterHiBytes;
uint16_t LastModTime;
uint16_t LastModDate;
uint16_t FirstCluster;
uint32_t FileSize;
}__attribute__((packed)) FATDIR, *PFATDIR;
typedef struct _FAT_DIR_SECTOR {
FATDIR DIRENT[16];
} DIRSEC, *PDIRSEC;
typedef struct _TEMP_DIR {
DIRSEC Sector[4096];
} TDIR, *PTDIR;
void _FAT_init(void);
#endif | basicfreak/BOS | 0.0.1/SRC/SYSTEM/FS/FAT.H | C++ | unlicense | 2,287 |
#include "Union.h"
bool Union::contains(const Vector2D& point) const
{
for (auto&& figure : figures)
if (figure->contains(point))
return true;
return false;
}
Figure* Union::createCopy() const {
return new Union(*this);
}
std::ostream &operator<<(std::ostream& os, const Union* un)
{
return un->serializeFigures(os);
}
std::istream &operator>>(std::istream& is, Union*& un)
{
std::vector<Figure*> figures = FigureGroup::unserializeFigures(is);
un = new Union(figures);
return is;
}
| Lyrositor/insa | 3if/oo/tp-oo_4/src/Union.cpp | C++ | unlicense | 535 |
---
title: Contact
layout: blank
---
<p>Contact me at <a href="mailto:[email protected]">[email protected]</a> or <a href="http://www.github.com/mssurajkaiga">www.github.com/mssurajkaiga</a></p> | mssurajkaiga/mssurajkaiga.github.io | contact/index.html | HTML | unlicense | 205 |
from bitmovin.utils import Serializable
class AutoRestartConfiguration(Serializable):
def __init__(self, segments_written_timeout: float = None, bytes_written_timeout: float = None,
frames_written_timeout: float = None, hls_manifests_update_timeout: float = None,
dash_manifests_update_timeout: float = None, schedule_expression: str = None):
super().__init__()
self.segmentsWrittenTimeout = segments_written_timeout
self.bytesWrittenTimeout = bytes_written_timeout
self.framesWrittenTimeout = frames_written_timeout
self.hlsManifestsUpdateTimeout = hls_manifests_update_timeout
self.dashManifestsUpdateTimeout = dash_manifests_update_timeout
self.scheduleExpression = schedule_expression
| bitmovin/bitmovin-python | bitmovin/resources/models/encodings/live/auto_restart_configuration.py | Python | unlicense | 785 |
#include "com_object.hpp"
#include <Windows.h>
namespace pw
{
com_object::com_object()
{
CoInitializeEx(nullptr, COINIT_MULTITHREADED);
}
com_object::~com_object()
{
CoUninitialize();
}
}
| phwitti/cmdhere | src/base/com_object.cpp | C++ | unlicense | 231 |
package crashreporter.api;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Registry for API provider objects.
*
* @author Richard
*/
public class Registry {
private static final Map<String, PastebinProvider> pastebinProviders = new HashMap<String, PastebinProvider>();
private static final Map<String, Class<? extends NotificationProvider>> notificationProviders = new HashMap<String, Class<? extends NotificationProvider>>();
/**
* Register a {@link PastebinProvider}.
*
* @param id ID name for the provider, used in the config file
* @param provider The provider
*/
public static void registerPastebinProvider(String id, PastebinProvider provider) {
if (pastebinProviders.containsKey(id)) throw new IllegalArgumentException("Pastebin provider " + id + " already registered by " + pastebinProviders.get(id) + " when registering " + provider);
pastebinProviders.put(id, provider);
}
/**
* Get a {@link PastebinProvider} by its ID.
*
* @param id ID name for the provider
* @return The provider, or null if there is no such provider
*/
public static PastebinProvider getPastebinProvider(String id) {
return pastebinProviders.get(id);
}
/**
* Get a list of {@link PastebinProvider}s, the first one being the user's preferred pastebin.
*
* @return List of providers
*/
public static List<PastebinProvider> getPastebinProviders() {
List<PastebinProvider> providers = new ArrayList<PastebinProvider>(pastebinProviders.size());
// first the preferred one
PastebinProvider preferred = CallHandler.instance.getPastebin();
if (preferred != null) providers.add(preferred);
// then the rest
providers.addAll(pastebinProviders.values());
return providers;
}
/**
* Get a map of all {@link PastebinProvider}s, in no particular order.
*
* @return Map of providers
*/
public static Map<String, PastebinProvider> getAllPastebinProviders() {
return Collections.unmodifiableMap(pastebinProviders);
}
/**
* Register a {@link NotificationProvider} class.
*
* @param id ID name for the provider, used in the config file
* @param provider The provider class
*/
public static void registerNotificationProvider(String id, Class<? extends NotificationProvider> provider) {
if (notificationProviders.containsKey(id)) throw new IllegalArgumentException("Notification provider " + id + " already registered by " + notificationProviders.get(id) + " when registering " + provider);
notificationProviders.put(id, provider);
}
/**
* Get a {@link NotificationProvider} class by its ID.
*
* @param id ID name for the provider class
* @return The provider class, or null if there is no such provider
*/
public static Class<? extends NotificationProvider> getNotificationProvider(String id) {
return notificationProviders.get(id);
}
/**
* Get a list of {@link NotificationProvider} classes.
*
* @return List of provider classes
* @see CallHandler#getActiveNotificationProviders()
*/
public static List<Class<? extends NotificationProvider>> getNotificationProviders() {
List<Class<? extends NotificationProvider>> providers = new ArrayList<Class<? extends NotificationProvider>>(notificationProviders.size());
providers.addAll(notificationProviders.values());
return providers;
}
/**
* Get a map of all {@link NotificationProvider} classes.
*
* @return Map of provider classes
* @see CallHandler#getActiveNotificationProviders()
*/
public static Map<String, Class<? extends NotificationProvider>> getAllNotificationProviders() {
return Collections.unmodifiableMap(notificationProviders);
}
}
| richardg867/CrashReporter | src/crashreporter/api/Registry.java | Java | unlicense | 3,754 |
package gui.dragndrop;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class DragAndDrop extends Application
{
public void start(Stage stage)
{
AnchorPane root = new AnchorPane();
Label source = new Label("DRAG ME");
source.setLayoutX(50);
source.setLayoutY(100);
source.setScaleX(2.0);
source.setScaleY(2.0);
root.getChildren().add(source);
Label target = new Label("DROP HERE");
target.setLayoutX(250);
target.setLayoutY(100);
target.setScaleX(2.0);
target.setScaleY(2.0);
root.getChildren().add(target);
source.setOnDragDetected(e->onDragDetected(e));
target.setOnDragOver(e->onDragOver(e));
target.setOnDragEntered(e->onDragEntered(e));
target.setOnDragExited(e->onDragExited(e));
target.setOnDragDropped(e->onDragDropped(e));
source.setOnDragDone(e->onDragDone(e));
Scene scene = new Scene(root, 400, 200);
stage.setScene(scene);
stage.setTitle("Drag and Drop");
stage.show();
}
private void onDragDetected(MouseEvent e)
{
System.out.println("onDragDetected");
Label source = (Label)e.getSource();
Dragboard db = source.startDragAndDrop(TransferMode.ANY);
ClipboardContent content = new ClipboardContent();
content.putString(source.getText());
db.setContent(content);
}
private void onDragOver(DragEvent e)
{
System.out.println("onDragOver");
Label target = (Label)e.getSource();
if(e.getGestureSource() != target && e.getDragboard().hasString())
{
e.acceptTransferModes(TransferMode.COPY_OR_MOVE);
}
}
private void onDragEntered(DragEvent e)
{
System.out.println("onDragEntered");
Label target = (Label)e.getSource();
if(e.getGestureSource() != target && e.getDragboard().hasString())
{
target.setTextFill(Color.RED);
}
}
private void onDragExited(DragEvent e)
{
System.out.println("onDragExited");
Label target = (Label)e.getSource();
target.setTextFill(Color.BLACK);
}
private void onDragDropped(DragEvent e)
{
System.out.println("onDragDropped");
Label target = (Label)e.getSource();
Dragboard db = e.getDragboard();
boolean success = false;
if(db.hasString())
{
target.setText(db.getString());
success = true;
}
e.setDropCompleted(success);
}
private void onDragDone(DragEvent e)
{
System.out.println("onDragDone");
Label source = (Label)e.getSource();
if (e.getTransferMode() == TransferMode.MOVE)
{
source.setText("");
}
}
public static void main(String[] args)
{
launch(args);
}
} | KonstantinTwardzik/Graphical-User-Interfaces | CodeExamples/src/gui/dragndrop/DragAndDrop.java | Java | unlicense | 3,091 |
var leaderboard2 = function(data) {
return data.data.sort(function(a,b){return b.points-a.points;});
};
function liCreate(name,points) {
var li = $('<li>'+name+'</li>');
li.append('<span>'+points+'</span>');
}
$(document).ready(function() {
// var sorted = leaderboard2(data);
// for (var i=0; i<sorted.length; i++) {
// $('body').append('<div><p>'+sorted[i].name+' '+sorted[i].points+'</p></div>')
// }
// //problem here is with repeated DOM manipulation
var studentArray = [];
$.getJSON('http://192.168.1.35:8000/data.json').success(function(data){
//using '$.getJSON' as opposed to $.ajax specifies
//also, include both success and error handler to account for asynchrony.
//i.e., if/when SUCCESS, execute some code block; if ERROR, execute another.
console.log(data);
var sorted = leaderboard2(data);
for (var i=0; i<sorted.length; i++) {
var student = ('<div><p>'+sorted[i].name+' '+sorted[i].points+'</p></div>');
studentArray.push(student);
}
//^^ FIXED!!! Append entire array ^^
console.log(studentArray);
$('body').append(studentArray);
})
.error(function(error){
console.log(error);
});
});
| sherylpeebee/redditClone | own-playground/karma/script.js | JavaScript | unlicense | 1,196 |
package lcd2usb
import (
"errors"
"fmt"
"github.com/schleibinger/sio"
)
type cmd byte
const (
cmdPrefix cmd = 0xfe
cmdBacklightOn = 0x42
cmdBacklightOff = 0x46
cmdBrightnes = 0x99 // brightnes
cmdContrast = 0x50 // contrast
cmdAutoscrollOn = 0x51
cmdAutoscrollOff = 0x52
cmdClearScreen = 0x58
cmdChangeSplash = 0x40 // Write number of chars for splash
cmdCursorPosition = 0x47 // x, y
cmdHome = 0x48
cmdCursorBack = 0x4c
cmdCursorForward = 0x4d
cmdUnderlineOn = 0x4a
cmdUnderlineOff = 0x4b
cmdBlockOn = 0x53
cmdBlockOff = 0x54
cmdBacklightColor = 0xd0 // r, g, b
cmdLCDSize = 0xd1 // cols, rows
cmdCreateChar = 0x4e
cmdSaveChar = 0xc1
cmdLoadChar = 0xc0
)
type Device struct {
rows uint8
cols uint8
p *sio.Port
}
func Open(name string, rows, cols uint8) (*Device, error) {
p, err := sio.Open(name, 9600)
if err != nil {
return nil, err
}
d := &Device{
rows: rows,
cols: cols,
p: p,
}
if err = d.send(cmdLCDSize, cols, rows); err != nil {
return nil, err
}
return d, nil
}
func (d *Device) Close() error {
if d.p != nil {
err := d.p.Close()
d.p = nil
return err
}
return nil
}
func (d *Device) Write(buf []byte) (n int, err error) {
if d.p == nil {
return 0, errors.New("writing to closed deviced")
}
return d.p.Write(buf)
}
func (d *Device) send(c cmd, args ...byte) error {
_, err := d.Write(append([]byte{byte(cmdPrefix), byte(c)}, args...))
return err
}
func (d *Device) Backlight(on bool) error {
if on {
return d.send(cmdBacklightOn)
} else {
return d.send(cmdBacklightOff)
}
}
func (d *Device) Brightnes(set uint8) error {
return d.send(cmdBrightnes, set)
}
func (d *Device) Contrast(set uint8) error {
return d.send(cmdContrast, set)
}
func (d *Device) Autoscroll(on bool) error {
if on {
return d.send(cmdAutoscrollOn)
} else {
return d.send(cmdAutoscrollOff)
}
}
func (d *Device) Clear() error {
return d.send(cmdClearScreen)
}
func (d *Device) ChangeSplash(set []byte) error {
cells := int(d.rows) * int(d.cols)
if len(set) > cells {
return fmt.Errorf("wrong number of characters: expected %d", cells)
}
return d.send(cmdChangeSplash, set...)
}
func (d *Device) CursorPosition(x, y uint8) error {
if x > d.cols || y > d.rows {
return fmt.Errorf("setting cursor out of bounds")
}
return d.send(cmdCursorPosition, x, y)
}
func (d *Device) Home() error {
return d.send(cmdHome)
}
func (d *Device) CursorBack() error {
return d.send(cmdCursorBack)
}
func (d *Device) CursorForward() error {
return d.send(cmdCursorForward)
}
func (d *Device) Underline(on bool) error {
if on {
return d.send(cmdUnderlineOn)
} else {
return d.send(cmdUnderlineOff)
}
}
func (d *Device) Block(on bool) error {
if on {
return d.send(cmdBlockOn)
} else {
return d.send(cmdBlockOff)
}
}
func (d *Device) Color(r, g, b uint8) error {
return d.send(cmdBacklightColor, r, g, b)
}
| Merovius/go-misc | lcd2usb/main.go | GO | unlicense | 3,074 |
public class Student {
private String namn;
private int födelseår, status, id;
public Student(){}
public String getNamn() {
return namn;
}
public void setNamn(String nyNamn) {
namn=nyNamn;
}
public int getId() {
return id;
}
public void setId(int nyId) {
id=nyId;
}
public int getStatus() {
return status;
}
public void setStatus(int nyStatus) {
status=nyStatus;
}
public int getFödelseår() {
return födelseår;
}
public void setFödelseår(int nyFödelseår) {
födelseår=nyFödelseår;
}
public String print() {
return namn+"\t"+id+"\t"+födelseår;
}
}
| andreasaronsson/introduktion_till_informatik | tebrakod/Student.java | Java | apache-2.0 | 589 |
package com.jerry.controller;
import com.jerry.model.TBanquet;
import com.jerry.service.BanquetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/banquet")
public class BanquetController {
@Autowired
BanquetService banquetService;
@GetMapping("/listBanquetByRestaurantId")
public List<TBanquet> listBanquetByRestaurantId(String restaurantId) {
return banquetService.listBanquetByRestaurantId(restaurantId);
}
@GetMapping("/findOne")
public TBanquet findOne(String banquetId) {
return banquetService.findOne(banquetId);
}
}
| luoyefeiwu/learn_java | jpa/src/main/java/com/jerry/controller/BanquetController.java | Java | apache-2.0 | 840 |
---
title: Multicluster
test: n/a
---
Multicluster is a deployment model that consists of a
[mesh](/docs/reference/glossary/#service-mesh) with multiple
[clusters](/docs/reference/glossary/#cluster).
| istio/istio.io | content/en/docs/reference/glossary/multicluster.md | Markdown | apache-2.0 | 201 |
/*!
* Ext JS Library 3.4.0
* Copyright(c) 2006-2011 Sencha Inc.
* [email protected]
* http://www.sencha.com/license
*/
/**
* @class Ext.dd.DragTracker
* @extends Ext.util.Observable
* A DragTracker listens for drag events on an Element and fires events at the start and end of the drag,
* as well as during the drag. This is useful for components such as {@link Ext.slider.MultiSlider}, where there is
* an element that can be dragged around to change the Slider's value.
* DragTracker provides a series of template methods that should be overridden to provide functionality
* in response to detected drag operations. These are onBeforeStart, onStart, onDrag and onEnd.
* See {@link Ext.slider.MultiSlider}'s initEvents function for an example implementation.
*/
Ext.dd.DragTracker = Ext.extend(Ext.util.Observable, {
/**
* @cfg {Boolean} active
* Defaults to <tt>false</tt>.
*/
active: false,
/**
* @cfg {Number} tolerance
* Number of pixels the drag target must be moved before dragging is considered to have started. Defaults to <tt>5</tt>.
*/
tolerance: 5,
/**
* @cfg {Boolean/Number} autoStart
* Defaults to <tt>false</tt>. Specify <tt>true</tt> to defer trigger start by 1000 ms.
* Specify a Number for the number of milliseconds to defer trigger start.
*/
autoStart: false,
constructor : function(config){
Ext.apply(this, config);
this.addEvents(
/**
* @event mousedown
* @param {Object} this
* @param {Object} e event object
*/
'mousedown',
/**
* @event mouseup
* @param {Object} this
* @param {Object} e event object
*/
'mouseup',
/**
* @event mousemove
* @param {Object} this
* @param {Object} e event object
*/
'mousemove',
/**
* @event dragstart
* @param {Object} this
* @param {Object} e event object
*/
'dragstart',
/**
* @event dragend
* @param {Object} this
* @param {Object} e event object
*/
'dragend',
/**
* @event drag
* @param {Object} this
* @param {Object} e event object
*/
'drag'
);
this.dragRegion = new Ext.lib.Region(0,0,0,0);
if(this.el){
this.initEl(this.el);
}
Ext.dd.DragTracker.superclass.constructor.call(this, config);
},
initEl: function(el){
this.el = Ext.get(el);
el.on('mousedown', this.onMouseDown, this,
this.delegate ? {delegate: this.delegate} : undefined);
},
destroy : function(){
this.el.un('mousedown', this.onMouseDown, this);
delete this.el;
},
onMouseDown: function(e, target){
if(this.fireEvent('mousedown', this, e) !== false && this.onBeforeStart(e) !== false){
this.startXY = this.lastXY = e.getXY();
this.dragTarget = this.delegate ? target : this.el.dom;
if(this.preventDefault !== false){
e.preventDefault();
}
Ext.getDoc().on({
scope: this,
mouseup: this.onMouseUp,
mousemove: this.onMouseMove,
selectstart: this.stopSelect
});
if(this.autoStart){
this.timer = this.triggerStart.defer(this.autoStart === true ? 1000 : this.autoStart, this, [e]);
}
}
},
onMouseMove: function(e, target){
// HACK: IE hack to see if button was released outside of window. */
if(this.active && Ext.isIE && !e.browserEvent.button){
e.preventDefault();
this.onMouseUp(e);
return;
}
e.preventDefault();
var xy = e.getXY(), s = this.startXY;
this.lastXY = xy;
if(!this.active){
if(Math.abs(s[0]-xy[0]) > this.tolerance || Math.abs(s[1]-xy[1]) > this.tolerance){
this.triggerStart(e);
}else{
return;
}
}
this.fireEvent('mousemove', this, e);
this.onDrag(e);
this.fireEvent('drag', this, e);
},
onMouseUp: function(e) {
var doc = Ext.getDoc(),
wasActive = this.active;
doc.un('mousemove', this.onMouseMove, this);
doc.un('mouseup', this.onMouseUp, this);
doc.un('selectstart', this.stopSelect, this);
e.preventDefault();
this.clearStart();
this.active = false;
delete this.elRegion;
this.fireEvent('mouseup', this, e);
if(wasActive){
this.onEnd(e);
this.fireEvent('dragend', this, e);
}
},
triggerStart: function(e) {
this.clearStart();
this.active = true;
this.onStart(e);
this.fireEvent('dragstart', this, e);
},
clearStart : function() {
if(this.timer){
clearTimeout(this.timer);
delete this.timer;
}
},
stopSelect : function(e) {
e.stopEvent();
return false;
},
/**
* Template method which should be overridden by each DragTracker instance. Called when the user first clicks and
* holds the mouse button down. Return false to disallow the drag
* @param {Ext.EventObject} e The event object
*/
onBeforeStart : function(e) {
},
/**
* Template method which should be overridden by each DragTracker instance. Called when a drag operation starts
* (e.g. the user has moved the tracked element beyond the specified tolerance)
* @param {Ext.EventObject} e The event object
*/
onStart : function(xy) {
},
/**
* Template method which should be overridden by each DragTracker instance. Called whenever a drag has been detected.
* @param {Ext.EventObject} e The event object
*/
onDrag : function(e) {
},
/**
* Template method which should be overridden by each DragTracker instance. Called when a drag operation has been completed
* (e.g. the user clicked and held the mouse down, dragged the element and then released the mouse button)
* @param {Ext.EventObject} e The event object
*/
onEnd : function(e) {
},
/**
* Returns the drag target
* @return {Ext.Element} The element currently being tracked
*/
getDragTarget : function(){
return this.dragTarget;
},
getDragCt : function(){
return this.el;
},
getXY : function(constrain){
return constrain ?
this.constrainModes[constrain].call(this, this.lastXY) : this.lastXY;
},
getOffset : function(constrain){
var xy = this.getXY(constrain),
s = this.startXY;
return [s[0]-xy[0], s[1]-xy[1]];
},
constrainModes: {
'point' : function(xy){
if(!this.elRegion){
this.elRegion = this.getDragCt().getRegion();
}
var dr = this.dragRegion;
dr.left = xy[0];
dr.top = xy[1];
dr.right = xy[0];
dr.bottom = xy[1];
dr.constrainTo(this.elRegion);
return [dr.left, dr.top];
}
}
}); | ahwxl/cms | icms/src/main/webapp/res/extjs/src/dd/DragTracker.js | JavaScript | apache-2.0 | 7,637 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link rel="SHORTCUT ICON" href="../../../../../img/clover.ico" />
<link rel="stylesheet" href="../../../../../aui/css/aui.min.css" media="all"/>
<link rel="stylesheet" href="../../../../../aui/css/aui-experimental.min.css" media="all"/>
<!--[if IE 9]><link rel="stylesheet" href="../../../../../aui/css/aui-ie9.min.css" media="all"/><![endif]-->
<style type="text/css" media="all">
@import url('../../../../../style.css');
@import url('../../../../../tree.css');
</style>
<script src="../../../../../jquery-1.8.3.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-experimental.min.js" type="text/javascript"></script>
<script src="../../../../../aui/js/aui-soy.min.js" type="text/javascript"></script>
<script src="../../../../../package-nodes-tree.js" type="text/javascript"></script>
<script src="../../../../../clover-tree.js" type="text/javascript"></script>
<script src="../../../../../clover.js" type="text/javascript"></script>
<script src="../../../../../clover-descriptions.js" type="text/javascript"></script>
<script src="../../../../../cloud.js" type="text/javascript"></script>
<title>ABA Route Transit Number Validator 1.0.1-SNAPSHOT</title>
</head>
<body>
<div id="page">
<header id="header" role="banner">
<nav class="aui-header aui-dropdown2-trigger-group" role="navigation">
<div class="aui-header-inner">
<div class="aui-header-primary">
<h1 id="logo" class="aui-header-logo aui-header-logo-clover">
<a href="http://openclover.org" title="Visit OpenClover home page"><span class="aui-header-logo-device">OpenClover</span></a>
</h1>
</div>
<div class="aui-header-secondary">
<ul class="aui-nav">
<li id="system-help-menu">
<a class="aui-nav-link" title="Open online documentation" target="_blank"
href="http://openclover.org/documentation">
<span class="aui-icon aui-icon-small aui-iconfont-help"> Help</span>
</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="aui-page-panel">
<div class="aui-page-panel-inner">
<div class="aui-page-panel-nav aui-page-panel-nav-clover">
<div class="aui-page-header-inner" style="margin-bottom: 20px;">
<div class="aui-page-header-image">
<a href="http://cardatechnologies.com" target="_top">
<div class="aui-avatar aui-avatar-large aui-avatar-project">
<div class="aui-avatar-inner">
<img src="../../../../../img/clover_logo_large.png" alt="Clover icon"/>
</div>
</div>
</a>
</div>
<div class="aui-page-header-main" >
<h1>
<a href="http://cardatechnologies.com" target="_top">
ABA Route Transit Number Validator 1.0.1-SNAPSHOT
</a>
</h1>
</div>
</div>
<nav class="aui-navgroup aui-navgroup-vertical">
<div class="aui-navgroup-inner">
<ul class="aui-nav">
<li class="">
<a href="../../../../../dashboard.html">Project overview</a>
</li>
</ul>
<div class="aui-nav-heading packages-nav-heading">
<strong>Packages</strong>
</div>
<div class="aui-nav project-packages">
<form method="get" action="#" class="aui package-filter-container">
<input type="text" autocomplete="off" class="package-filter text"
placeholder="Type to filter packages..." name="package-filter" id="package-filter"
title="Start typing package name (or part of the name) to search through the tree. Use arrow keys and the Enter key to navigate."/>
</form>
<p class="package-filter-no-results-message hidden">
<small>No results found.</small>
</p>
<div class="packages-tree-wrapper" data-root-relative="../../../../../" data-package-name="com.cardatechnologies.utils.validators.abaroutevalidator">
<div class="packages-tree-container"></div>
<div class="clover-packages-lozenges"></div>
</div>
</div>
</div>
</nav> </div>
<section class="aui-page-panel-content">
<div class="aui-page-panel-content-clover">
<div class="aui-page-header-main"><ol class="aui-nav aui-nav-breadcrumbs">
<li><a href="../../../../../dashboard.html"> Project Clover database Sat Aug 7 2021 12:29:33 MDT</a></li>
<li><a href="test-pkg-summary.html">Package com.cardatechnologies.utils.validators.abaroutevalidator</a></li>
<li><a href="test-Test_AbaRouteValidator_03.html">Class Test_AbaRouteValidator_03</a></li>
</ol></div>
<h1 class="aui-h2-clover">
Test testAbaNumberCheck_4953_good
</h1>
<table class="aui">
<thead>
<tr>
<th>Test</th>
<th><label title="The test result. Either a Pass, Fail or Error.">Status</label></th>
<th><label title="When the test execution was started">Start time</label></th>
<th><label title="The total time in seconds taken to run this test.">Time (seconds)</label></th>
<th><label title="A failure or error message if the test is not successful.">Message</label></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_03.html?line=58937#src-58937" >testAbaNumberCheck_4953_good</a>
</td>
<td>
<span class="sortValue">1</span><span class="aui-lozenge aui-lozenge-success">PASS</span>
</td>
<td>
7 Aug 12:33:30
</td>
<td>
0.0 </td>
<td>
<div></div>
<div class="errorMessage"></div>
</td>
</tr>
</tbody>
</table>
<div> </div>
<table class="aui aui-table-sortable">
<thead>
<tr>
<th style="white-space:nowrap;"><label title="A class that was directly hit by this test.">Target Class</label></th>
<th colspan="4"><label title="The percentage of coverage contributed by each single test.">Coverage contributed by</label> testAbaNumberCheck_4953_good</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<span class="sortValue">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</span>
  <a href="../../../../../com/cardatechnologies/utils/validators/abaroutevalidator/AbaRouteValidator.html?id=14548#AbaRouteValidator" title="AbaRouteValidator" name="sl-47">com.cardatechnologies.utils.validators.abaroutevalidator.AbaRouteValidator</a>
</td>
<td>
<span class="sortValue">0.7352941</span>73.5%
</td>
<td class="align-middle" style="width: 100%" colspan="3">
<div>
<div title="73.5% Covered" style="min-width:40px;" class="barNegative contribBarNegative contribBarNegative"><div class="barPositive contribBarPositive contribBarPositive" style="width:73.5%"></div></div></div> </td>
</tr>
</tbody>
</table>
</div> <!-- class="aui-page-panel-content-clover" -->
<footer id="footer" role="contentinfo">
<section class="footer-body">
<ul>
<li>
Report generated by <a target="_new" href="http://openclover.org">OpenClover</a> v 4.4.1
on Sat Aug 7 2021 12:49:26 MDT using coverage data from Sat Aug 7 2021 12:47:23 MDT.
</li>
</ul>
<ul>
<li>OpenClover is free and open-source software. </li>
</ul>
</section>
</footer> </section> <!-- class="aui-page-panel-content" -->
</div> <!-- class="aui-page-panel-inner" -->
</div> <!-- class="aui-page-panel" -->
</div> <!-- id="page" -->
</body>
</html> | dcarda/aba.route.validator | target13/site/clover/com/cardatechnologies/utils/validators/abaroutevalidator/Test_AbaRouteValidator_03_testAbaNumberCheck_4953_good_b84.html | HTML | apache-2.0 | 9,178 |
<?php
/**
* @link https://www.humhub.org/
* @copyright Copyright (c) 2015 HumHub GmbH & Co. KG
* @license https://www.humhub.com/licences
*/
namespace humhub\modules\content\widgets;
/**
* Delete Link for Wall Entries
*
* This widget will attached to the WallEntryControlsWidget and displays
* the "Delete" Link to the Content Objects.
*
* @package humhub.modules_core.wall.widgets
* @since 0.5
*/
class DeleteLink extends \yii\base\Widget
{
/**
* @var \humhub\modules\content\components\ContentActiveRecord
*/
public $content = null;
/**
* Executes the widget.
*/
public function run()
{
if ($this->content->content->canDelete()) {
return $this->render('deleteLink', array(
'model' => $this->content->content->object_model,
'id' => $this->content->content->object_id
));
}
}
}
?> | calonso-conabio/intranet | protected/humhub/modules/content/widgets/DeleteLink.php | PHP | apache-2.0 | 931 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package net.gcolin.jmx.console.embedded;
import net.gcolin.jmx.console.JmxHtml;
import net.gcolin.jmx.console.JmxProcessException;
import net.gcolin.jmx.console.JmxResult;
import net.gcolin.jmx.console.JmxTool;
import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* A Jmx servlet with bootstrap style.
*
* @author Gael COLIN
*
*/
public class BootStrapJmxServlet extends HttpServlet {
private static final long serialVersionUID = 7998004606230901933L;
protected transient JmxTool tool;
protected transient JmxHtml html;
@Override
public void init() throws ServletException {
tool = new JmxTool();
html = new JmxHtml() {
protected String getButtonCss() {
return "btn btn-primary";
}
protected String getInputTextClass() {
return "form-control";
}
protected String getFormClass() {
return "form-inline";
}
protected String getSelectClass() {
return "form-control";
}
protected String getMenuUlClass() {
return "menu";
}
@Override
protected String getTableClass() {
return "table table-bordered";
}
protected void writeCss(Writer writer) throws IOException {
writer.write("<link href=\"/css/bootstrap.min.css\" rel=\"stylesheet\" />");
writer.write("<link href=\"/css/bootstrap-theme.min.css\" rel=\"stylesheet\" />");
writer.write("<style type='text/css'>.menu li.active>a{font-weight:bold}"
+ ".col{display:table-cell}.space{padding-left:16px;}</style>");
}
};
}
@SuppressWarnings("unchecked")
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Map<String, String> parameters = new HashMap<String, String>();
for (Object elt : req.getParameterMap().entrySet()) {
Entry<String, String[]> entry = (Entry<String, String[]>) elt;
parameters.put(entry.getKey(), entry.getValue()[0]);
}
JmxResult result;
try {
result = tool.build(parameters);
} catch (JmxProcessException ex) {
throw new ServletException(ex);
}
result.setRequestUri(req.getRequestURI());
result.setQueryParams(req.getQueryString());
resp.setContentType("text/html");
html.write(result, parameters, resp.getWriter());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
| gcolin/jmx-web-console | jmx-embedded/src/main/java/net/gcolin/jmx/console/embedded/BootStrapJmxServlet.java | Java | apache-2.0 | 3,657 |
using IronFoundry.Warden.Containers;
using Xunit;
namespace IronFoundry.Warden.Test
{
using System;
public class ContainerHandleTests
{
[Theory]
[InlineData(1, "idq1ypm7dyb")]
[InlineData(2, "1of9dl2qia1")]
public void GeneratesIdFromRandomGenerator(int input, string expectedId)
{
var handle = new ContainerHandle(new Random(input));
Assert.Equal<string>(expectedId, handle);
}
[Fact]
public void GeneratesUniqueIds()
{
var handle1 = new ContainerHandle();
var handle2 = new ContainerHandle();
Assert.Equal(11, handle1.ToString().Length);
Assert.Equal(11, handle2.ToString().Length);
Assert.NotEqual(handle1, handle2);
}
}
}
| cloudfoundry-incubator/if_warden | IronFoundry.Warden.Test/Containers/ContainerHandleTests.cs | C# | apache-2.0 | 813 |
Pindrop {#pindrop_index}
=======
[Pindrop][] is an audio engine designed with the needs of games in mind. It's
not just an audio mixer, it also manages the prioritization, adjusts gain based
distance, manages buses, and more. It is largely data-driven. The library user
needs only to load a handful of configuration files and Pindrop handles the
rest.
## Features
### Sound Bank Management
To save memory, only load the sounds you need by grouping them into sound banks.
Load as many banks as you need. Samples are reference counted, so you'll never
load the same sample multiple times.
### Channel Prioritization
In a busy scene a game might have thousands of samples playing at the same time.
Sometimes that is more than the game can handle. Pindrop will manage the
priority of each audio channel and only drop the least important channels when
too many simultaneous streams play at once.
### Distance Attenuation
[Pindrop][] supports positional and non-positional sounds. Positional sounds can
be set to attenuate based on their distance from the listener. The attenuation
curve can be customized so that the audio rolls off with the curve that sounds
right.
### Buses
A series of hierarchical buses may be specified that can automatically adjust
channel gain on the fly. If there is an important sound or voice over that needs
to be heard, audio playing on less important buses can be [ducked][] to ensure
the player hears what they need.
### Easy to Use
[Pindrop][] only requires a few [JSON][] based configuration files, and the code
required to hook it into your own game engine is minimal. File loading is made
fast by [FlatBuffers][]. All you need to do is initialize the library and run
`AdvanceFrame` once each frame in your main loop.
## Dependencies
[FlatBuffers][], a fast serialization system, is used to store the game's data.
The game configuration data is stored in [JSON][] files which are converted to
FlatBuffer binary files using the flatc compiler.
[MathFu][], a geometry math library optimized for [ARM][] and [x86][]
processors. Pindrop uses [MathFu][] three dimensional vectors for distance
attenuation calculations.
[SDL Mixer][], an audio mixing library that sits on top of [SDL][]. SDL Mixer
handles mixing the playing audio samples and streams that Pindrop manages. SDL
Mixer in turn depends on [libogg][] and [libvorbis][] as well.
In addition, [fplutil][] is used to build, deploy, and run the game; build and
archive the game; and profile the game's CPU performance.
## Supported Platforms
[Pindrop][] has been tested on the following platforms:
* [Nexus Player][], an [Android TV][] device
* [Android][] phones and tablets
* [Linux][] (x86_64)
* [OS X][]
* [Windows][]
We use [SDL][] as our cross platform layer.
[Pindrop][] is written entirely in C++. The library can be compiled using
[Linux][], [OS X][] or [Windows][].
## Download
[Pindrop][] can be downloaded from:
* [GitHub][] (source)
* [GitHub Releases Page](http://github.com/google/pindrop/releases) (source)
**Important**: Pindrop uses submodules to reference other components it
depends upon, so download the source from [GitHub][] using:
~~~{.sh}
git clone --recursive https://github.com/google/pindrop.git
~~~
## Feedback and Reporting Bugs
* Discuss Pindrop with other developers and users on the
[Pindrop Google Group][].
* File issues on the [Pindrop Issues Tracker][].
* Post your questions to [stackoverflow.com][] with a mention of
**fpl pindrop**.
<br>
[Android TV]: http://www.android.com/tv/
[Android]: http://www.android.com
[ducked]: http://en.wikipedia.org/wiki/Ducking
[FlatBuffers]: http://google-opensource.blogspot.ca/2014/06/flatbuffers-memory-efficient.html
[fplutil]: http://android-developers.blogspot.ca/2014/11/utilities-for-cc-android-developers.html
[GitHub]: http://github.com/google/pindrop
[JSON]: http://www.json.org/
[Linux]: http://en.m.wikipedia.org/wiki/Linux
[MathFu]: http://googledevelopers.blogspot.ca/2014/11/geometry-math-library-for-c-game.html
[Nexus Player]: http://www.google.com/nexus/player/
[OS X]: http://www.apple.com/osx/
[Pindrop Google Group]: http://groups.google.com/group/pindrop
[Pindrop Issues Tracker]: http://github.com/google/pindrop/issues
[Pindrop]: @ref pindrop_index
[SDL]: https://www.libsdl.org/
[stackoverflow.com]: http://stackoverflow.com/search?q=fpl+pindrop
[stackoverflow.com]: http://www.stackoverflow.com
[WebP]: https://developers.google.com/speed/webp
[Windows]: http://windows.microsoft.com/
[x86]: http://en.wikipedia.org/wiki/X86
| google/pindrop | docs/src/index.md | Markdown | apache-2.0 | 4,628 |
/**
* Copyright 2014 TangoMe Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tango.logstash.flume.redis.sink.serializer;
import org.apache.flume.Event;
import org.apache.flume.conf.Configurable;
import org.apache.flume.conf.ConfigurableComponent;
public interface Serializer extends Configurable, ConfigurableComponent {
/**
* Serialize an event for storage in Redis
*
* @param event
* Event to serialize
* @return Serialized data
*/
byte[] serialize(Event event) throws RedisSerializerException;
}
| DevOps-TangoMe/flume-redis | flume-redis-sink/src/main/java/com/tango/logstash/flume/redis/sink/serializer/Serializer.java | Java | apache-2.0 | 1,070 |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.OutputStream;
/**
* Classic splitter of OutputStream. Named after the unix 'tee'
* command. It allows a stream to be branched off so there
* are now two streams.
*
*/
public class TeeOutputStream extends ProxyOutputStream {
/** the second OutputStream to write to */
protected OutputStream branch; //TODO consider making this private
/**
* Constructs a TeeOutputStream.
* @param out the main OutputStream
* @param branch the second OutputStream
*/
public TeeOutputStream(final OutputStream out, final OutputStream branch) {
super(out);
this.branch = branch;
}
/**
* Write the bytes to both streams.
* @param b the bytes to write
* @throws IOException if an I/O error occurs
*/
@Override
public synchronized void write(final byte[] b) throws IOException {
super.write(b);
this.branch.write(b);
}
/**
* Write the specified bytes to both streams.
* @param b the bytes to write
* @param off The start offset
* @param len The number of bytes to write
* @throws IOException if an I/O error occurs
*/
@Override
public synchronized void write(final byte[] b, final int off, final int len) throws IOException {
super.write(b, off, len);
this.branch.write(b, off, len);
}
/**
* Write a byte to both streams.
* @param b the byte to write
* @throws IOException if an I/O error occurs
*/
@Override
public synchronized void write(final int b) throws IOException {
super.write(b);
this.branch.write(b);
}
/**
* Flushes both streams.
* @throws IOException if an I/O error occurs
*/
@Override
public void flush() throws IOException {
super.flush();
this.branch.flush();
}
/**
* Closes both output streams.
*
* If closing the main output stream throws an exception, attempt to close the branch output stream.
*
* If closing the main and branch output streams both throw exceptions, which exceptions is thrown by this method is
* currently unspecified and subject to change.
*
* @throws IOException
* if an I/O error occurs
*/
@Override
public void close() throws IOException {
try {
super.close();
} finally {
this.branch.close();
}
}
}
| pimtegelaar/commons-io-test3 | src/main/java/org/apache/commons/io/output/TeeOutputStream.java | Java | apache-2.0 | 3,320 |
package org.renjin.primitives;
import org.renjin.eval.Context;
import org.renjin.eval.EvalException;
import org.renjin.primitives.annotations.processor.ArgumentException;
import org.renjin.primitives.annotations.processor.ArgumentIterator;
import org.renjin.primitives.annotations.processor.WrapperRuntime;
import org.renjin.primitives.files.Files;
import org.renjin.sexp.BuiltinFunction;
import org.renjin.sexp.DoubleVector;
import org.renjin.sexp.Environment;
import org.renjin.sexp.FunctionCall;
import org.renjin.sexp.IntVector;
import org.renjin.sexp.LogicalVector;
import org.renjin.sexp.PairList;
import org.renjin.sexp.SEXP;
import org.renjin.sexp.StringVector;
public class R$primitive$file$access
extends BuiltinFunction
{
public R$primitive$file$access() {
super("file.access");
}
public SEXP apply(Context context, Environment environment, FunctionCall call, PairList args) {
try {
ArgumentIterator argIt = new ArgumentIterator(context, environment, args);
SEXP s0 = argIt.evalNext();
SEXP s1 = argIt.evalNext();
if (!argIt.hasNext()) {
return this.doApply(context, environment, s0, s1);
}
throw new EvalException("file.access: too many arguments, expected at most 2.");
} catch (ArgumentException e) {
throw new EvalException(context, "Invalid argument: %s. Expected:\n\tfile.access(character, integer(1))", e.getMessage());
} catch (EvalException e) {
e.initContext(context);
throw e;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new EvalException(e);
}
}
public static SEXP doApply(Context context, Environment environment, FunctionCall call, String[] argNames, SEXP[] args) {
try {
if ((args.length) == 2) {
return doApply(context, environment, args[ 0 ], args[ 1 ]);
}
} catch (EvalException e) {
e.initContext(context);
throw e;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new EvalException(e);
}
throw new EvalException("file.access: max arity is 2");
}
public SEXP apply(Context context, Environment environment, FunctionCall call, String[] argNames, SEXP[] args) {
return R$primitive$file$access.doApply(context, environment, call, argNames, args);
}
public static SEXP doApply(Context context, Environment environment, SEXP arg0, SEXP arg1)
throws Exception
{
if ((arg0 instanceof StringVector)&&(((arg1 instanceof IntVector)||(arg1 instanceof DoubleVector))||(arg1 instanceof LogicalVector))) {
return Files.fileAccess(context, ((StringVector) arg0), WrapperRuntime.convertToInt(arg1));
} else {
throw new EvalException(String.format("Invalid argument:\n\tfile.access(%s, %s)\n\tExpected:\n\tfile.access(character, integer(1))", arg0 .getTypeName(), arg1 .getTypeName()));
}
}
}
| bedatadriven/renjin-statet | org.renjin.core/src-gen/org/renjin/primitives/R$primitive$file$access.java | Java | apache-2.0 | 3,115 |
/*******************************************************************************
* Copyright 2012 EMBL-EBI, Hinxton outstation
*
* 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 uk.ac.ebi.embl.api.validation.check.sourcefeature;
import static org.junit.Assert.*;
import java.util.Collection;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import uk.ac.ebi.embl.api.entry.Entry;
import uk.ac.ebi.embl.api.entry.EntryFactory;
import uk.ac.ebi.embl.api.entry.feature.Feature;
import uk.ac.ebi.embl.api.entry.feature.FeatureFactory;
import uk.ac.ebi.embl.api.entry.qualifier.Qualifier;
import uk.ac.ebi.embl.api.entry.sequence.Sequence;
import uk.ac.ebi.embl.api.entry.sequence.SequenceFactory;
import uk.ac.ebi.embl.api.storage.DataRow;
import uk.ac.ebi.embl.api.validation.*;
public class MoleculeTypeAndSourceQualifierCheckTest {
private Entry entry;
private Feature source;
private MoleculeTypeAndSourceQualifierCheck check;
@Before
public void setUp() {
ValidationMessageManager
.addBundle(ValidationMessageManager.STANDARD_VALIDATION_BUNDLE);
EntryFactory entryFactory = new EntryFactory();
SequenceFactory sequenceFactory = new SequenceFactory();
FeatureFactory featureFactory = new FeatureFactory();
entry = entryFactory.createEntry();
source = featureFactory.createSourceFeature();
entry.addFeature(source);
Sequence sequence = sequenceFactory.createSequence();
entry.setSequence(sequence);
DataRow dataRow = new DataRow(
"tissue_type,dev_stage,isolation_source,collection_date,host,lab_host,sex,mating_type,haplotype,cultivar,ecotype,variety,breed,isolate,strain,clone,country,lat_lon,specimen_voucher,culture_collection,biomaterial,PCR_primers",
"mRNA");
GlobalDataSets.addTestDataSet(GlobalDataSetFile.MOLTYPE_SOURCE_QUALIFIERS, dataRow);
DataRow dataRow1=new DataRow("genomic DNA",Qualifier.GERMLINE_QUALIFIER_NAME);
GlobalDataSets.addTestDataSet(GlobalDataSetFile.SOURCE_QUALIFIERS_MOLTYPE_VALUES, dataRow1);
check = new MoleculeTypeAndSourceQualifierCheck();
}
@After
public void tearDown() {
GlobalDataSets.resetTestDataSets();
}
@Test
public void testCheck_NoEntry() {
assertTrue(check.check(null).isValid());
}
@Test
public void testCheck_NoMoleculeType() {
entry.getSequence().setMoleculeType(null);
source.addQualifier("organism", "Deltavirus");
assertTrue(check.check(entry).isValid());
}
@Test
public void testCheck_NoSequence() {
entry.setSequence(null);
source.addQualifier("organism", "liver");
assertTrue(check.check(entry).isValid());
}
@Test
public void testCheck_noSourceQualifier() {
entry.getSequence().setMoleculeType("mRNA");
ValidationResult result = check.check(entry);
assertEquals(2, result.count("MoleculeTypeAndSourceQualifierCheck",
Severity.ERROR));
}
@Test
public void testCheck_NoSource() {
entry.getSequence().setMoleculeType("mRNA");
entry.removeFeature(source);
ValidationResult result = check.check(entry);
assertEquals(0, result.getMessages().size());
}
@Test
public void testCheck_noRequiredQualifier() {
entry.getSequence().setMoleculeType("mRNA");
source.addQualifier("organism", "some organism");
ValidationResult result = check.check(entry);
assertEquals(1, result.getMessages().size());
}
@Test
public void testCheck_requiredQualifier() {
entry.getSequence().setMoleculeType("mRNA");
source.addQualifier("tissue_type", "liver");
ValidationResult result = check.check(entry);
assertEquals(0, result.getMessages().size());
}
@Test
public void testCheck_Message() {
entry.getSequence().setMoleculeType("mRNA");
ValidationResult result = check.check(entry);
Collection<ValidationMessage<Origin>> messages = result.getMessages(
"MoleculeTypeAndSourceQualifierCheck", Severity.ERROR);
assertEquals(
"At least one of the Qualifiers \"tissue_type, dev_stage, isolation_source, collection_date, host, lab_host, sex, mating_type, haplotype, cultivar, ecotype, variety, breed, isolate, strain, clone, country, lat_lon, specimen_voucher, culture_collection, biomaterial, PCR_primers\" must exist in Source feature if Molecule Type matches the Value \"mRNA\".",
messages.iterator().next().getMessage());
}
@Test
public void testCheck_invalidMolTypeValue() {
entry.getSequence().setMoleculeType("mRNA");
source.addQualifier(Qualifier.GERMLINE_QUALIFIER_NAME);
entry.addFeature(source);
ValidationResult result = check.check(entry);
assertEquals(1,result.getMessages("MoleculeTypeAndSourceQualifierCheck_1", Severity.ERROR).size());
}
@Test
public void testCheck_validMolTypeValue() {
entry.getSequence().setMoleculeType("genomic DNA");
source.addQualifier(Qualifier.GERMLINE_QUALIFIER_NAME);
entry.addFeature(source);
ValidationResult result = check.check(entry);
assertEquals(0,result.getMessages("MoleculeTypeAndSourceQualifierCheck_1", Severity.ERROR).size());
}
}
| enasequence/sequencetools | src/test/java/uk/ac/ebi/embl/api/validation/check/sourcefeature/MoleculeTypeAndSourceQualifierCheckTest.java | Java | apache-2.0 | 5,528 |
<p>
This example shows how Telerik DatePicker for ASP.NET MVC is being validated through the built-in server-side validation capabilities of ASP.NET MVC.
</p>
<pre class="prettyprint">
<%= Html.ValidationSummary() %>
<% using (Html.BeginForm("Action", "Controller")) { %>
<%= Html.Telerik().DatePicker()
.Name("deliveryDate")
%>
<%= Html.ValidationMessage("deliveryDate", "*") %>
<input type="submit" value="Post" />
<% } %>
</pre>
<p>
Additionally you can use <em>DatePickerFor</em> extension in order to create DatePicker for a concrete <em>Model property</em>.
If it has <strong>Range</strong> attribute, DatePicker component will use it to define min and max date
contraints.
</p> | wenbinke/susucms | SusuCMS.Web/Content/DatePicker/Descriptions/ServerValidation.html | HTML | apache-2.0 | 752 |
package com.baicai.util.help;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.FileResourceLoader;
/**
*
* @Description: 使用beetl来生成model类,未完成
* @author 猪肉有毒 [email protected]
* @date 2016年1月16日 下午11:31:04
* @version V1.0 我只为你回眸一笑,即使不够倾国倾城,我只为你付出此生,换来生再次相守
*/
public class GenModel {
public static final String RESOURCEPATH = "F:/data/eclipse/p2p/src/test/resources";
public static void generetor(String tableName) throws IOException {
FileResourceLoader resourceLo = new FileResourceLoader(RESOURCEPATH, "utf-8");
resourceLo.setRoot(RESOURCEPATH);
Configuration config = Configuration.defaultConfiguration();
config.getResourceMap().put("root", null);// 这里需要重置root,否则会去找配置文件
GroupTemplate gt = new GroupTemplate(resourceLo, config);
Template t = gt.getTemplate("model.htm");
TableBean tb = Generator.getTable(tableName);
String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date());
t.binding("table", tb);
t.binding("package", Generator.PACKAGE_BASE);
t.binding("createDate", date);
String str = t.render();
System.out.println(str);
File f = new File(Generator.OUTPUT_PATH+tb.getTableNameCapitalized()+".java");// 新建一个文件对象
FileWriter fw;
try {
fw = new FileWriter(f);// 新建一个FileWriter
fw.write(str);// 将字符串写入到指定的路径下的文件中
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
generetor("p2p_project");
}
}
| iminto/baicai | src/main/java/com/baicai/util/help/GenModel.java | Java | apache-2.0 | 1,924 |
using System.Diagnostics;
namespace Lucene.Net.Index
{
using Lucene.Net.Util;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Filters the incoming reader and makes all documents appear deleted.
/// </summary>
public class AllDeletedFilterReader : FilterAtomicReader
{
internal readonly IBits LiveDocs_Renamed;
public AllDeletedFilterReader(AtomicReader @in)
: base(@in)
{
LiveDocs_Renamed = new Bits.MatchNoBits(@in.MaxDoc);
Debug.Assert(MaxDoc == 0 || HasDeletions);
}
public override IBits LiveDocs
{
get
{
return LiveDocs_Renamed;
}
}
public override int NumDocs
{
get { return 0; }
}
}
} | laimis/lucenenet | src/Lucene.Net.TestFramework/Index/AllDeletedFilterReader.cs | C# | apache-2.0 | 1,641 |
package files
import (
"bytes"
"io"
"io/ioutil"
"strings"
"github.com/golang/protobuf/proto"
"github.com/octavore/nagax/util/errors"
uuid "github.com/satori/go.uuid"
"github.com/willnorris/imageproxy"
"github.com/ketchuphq/ketchup/proto/ketchup/models"
)
func (m *Module) Upload(filename string, wr io.Reader) (*models.File, error) {
// files are assigned a random id when stored to discourage manual renaming of files
filename = strings.TrimPrefix(filename, "/")
file, err := m.DB.GetFileByName(filename)
if err != nil {
return nil, errors.Wrap(err)
}
if file == nil || file.GetUuid() == "" {
file = &models.File{
Uuid: proto.String(uuid.NewV4().String()),
Name: proto.String(filename),
}
}
err = m.store.Upload(file.GetUuid(), wr)
if err != nil {
return nil, errors.Wrap(err)
}
err = m.DB.UpdateFile(file)
if err != nil {
return nil, errors.Wrap(err)
}
return file, nil
}
// Get returns a reader, and nil, nil if file is not found
func (m *Module) Get(filename string) (io.ReadCloser, error) {
filename = strings.TrimPrefix(filename, "/")
file, err := m.DB.GetFileByName(filename)
if err != nil {
return nil, errors.Wrap(err)
}
if file == nil {
return nil, nil
}
return m.store.Get(file.GetUuid())
}
// Get returns a reader, and nil, nil if file is not found
func (m *Module) Delete(uuid string) error {
file, err := m.DB.GetFile(uuid)
if err != nil {
return errors.Wrap(err)
}
if file == nil {
return nil
}
err = m.DB.DeleteFile(file)
if err != nil {
return errors.Wrap(err)
}
return m.store.Delete(file.GetUuid())
}
// GetWithTransform attempts to transform the image
func (m *Module) GetWithTransform(filename string, optStr string) (io.ReadCloser, error) {
filename = strings.TrimPrefix(filename, "/")
r, err := m.Get(filename)
if r == nil || err != nil || optStr == "" {
return r, err
}
defer r.Close()
data, err := ioutil.ReadAll(r)
if err != nil {
return nil, errors.Wrap(err)
}
opts := imageproxy.ParseOptions(optStr)
output, err := imageproxy.Transform(data, opts)
if err != nil {
return nil, errors.Wrap(err)
}
return ioutil.NopCloser(bytes.NewBuffer(output)), nil
}
| ketchuphq/ketchup | server/files/actions.go | GO | apache-2.0 | 2,177 |
<!-- Do not edit this file. It is automatically generated by API Documenter. -->
[Home](./index.md) > [puppeteer](./puppeteer.md) > [Protocol](./puppeteer.protocol.md) > [SystemInfo](./puppeteer.protocol.systeminfo.md) > [GPUInfo](./puppeteer.protocol.systeminfo.gpuinfo.md) > [videoEncoding](./puppeteer.protocol.systeminfo.gpuinfo.videoencoding.md)
## Protocol.SystemInfo.GPUInfo.videoEncoding property
Supported accelerated video encoding capabilities.
<b>Signature:</b>
```typescript
videoEncoding: VideoEncodeAcceleratorCapability[];
```
| GoogleChrome/puppeteer | new-docs/puppeteer.protocol.systeminfo.gpuinfo.videoencoding.md | Markdown | apache-2.0 | 576 |
sap.ui.define(['sap/ui/webc/common/thirdparty/base/asset-registries/Icons'], function (Icons) { 'use strict';
const name = "status-completed";
const pathData = "M256 0q53 0 99.5 20T437 75t55 81.5 20 99.5-20 99.5-55 81.5-81.5 55-99.5 20-99.5-20T75 437t-55-81.5T0 256t20-99.5T75 75t81.5-55T256 0zM128 256q-14 0-23 9t-9 23q0 12 9 23l64 64q11 9 23 9 13 0 23-9l192-192q9-11 9-23 0-13-9.5-22.5T384 128q-12 0-23 9L192 307l-41-42q-10-9-23-9z";
const ltr = false;
const collection = "SAP-icons-v5";
const packageName = "@ui5/webcomponents-icons";
Icons.registerIcon(name, { pathData, ltr, collection, packageName });
var pathDataV4 = { pathData };
return pathDataV4;
});
| SAP/openui5 | src/sap.ui.webc.common/src/sap/ui/webc/common/thirdparty/icons/v5/status-completed.js | JavaScript | apache-2.0 | 673 |
package com.yueny.demo.downlatch.holder;
import java.util.List;
import java.util.Vector;
import org.apache.commons.collections4.CollectionUtils;
import com.yueny.demo.downlatch.bo.RecoverResult;
/**
* @author yueny09 <[email protected]>
*
* @DATE 2016年3月22日 下午1:15:25
*
*/
public class TransResultHolder {
private final List<RecoverResult> failList = new Vector<RecoverResult>();
private Integer recoverCount = 0;
private final List<String> succList = new Vector<String>();
public synchronized void addResults(final List<RecoverResult> resultList) {
if (!CollectionUtils.isEmpty(resultList)) {
recoverCount += resultList.size();
for (final RecoverResult recoverResult : resultList) {
if (recoverResult.isSucc()) {
succList.add(recoverResult.getTransId());
} else {
failList.add(recoverResult);
}
}
}
}
public synchronized List<RecoverResult> getFailList() {
return failList;
}
public synchronized Integer getRecoverCount() {
return recoverCount;
}
public synchronized List<String> getSuccList() {
return succList;
}
}
| yueny/pra | exec/src/main/java/com/yueny/demo/downlatch/holder/TransResultHolder.java | Java | apache-2.0 | 1,149 |
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web.Http;
using Divergent.Sales.Data.Context;
namespace Divergent.Sales.API.Controllers
{
[RoutePrefix("api/orders")]
public class OrdersController : ApiController
{
private readonly ISalesContext _context;
public OrdersController(ISalesContext context)
{
_context = context;
}
[HttpGet]
public IEnumerable<dynamic> Get(int p = 0, int s = 10)
{
var orders = _context.Orders
.Include(i => i.Items)
.Include(i => i.Items.Select(x => x.Product))
.ToArray();
return orders
.Skip(p * s)
.Take(s)
.Select(o => new
{
o.Id,
o.CustomerId,
ProductIds = o.Items.Select(i => i.Product.Id),
ItemsCount = o.Items.Count
});
}
}
}
| jbogard/Workshop.Microservices | exercises/src/01 CompositeUI/after/Divergent.Sales.API/Controllers/OrdersController.cs | C# | apache-2.0 | 1,038 |
from google.appengine.ext import db
class Stuff (db.Model):
owner = db.UserProperty(required=True, auto_current_user=True)
pulp = db.BlobProperty()
class Greeting(db.Model):
author = db.UserProperty()
content = db.StringProperty(multiline=True)
avatar = db.BlobProperty()
date = db.DateTimeProperty(auto_now_add=True)
class Placebo(db.Model):
developer = db.StringProperty()
OID = db.StringProperty()
concept = db.StringProperty()
category = db.StringProperty()
taxonomy = db.StringProperty()
taxonomy_version = db.StringProperty()
code = db.StringProperty()
descriptor = db.StringProperty()
| 0--key/lib | portfolio/2009_GoogleAppEngine/apps/0--key/models.py | Python | apache-2.0 | 651 |
package io.github.mayunfei.simple;
/**
* Created by mayunfei on 17-9-7.
*/
public class OrientationUtils {
}
| MaYunFei/TXLiveDemo | app/src/main/java/io/github/mayunfei/simple/OrientationUtils.java | Java | apache-2.0 | 113 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LCL.Domain.Model;
using LCL.Domain.Specifications;
namespace LCL.Domain.Repositories.Specifications
{
public class SalesOrderIDEqualsSpecification : Specification<SalesOrder>
{
private readonly Guid orderID;
public SalesOrderIDEqualsSpecification(Guid orderID)
{
this.orderID = orderID;
}
public override System.Linq.Expressions.Expression<Func<SalesOrder, bool>> GetExpression()
{
return p => p.ID == orderID;
}
}
}
| luomingui/LCLFramework | LCLDemo/LCL.Domain/Specifications/SalesOrderIDEqualsSpecification.cs | C# | apache-2.0 | 635 |
/*
* Swift Parallel Scripting Language (http://swift-lang.org)
* Code from Java CoG Kit Project (see notice below) with modifications.
*
* Copyright 2005-2014 University of Chicago
*
* 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.
*/
//----------------------------------------------------------------------
//This code is developed as part of the Java CoG Kit project
//The terms of the license can be found at http://www.cogkit.org/license
//This message may not be removed or altered.
//----------------------------------------------------------------------
/*
* Created on Mar 28, 2014
*/
package org.griphyn.vdl.mapping.nodes;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import k.thr.LWThread;
import org.griphyn.vdl.karajan.Pair;
import org.griphyn.vdl.mapping.DSHandle;
import org.griphyn.vdl.mapping.DuplicateMappingChecker;
import org.griphyn.vdl.mapping.HandleOpenException;
import org.griphyn.vdl.mapping.Mapper;
import org.griphyn.vdl.mapping.Path;
import org.griphyn.vdl.mapping.RootHandle;
import org.griphyn.vdl.mapping.file.FileGarbageCollector;
import org.griphyn.vdl.type.Field;
import org.griphyn.vdl.type.Types;
public class RootClosedMapDataNode extends AbstractClosedDataNode implements ArrayHandle, RootHandle {
private int line = -1;
private LWThread thread;
private Mapper mapper;
private Map<Comparable<?>, DSHandle> values;
public RootClosedMapDataNode(Field field, Map<?, ?> values, DuplicateMappingChecker dmChecker) {
super(field);
setValues(values);
if (getType().itemType().hasMappedComponents()) {
this.mapper = new InitMapper(dmChecker);
}
}
private void setValues(Map<?, ?> m) {
values = new HashMap<Comparable<?>, DSHandle>();
for (Map.Entry<?, ? extends Object> e : m.entrySet()) {
Comparable<?> k = (Comparable<?>) e.getKey();
Object n = e.getValue();
if (n instanceof DSHandle) {
values.put(k, (DSHandle) n);
}
else if (n instanceof String) {
values.put(k,
NodeFactory.newNode(Field.Factory.createField(k, Types.STRING), getRoot(), this, n));
}
else if (n instanceof Integer) {
values.put(k,
NodeFactory.newNode(Field.Factory.createField(k, Types.INT), getRoot(), this, n));
}
else if (n instanceof Double) {
values.put(k,
NodeFactory.newNode(Field.Factory.createField(k, Types.FLOAT), getRoot(), this, n));
}
else {
throw new RuntimeException(
"An array variable can only be initialized by a list of DSHandle or primitive values");
}
}
}
@Override
public RootHandle getRoot() {
return this;
}
@Override
public DSHandle getParent() {
return null;
}
@Override
public Path getPathFromRoot() {
return Path.EMPTY_PATH;
}
@Override
public void init(Mapper mapper) {
if (!getType().itemType().hasMappedComponents()) {
return;
}
if (mapper == null) {
initialized();
}
else {
this.getInitMapper().setMapper(mapper);
this.mapper.initialize(this);
}
}
@Override
public void mapperInitialized(Mapper mapper) {
synchronized(this) {
this.mapper = mapper;
}
initialized();
}
protected void initialized() {
if (variableTracer.isEnabled()) {
variableTracer.trace(thread, line, getName() + " INITIALIZED " + mapper);
}
}
public synchronized Mapper getMapper() {
if (mapper instanceof InitMapper) {
return ((InitMapper) mapper).getMapper();
}
else {
return mapper;
}
}
@Override
public int getLine() {
return line;
}
@Override
public void setLine(int line) {
this.line = line;
}
@Override
public void setThread(LWThread thread) {
this.thread = thread;
}
@Override
public LWThread getThread() {
return thread;
}
@Override
public String getName() {
return (String) getField().getId();
}
@Override
protected AbstractDataNode getParentNode() {
return null;
}
@Override
public Mapper getActualMapper() {
return mapper;
}
@Override
public void closeArraySizes() {
// already closed
}
@Override
public Object getValue() {
return values;
}
@Override
public Map<Comparable<?>, DSHandle> getArrayValue() {
return values;
}
@Override
public boolean isArray() {
return true;
}
@Override
public Iterable<List<?>> entryList() {
final Iterator<Map.Entry<Comparable<?>, DSHandle>> i = values.entrySet().iterator();
return new Iterable<List<?>>() {
@Override
public Iterator<List<?>> iterator() {
return new Iterator<List<?>>() {
@Override
public boolean hasNext() {
return i.hasNext();
}
@Override
public List<?> next() {
Map.Entry<Comparable<?>, DSHandle> e = i.next();
return new Pair<Object>(e.getKey(), e.getValue());
}
@Override
public void remove() {
i.remove();
}
};
}
};
}
@Override
protected Object getRawValue() {
return values;
}
@Override
protected void getFringePaths(List<Path> list, Path myPath)
throws HandleOpenException {
for (Map.Entry<Comparable<?>, DSHandle> e : values.entrySet()) {
DSHandle h = e.getValue();
if (h instanceof AbstractDataNode) {
AbstractDataNode ad = (AbstractDataNode) h;
ad.getFringePaths(list, myPath.addLast(e.getKey()));
}
else {
list.addAll(h.getFringePaths());
}
}
}
@Override
public void getLeaves(List<DSHandle> list) throws HandleOpenException {
for (Map.Entry<Comparable<?>, DSHandle> e : values.entrySet()) {
DSHandle h = e.getValue();
if (h instanceof AbstractDataNode) {
AbstractDataNode ad = (AbstractDataNode) h;
ad.getLeaves(list);
}
else {
list.addAll(h.getLeaves());
}
}
}
@Override
public int arraySize() {
return values.size();
}
@Override
protected void clean0() {
FileGarbageCollector.getDefault().clean(this);
super.clean0();
}
@Override
protected void finalize() throws Throwable {
if (!isCleaned()) {
clean();
}
super.finalize();
}
}
| swift-lang/swift-k | src/org/griphyn/vdl/mapping/nodes/RootClosedMapDataNode.java | Java | apache-2.0 | 7,772 |
var baseClone = require('./_baseClone');
/**
* This method is like `_.clone` except that it accepts `customizer` which
* is invoked to produce the cloned value. If `customizer` returns `undefined`,
* cloning is handled by the method instead. The `customizer` is invoked with
* up to four arguments; (value [, index|key, object, stack]).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to clone.
* @param {Function} [customizer] The function to customize cloning.
* @returns {*} Returns the cloned value.
* @see _.cloneDeepWith
* @example
*
* function customizer(value) {
* if (_.isElement(value)) {
* return value.cloneNode(false);
* }
* }
*
* var el = _.cloneWith(document.body, customizer);
*
* console.log(el === document.body);
* // => false
* console.log(el.nodeName);
* // => 'BODY'
* console.log(el.childNodes.length);
* // => 0
*/
function cloneWith(value, customizer) {
customizer = typeof customizer == 'function' ? customizer : undefined;
return baseClone(value, false, true, customizer);
}
module.exports = cloneWith;
| ionutbarau/petstore | petstore-app/src/main/resources/static/node_modules/bower/lib/node_modules/lodash/cloneWith.js | JavaScript | apache-2.0 | 1,117 |
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for tensorflow.ops.math_ops.matmul."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.python.platform
import numpy as np
import tensorflow as tf
from tensorflow.python.kernel_tests import gradient_checker as gc
class MatMulTest(tf.test.TestCase):
def _testCpuMatmul(self, x, y, transpose_x=False, transpose_y=False):
x_mat = np.matrix(x).T if transpose_x else np.matrix(x)
y_mat = np.matrix(y).T if transpose_y else np.matrix(y)
np_ans = x_mat * y_mat
with self.test_session(use_gpu=False):
tf_ans = tf.matmul(x, y, transpose_x, transpose_y).eval()
self.assertAllClose(np_ans, tf_ans)
self.assertAllEqual(np_ans.shape, tf_ans.shape)
def _testGpuMatmul(self, x, y, transpose_x=False, transpose_y=False):
x_mat = np.matrix(x).T if transpose_x else np.matrix(x)
y_mat = np.matrix(y).T if transpose_y else np.matrix(y)
np_ans = x_mat * y_mat
with self.test_session(use_gpu=True):
tf_ans = tf.matmul(x, y, transpose_x, transpose_y).eval()
self.assertAllClose(np_ans, tf_ans)
self.assertAllEqual(np_ans.shape, tf_ans.shape)
def _randMatrix(self, rows, cols, dtype):
if dtype is np.complex64:
real = self._randMatrix(rows, cols, np.float32)
imag = self._randMatrix(rows, cols, np.float32)
return real + np.complex(0, 1) * imag
else:
return np.random.uniform(low=1.0, high=100.0, size=rows * cols).reshape(
[rows, cols]).astype(dtype)
# Basic test:
# [ [1],
# [2],
# [3], * [1, 2]
# [4] ]
def testFloatBasic(self):
x = np.arange(1., 5.).reshape([4, 1]).astype(np.float32)
y = np.arange(1., 3.).reshape([1, 2]).astype(np.float32)
self._testCpuMatmul(x, y)
self._testGpuMatmul(x, y)
def testDoubleBasic(self):
x = np.arange(1., 5.).reshape([4, 1]).astype(np.float64)
y = np.arange(1., 3.).reshape([1, 2]).astype(np.float64)
self._testCpuMatmul(x, y)
def testInt32Basic(self):
x = np.arange(1., 5.).reshape([4, 1]).astype(np.int32)
y = np.arange(1., 3.).reshape([1, 2]).astype(np.int32)
self._testCpuMatmul(x, y)
def testSComplexBasic(self):
x = np.arange(1., 5.).reshape([4, 1]).astype(np.complex64)
y = np.arange(1., 3.).reshape([1, 2]).astype(np.complex64)
self._testCpuMatmul(x, y)
# Tests testing random sized matrices.
def testFloatRandom(self):
for _ in range(10):
n, k, m = np.random.randint(1, 100, size=3)
x = self._randMatrix(n, k, np.float32)
y = self._randMatrix(k, m, np.float32)
self._testCpuMatmul(x, y)
self._testGpuMatmul(x, y)
def testDoubleRandom(self):
for _ in range(10):
n, k, m = np.random.randint(1, 100, size=3)
x = self._randMatrix(n, k, np.float64)
y = self._randMatrix(k, m, np.float64)
self._testCpuMatmul(x, y)
def testInt32Random(self):
for _ in range(10):
n, k, m = np.random.randint(1, 100, size=3)
x = self._randMatrix(n, k, np.int32)
y = self._randMatrix(k, m, np.int32)
self._testCpuMatmul(x, y)
def testSComplexRandom(self):
for _ in range(10):
n, k, m = np.random.randint(1, 100, size=3)
x = self._randMatrix(n, k, np.complex64)
y = self._randMatrix(k, m, np.complex64)
self._testCpuMatmul(x, y)
# Test the cases that transpose the matrices before multiplying.
# NOTE(keveman): The cases where only one of the inputs is
# transposed are covered by tf.matmul's gradient function.
def testFloatRandomTransposeBoth(self):
for _ in range(10):
n, k, m = np.random.randint(1, 100, size=3)
x = self._randMatrix(k, n, np.float32)
y = self._randMatrix(m, k, np.float32)
self._testCpuMatmul(x, y, True, True)
self._testGpuMatmul(x, y, True, True)
def testDoubleRandomTranposeBoth(self):
for _ in range(10):
n, k, m = np.random.randint(1, 100, size=3)
x = self._randMatrix(k, n, np.float64)
y = self._randMatrix(m, k, np.float64)
self._testCpuMatmul(x, y, True, True)
def testMatMul_OutEmpty_A(self):
n, k, m = 0, 8, 3
x = self._randMatrix(n, k, np.float32)
y = self._randMatrix(k, m, np.float32)
self._testCpuMatmul(x, y)
self._testGpuMatmul(x, y)
def testMatMul_OutEmpty_B(self):
n, k, m = 3, 8, 0
x = self._randMatrix(n, k, np.float32)
y = self._randMatrix(k, m, np.float32)
self._testCpuMatmul(x, y)
self._testGpuMatmul(x, y)
def testMatMul_Inputs_Empty(self):
n, k, m = 3, 0, 4
x = self._randMatrix(n, k, np.float32)
y = self._randMatrix(k, m, np.float32)
self._testCpuMatmul(x, y)
self._testGpuMatmul(x, y)
# TODO(zhifengc): Figures out how to test matmul gradients on GPU.
class MatMulGradientTest(tf.test.TestCase):
def testGradientInput0(self):
with self.test_session(use_gpu=False):
x = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2],
dtype=tf.float64, name="x")
y = tf.constant([1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7],
shape=[2, 4], dtype=tf.float64, name="y")
m = tf.matmul(x, y, name="matmul")
err = gc.ComputeGradientError(x, [3, 2], m, [3, 4])
print("matmul input0 gradient err = ", err)
self.assertLess(err, 1e-10)
def testGradientInput1(self):
with self.test_session(use_gpu=False):
x = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2],
dtype=tf.float64, name="x")
y = tf.constant([1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7],
shape=[2, 4], dtype=tf.float64, name="y")
m = tf.matmul(x, y, name="matmul")
err = gc.ComputeGradientError(y, [2, 4], m, [3, 4])
print("matmul input1 gradient err = ", err)
self.assertLess(err, 1e-10)
def _VerifyInput0(self, transpose_a, transpose_b):
shape_x = [3, 2]
shape_y = [2, 4]
if transpose_a:
shape_x = list(reversed(shape_x))
if transpose_b:
shape_y = list(reversed(shape_y))
with self.test_session(use_gpu=False):
x = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=shape_x,
dtype=tf.float64, name="x")
y = tf.constant([1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7],
shape=shape_y, dtype=tf.float64, name="y")
m = tf.matmul(x, y, transpose_a, transpose_b, name="matmul")
err = gc.ComputeGradientError(x, shape_x, m, [3, 4])
print("matmul input0 gradient err = ", err)
self.assertLess(err, 1e-10)
def testGradientInput0WithTranspose(self):
self._VerifyInput0(transpose_a=True, transpose_b=False)
self._VerifyInput0(transpose_a=False, transpose_b=True)
self._VerifyInput0(transpose_a=True, transpose_b=True)
def _VerifyInput1(self, transpose_a, transpose_b):
shape_x = [3, 2]
shape_y = [2, 4]
if transpose_a:
shape_x = list(reversed(shape_x))
if transpose_b:
shape_y = list(reversed(shape_y))
with self.test_session(use_gpu=False):
x = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=shape_x,
dtype=tf.float64, name="x")
y = tf.constant([1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7],
shape=shape_y, dtype=tf.float64, name="y")
m = tf.matmul(x, y, transpose_a, transpose_b, name="matmul")
err = gc.ComputeGradientError(y, shape_y, m, [3, 4])
print("matmul input1 gradient err = ", err)
self.assertLess(err, 1e-10)
def testGradientInput1WithTranspose(self):
self._VerifyInput1(transpose_a=True, transpose_b=False)
self._VerifyInput1(transpose_a=False, transpose_b=True)
self._VerifyInput1(transpose_a=True, transpose_b=True)
if __name__ == "__main__":
tf.test.main()
| MehdiSfr/tensor-flow | tensorflow/python/kernel_tests/matmul_op_test.py | Python | apache-2.0 | 8,392 |
/*
* #!
* Ontopoly Editor
* #-
* Copyright (C) 2001 - 2013 The Ontopia Project
* #-
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* !#
*/
package ontopoly.components;
import java.util.Objects;
import net.ontopia.topicmaps.core.OccurrenceIF;
import ontopoly.model.FieldInstance;
import ontopoly.models.FieldValueModel;
import ontopoly.pages.AbstractOntopolyPage;
import ontopoly.validators.ExternalValidation;
import ontopoly.validators.RegexValidator;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.Model;
public class FieldInstanceNumberField extends TextField<String> {
private FieldValueModel fieldValueModel;
private String oldValue;
private String cols = "20";
public FieldInstanceNumberField(String id, FieldValueModel fieldValueModel) {
super(id);
this.fieldValueModel = fieldValueModel;
OccurrenceIF occ = (OccurrenceIF)fieldValueModel.getObject();
this.oldValue = (occ == null ? null : occ.getValue());
setModel(new Model<String>(oldValue));
add(new RegexValidator(this, fieldValueModel.getFieldInstanceModel()) {
@Override
protected String getRegex() {
return "^[-+]?\\d+(\\.\\d+)?$";
}
@Override
protected String resourceKeyInvalidValue() {
return "validators.RegexValidator.number";
}
});
// validate field using registered validators
ExternalValidation.validate(this, oldValue);
}
public void setCols(int cols) {
this.cols = Integer.toString(cols);
}
@Override
protected void onComponentTag(ComponentTag tag) {
tag.setName("input");
tag.put("type", "text");
tag.put("size", cols);
super.onComponentTag(tag);
}
@Override
protected void onModelChanged() {
super.onModelChanged();
String newValue = (String)getModelObject();
if (Objects.equals(newValue, oldValue)) return;
AbstractOntopolyPage page = (AbstractOntopolyPage)getPage();
FieldInstance fieldInstance = fieldValueModel.getFieldInstanceModel().getFieldInstance();
if (fieldValueModel.isExistingValue() && oldValue != null)
fieldInstance.removeValue(oldValue, page.getListener());
if (newValue != null && !newValue.equals("")) {
fieldInstance.addValue(newValue, page.getListener());
fieldValueModel.setExistingValue(newValue);
}
oldValue = newValue;
}
}
| ontopia/ontopia | ontopoly-editor/src/main/java/ontopoly/components/FieldInstanceNumberField.java | Java | apache-2.0 | 2,944 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_45) on Tue Jul 28 00:20:21 PDT 2015 -->
<title>Uses of Package org.apache.zookeeper.client (ZooKeeper 3.5.1-alpha API)</title>
<meta name="date" content="2015-07-28">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Package org.apache.zookeeper.client (ZooKeeper 3.5.1-alpha API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/zookeeper/client/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Uses of Package org.apache.zookeeper.client" class="title">Uses of Package<br>org.apache.zookeeper.client</h1>
</div>
<div class="contentContainer">No usage of org.apache.zookeeper.client</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Use</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/apache/zookeeper/client/package-use.html" target="_top">Frames</a></li>
<li><a href="package-use.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2015 The Apache Software Foundation</small></p>
</body>
</html>
| BZCareer/zookeeper-quickstart | docs/api/org/apache/zookeeper/client/package-use.html | HTML | apache-2.0 | 4,173 |
This quick start guide will teach you how to wire up TypeScript with [Knockout.js](http://knockoutjs.com/).
We assume that you're already using [Node.js](https://nodejs.org/) with [npm](https://www.npmjs.com/).
# Lay out the project
Let's start out with a new directory.
We'll name it `proj` for now, but you can change it to whatever you want.
```shell
mkdir proj
cd proj
```
To start, we're going to structure our project in the following way:
```text
proj/
+- src/
+- built/
```
TypeScript files will start out in your `src` folder, run through the TypeScript compiler, and end up in `built`.
Let's scaffold this out:
```shell
mkdir src
mkdir built
```
# Install our build dependencies
First ensure TypeScript and Typings are installed globally.
```shell
npm install -g typescript typings
```
You obviously know about TypeScript, but you might not know about Typings.
[Typings](https://www.npmjs.com/package/typings) is a package manager for grabbing definition files.
We'll now use Typings to grab declaration files for Knockout:
```shell
typings install --global --save dt~knockout
```
The `--global` flag will tell Typings to grab any declaration files from [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped), a repository of community-authored `.d.ts` files.
This command will create a file called `typings.json` and a folder called `typings` in the current directory.
# Grab our runtime dependencies
We'll need to grab Knockout itself, as well as something called RequireJS.
[RequireJS](http://www.requirejs.org/) is a library that enables us to load modules at runtime asynchronously.
There are several ways we can go about this:
1. Download the files manually and host them.
2. Download the files through a package manager like [Bower](http://bower.io/) and host them.
3. Use a Content Delivery Network (CDN) to host both files.
We'll keep it simple and go with the first option, but Knockout's documentation has [details on using a CDN](http://knockoutjs.com/downloads/index.html), and more libraries like RequireJS can be searched for on [cdnjs](https://cdnjs.com/).
Let's create an `externals` folder in the root of our project.
```shell
mkdir externals
```
Now [download Knockout](http://knockoutjs.com/downloads/index.html) and [download RequireJS](http://www.requirejs.org/docs/download.html#latest) into that folder.
The latest and minified versions of the files should work just fine.
# Add a TypeScript configuration file
You'll want to bring your TypeScript files together - both the code you'll be writing as well as any necessary declaration files.
To do this, you'll need to create a `tsconfig.json` which contains a list of your input files as well as all your compilation settings.
Simply create a new file in your project root named `tsconfig.json` and fill it with the following contents:
```json
{
"compilerOptions": {
"outDir": "./built/",
"sourceMap": true,
"noImplicitAny": true,
"module": "amd",
"target": "es5"
},
"files": [
"./typings/index.d.ts",
"./src/require-config.ts",
"./src/hello.ts"
]
}
```
We're including `typings/index.d.ts`, which Typings created for us.
That file automatically includes all of your installed dependencies.
You can learn more about `tsconfig.json` files [here](../tsconfig.json.md).
# Write some code
Let's write our first TypeScript file using Knockout.
First, create a new file in your `src` directory named `hello.ts`.
```ts
import * as ko from "knockout";
class HelloViewModel {
language: KnockoutObservable<string>
framework: KnockoutObservable<string>
constructor(language: string, framework: string) {
this.language = ko.observable(language);
this.framework = ko.observable(framework);
}
}
ko.applyBindings(new HelloViewModel("TypeScript", "Knockout"));
```
Next, we'll create a file named `require-config.ts` in `src` as well.
```ts
declare var require: any;
require.config({
paths: {
"knockout": "externals/knockout-3.4.0",
}
});
```
This file will tell RequireJS where to find Knockout when we import it, just like we did in `hello.ts`.
Any page that you create should include this immediately after RequireJS, but before importing anything else.
To get a better understanding of this file and how to configure RequireJS, you can [read up on its documentation](http://requirejs.org/docs/api.html#config).
We'll also need a view to display our `HelloViewModel`.
Create a file at the root of `proj` named `index.html` with the following contents:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello Knockout!</title>
</head>
<body>
<p>
Hello from
<strong data-bind="text: language">todo</strong>
and
<strong data-bind="text: framework">todo</strong>!
</p>
<p>Language: <input data-bind="value: language" /></p>
<p>Framework: <input data-bind="value: framework" /></p>
<script src="./externals/require.js"></script>
<script src="./built/require-config.js"></script>
<script>
require(["built/hello"]);
</script>
</body>
</html>
```
Notice there are three script tags.
First, we're including RequireJS itself.
Then we're mapping the paths of our external dependencies in `require-config.js` so that RequireJS knows where to look for them.
Finally, we're calling `require` with a list of modules we'd like to load.
# Putting it all together
Just run:
```shell
tsc
```
Now open up `index.html` in your favorite browser and everything should be ready to use!
You should see a page that says "Hello from TypeScript and Knockout!"
Below that, you'll also see two input boxes.
As you modify their contents and switch focus, you'll see that the original message changes.
| zspitz/TypeScript-Handbook | pages/tutorials/Knockout.md | Markdown | apache-2.0 | 5,913 |
/**********************************************************************
Copyright (c) 2006 Erik Bengtson and others. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contributors:
...
**********************************************************************/
package org.jpox.samples.types.stringbuffer;
/**
* Object with a StringBuffer.
*/
public class StringBufferHolder
{
StringBuffer sb = new StringBuffer();
public StringBuffer getStringBuffer()
{
return sb;
}
public void setStringBuffer(StringBuffer sb)
{
this.sb = sb;
}
public void appendText(String text)
{
// Since DataNucleus doesn't support updates to the contents of a StringBuffer we replace it
StringBuffer sb2 = new StringBuffer(sb.append(text));
sb = sb2;
}
public String getText()
{
return sb.toString();
}
} | hopecee/texsts | samples/src/java/org/jpox/samples/types/stringbuffer/StringBufferHolder.java | Java | apache-2.0 | 1,432 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.importexport.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.importexport.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.StringUtils;
/**
* CancelJobRequest Marshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class CancelJobRequestMarshaller implements Marshaller<Request<CancelJobRequest>, CancelJobRequest> {
public Request<CancelJobRequest> marshall(CancelJobRequest cancelJobRequest) {
if (cancelJobRequest == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
Request<CancelJobRequest> request = new DefaultRequest<CancelJobRequest>(cancelJobRequest, "AmazonImportExport");
request.addParameter("Action", "CancelJob");
request.addParameter("Version", "2010-06-01");
request.setHttpMethod(HttpMethodName.POST);
if (cancelJobRequest.getJobId() != null) {
request.addParameter("JobId", StringUtils.fromString(cancelJobRequest.getJobId()));
}
if (cancelJobRequest.getAPIVersion() != null) {
request.addParameter("APIVersion", StringUtils.fromString(cancelJobRequest.getAPIVersion()));
}
return request;
}
}
| aws/aws-sdk-java | aws-java-sdk-importexport/src/main/java/com/amazonaws/services/importexport/model/transform/CancelJobRequestMarshaller.java | Java | apache-2.0 | 2,038 |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.personalize.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
/**
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/personalize-2018-05-22/DescribeAlgorithm" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeAlgorithmRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* <p>
* The Amazon Resource Name (ARN) of the algorithm to describe.
* </p>
*/
private String algorithmArn;
/**
* <p>
* The Amazon Resource Name (ARN) of the algorithm to describe.
* </p>
*
* @param algorithmArn
* The Amazon Resource Name (ARN) of the algorithm to describe.
*/
public void setAlgorithmArn(String algorithmArn) {
this.algorithmArn = algorithmArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the algorithm to describe.
* </p>
*
* @return The Amazon Resource Name (ARN) of the algorithm to describe.
*/
public String getAlgorithmArn() {
return this.algorithmArn;
}
/**
* <p>
* The Amazon Resource Name (ARN) of the algorithm to describe.
* </p>
*
* @param algorithmArn
* The Amazon Resource Name (ARN) of the algorithm to describe.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public DescribeAlgorithmRequest withAlgorithmArn(String algorithmArn) {
setAlgorithmArn(algorithmArn);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getAlgorithmArn() != null)
sb.append("AlgorithmArn: ").append(getAlgorithmArn());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof DescribeAlgorithmRequest == false)
return false;
DescribeAlgorithmRequest other = (DescribeAlgorithmRequest) obj;
if (other.getAlgorithmArn() == null ^ this.getAlgorithmArn() == null)
return false;
if (other.getAlgorithmArn() != null && other.getAlgorithmArn().equals(this.getAlgorithmArn()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getAlgorithmArn() == null) ? 0 : getAlgorithmArn().hashCode());
return hashCode;
}
@Override
public DescribeAlgorithmRequest clone() {
return (DescribeAlgorithmRequest) super.clone();
}
}
| aws/aws-sdk-java | aws-java-sdk-personalize/src/main/java/com/amazonaws/services/personalize/model/DescribeAlgorithmRequest.java | Java | apache-2.0 | 3,808 |
package testPpermission;
import android.annotation.TargetApi;
import android.app.Application;
import android.os.Build;
/**
* Created by nubor on 13/02/2017.
*/
public class App extends Application {
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) @Override public void onCreate() {
super.onCreate();
this.registerActivityLifecycleCallbacks(new AppLifeCycle() );
}
}
| GigigoGreenLabs/gggUtilsSuite | testapplication/src/main/java/testPpermission/App.java | Java | apache-2.0 | 382 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="0;URL=type.U27.html">
</head>
<body>
<p>Redirecting to <a href="type.U27.html">type.U27.html</a>...</p>
<script>location.replace("type.U27.html" + location.search + location.hash);</script>
</body>
</html> | nitro-devs/nitro-game-engine | docs/typenum/consts/U27.t.html | HTML | apache-2.0 | 293 |
package com.couchbase.lite.testapp.ektorp.tests;
import org.ektorp.support.OpenCouchDbDocument;
import java.util.List;
import java.util.Set;
@SuppressWarnings("serial")
public class TestObject extends OpenCouchDbDocument {
private Integer foo;
private Boolean bar;
private String baz;
private String status;
private String key;
private List<String> stuff;
private Set<String> stuffSet;
public Set<String> getStuffSet() {
return stuffSet;
}
public void setStuffSet(Set<String> stuffSet) {
this.stuffSet = stuffSet;
}
public List<String> getStuff() {
return stuff;
}
public void setStuff(List<String> stuff) {
this.stuff = stuff;
}
public Integer getFoo() {
return foo;
}
public void setFoo(Integer foo) {
this.foo = foo;
}
public Boolean getBar() {
return bar;
}
public void setBar(Boolean bar) {
this.bar = bar;
}
public String getBaz() {
return baz;
}
public void setBaz(String baz) {
this.baz = baz;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public TestObject() {
}
public TestObject(Integer foo, Boolean bar, String baz) {
this.foo = foo;
this.bar = bar;
this.baz = baz;
this.status = null;
}
public TestObject(Integer foo, Boolean bar, String baz, String status) {
this.foo = foo;
this.bar = bar;
this.baz = baz;
this.status = status;
}
public TestObject(String id, String key) {
this.setId(id);
this.key = key;
}
@Override
public boolean equals(Object o) {
if(o instanceof TestObject) {
TestObject other = (TestObject)o;
if(getId() != null && other.getId() != null && getId().equals(other.getId())) {
return true;
}
}
return false;
}
}
| couchbaselabs/couchbase-lite-android-ektorp | src/instrumentTest/java/com/couchbase/lite/testapp/ektorp/tests/TestObject.java | Java | apache-2.0 | 2,177 |
package libgbust
import (
"io/ioutil"
"net/http"
"net/url"
"unicode/utf8"
)
// CheckDir is used to execute a directory check
func (a *Attacker) CheckDir(word string) *Result {
end, err := url.Parse(word)
if err != nil {
return &Result{
Msg: "[!] failed to parse word",
Err: err,
}
}
fullURL := a.config.URL.ResolveReference(end)
req, err := http.NewRequest("GET", fullURL.String(), nil)
if err != nil {
return &Result{
Msg: "[!] failed to create new request",
Err: err,
}
}
for _, cookie := range a.config.Cookies {
req.Header.Set("Cookie", cookie)
}
resp, err := a.client.Do(req)
if err != nil {
return &Result{
Err: err,
Msg: "[!] failed to do request",
}
}
defer resp.Body.Close()
length := new(int64)
if resp.ContentLength <= 0 {
body, err := ioutil.ReadAll(resp.Body)
if err == nil {
*length = int64(utf8.RuneCountInString(string(body)))
}
} else {
*length = resp.ContentLength
}
return &Result{
StatusCode: resp.StatusCode,
Size: length,
URL: resp.Request.URL,
}
}
| kkirsche/gbust | libgbust/check.go | GO | apache-2.0 | 1,062 |
# Uragoga erythrantha Kuntze SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Palicourea/Palicourea crocea/ Syn. Uragoga erythrantha/README.md | Markdown | apache-2.0 | 183 |
# Unona buchananii Engl. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Magnoliales/Annonaceae/Monanthotaxis/Monanthotaxis buchananii/ Syn. Unona buchananii/README.md | Markdown | apache-2.0 | 179 |
# Stecchericium solomonense Corner, 1989 SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
Beih. Nova Hedwigia 96: 124 (1989)
#### Original name
Stecchericium solomonense Corner, 1989
### Remarks
null | mdoering/backbone | life/Fungi/Basidiomycota/Agaricomycetes/Russulales/Bondarzewiaceae/Wrightoporia/Wrightoporia solomonensis/ Syn. Stecchericium solomonense/README.md | Markdown | apache-2.0 | 259 |
# Tasmannia coriacea (Pulle) A.C.Sm. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Canellales/Winteraceae/Tasmannia/Tasmannia coriacea/README.md | Markdown | apache-2.0 | 184 |
# Carex diclina Phil. SPECIES
#### Status
SYNONYM
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Liliopsida/Poales/Cyperaceae/Carex/Carex gayana/ Syn. Carex diclina/README.md | Markdown | apache-2.0 | 176 |
# Otopappus pittieri (Greenm.) B.L.Turner SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
Zexmenia pittieri Greenm.
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Otopappus/Otopappus pittieri/README.md | Markdown | apache-2.0 | 210 |
# Schima beccarii Warb. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Ericales/Theaceae/Schima/Schima beccarii/README.md | Markdown | apache-2.0 | 171 |
# Amyridaceae Kunth FAMILY
#### Status
SYNONYM
#### According to
GRIN Taxonomy for Plants
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Sapindales/Rutaceae/ Syn. Amyridaceae/README.md | Markdown | apache-2.0 | 158 |
# Eugenia turneri McVaugh SPECIES
#### Status
ACCEPTED
#### According to
The Catalogue of Life, 3rd January 2011
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Myrtales/Myrtaceae/Eugenia/Eugenia turneri/README.md | Markdown | apache-2.0 | 181 |
# Ebnerella moelleriana (Boed.) P.Buxb. SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Caryophyllales/Cactaceae/Mammillaria/Ebnerella moelleriana/README.md | Markdown | apache-2.0 | 187 |
# Biophytum casiquiarense Knuth SPECIES
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Magnoliophyta/Magnoliopsida/Oxalidales/Oxalidaceae/Biophytum/Biophytum casiquiarense/README.md | Markdown | apache-2.0 | 179 |
# Gigotorcya Buc'hoz GENUS
#### Status
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | mdoering/backbone | life/Plantae/Gigotorcya/README.md | Markdown | apache-2.0 | 166 |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.s4.comm.zk;
import org.apache.s4.comm.core.CommEventCallback;
import org.apache.s4.comm.core.DefaultWatcher;
import org.apache.s4.comm.core.TaskManager;
import org.apache.s4.comm.util.JSONUtil;
import org.apache.s4.comm.util.ConfigParser.Cluster.ClusterType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs.Ids;
import org.apache.zookeeper.data.Stat;
public class ZkTaskManager extends DefaultWatcher implements TaskManager {
static Logger logger = Logger.getLogger(ZkTaskManager.class);
String tasksListRoot;
String processListRoot;
public ZkTaskManager(String address, String ClusterName, ClusterType clusterType) {
this(address, ClusterName, clusterType, null);
}
/**
* Constructor of TaskManager
*
* @param address
* @param ClusterName
*/
public ZkTaskManager(String address, String ClusterName, ClusterType clusterType,
CommEventCallback callbackHandler) {
super(address, callbackHandler);
this.root = "/" + ClusterName + "/" + clusterType.toString();
this.tasksListRoot = root + "/task";
this.processListRoot = root + "/process";
}
/**
* This will block the process thread from starting the task, when it is
* unblocked it will return the data stored in the task node. This data can
* be used by the This call assumes that the tasks are already set up
*
* @return Object containing data related to the task
*/
@Override
public Object acquireTask(Map<String, String> customTaskData) {
while (true) {
synchronized (mutex) {
try {
Stat tExists = zk.exists(tasksListRoot, false);
if (tExists == null) {
logger.error("Tasks znode:" + tasksListRoot
+ " not setup.Going to wait");
tExists = zk.exists(tasksListRoot, true);
if (tExists == null) {
mutex.wait();
}
continue;
}
Stat pExists = zk.exists(processListRoot, false);
if (pExists == null) {
logger.error("Process root znode:" + processListRoot
+ " not setup.Going to wait");
pExists = zk.exists(processListRoot, true);
if (pExists == null) {
mutex.wait();
}
continue;
}
// setting watch true to tasks node will trigger call back
// if there is any change to task node,
// this is useful to add additional tasks
List<String> tasks = zk.getChildren(tasksListRoot, true);
List<String> processes = zk.getChildren(processListRoot,
true);
if (processes.size() < tasks.size()) {
ArrayList<String> tasksAvailable = new ArrayList<String>();
for (int i = 0; i < tasks.size(); i++) {
tasksAvailable.add("" + i);
}
if (processes != null) {
for (String s : processes) {
String taskId = s.split("-")[1];
tasksAvailable.remove(taskId);
}
}
// try pick up a random task
Random random = new Random();
int id = Integer.parseInt(tasksAvailable.get(random.nextInt(tasksAvailable.size())));
String pNode = processListRoot + "/" + "task-" + id;
String tNode = tasksListRoot + "/" + "task-" + id;
Stat pNodeStat = zk.exists(pNode, false);
if (pNodeStat == null) {
Stat tNodeStat = zk.exists(tNode, false);
byte[] bytes = zk.getData(tNode, false, tNodeStat);
Map<String, Object> map = (Map<String, Object>) JSONUtil.getMapFromJson(new String(bytes));
// if(!map.containsKey("address")){
// map.put("address",
// InetAddress.getLocalHost().getHostName());
// }
if (customTaskData != null) {
for (String key : customTaskData.keySet()) {
if (!map.containsKey(key)) {
map.put(key, customTaskData.get(key));
}
}
}
map.put("taskSize", "" + tasks.size());
map.put("tasksRootNode", tasksListRoot);
map.put("processRootNode", processListRoot);
String create = zk.create(pNode,
JSONUtil.toJsonString(map)
.getBytes(),
Ids.OPEN_ACL_UNSAFE,
CreateMode.EPHEMERAL);
logger.info("Created process Node:" + pNode + " :"
+ create);
return map;
}
} else {
// all the tasks are taken up, will wait for the
logger.info("No task available to take up. Going to wait");
mutex.wait();
}
} catch (KeeperException e) {
logger.info("Warn:mostly ignorable " + e.getMessage(), e);
} catch (InterruptedException e) {
logger.info("Warn:mostly ignorable " + e.getMessage(), e);
}
}
}
}
}
| s4/s4 | s4-comm/src/main/java/org/apache/s4/comm/zk/ZkTaskManager.java | Java | apache-2.0 | 7,311 |
package chatty.util.api;
import chatty.Helper;
import chatty.util.DateTime;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.logging.Logger;
/**
* Holds the current info (name, viewers, title, game) of a stream, as well
* as a history of the same information and stuff like when the info was
* last requested, whether it's currently waiting for an API response etc.
*
* @author tduva
*/
public class StreamInfo {
private static final Logger LOGGER = Logger.getLogger(StreamInfo.class.getName());
/**
* All lowercase name of the stream
*/
public final String stream;
/**
* Correctly capitalized name of the stream. May be null if no set.
*/
private String display_name;
private long lastUpdated = 0;
private long lastStatusChange = 0;
private String status = "";
private String game = "";
private int viewers = 0;
private long startedAt = -1;
private long lastOnline = -1;
private long startedAtWithPicnic = -1;
private boolean online = false;
private boolean updateSucceeded = false;
private int updateFailedCounter = 0;
private boolean requested = false;
private boolean followed = false;
/**
* The time the stream was changed from online -> offline, so recheck if
* that actually is correct after some time. If this is -1, then do nothing.
* Should be set to -1 with EVERY update (received data), except when it's
* not already -1 on the change from online -> offline (to avoid request
* spam if recheckOffline() is always true).
*/
private long recheckOffline = -1;
// When the viewer stats where last calculated
private long lastViewerStats;
// How long at least between viewer stats calculations
private static final int VIEWERSTATS_DELAY = 30*60*1000;
// How long a stats range can be at most
private static final int VIEWERSTATS_MAX_LENGTH = 35*60*1000;
private static final int RECHECK_OFFLINE_DELAY = 10*1000;
/**
* Maximum length in seconds of what should count as a PICNIC (short stream
* offline period), to set the online time with PICNICs correctly.
*/
private static final int MAX_PICNIC_LENGTH = 600;
/**
* The current full status (title + game), updated when new data is set.
*/
private String currentFullStatus;
private String prevFullStatus;
private final LinkedHashMap<Long,StreamInfoHistoryItem> history = new LinkedHashMap<>();
private int expiresAfter = 300;
private final StreamInfoListener listener;
public StreamInfo(String stream, StreamInfoListener listener) {
this.listener = listener;
this.stream = stream.toLowerCase(Locale.ENGLISH);
}
private void streamInfoUpdated() {
if (listener != null) {
listener.streamInfoUpdated(this);
}
}
public void setRequested() {
this.requested = true;
}
public boolean isRequested() {
return requested;
}
private void streamInfoStatusChanged() {
lastStatusChange = System.currentTimeMillis();
if (listener != null) {
listener.streamInfoStatusChanged(this, getFullStatus());
}
}
@Override
public String toString() {
return "Online: "+online+
" Status: "+status+
" Game: "+game+
" Viewers: "+viewers;
}
public String getFullStatus() {
return currentFullStatus;
}
private String makeFullStatus() {
if (online) {
String fullStatus = status;
if (status == null) {
fullStatus = "No stream title set";
}
if (game != null) {
fullStatus += " ("+game+")";
}
return fullStatus;
}
else if (!updateSucceeded) {
return "";
}
else {
return "Stream offline";
}
}
public String getStream() {
return stream;
}
/**
* The correctly capitalized name of the stream, or the all lowercase name
* if correctly capitalized name is not set.
*
* @return The correctly capitalized name or all lowercase name
*/
public String getDisplayName() {
return display_name != null ? display_name : stream;
}
/**
* Whether a correctly capitalized name is set, which if true is returned
* by {@see getDisplayName()}.
*
* @return true if a correctly capitalized name is set, false otherwise
*/
public boolean hasDisplayName() {
return display_name != null;
}
/**
* Sets the correctly capitalized name for this stream.
*
* @param name The correctly capitalized name
*/
public void setDisplayName(String name) {
this.display_name = name;
}
/**
* Set stream info from followed streams request.
*
* @param status The current stream title
* @param game The current game being played
* @param viewers The current viewercount
* @param startedAt The timestamp when the stream was started, -1 if not set
*/
public void setFollowed(String status, String game, int viewers, long startedAt) {
//System.out.println(status);
followed = true;
boolean saveToHistory = false;
if (hasExpired()) {
saveToHistory = true;
}
set(status, game, viewers, startedAt, saveToHistory);
}
/**
* Set stream info from a regular stream info request.
*
* @param status The current stream title
* @param game The current game being played
* @param viewers The current viewercount
* @param startedAt The timestamp when the stream was started, -1 if not set
*/
public void set(String status, String game, int viewers, long startedAt) {
set(status, game, viewers, startedAt, true);
}
/**
* This should only be used when the update was successful.
*
* @param status The current title of the stream
* @param game The current game
* @param viewers The current viewercount
* @param startedAt The timestamp when the stream was started, -1 if not set
* @param saveToHistory Whether to save the data to history
*/
private void set(String status, String game, int viewers, long startedAt, boolean saveToHistory) {
this.status = Helper.trim(Helper.removeLinebreaks(status));
this.game = Helper.trim(game);
this.viewers = viewers;
// Always set to -1 (do nothing) when stream is set as online, but also
// output a message if necessary
if (recheckOffline != -1) {
if (this.startedAt < startedAt) {
LOGGER.info("StreamInfo " + stream + ": Stream not offline anymore");
} else {
LOGGER.info("StreamInfo " + stream + ": Stream not offline");
}
}
recheckOffline = -1;
if (lastOnlineAgo() > MAX_PICNIC_LENGTH) {
// Only update online time with PICNICs when offline time was long
// enough (of course also depends on what stream data Chatty has)
this.startedAtWithPicnic = startedAt;
}
this.startedAt = startedAt;
this.lastOnline = System.currentTimeMillis();
this.online = true;
if (saveToHistory) {
addHistoryItem(System.currentTimeMillis(),new StreamInfoHistoryItem(viewers, status, game));
}
setUpdateSucceeded(true);
}
public void setExpiresAfter(int expiresAfter) {
this.expiresAfter = expiresAfter;
}
public void setUpdateFailed() {
setUpdateSucceeded(false);
}
private void setUpdateSucceeded(boolean succeeded) {
updateSucceeded = succeeded;
setUpdated();
if (succeeded) {
updateFailedCounter = 0;
}
else {
updateFailedCounter++;
if (recheckOffline != -1) {
// If an offline check is pending and the update failed, then
// just set as offline now (may of course not be accurate at all
// anymore).
LOGGER.warning("StreamInfo "+stream+": Update failed, delayed setting offline");
setOffline();
}
}
currentFullStatus = makeFullStatus();
if (succeeded && !currentFullStatus.equals(prevFullStatus) ||
lastUpdateLongAgo()) {
prevFullStatus = currentFullStatus;
streamInfoStatusChanged();
}
// Call at the end, so stuff is already updated
streamInfoUpdated();
}
public void setOffline() {
// If switching from online to offline
if (online && recheckOffline == -1) {
LOGGER.info("Waiting to recheck offline status for " + stream);
recheckOffline = System.currentTimeMillis();
} else {
if (recheckOffline != -1) {
//addHistoryItem(recheckOffline, new StreamInfoHistoryItem());
LOGGER.info("Offline after check: "+stream);
}
recheckOffline = -1;
this.online = false;
addHistoryItem(System.currentTimeMillis(), new StreamInfoHistoryItem());
}
setUpdateSucceeded(true);
}
/**
* Whether to recheck the offline status by requesting the stream status
* again earlier than usual.
*
* @return true if it should be checked, false otherwise
*/
public boolean recheckOffline() {
return recheckOffline != -1
&& System.currentTimeMillis() - recheckOffline > RECHECK_OFFLINE_DELAY;
}
public boolean getFollowed() {
return followed;
}
public boolean getOnline() {
return this.online;
}
/**
* The time the stream was started. As always, this may contain stale data
* if the stream info is not valid or the stream offline.
*
* @return The timestamp or -1 if no time was received
*/
public long getTimeStarted() {
return startedAt;
}
/**
* The time the stream was started, including short disconnects (max 10
* minutes). If there was no disconnect, then the time is equal to
* getTimeStarted(). As always, this may contain stale data if the stream
* info is not valid or the stream offline.
*
* @return The timestamp or -1 if not time was received or the time is
* invalid
*/
public long getTimeStartedWithPicnic() {
return startedAtWithPicnic;
}
/**
* How long ago the stream was last online. If the stream was never seen as
* online this session, then a huge number will be returned.
*
* @return The number of seconds that have passed since the stream was last
* seen as online
*/
public long lastOnlineAgo() {
return (System.currentTimeMillis() - lastOnline) / 1000;
}
public long getLastOnlineTime() {
return lastOnline;
}
private void setUpdated() {
lastUpdated = System.currentTimeMillis() / 1000;
requested = false;
}
// Getters
/**
* Gets the status stored for this stream. May not be correct, check
* isValid() before using any data.
*
* @return
*/
public String getStatus() {
return status;
}
/**
* Gets the title stored for this stream, which is the same as the status,
* unless the status is null. As opposed to getStatus() this never returns
* null.
*
* @return
*/
public String getTitle() {
if (status == null) {
return "No stream title set";
}
return status;
}
/**
* Gets the game stored for this stream. May not be correct, check
* isValid() before using any data.
*
* @return
*/
public String getGame() {
return game;
}
/**
* Gets the viewers stored for this stream. May not be correct, check
* isValid() before using any data.
*
* @return
*/
public int getViewers() {
return viewers;
}
/**
* Calculates the number of seconds that passed after the last update
*
* @return Number of seconds that have passed after the last update
*/
public long getUpdatedDelay() {
return (System.currentTimeMillis() / 1000) - lastUpdated;
}
/**
* Checks if the info should be updated. The stream info takes longer
* to expire when there were failed attempts at downloading the info from
* the API. This only affects hasExpired(), not isValid().
*
* @return true if the info should be updated, false otherwise
*/
public boolean hasExpired() {
return getUpdatedDelay() > expiresAfter * (1+ updateFailedCounter / 2);
}
/**
* Checks if the info is valid, taking into account if the last request
* succeeded and how old the data is.
*
* @return true if the info can be used, false otherwise
*/
public boolean isValid() {
if (!updateSucceeded || getUpdatedDelay() > expiresAfter*2) {
return false;
}
return true;
}
public boolean lastUpdateLongAgo() {
if (updateSucceeded && getUpdatedDelay() > expiresAfter*4) {
return true;
}
return false;
}
/**
* Returns the number of seconds the last status change is ago.
*
* @return
*/
public long getStatusChangeTimeAgo() {
return (System.currentTimeMillis() - lastStatusChange) / 1000;
}
public long getStatusChangeTime() {
return lastStatusChange;
}
private void addHistoryItem(Long time, StreamInfoHistoryItem item) {
synchronized(history) {
history.put(time, item);
}
}
public LinkedHashMap<Long,StreamInfoHistoryItem> getHistory() {
synchronized(history) {
return new LinkedHashMap<>(history);
}
}
/**
* Create a summary of the viewercount in the interval that hasn't been
* calculated yet (delay set as a constant).
*
* @param force Get stats even if the delay hasn't passed yet.
* @return
*/
public ViewerStats getViewerStats(boolean force) {
synchronized(history) {
if (lastViewerStats == 0 && !force) {
// No stats output yet, so assume current time as start, so
// it's output after the set delay
lastViewerStats = System.currentTimeMillis() - 5000;
}
long timePassed = System.currentTimeMillis() - lastViewerStats;
if (!force && timePassed < VIEWERSTATS_DELAY) {
return null;
}
long startAt = lastViewerStats+1;
// Only calculate the max length
if (timePassed > VIEWERSTATS_MAX_LENGTH) {
startAt = System.currentTimeMillis() - VIEWERSTATS_MAX_LENGTH;
}
int min = -1;
int max = -1;
int total = 0;
int count = 0;
long firstTime = -1;
long lastTime = -1;
StringBuilder b = new StringBuilder();
// Initiate with -2, because -1 already means offline
int prevViewers = -2;
for (long time : history.keySet()) {
if (time < startAt) {
continue;
}
// Start doing anything for values >= startAt
// Update so that it contains the last value that was looked at
// at the end of this method
lastViewerStats = time;
int viewers = history.get(time).getViewers();
// Append to viewercount development String
if (prevViewers > -1 && viewers != -1) {
// If there is a prevViewers set and if online
int diff = viewers - prevViewers;
if (diff >= 0) {
b.append("+");
}
b.append(Helper.formatViewerCount(diff));
} else if (viewers != -1) {
if (prevViewers == -1) {
// Previous was offline, so show that
b.append("_");
}
b.append(Helper.formatViewerCount(viewers));
}
prevViewers = viewers;
if (viewers == -1) {
continue;
}
// Calculate min/max/sum/count only when online
if (firstTime == -1) {
firstTime = time;
}
lastTime = time;
if (viewers > max) {
max = viewers;
}
if (min == -1 || viewers < min) {
min = viewers;
}
total += viewers;
count++;
}
// After going through all values, do some finishing work
if (prevViewers == -1) {
// Last value was offline, so show that
b.append("_");
}
if (count == 0) {
return null;
}
int avg = total / count;
return new ViewerStats(min, max, avg, firstTime, lastTime, count, b.toString());
}
}
/**
* Holds a set of immutable values that make up viewerstats.
*/
public static class ViewerStats {
public final int max;
public final int min;
public final int avg;
public final long startTime;
public final long endTime;
public final int count;
public final String history;
public ViewerStats(int min, int max, int avg, long startTime,
long endTime, int count, String history) {
this.max = max;
this.min = min;
this.avg = avg;
this.startTime = startTime;
this.endTime = endTime;
this.count = count;
this.history = history;
}
/**
* Which duration the data in this stats covers. This is not necessarily
* the whole duration that was worked with (e.g. if the stream went
* offline at the end, that data may not be included). This is the range
* between the first and last valid data point.
*
* @return The number of seconds this data covers.
*/
public long duration() {
return (endTime - startTime) / 1000;
}
/**
* Checks if these viewerstats contain any viewer data.
*
* @return
*/
public boolean isValid() {
// If min was set to another value than the initial one, then this
// means at least one data point with a viewercount was there.
return min != -1;
}
@Override
public String toString() {
return "Viewerstats ("+DateTime.format2(startTime)
+"-"+DateTime.format2(endTime)+"):"
+ " avg:"+Helper.formatViewerCount(avg)
+ " min:"+Helper.formatViewerCount(min)
+ " max:"+Helper.formatViewerCount(max)
+ " ["+count+"/"+history+"]";
}
}
}
| Javaec/ChattyRus | src/chatty/util/api/StreamInfo.java | Java | apache-2.0 | 19,898 |
# Authorized Buyers Marketplace API Client Library for Java
The Authorized Buyers Marketplace API allows buyers programmatically discover inventory; propose, retrieve and negotiate deals with publishers.
This page contains information about getting started with the Authorized Buyers Marketplace API
using the Google API Client Library for Java. In addition, you may be interested
in the following documentation:
* Browse the [Javadoc reference for the Authorized Buyers Marketplace API][javadoc]
* Read the [Developer's Guide for the Google API Client Library for Java][google-api-client].
* Interact with this API in your browser using the [APIs Explorer for the Authorized Buyers Marketplace API][api-explorer]
## Installation
### Maven
Add the following lines to your `pom.xml` file:
```xml
<project>
<dependencies>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-authorizedbuyersmarketplace</artifactId>
<version>v1-rev20220212-1.32.1</version>
</dependency>
</dependencies>
</project>
```
### Gradle
```gradle
repositories {
mavenCentral()
}
dependencies {
implementation 'com.google.apis:google-api-services-authorizedbuyersmarketplace:v1-rev20220212-1.32.1'
}
```
[javadoc]: https://googleapis.dev/java/google-api-services-authorizedbuyersmarketplace/latest/index.html
[google-api-client]: https://github.com/googleapis/google-api-java-client/
[api-explorer]: https://developers.google.com/apis-explorer/#p/authorizedbuyersmarketplace/v1/
| googleapis/google-api-java-client-services | clients/google-api-services-authorizedbuyersmarketplace/v1/1.31.0/README.md | Markdown | apache-2.0 | 1,523 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0"
/>
<title>Bootstrap3响应式后台管理系统模版MeAdmin 表单布局</title>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"
/>
<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css" href="plugins/jquery-ui/jquery.ui.1.10.2.ie.css"
/>
<![endif]-->
<link href="assets/css/main.css" rel="stylesheet" type="text/css" />
<link href="assets/css/plugins.css" rel="stylesheet" type="text/css" />
<link href="assets/css/responsive.css" rel="stylesheet" type="text/css"
/>
<link href="assets/css/icons.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="assets/css/fontawesome/font-awesome.min.css">
<!--[if IE 7]>
<link rel="stylesheet" href="assets/css/fontawesome/font-awesome-ie7.min.css">
<![endif]-->
<!--[if IE 8]>
<link href="assets/css/ie8.css" rel="stylesheet" type="text/css" />
<![endif]-->
<link href='http://fonts.useso.com/css?family=Open+Sans:400,600,700'
rel='stylesheet' type='text/css'>
<script type="text/javascript" src="assets/js/libs/jquery-1.10.2.min.js">
</script>
<script type="text/javascript" src="plugins/jquery-ui/jquery-ui-1.10.2.custom.min.js">
</script>
<script type="text/javascript" src="bootstrap/js/bootstrap.min.js">
</script>
<script type="text/javascript" src="assets/js/libs/lodash.compat.min.js">
</script>
<!--[if lt IE 9]>
<script src="assets/js/libs/html5shiv.js">
</script>
<![endif]-->
<script type="text/javascript" src="plugins/touchpunch/jquery.ui.touch-punch.min.js">
</script>
<script type="text/javascript" src="plugins/event.swipe/jquery.event.move.js">
</script>
<script type="text/javascript" src="plugins/event.swipe/jquery.event.swipe.js">
</script>
<script type="text/javascript" src="assets/js/libs/breakpoints.js">
</script>
<script type="text/javascript" src="plugins/respond/respond.min.js">
</script>
<script type="text/javascript" src="plugins/cookie/jquery.cookie.min.js">
</script>
<script type="text/javascript" src="plugins/slimscroll/jquery.slimscroll.min.js">
</script>
<script type="text/javascript" src="plugins/slimscroll/jquery.slimscroll.horizontal.min.js">
</script>
<script type="text/javascript" src="plugins/sparkline/jquery.sparkline.min.js">
</script>
<script type="text/javascript" src="plugins/daterangepicker/moment.min.js">
</script>
<script type="text/javascript" src="plugins/daterangepicker/daterangepicker.js">
</script>
<script type="text/javascript" src="plugins/blockui/jquery.blockUI.min.js">
</script>
<script type="text/javascript" src="assets/js/app.js">
</script>
<script type="text/javascript" src="assets/js/plugins.js">
</script>
<script type="text/javascript" src="assets/js/plugins.form-components.js">
</script>
<script>
$(document).ready(function() {
App.init();
Plugins.init();
FormComponents.init()
});
</script>
<script type="text/javascript" src="assets/js/custom.js">
</script>
</head>
<body>
<header class="header navbar navbar-fixed-top" role="banner">
<div class="container">
<ul class="nav navbar-nav">
<li class="nav-toggle">
<a href="javascript:void(0);" title="">
<i class="icon-reorder">
</i>
</a>
</li>
</ul>
<a class="navbar-brand" href="index.html">
<img src="assets/img/logo.png" alt="logo" />
<strong>
Me
</strong>
Admin
</a>
<a href="#" class="toggle-sidebar bs-tooltip" data-placement="bottom"
data-original-title="Toggle navigation">
<i class="icon-reorder">
</i>
</a>
<ul class="nav navbar-nav navbar-left hidden-xs hidden-sm">
<li>
<a href="#">
Dashboard
</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Dropdown
<i class="icon-caret-down small">
</i>
</a>
<ul class="dropdown-menu">
<li>
<a href="#">
<i class="icon-user">
</i>
Example #1
</a>
</li>
<li>
<a href="#">
<i class="icon-calendar">
</i>
Example #2
</a>
</li>
<li class="divider">
</li>
<li>
<a href="#">
<i class="icon-tasks">
</i>
Example #3
</a>
</li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-warning-sign">
</i>
<span class="badge">
5
</span>
</a>
<ul class="dropdown-menu extended notification">
<li class="title">
<p>
You have 5 new notifications
</p>
</li>
<li>
<a href="javascript:void(0);">
<span class="label label-success">
<i class="icon-plus">
</i>
</span>
<span class="message">
New user registration.
</span>
<span class="time">
1 mins
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="label label-danger">
<i class="icon-warning-sign">
</i>
</span>
<span class="message">
High CPU load on cluster #2.
</span>
<span class="time">
5 mins
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="label label-success">
<i class="icon-plus">
</i>
</span>
<span class="message">
New user registration.
</span>
<span class="time">
10 mins
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="label label-info">
<i class="icon-bullhorn">
</i>
</span>
<span class="message">
New items are in queue.
</span>
<span class="time">
25 mins
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="label label-warning">
<i class="icon-bolt">
</i>
</span>
<span class="message">
Disk space to 85% full.
</span>
<span class="time">
55 mins
</span>
</a>
</li>
<li class="footer">
<a href="javascript:void(0);">
View all notifications
</a>
</li>
</ul>
</li>
<li class="dropdown hidden-xs hidden-sm">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-tasks">
</i>
<span class="badge">
7
</span>
</a>
<ul class="dropdown-menu extended notification">
<li class="title">
<p>
You have 7 pending tasks
</p>
</li>
<li>
<a href="javascript:void(0);">
<span class="task">
<span class="desc">
Preparing new release
</span>
<span class="percent">
30%
</span>
</span>
<div class="progress progress-small">
<div style="width: 30%;" class="progress-bar progress-bar-info">
</div>
</div>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="task">
<span class="desc">
Change management
</span>
<span class="percent">
80%
</span>
</span>
<div class="progress progress-small progress-striped active">
<div style="width: 80%;" class="progress-bar progress-bar-danger">
</div>
</div>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="task">
<span class="desc">
Mobile development
</span>
<span class="percent">
60%
</span>
</span>
<div class="progress progress-small">
<div style="width: 60%;" class="progress-bar progress-bar-success">
</div>
</div>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="task">
<span class="desc">
Database migration
</span>
<span class="percent">
20%
</span>
</span>
<div class="progress progress-small">
<div style="width: 20%;" class="progress-bar progress-bar-warning">
</div>
</div>
</a>
</li>
<li class="footer">
<a href="javascript:void(0);">
View all tasks
</a>
</li>
</ul>
</li>
<li class="dropdown hidden-xs hidden-sm">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-envelope">
</i>
<span class="badge">
1
</span>
</a>
<ul class="dropdown-menu extended notification">
<li class="title">
<p>
You have 3 new messages
</p>
</li>
<li>
<a href="javascript:void(0);">
<span class="photo">
<img src="assets/img/demo/avatar-1.jpg" alt="" />
</span>
<span class="subject">
<span class="from">
Bob Carter
</span>
<span class="time">
Just Now
</span>
</span>
<span class="text">
Consetetur sadipscing elitr...
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="photo">
<img src="assets/img/demo/avatar-2.jpg" alt="" />
</span>
<span class="subject">
<span class="from">
Jane Doe
</span>
<span class="time">
45 mins
</span>
</span>
<span class="text">
Sed diam nonumy...
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="photo">
<img src="assets/img/demo/avatar-3.jpg" alt="" />
</span>
<span class="subject">
<span class="from">
Patrick Nilson
</span>
<span class="time">
6 hours
</span>
</span>
<span class="text">
No sea takimata sanctus...
</span>
</a>
</li>
<li class="footer">
<a href="javascript:void(0);">
View all messages
</a>
</li>
</ul>
</li>
<li>
<a href="#" class="dropdown-toggle row-bg-toggle">
<i class="icon-resize-vertical">
</i>
</a>
</li>
<li class="dropdown">
<a href="#" class="project-switcher-btn dropdown-toggle">
<i class="icon-folder-open">
</i>
<span>
Projects
</span>
</a>
</li>
<li class="dropdown user">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-male">
</i>
<span class="username">
John Doe
</span>
<i class="icon-caret-down small">
</i>
</a>
<ul class="dropdown-menu">
<li>
<a href="pages_user_profile.html">
<i class="icon-user">
</i>
My Profile
</a>
</li>
<li>
<a href="pages_calendar.html">
<i class="icon-calendar">
</i>
My Calendar
</a>
</li>
<li>
<a href="#">
<i class="icon-tasks">
</i>
My Tasks
</a>
</li>
<li class="divider">
</li>
<li>
<a href="login.html">
<i class="icon-key">
</i>
Log Out
</a>
</li>
</ul>
</li>
</ul>
</div>
<div id="project-switcher" class="container project-switcher">
<div id="scrollbar">
<div class="handle">
</div>
</div>
<div id="frame">
<ul class="project-list">
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-desktop">
</i>
</span>
<span class="title">
Lorem ipsum dolor
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-compass">
</i>
</span>
<span class="title">
Dolor sit invidunt
</span>
</a>
</li>
<li class="current">
<a href="javascript:void(0);">
<span class="image">
<i class="icon-male">
</i>
</span>
<span class="title">
Consetetur sadipscing elitr
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-thumbs-up">
</i>
</span>
<span class="title">
Sed diam nonumy
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-female">
</i>
</span>
<span class="title">
At vero eos et
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-beaker">
</i>
</span>
<span class="title">
Sed diam voluptua
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-desktop">
</i>
</span>
<span class="title">
Lorem ipsum dolor
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-compass">
</i>
</span>
<span class="title">
Dolor sit invidunt
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-male">
</i>
</span>
<span class="title">
Consetetur sadipscing elitr
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-thumbs-up">
</i>
</span>
<span class="title">
Sed diam nonumy
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-female">
</i>
</span>
<span class="title">
At vero eos et
</span>
</a>
</li>
<li>
<a href="javascript:void(0);">
<span class="image">
<i class="icon-beaker">
</i>
</span>
<span class="title">
Sed diam voluptua
</span>
</a>
</li>
</ul>
</div>
</div>
</header>
<div id="container">
<div id="sidebar" class="sidebar-fixed">
<div id="sidebar-content">
<form class="sidebar-search">
<div class="input-box">
<button type="submit" class="submit">
<i class="icon-search">
</i>
</button>
<span>
<input type="text" placeholder="Search...">
</span>
</div>
</form>
<div class="sidebar-search-results">
<i class="icon-remove close">
</i>
<div class="title">
Documents
</div>
<ul class="notifications">
<li>
<a href="javascript:void(0);">
<div class="col-left">
<span class="label label-info">
<i class="icon-file-text">
</i>
</span>
</div>
<div class="col-right with-margin">
<span class="message">
<strong>
John Doe
</strong>
received $1.527,32
</span>
<span class="time">
finances.xls
</span>
</div>
</a>
</li>
<li>
<a href="javascript:void(0);">
<div class="col-left">
<span class="label label-success">
<i class="icon-file-text">
</i>
</span>
</div>
<div class="col-right with-margin">
<span class="message">
My name is
<strong>
John Doe
</strong>
...
</span>
<span class="time">
briefing.docx
</span>
</div>
</a>
</li>
</ul>
<div class="title">
Persons
</div>
<ul class="notifications">
<li>
<a href="javascript:void(0);">
<div class="col-left">
<span class="label label-danger">
<i class="icon-female">
</i>
</span>
</div>
<div class="col-right with-margin">
<span class="message">
Jane
<strong>
Doe
</strong>
</span>
<span class="time">
21 years old
</span>
</div>
</a>
</li>
</ul>
</div>
<ul id="nav">
<li>
<a href="index.html">
<i class="icon-dashboard">
</i>
Dashboard
</a>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-desktop">
</i>
UI Features
<span class="label label-info pull-right">
6
</span>
</a>
<ul class="sub-menu">
<li>
<a href="ui_general.html">
<i class="icon-angle-right">
</i>
General
</a>
</li>
<li>
<a href="ui_buttons.html">
<i class="icon-angle-right">
</i>
Buttons
</a>
</li>
<li>
<a href="ui_tabs_accordions.html">
<i class="icon-angle-right">
</i>
Tabs & Accordions
</a>
</li>
<li>
<a href="ui_sliders.html">
<i class="icon-angle-right">
</i>
Sliders
</a>
</li>
<li>
<a href="ui_nestable_list.html">
<i class="icon-angle-right">
</i>
Nestable List
</a>
</li>
<li>
<a href="ui_typography.html">
<i class="icon-angle-right">
</i>
Typography / Icons
</a>
</li>
<li>
<a href="ui_google_maps.html">
<i class="icon-angle-right">
</i>
Google Maps
</a>
</li>
<li>
<a href="ui_grid.html">
<i class="icon-angle-right">
</i>
Grid
</a>
</li>
</ul>
</li>
<li class="current open">
<a href="javascript:void(0);">
<i class="icon-edit">
</i>
Form Elements
</a>
<ul class="sub-menu">
<li>
<a href="form_components.html">
<i class="icon-angle-right">
</i>
Form Components
</a>
</li>
<li class="current">
<a href="form_layouts.html">
<i class="icon-angle-right">
</i>
Form Layouts
</a>
</li>
<li>
<a href="form_validation.html">
<i class="icon-angle-right">
</i>
Form Validation
</a>
</li>
<li>
<a href="form_wizard.html">
<i class="icon-angle-right">
</i>
Form Wizard
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-table">
</i>
Tables
</a>
<ul class="sub-menu">
<li>
<a href="tables_static.html">
<i class="icon-angle-right">
</i>
Static Tables
</a>
</li>
<li>
<a href="http://envato.stammtec.de/themeforest/melon/tables_dynamic.html">
<i class="icon-angle-right">
</i>
Dynamic Tables (DataTables)
</a>
</li>
<li>
<a href="tables_responsive.html">
<i class="icon-angle-right">
</i>
Responsive Tables
</a>
</li>
</ul>
</li>
<li>
<a href="charts.html">
<i class="icon-bar-chart">
</i>
Charts & Statistics
</a>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-folder-open-alt">
</i>
Pages
</a>
<ul class="sub-menu">
<li>
<a href="login.html">
<i class="icon-angle-right">
</i>
Login
</a>
</li>
<li>
<a href="pages_user_profile.html">
<i class="icon-angle-right">
</i>
User Profile
</a>
</li>
<li>
<a href="pages_calendar.html">
<i class="icon-angle-right">
</i>
Calendar
</a>
</li>
<li>
<a href="pages_invoice.html">
<i class="icon-angle-right">
</i>
Invoice
</a>
</li>
<li>
<a href="404.html">
<i class="icon-angle-right">
</i>
404 Page
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-list-ol">
</i>
4 Level Menu
</a>
<ul class="sub-menu">
<li class="open-default">
<a href="javascript:void(0);">
<i class="icon-cogs">
</i>
Item 1
<span class="arrow">
</span>
</a>
<ul class="sub-menu">
<li class="open-default">
<a href="javascript:void(0);">
<i class="icon-user">
</i>
Sample Link 1
<span class="arrow">
</span>
</a>
<ul class="sub-menu">
<li class="current">
<a href="javascript:void(0);">
<i class="icon-remove">
</i>
Sample Link 1
</a>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-pencil">
</i>
Sample Link 1
</a>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-edit">
</i>
Sample Link 1
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-user">
</i>
Sample Link 1
</a>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-external-link">
</i>
Sample Link 2
</a>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-bell">
</i>
Sample Link 3
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-globe">
</i>
Item 2
<span class="arrow">
</span>
</a>
<ul class="sub-menu">
<li>
<a href="javascript:void(0);">
<i class="icon-user">
</i>
Sample Link 1
</a>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-external-link">
</i>
Sample Link 1
</a>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-bell">
</i>
Sample Link 1
</a>
</li>
</ul>
</li>
<li>
<a href="javascript:void(0);">
<i class="icon-folder-open">
</i>
Item 3
</a>
</li>
</ul>
</li>
</ul>
<div class="sidebar-title">
<span>
Notifications
</span>
</div>
<ul class="notifications demo-slide-in">
<li style="display: none;">
<div class="col-left">
<span class="label label-danger">
<i class="icon-warning-sign">
</i>
</span>
</div>
<div class="col-right with-margin">
<span class="message">
Server
<strong>
#512
</strong>
crashed.
</span>
<span class="time">
few seconds ago
</span>
</div>
</li>
<li style="display: none;">
<div class="col-left">
<span class="label label-info">
<i class="icon-envelope">
</i>
</span>
</div>
<div class="col-right with-margin">
<span class="message">
<strong>
John
</strong>
sent you a message
</span>
<span class="time">
few second ago
</span>
</div>
</li>
<li>
<div class="col-left">
<span class="label label-success">
<i class="icon-plus">
</i>
</span>
</div>
<div class="col-right with-margin">
<span class="message">
<strong>
Emma
</strong>
's account was created
</span>
<span class="time">
4 hours ago
</span>
</div>
</li>
</ul>
<div class="sidebar-widget align-center">
<div class="btn-group" data-toggle="buttons" id="theme-switcher">
<label class="btn active">
<input type="radio" name="theme-switcher" data-theme="bright">
<i class="icon-sun">
</i>
Bright
</label>
<label class="btn">
<input type="radio" name="theme-switcher" data-theme="dark">
<i class="icon-moon">
</i>
Dark
</label>
</div>
</div>
</div>
<div id="divider" class="resizeable">
</div>
</div>
<div id="content">
<div class="container">
<div class="crumbs">
<ul id="breadcrumbs" class="breadcrumb">
<li>
<i class="icon-home">
</i>
<a href="index.html">
Dashboard
</a>
</li>
<li class="current">
<a href="pages_calendar.html" title="">
Calendar
</a>
</li>
</ul>
<ul class="crumb-buttons">
<li>
<a href="charts.html" title="">
<i class="icon-signal">
</i>
<span>
Statistics
</span>
</a>
</li>
<li class="dropdown">
<a href="#" title="" data-toggle="dropdown">
<i class="icon-tasks">
</i>
<span>
Users
<strong>
(+3)
</strong>
</span>
<i class="icon-angle-down left-padding">
</i>
</a>
<ul class="dropdown-menu pull-right">
<li>
<a href="form_components.html" title="">
<i class="icon-plus">
</i>
Add new User
</a>
</li>
<li>
<a href="http://envato.stammtec.de/themeforest/melon/tables_dynamic.html"
title="">
<i class="icon-reorder">
</i>
Overview
</a>
</li>
</ul>
</li>
<li class="range">
<a href="#">
<i class="icon-calendar">
</i>
<span>
</span>
<i class="icon-angle-down">
</i>
</a>
</li>
</ul>
</div>
<div class="page-header">
<div class="page-title">
<h3>
Form Layouts
</h3>
<span>
Good morning, John!
</span>
</div>
<ul class="page-stats">
<li>
<div class="summary">
<span>
New orders
</span>
<h3>
17,561
</h3>
</div>
<div id="sparkline-bar" class="graph sparkline hidden-xs">
20,15,8,50,20,40,20,30,20,15,30,20,25,20
</div>
</li>
<li>
<div class="summary">
<span>
My balance
</span>
<h3>
$21,561.21
</h3>
</div>
<div id="sparkline-bar2" class="graph sparkline hidden-xs">
20,15,8,50,20,40,20,30,20,15,30,20,25,20
</div>
</li>
</ul>
</div>
<div class="row">
<div class="col-md-12">
<div class="widget box">
<div class="widget-header">
<h4>
<i class="icon-reorder">
</i>
Horizontal Forms
</h4>
</div>
<div class="widget-content">
<form class="form-horizontal row-border" action="#">
<div class="form-group">
<label class="col-md-2 control-label">
Full width input:
</label>
<div class="col-md-10">
<input type="text" name="regular" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">
Multiple inputs:
</label>
<div class="col-md-10">
<div class="row">
<div class="col-md-4">
<input type="text" name="regular" class="form-control">
<span class="help-block">
Left aligned helper
</span>
</div>
<div class="col-md-4">
<input type="text" name="regular" class="form-control">
<span class="help-block align-center">
Centered helper
</span>
</div>
<div class="col-md-4">
<input type="text" name="regular" class="form-control">
<span class="help-block align-right">
Right aligned helper
</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">
Predefined width:
</label>
<div class="col-md-10">
<input class="form-control input-width-mini" type="text" placeholder=".input-width-mini"
style="display: block;">
<input class="form-control input-width-small" type="text" placeholder=".input-width-small"
style="display: block; margin-top: 6px;">
<input class="form-control input-width-medium" type="text" placeholder=".input-width-medium"
style="display: block; margin-top: 6px;">
<input class="form-control input-width-large" type="text" placeholder=".input-width-large"
style="display: block; margin-top: 6px;">
<input class="form-control input-width-xlarge" type="text" placeholder=".input-width-xlarge"
style="display: block; margin-top: 6px;">
<input class="form-control input-width-xxlarge" type="text" placeholder=".input-width-xxlarge"
style="display: block; margin-top: 6px;">
<input class="form-control input-block-level" type="text" placeholder=".input-block-level"
style="display: block; margin-top: 6px;">
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">
Select:
</label>
<div class="col-md-10">
<div class="row">
<div class="col-md-4">
<select class="form-control" name="select">
<option value="opt1">
col-md-4
</option>
<option value="opt2">
Option 2
</option>
<option value="opt3">
Option 3
</option>
</select>
</div>
</div>
<div class="row next-row">
<div class="col-md-6">
<select class="form-control" name="select">
<option value="opt1">
col-md-6
</option>
<option value="opt2">
Option 2
</option>
<option value="opt3">
Option 3
</option>
</select>
</div>
</div>
<div class="row next-row">
<div class="col-md-8">
<select class="form-control" name="select">
<option value="opt1">
col-md-8
</option>
<option value="opt2">
Option 2
</option>
<option value="opt3">
Option 3
</option>
</select>
</div>
</div>
<div class="row next-row">
<div class="col-md-12">
<select class="form-control" name="select">
<option value="opt1">
col-md-12
</option>
<option value="opt2">
Option 2
</option>
<option value="opt3">
Option 3
</option>
</select>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="widget box">
<div class="widget-header">
<h4>
<i class="icon-reorder">
</i>
Vertical Forms
</h4>
</div>
<div class="widget-content">
<form class="form-vertical row-border" action="#">
<div class="form-group">
<label class="control-label">
Full width input:
</label>
<input type="text" name="regular" class="form-control">
</div>
<div class="form-group">
<label class="control-label">
Multiple inputs:
</label>
<div class="row">
<div class="col-md-4">
<input type="text" name="regular" class="form-control">
<span class="help-block">
Left aligned helper
</span>
</div>
<div class="col-md-4">
<input type="text" name="regular" class="form-control">
<span class="help-block align-center">
Centered helper
</span>
</div>
<div class="col-md-4">
<input type="text" name="regular" class="form-control">
<span class="help-block align-right">
Right aligned helper
</span>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label">
Predefined width:
</label>
<input class="form-control input-width-mini" type="text" placeholder=".input-width-mini"
style="display: block;">
<input class="form-control input-width-small" type="text" placeholder=".input-width-small"
style="display: block; margin-top: 6px;">
<input class="form-control input-width-medium" type="text" placeholder=".input-width-medium"
style="display: block; margin-top: 6px;">
<input class="form-control input-width-large" type="text" placeholder=".input-width-large"
style="display: block; margin-top: 6px;">
<input class="form-control input-width-xlarge" type="text" placeholder=".input-width-xlarge"
style="display: block; margin-top: 6px;">
<input class="form-control input-width-xxlarge" type="text" placeholder=".input-width-xxlarge"
style="display: block; margin-top: 6px;">
<input class="form-control input-block-level" type="text" placeholder=".input-block-level"
style="display: block; margin-top: 6px;">
</div>
<div class="form-group">
<label class="control-label">
Select:
</label>
<div class="row">
<div class="col-md-4">
<select class="form-control" name="select">
<option value="opt1">
col-md-4
</option>
<option value="opt2">
Option 2
</option>
<option value="opt3">
Option 3
</option>
</select>
</div>
</div>
<div class="row next-row">
<div class="col-md-6">
<select class="form-control" name="select">
<option value="opt1">
col-md-6
</option>
<option value="opt2">
Option 2
</option>
<option value="opt3">
Option 3
</option>
</select>
</div>
</div>
<div class="row next-row">
<div class="col-md-8">
<select class="form-control" name="select">
<option value="opt1">
col-md-8
</option>
<option value="opt2">
Option 2
</option>
<option value="opt3">
Option 3
</option>
</select>
</div>
</div>
<div class="row next-row">
<div class="col-md-12">
<select class="form-control" name="select">
<option value="opt1">
col-md-12
</option>
<option value="opt2">
Option 2
</option>
<option value="opt3">
Option 3
</option>
</select>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="widget box">
<div class="widget-header">
<h4>
<i class="icon-reorder">
</i>
Form Grid
</h4>
</div>
<div class="widget-content">
<form class="form-vertical" action="#">
<div class="form-group">
<div class="row">
<div class="col-md-12">
<input type="text" name="regular" class="form-control" placeholder=".col-md-12">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-11">
<input type="text" name="regular" class="form-control" placeholder=".col-md-11">
</div>
<div class="col-md-1">
<input type="text" name="regular" class="form-control" placeholder=".col-md-1">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-10">
<input type="text" name="regular" class="form-control" placeholder=".col-md-10">
</div>
<div class="col-md-2">
<input type="text" name="regular" class="form-control" placeholder=".col-md-2">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-9">
<input type="text" name="regular" class="form-control" placeholder=".col-md-9">
</div>
<div class="col-md-3">
<input type="text" name="regular" class="form-control" placeholder=".col-md-3">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-8">
<input type="text" name="regular" class="form-control" placeholder=".col-md-8">
</div>
<div class="col-md-4">
<input type="text" name="regular" class="form-control" placeholder=".col-md-4">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-7">
<input type="text" name="regular" class="form-control" placeholder=".col-md-7">
</div>
<div class="col-md-5">
<input type="text" name="regular" class="form-control" placeholder=".col-md-5">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-6">
<input type="text" name="regular" class="form-control" placeholder=".col-md-6">
</div>
<div class="col-md-6">
<input type="text" name="regular" class="form-control" placeholder=".col-md-6">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-5">
<input type="text" name="regular" class="form-control" placeholder=".col-md-5">
</div>
<div class="col-md-7">
<input type="text" name="regular" class="form-control" placeholder=".col-md-7">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-4">
<input type="text" name="regular" class="form-control" placeholder=".col-md-4">
</div>
<div class="col-md-8">
<input type="text" name="regular" class="form-control" placeholder=".col-md-8">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-3">
<input type="text" name="regular" class="form-control" placeholder=".col-md-3">
</div>
<div class="col-md-9">
<input type="text" name="regular" class="form-control" placeholder=".col-md-9">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2">
<input type="text" name="regular" class="form-control" placeholder=".col-md-2">
</div>
<div class="col-md-10">
<input type="text" name="regular" class="form-control" placeholder=".col-md-10">
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-1">
<input type="text" name="regular" class="form-control" placeholder=".col-md-1">
</div>
<div class="col-md-11">
<input type="text" name="regular" class="form-control" placeholder=".col-md-11">
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html> | zhangyage/Python-oldboy | day10/meAdmin/form_layouts.html | HTML | apache-2.0 | 57,776 |
To access the approval page, click on "Approval" in the main menu. It provides Interest Adjustments,
Pending Payments and Payment Moves Approval for supervisors.
| NASA-Tournament-Lab/CoECI-OPM-Service-Credit-Redeposit-Deposit-Application | Code/SCRD_BRE/src/web/help/approvalPageSubject.html | HTML | apache-2.0 | 162 |
/***********************************************************************************************
*
* Copyright (C) 2016, IBL Software Engineering spol. s r. o.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
***********************************************************************************************/
package com.iblsoft.iwxxm.webservice.ws.internal;
import com.googlecode.jsonrpc4j.JsonRpcParam;
import com.iblsoft.iwxxm.webservice.util.Log;
import com.iblsoft.iwxxm.webservice.validator.IwxxmValidator;
import com.iblsoft.iwxxm.webservice.validator.ValidationError;
import com.iblsoft.iwxxm.webservice.validator.ValidationResult;
import com.iblsoft.iwxxm.webservice.ws.IwxxmWebService;
import com.iblsoft.iwxxm.webservice.ws.messages.ValidationRequest;
import com.iblsoft.iwxxm.webservice.ws.messages.ValidationResponse;
import java.io.File;
import static com.google.common.base.Preconditions.checkArgument;
/**
* Implementation class of IwxxmWebService interface.
*/
public class IwxxmWebServiceImpl implements IwxxmWebService {
private final IwxxmValidator iwxxmValidator;
public IwxxmWebServiceImpl(File validationCatalogFile, File validationRulesDir, String defaultIwxxmVersion) {
this.iwxxmValidator = new IwxxmValidator(validationCatalogFile, validationRulesDir, defaultIwxxmVersion);
}
@Override
public ValidationResponse validate(@JsonRpcParam("request") ValidationRequest request) {
Log.INSTANCE.debug("IwxxmWebService.validate request started");
checkRequestVersion(request.getRequestVersion());
ValidationResult validationResult = iwxxmValidator.validate(request.getIwxxmData(), request.getIwxxmVersion());
ValidationResponse.Builder responseBuilder = ValidationResponse.builder();
for (ValidationError ve : validationResult.getValidationErrors()) {
responseBuilder.addValidationError(ve.getError(), ve.getLineNumber(), ve.getColumnNumber());
}
Log.INSTANCE.debug("IwxxmWebService.validate request finished");
return responseBuilder.build();
}
private void checkRequestVersion(String requestVersion) {
checkArgument(requestVersion != null && requestVersion.equals("1.0"), "Unsupported request version.");
}
}
| iblsoft/iwxxm-validator | src/main/java/com/iblsoft/iwxxm/webservice/ws/internal/IwxxmWebServiceImpl.java | Java | apache-2.0 | 2,770 |
# Copyright 2011 WebDriver committers
# Copyright 2011 Google Inc.
#
# 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.
"""The ActionChains implementation."""
from selenium.webdriver.remote.command import Command
class ActionChains(object):
"""Generate user actions.
All actions are stored in the ActionChains object. Call perform() to fire
stored actions."""
def __init__(self, driver):
"""Creates a new ActionChains.
Args:
driver: The WebDriver instance which performs user actions.
"""
self._driver = driver
self._actions = []
def perform(self):
"""Performs all stored actions."""
for action in self._actions:
action()
def click(self, on_element=None):
"""Clicks an element.
Args:
on_element: The element to click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 0}))
return self
def click_and_hold(self, on_element):
"""Holds down the left mouse button on an element.
Args:
on_element: The element to mouse down.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_DOWN, {}))
return self
def context_click(self, on_element):
"""Performs a context-click (right click) on an element.
Args:
on_element: The element to context-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.CLICK, {'button': 2}))
return self
def double_click(self, on_element):
"""Double-clicks an element.
Args:
on_element: The element to double-click.
If None, clicks on current mouse position.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.DOUBLE_CLICK, {}))
return self
def drag_and_drop(self, source, target):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
target: The element to mouse up.
"""
self.click_and_hold(source)
self.release(target)
return self
def drag_and_drop_by_offset(self, source, xoffset, yoffset):
"""Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
Args:
source: The element to mouse down.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self.click_and_hold(source)
self.move_by_offset(xoffset, yoffset)
self.release(source)
return self
def key_down(self, key, element=None):
"""Sends a key press only, without releasing it.
Should only be used with modifier keys (Control, Alt and Shift).
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": True}))
return self
def key_up(self, key, element=None):
"""Releases a modifier key.
Args:
key: The modifier key to send. Values are defined in Keys class.
target: The element to send keys.
If None, sends a key to current focused element.
"""
if element: self.click(element)
self._actions.append(lambda:
self._driver.execute(Command.SEND_MODIFIER_KEY_TO_ACTIVE_ELEMENT, {
"value": key,
"isdown": False}))
return self
def move_by_offset(self, xoffset, yoffset):
"""Moving the mouse to an offset from current mouse position.
Args:
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def move_to_element(self, to_element):
"""Moving the mouse to the middle of an element.
Args:
to_element: The element to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {'element': to_element.id}))
return self
def move_to_element_with_offset(self, to_element, xoffset, yoffset):
"""Move the mouse by an offset of the specificed element.
Offsets are relative to the top-left corner of the element.
Args:
to_element: The element to move to.
xoffset: X offset to move to.
yoffset: Y offset to move to.
"""
self._actions.append(lambda:
self._driver.execute(Command.MOVE_TO, {
'element': to_element.id,
'xoffset': xoffset,
'yoffset': yoffset}))
return self
def release(self, on_element):
"""Releasing a held mouse button.
Args:
on_element: The element to mouse up.
"""
if on_element: self.move_to_element(on_element)
self._actions.append(lambda:
self._driver.execute(Command.MOUSE_UP, {}))
return self
def send_keys(self, *keys_to_send):
"""Sends keys to current focused element.
Args:
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
self._driver.switch_to_active_element().send_keys(*keys_to_send))
return self
def send_keys_to_element(self, element, *keys_to_send):
"""Sends keys to an element.
Args:
element: The element to send keys.
keys_to_send: The keys to send.
"""
self._actions.append(lambda:
element.send_keys(*keys_to_send))
return self
| hali4ka/robotframework-selenium2library | src/Selenium2Library/lib/selenium-2.8.1/py/selenium/webdriver/common/action_chains.py | Python | apache-2.0 | 7,157 |
package org.jboss.resteasy.reactive.client.processor.beanparam;
import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.BEAN_PARAM;
import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.COOKIE_PARAM;
import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.FORM_PARAM;
import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.HEADER_PARAM;
import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.PATH_PARAM;
import static org.jboss.resteasy.reactive.common.processor.ResteasyReactiveDotNames.QUERY_PARAM;
import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import org.jboss.jandex.AnnotationInstance;
import org.jboss.jandex.AnnotationTarget;
import org.jboss.jandex.ClassInfo;
import org.jboss.jandex.DotName;
import org.jboss.jandex.FieldInfo;
import org.jboss.jandex.IndexView;
import org.jboss.jandex.MethodInfo;
import org.jboss.jandex.Type;
import org.jboss.resteasy.reactive.common.processor.JandexUtil;
public class BeanParamParser {
public static List<Item> parse(ClassInfo beanParamClass, IndexView index) {
Set<ClassInfo> processedBeanParamClasses = Collections.newSetFromMap(new IdentityHashMap<>());
return parseInternal(beanParamClass, index, processedBeanParamClasses);
}
private static List<Item> parseInternal(ClassInfo beanParamClass, IndexView index,
Set<ClassInfo> processedBeanParamClasses) {
if (!processedBeanParamClasses.add(beanParamClass)) {
throw new IllegalArgumentException("Cycle detected in BeanParam annotations; already processed class "
+ beanParamClass.name());
}
try {
List<Item> resultList = new ArrayList<>();
// Parse class tree recursively
if (!JandexUtil.DOTNAME_OBJECT.equals(beanParamClass.superName())) {
resultList
.addAll(parseInternal(index.getClassByName(beanParamClass.superName()), index,
processedBeanParamClasses));
}
resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, QUERY_PARAM,
(annotationValue, fieldInfo) -> new QueryParamItem(annotationValue,
new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString()),
fieldInfo.type()),
(annotationValue, getterMethod) -> new QueryParamItem(annotationValue, new GetterExtractor(getterMethod),
getterMethod.returnType())));
resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, BEAN_PARAM,
(annotationValue, fieldInfo) -> {
Type type = fieldInfo.type();
if (type.kind() == Type.Kind.CLASS) {
List<Item> subBeanParamItems = parseInternal(index.getClassByName(type.asClassType().name()), index,
processedBeanParamClasses);
return new BeanParamItem(subBeanParamItems,
new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString()));
} else {
throw new IllegalArgumentException("BeanParam annotation used on a field that is not an object: "
+ beanParamClass.name() + "." + fieldInfo.name());
}
},
(annotationValue, getterMethod) -> {
Type returnType = getterMethod.returnType();
List<Item> items = parseInternal(index.getClassByName(returnType.name()), index,
processedBeanParamClasses);
return new BeanParamItem(items, new GetterExtractor(getterMethod));
}));
resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, COOKIE_PARAM,
(annotationValue, fieldInfo) -> new CookieParamItem(annotationValue,
new FieldExtractor(null, fieldInfo.name(),
fieldInfo.declaringClass().name().toString()),
fieldInfo.type().name().toString()),
(annotationValue, getterMethod) -> new CookieParamItem(annotationValue,
new GetterExtractor(getterMethod), getterMethod.returnType().name().toString())));
resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, HEADER_PARAM,
(annotationValue, fieldInfo) -> new HeaderParamItem(annotationValue,
new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString()),
fieldInfo.type().name().toString()),
(annotationValue, getterMethod) -> new HeaderParamItem(annotationValue,
new GetterExtractor(getterMethod), getterMethod.returnType().name().toString())));
resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, PATH_PARAM,
(annotationValue, fieldInfo) -> new PathParamItem(annotationValue, fieldInfo.type().name().toString(),
new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString())),
(annotationValue, getterMethod) -> new PathParamItem(annotationValue,
getterMethod.returnType().name().toString(),
new GetterExtractor(getterMethod))));
resultList.addAll(paramItemsForFieldsAndMethods(beanParamClass, FORM_PARAM,
(annotationValue, fieldInfo) -> new FormParamItem(annotationValue,
fieldInfo.type().name().toString(),
new FieldExtractor(null, fieldInfo.name(), fieldInfo.declaringClass().name().toString())),
(annotationValue, getterMethod) -> new FormParamItem(annotationValue,
getterMethod.returnType().name().toString(),
new GetterExtractor(getterMethod))));
return resultList;
} finally {
processedBeanParamClasses.remove(beanParamClass);
}
}
private static MethodInfo getGetterMethod(ClassInfo beanParamClass, MethodInfo methodInfo) {
MethodInfo getter = null;
if (methodInfo.parameters().size() > 0) { // should be setter
// find the corresponding getter:
String setterName = methodInfo.name();
if (setterName.startsWith("set")) {
getter = beanParamClass.method(setterName.replace("^set", "^get"));
}
} else if (methodInfo.name().startsWith("get")) {
getter = methodInfo;
}
if (getter == null) {
throw new IllegalArgumentException(
"No getter corresponding to " + methodInfo.declaringClass().name() + "#" + methodInfo.name() + " found");
}
return getter;
}
private static <T extends Item> List<T> paramItemsForFieldsAndMethods(ClassInfo beanParamClass, DotName parameterType,
BiFunction<String, FieldInfo, T> fieldExtractor, BiFunction<String, MethodInfo, T> methodExtractor) {
return ParamTypeAnnotations.of(beanParamClass, parameterType).itemsForFieldsAndMethods(fieldExtractor, methodExtractor);
}
private BeanParamParser() {
}
private static class ParamTypeAnnotations {
private final ClassInfo beanParamClass;
private final List<AnnotationInstance> annotations;
private ParamTypeAnnotations(ClassInfo beanParamClass, DotName parameterType) {
this.beanParamClass = beanParamClass;
List<AnnotationInstance> relevantAnnotations = beanParamClass.annotations().get(parameterType);
this.annotations = relevantAnnotations == null
? Collections.emptyList()
: relevantAnnotations.stream().filter(this::isFieldOrMethodAnnotation).collect(Collectors.toList());
}
private static ParamTypeAnnotations of(ClassInfo beanParamClass, DotName parameterType) {
return new ParamTypeAnnotations(beanParamClass, parameterType);
}
private <T extends Item> List<T> itemsForFieldsAndMethods(BiFunction<String, FieldInfo, T> itemFromFieldExtractor,
BiFunction<String, MethodInfo, T> itemFromMethodExtractor) {
return annotations.stream()
.map(annotation -> toItem(annotation, itemFromFieldExtractor, itemFromMethodExtractor))
.collect(Collectors.toList());
}
private <T extends Item> T toItem(AnnotationInstance annotation,
BiFunction<String, FieldInfo, T> itemFromFieldExtractor,
BiFunction<String, MethodInfo, T> itemFromMethodExtractor) {
String annotationValue = annotation.value() == null ? null : annotation.value().asString();
return annotation.target().kind() == AnnotationTarget.Kind.FIELD
? itemFromFieldExtractor.apply(annotationValue, annotation.target().asField())
: itemFromMethodExtractor.apply(annotationValue,
getGetterMethod(beanParamClass, annotation.target().asMethod()));
}
private boolean isFieldOrMethodAnnotation(AnnotationInstance annotation) {
return annotation.target().kind() == AnnotationTarget.Kind.FIELD
|| annotation.target().kind() == AnnotationTarget.Kind.METHOD;
}
}
}
| quarkusio/quarkus | independent-projects/resteasy-reactive/client/processor/src/main/java/org/jboss/resteasy/reactive/client/processor/beanparam/BeanParamParser.java | Java | apache-2.0 | 9,998 |
import * as React from 'react'
import styled from 'styled-components'
import { colors } from 'styles/variables'
interface InputFeedbackProps {
className?: string
valid?: boolean
}
const InputFeedback: React.SFC<InputFeedbackProps> = ({ className, children }) => (
<div className={className}>{children}</div>
)
export default styled(InputFeedback)`
width: 100%;
margin-top: 0.25rem;
font-size: 80%;
color: ${props => (props.valid ? colors.green : colors.red)};
`
| blvdgroup/crater | priv/crater-web/src/components/ui/InputFeedback.tsx | TypeScript | apache-2.0 | 479 |
Potree.TranslationTool = function(camera) {
THREE.Object3D.call( this );
var scope = this;
this.camera = camera;
this.geometry = new THREE.Geometry();
this.material = new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
this.STATE = {
DEFAULT: 0,
TRANSLATE_X: 1,
TRANSLATE_Y: 2,
TRANSLATE_Z: 3
};
this.parts = {
ARROW_X : {name: "arrow_x", object: undefined, color: new THREE.Color( 0xff0000 ), state: this.STATE.TRANSLATE_X},
ARROW_Y : {name: "arrow_y", object: undefined, color: new THREE.Color( 0x00ff00 ), state: this.STATE.TRANSLATE_Y},
ARROW_Z : {name: "arrow_z", object: undefined, color: new THREE.Color( 0x0000ff ), state: this.STATE.TRANSLATE_Z}
}
this.translateStart;
this.state = this.STATE.DEFAULT;
this.highlighted;
this.targets;
this.build = function(){
var arrowX = scope.createArrow(scope.parts.ARROW_X, scope.parts.ARROW_X.color);
arrowX.rotation.z = -Math.PI/2;
var arrowY = scope.createArrow(scope.parts.ARROW_Y, scope.parts.ARROW_Y.color);
var arrowZ = scope.createArrow(scope.parts.ARROW_Z, scope.parts.ARROW_Z.color);
arrowZ.rotation.x = -Math.PI/2;
scope.add(arrowX);
scope.add(arrowY);
scope.add(arrowZ);
var boxXY = scope.createBox(new THREE.Color( 0xffff00 ));
boxXY.scale.z = 0.02;
boxXY.position.set(0.5, 0.5, 0);
var boxXZ = scope.createBox(new THREE.Color( 0xff00ff ));
boxXZ.scale.y = 0.02;
boxXZ.position.set(0.5, 0, -0.5);
var boxYZ = scope.createBox(new THREE.Color( 0x00ffff ));
boxYZ.scale.x = 0.02;
boxYZ.position.set(0, 0.5, -0.5);
scope.add(boxXY);
scope.add(boxXZ);
scope.add(boxYZ);
scope.parts.ARROW_X.object = arrowX;
scope.parts.ARROW_Y.object = arrowY;
scope.parts.ARROW_Z.object = arrowZ;
scope.scale.multiplyScalar(5);
};
this.createBox = function(color){
var boxGeometry = new THREE.BoxGeometry(1, 1, 1);
var boxMaterial = new THREE.MeshBasicMaterial({color: color, transparent: true, opacity: 0.5});
var box = new THREE.Mesh(boxGeometry, boxMaterial);
return box;
};
this.createArrow = function(partID, color){
var material = new THREE.MeshBasicMaterial({color: color});
var shaftGeometry = new THREE.CylinderGeometry(0.1, 0.1, 3, 10, 1, false);
var shaftMatterial = material;
var shaft = new THREE.Mesh(shaftGeometry, shaftMatterial);
shaft.position.y = 1.5;
var headGeometry = new THREE.CylinderGeometry(0, 0.3, 1, 10, 1, false);
var headMaterial = material;
var head = new THREE.Mesh(headGeometry, headMaterial);
head.position.y = 3;
var arrow = new THREE.Object3D();
arrow.add(shaft);
arrow.add(head);
arrow.partID = partID;
arrow.material = material;
return arrow;
};
this.setHighlighted = function(partID){
if(partID === undefined){
if(scope.highlighted){
scope.highlighted.object.material.color = scope.highlighted.color;
scope.highlighted = undefined;
}
return;
}else if(scope.highlighted !== undefined && scope.highlighted !== partID){
scope.highlighted.object.material.color = scope.highlighted.color;
}
scope.highlighted = partID;
partID.object.material.color = new THREE.Color(0xffff00);
}
this.getHoveredObject = function(mouse){
var vector = new THREE.Vector3( mouse.x, mouse.y, 0.5 );
vector.unproject(scope.camera);
var raycaster = new THREE.Raycaster();
raycaster.ray.set( scope.camera.position, vector.sub( scope.camera.position ).normalize() );
var intersections = raycaster.intersectObject(scope, true);
if(intersections.length === 0){
scope.setHighlighted(undefined);
return undefined;
}
var I = intersections[0];
var partID = I.object.parent.partID;
return partID;
}
this.onMouseMove = function(event){
var mouse = event.normalizedPosition;
if(scope.state === scope.STATE.DEFAULT){
scope.setHighlighted(scope.getHoveredObject(mouse));
}else if(scope.state === scope.STATE.TRANSLATE_X || scope.state === scope.STATE.TRANSLATE_Y || scope.state === scope.STATE.TRANSLATE_Z){
var origin = scope.start.lineStart.clone();
var direction = scope.start.lineEnd.clone().sub(scope.start.lineStart);
direction.normalize();
var mousePoint = new THREE.Vector3(mouse.x, mouse.y);
var directionDistance = new THREE.Vector3().subVectors(mousePoint, origin).dot(direction);
var pointOnLine = direction.clone().multiplyScalar(directionDistance).add(origin);
pointOnLine.unproject(scope.camera);
var diff = pointOnLine.clone().sub(scope.position);
scope.position.copy(pointOnLine);
for(var i = 0; i < scope.targets.length; i++){
var target = scope.targets[0];
target.position.add(diff);
}
event.signal.halt();
}
};
this.onMouseDown = function(event){
if(scope.state === scope.STATE.DEFAULT){
var hoveredObject = scope.getHoveredObject(event.normalizedPosition, scope.camera);
if(hoveredObject){
scope.state = hoveredObject.state;
var lineStart = scope.position.clone();
var lineEnd;
if(scope.state === scope.STATE.TRANSLATE_X){
lineEnd = scope.position.clone();
lineEnd.x += 2;
}else if(scope.state === scope.STATE.TRANSLATE_Y){
lineEnd = scope.position.clone();
lineEnd.y += 2;
}else if(scope.state === scope.STATE.TRANSLATE_Z){
lineEnd = scope.position.clone();
lineEnd.z -= 2;
}
lineStart.project(scope.camera);
lineEnd.project(scope.camera);
scope.start = {
mouse: event.normalizedPosition,
lineStart: lineStart,
lineEnd: lineEnd
};
event.signal.halt();
}
}
};
this.onMouseUp = function(event){
scope.setHighlighted();
scope.state = scope.STATE.DEFAULT;
};
this.setTargets = function(targets){
scope.targets = targets;
if(scope.targets.length === 0){
return;
}
//TODO calculate centroid of all targets
var centroid = targets[0].position.clone();
//for(var i = 0; i < targets.length; i++){
// var target = targets[i];
//}
scope.position.copy(centroid);
}
this.build();
};
Potree.TranslationTool.prototype = Object.create( THREE.Object3D.prototype );
| idunshee/Portfolio | Project/WPC/WPC_Viewer/src/utils/TranslationTool.js | JavaScript | apache-2.0 | 6,194 |
/*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2019 Serge Rider ([email protected])
*
* 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 org.jkiss.dbeaver.ui.actions;
import org.eclipse.core.expressions.PropertyTester;
import org.eclipse.core.resources.*;
import org.jkiss.dbeaver.runtime.DBWorkbench;
import org.jkiss.dbeaver.runtime.IPluginService;
import org.jkiss.dbeaver.ui.ActionUtils;
/**
* GlobalPropertyTester
*/
public class GlobalPropertyTester extends PropertyTester {
//static final Log log = LogFactory.get vLog(ObjectPropertyTester.class);
public static final String NAMESPACE = "org.jkiss.dbeaver.core.global";
public static final String PROP_STANDALONE = "standalone";
public static final String PROP_HAS_ACTIVE_PROJECT = "hasActiveProject";
public static final String PROP_HAS_MULTI_PROJECTS = "hasMultipleProjects";
@Override
public boolean test(Object receiver, String property, Object[] args, Object expectedValue) {
switch (property) {
case PROP_HAS_MULTI_PROJECTS:
return DBWorkbench.getPlatform().getWorkspace().getProjects().size() > 1;
case PROP_HAS_ACTIVE_PROJECT:
return DBWorkbench.getPlatform().getWorkspace().getActiveProject() != null;
case PROP_STANDALONE:
return DBWorkbench.getPlatform().getApplication().isStandalone();
}
return false;
}
public static void firePropertyChange(String propName)
{
ActionUtils.evaluatePropertyState(NAMESPACE + "." + propName);
}
public static class ResourceListener implements IPluginService, IResourceChangeListener {
@Override
public void activateService() {
ResourcesPlugin.getWorkspace().addResourceChangeListener(this);
}
@Override
public void deactivateService() {
ResourcesPlugin.getWorkspace().removeResourceChangeListener(this);
}
@Override
public void resourceChanged(IResourceChangeEvent event) {
if (event.getType() == IResourceChangeEvent.POST_CHANGE) {
for (IResourceDelta childDelta : event.getDelta().getAffectedChildren()) {
if (childDelta.getResource() instanceof IProject) {
if (childDelta.getKind() == IResourceDelta.ADDED || childDelta.getKind() == IResourceDelta.REMOVED) {
firePropertyChange(GlobalPropertyTester.PROP_HAS_MULTI_PROJECTS);
}
}
}
}
}
}
}
| liuyuanyuan/dbeaver | plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/actions/GlobalPropertyTester.java | Java | apache-2.0 | 3,123 |
<?php
/**
* Razorphyn
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade the extension
* to newer versions in the future.
*
* @copyright Copyright (c) 2013 Razorphyn
*
* Extended Coming Soon Countdown
*
* @author Razorphyn
* @Site http://razorphyn.com/
*/
umask(002);
//REMEBER THE FIRST 0
$folderperm=0755; //Folders Permissions
$fileperm=0644; //Files Permissions
if(!is_dir("session")) {mkdir("session",$folderperm);file_put_contents("session/.htaccess","Deny from All \n IndexIgnore * \n Header set X-Frame-Options SAMEORIGIN \n Header set X-XSS-Protection '1; mode=block' \n Header set X-Content-Type-Options 'nosniff'");}
ini_set("session.auto_start", "0");
ini_set("session.hash_function", "sha512");
ini_set("session.entropy_file", "/dev/urandom");
ini_set("session.entropy_length", "512");
ini_set("session.save_path", "session");
ini_set("session.gc_probability", "1");
ini_set("session.cookie_httponly", "1");
ini_set("session.use_only_cookies", "1");
ini_set("session.use_trans_sid", "0");
session_name("RazorphynExtendedComingsoon");
if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') {
ini_set('session.cookie_secure', '1');
}
session_start();
if(isset($_SESSION["created"]) && $_SESSION["created"]==true) {unset($_SESSION["created"]);header("Location: index.php");}
else{
$dir="../config";
$fileconfig=$dir."/config.txt";
$passfile=$dir."/pass.php";
$socialfile=$dir."/social.txt";
$dirmail= $dir."/mails/";
$filefnmail= $dir."/fnmail.txt";
$filefnmessage= $dir."/fnmessage.txt";
$filefnfooter= $dir."/footermail.txt";
$filelogo= $dir."/logo.txt";
$filefrontmess= $dir."/frontmess.txt";
$filenews= $dir."/news.txt";
$fileindexfoot= $dir."/indexfooter.txt";
$access= $dir."/.htaccess";
if(!is_dir($dir)){
if(mkdir($dir,0700)){
mkdir("../config/scheduled",$folderperm);
file_put_contents("../config/scheduled/.htaccess","Deny from All"."\n"."IndexIgnore * \n Header set X-Frame-Options SAMEORIGIN \n Header set X-XSS-Protection '1; mode=block' \n Header set X-Content-Type-Options 'nosniff'");
if(!is_file($fileconfig))file_put_contents($fileconfig,"");
if(!is_file($socialfile))file_put_contents($socialfile,"");
if(!is_dir($dirmail)){ mkdir($dirmail,$folderperm);file_put_contents($dirmail.".htaccess","Deny from All"."\n"."IndexIgnore * \n Header set X-Frame-Options SAMEORIGIN \n Header set X-XSS-Protection '1; mode=block' \n Header set X-Content-Type-Options 'nosniff'"); };
if(!is_file($filefnmail))file_put_contents($filefnmail,"");
if(!is_file($filefnmessage))file_put_contents($filefnmessage,"");
if(!is_file($filefnfooter))file_put_contents($filefnfooter,"");
if(!is_file($filelogo))file_put_contents($filelogo,"");
if(!is_file($filefrontmess))file_put_contents($filefrontmess,"");
if(!is_file($filenews))file_put_contents($filenews,"");
if(!is_file($fileindexfoot))file_put_contents($fileindexfoot,"");
if(!is_file($passfile))file_put_contents($passfile,'<?php $adminpassword=\''.(hash("whirlpool","admin")).'\'; ?>');
if(!is_file($access))file_put_contents($access,"Deny from All"."\n"."IndexIgnore * \n Header set X-Frame-Options SAMEORIGIN \n Header set X-XSS-Protection '1; mode=block' \n Header set X-Content-Type-Options 'nosniff'");
if(!is_file(".htaccess"))file_put_contents(".htaccess","IndexIgnore * \n Header set X-Frame-Options SAMEORIGIN \n Header set X-XSS-Protection '1; mode=block' \n Header set X-Content-Type-Options 'nosniff'");
chmod($fileconfig, $fileperm);
chmod($socialfile, $fileperm);
chmod($dirmail, $folderperm);
chmod($filefnmail, $fileperm);
chmod($filefnmessage, $fileperm);
chmod($filefnfooter, $fileperm);
chmod($filelogo, $fileperm);
chmod($filefrontmess, $fileperm);
chmod($filenews, $fileperm);
chmod($passfile, $fileperm);
$_SESSION["created"]=true;
}
}
else{
if(!is_dir("../config/scheduled")){
if(mkdir("../config/scheduled",$folderperm))
file_put_contents("../config/scheduled/.htaccess","Deny from All"."\n"."IndexIgnore * \n Header set X-Frame-Options SAMEORIGIN \n Header set X-XSS-Protection '1; mode=block' \n Header set X-Content-Type-Options 'nosniff'");
}
if(!is_file($fileconfig))file_put_contents($fileconfig,"");
if(!is_file($fileindexfoot))file_put_contents($fileindexfoot,"");
if(!is_file($socialfile))file_put_contents($socialfile,"");
if(!is_dir($dirmail)){mkdir($dirmail,folderperm);file_put_contents($dirmail.".htaccess","Deny from All"."\n"."IndexIgnore * \n Header set X-Frame-Options SAMEORIGIN \n Header set X-XSS-Protection '1; mode=block' \n Header set X-Content-Type-Options 'nosniff'"); };
if(!is_file($filefnmail))file_put_contents($filefnmail,"");
if(!is_file($filefnmessage))file_put_contents($filefnmessage,"");
if(!is_file($filefnfooter))file_put_contents($filefnfooter,"");
if(!is_file($filelogo))file_put_contents($filelogo,"");
if(!is_file($filefrontmess))file_put_contents($filefrontmess,"");
if(!is_file($filenews))file_put_contents($filenews,"");
if(!is_file($passfile))file_put_contents($passfile,'<?php $adminpassword=\''.(hash("whirlpool","admin")).'\'; ?>');
if(!is_file($access))file_put_contents($access,"Deny from All"."\n"."IndexIgnore *");
if(!is_file(".htaccess"))file_put_contents(".htaccess","IndexIgnore * \n Header set X-Frame-Options SAMEORIGIN \n Header set X-XSS-Protection '1; mode=block' \n Header set X-Content-Type-Options 'nosniff'");
chmod($fileconfig, $fileperm);
chmod($socialfile, $fileperm);
chmod($dirmail, $folderperm);
chmod($filefnmail, $fileperm);
chmod($filefnmessage, $fileperm);
chmod($filefnfooter, $fileperm);
chmod($filelogo, $fileperm);
chmod($filefrontmess, $fileperm);
chmod($filenews, $fileperm);
chmod($passfile, $fileperm);
$_SESSION["created"]=true;
}
echo "<html><head></head><body><button onclick='javascript:ref();' style='position:relative;display:block;margin:0 auto;top:45%'>Return Back</button><script>function ref(){location.reload(true);}</script></body></html>";
}
?>
| Razorphyn/Extended-Comingsoon-Countdown | admin/datacheck.php | PHP | apache-2.0 | 6,171 |
this is my new learning GitHub class
hello how are you doing
#This class is running in La Ciotat france
#this is github class
# this is test file
Pulling changes
Deepika Padukone talks about Katrina Kaif
Prabhas turned down Rs 10cr ad for Baahubali
Hrithik, Sussanne and Twinkle party together
Week 1: Baahubali 2 (Hindi) collects Rs 245 cr
Deepika wishes to take ‘Padmavati’ to Cannes
Soha on comparisons with Kareena
Milind wants to make a film on Lord Shiva
Pic: Sunny Leone sizzles in a special song
Then and now: Yesteryear actress Mumtaz
Movie review: Guardians of the Galaxy Vol. 2
| yogendra007/test-file | README.md | Markdown | apache-2.0 | 596 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Create a life that you love.">
<title>Are you trying to squeeze more into an already full life? - Quercus Coaching</title>
<link rel="canonical" href="/2016/03/30/blog-march/">
<!-- Bootstrap Core CSS -->
<link rel="stylesheet" href="/css/bootstrap.min.css">
<!-- Custom CSS -->
<link rel="stylesheet" href="/css/clean-blog.css">
<!-- Pygments Github CSS -->
<link rel="stylesheet" href="/css/syntax.css">
<!-- Custom Fonts -->
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href='//fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-default navbar-custom navbar-fixed-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header page-scroll">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Quercus Coaching</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li><a href="/" >Home</a></li>
<li><a href="/about/" >About</a></li>
<li><a href="/contact/" >Contact</a></li>
</ul>
<!-- <li>
<a href="/">Home</a>
</li>
<li>
<a href="/404.html">Page Not Found</a>
</li>
<li>
<a href="/about/">About</a>
</li>
<li>
<a href="/contact/">Contact</a>
</li>
</ul>
--> </div>
<!-- /.navbar-collapse -->
</div>
<!-- /.container -->
</nav>
<!-- Post Header -->
<header class="intro-header" style="background-image: url('/img/banner_photo.png')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="post-heading">
<h1>Are you trying to squeeze more into an already full life?</h1>
<h2 class="subheading">Have you ever noticed that so many things that could improve your life involve adding ... more?</h2>
<span class="meta">Posted by Alison Macduff on March 30, 2016</span>
</div>
</div>
</div>
</div>
</header>
<!-- Post Content -->
<article>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<p><em>Are you trying to squeeze more into an already full life?</em></p>
<p>Have you ever noticed that so many things that could improve your life involve adding … <strong>more?</strong></p>
<p><strong>For example:</strong></p>
<ul>
<li><strong>more</strong> time in the gym/with the kids/meditating/jogging</li>
<li><strong>more</strong> information about getting fit/healthy eating/how to succeed</li>
<li><strong>more</strong> attention to your loved ones/the present moment</li>
<li><strong>more</strong> action around career goals/marketing yourself/searching for The One.</li>
</ul>
<p>However, in my experience, trying to put more into a cup which is already full just results in overflow. In our lives that can feel like overwhelm - resulting in less sleep, poor health, low self esteem, guilt and even shame.</p>
<p>We are led to believe that if we only knew/did/had/were … (fill in the gap yourself) our lives would be perfect, and when we fail and end up feeling worse about ourselves – and less likely to try again.</p>
<p>Part of the job of a coach is to help you empty the cup – review your life to look at what’s working and, in areas of your life which aren’t working, examine what you have been doing and what you have learnt about yourself.</p>
<p>Part of emptying the cup also involves discarding the ‘shoulds’ in your life so that you are left with <u>your</u> core values – the ones that get you up in the morning. These values will be reflected in what you are committed to in life and the strengths that get you through the day.</p>
<p>Coaching can act like a knife to cut away everything that isn’t <u>you</u> or aligned with <u>your</u> values. Clients experience a clarity of vision that can be exhilarating, liberating the energy trapped in previous failed attempts, to be redirected into the strengths that have already got you this far.</p>
<p><u>For example</u>, who wants to lose weight? How many times have you tried and how much energy have you expended on this? However, to ‘lose weight’ covers many different areas- e.g. how healthy you feel, your size, what you eat, your shape.
What would it be like to give up the idea of losing weight? How would it feel to be ok about the weight you are now? Notice how your body responds to that thought.</p>
<p>Instead, what is it <u>specifically</u> that you want?</p>
<ul>
<li>To feel toned/fit into a size smaller?</li>
<li>To feel less out of breath?</li>
<li>To sleep better?</li>
<li>To give up coffee/sugar/alcohol/chocolate/smoking?</li>
<li>To have more energy?</li>
</ul>
<p><u>Choose one area</u> and look at:</p>
<ul>
<li>when you have tried and failed - and what you said about yourself.</li>
<li>what you think you ‘should’ do/be/have in this area.</li>
</ul>
<p>If you gave up all the regrets/blame/sense of failure, what one step could you do today to give you a positive result in this area?</p>
<p>Make it something that you enjoy, something that you are already good at or something that is aligned to a commitment you already have.</p>
<p>We are filled to the brim with knowledge, but knowledge isn’t enough until it works in the service of <u>your</u> values, <u>your</u> strengths and <u>your</u> commitments.
Enjoy!</p>
<hr>
<ul class="pager">
<li class="previous">
<a href="/2016/01/17/coaching-for-carers/" data-toggle="tooltip" data-placement="top" title="Coaching for carers">← Previous Post</a>
</li>
<li class="next">
<a href="/2016/04/28/are_you_sabotaging_yourself/" data-toggle="tooltip" data-placement="top" title="Are you sabotaging yourself?">Next Post →</a>
</li>
</ul>
</div>
</div>
</div>
</article>
<hr>
<!-- Footer -->
<footer>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<ul class="list-inline text-center">
<li>
<a href="/feed.xml">
<span class="fa-stack fa-lg">
<i class="fa fa-square fa-stack-2x"></i>
<i class="fa fa-rss fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
<li>
<a href="https://github.com/akmacduff">
<span class="fa-stack fa-lg">
<i class="fa fa-square fa-stack-2x"></i>
<i class="fa fa-github fa-stack-1x fa-inverse"></i>
</span>
</a>
</li>
</ul>
<p class="copyright text-muted">Copyright © Quercus Coaching 2016. Made using <a href="https://jekyllrb.com/">Jekyll</a> with the <a href="https://github.com/IronSummitMedia/startbootstrap-clean-blog-jekyll">startbootstrap clean blog jekyll theme</a>.</p>
</div>
</div>
</div>
</footer>
<!-- jQuery -->
<script src="/js/jquery.min.js "></script>
<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js "></script>
<!-- Custom Theme JavaScript -->
<script src="/js/clean-blog.min.js "></script>
</body>
</html>
| akmacduff/akmacduff.github.io | _site/2016/03/30/blog-march/index.html | HTML | apache-2.0 | 9,833 |
package bwhatsapp
import (
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"os"
"strings"
qrcodeTerminal "github.com/Baozisoftware/qrcode-terminal-go"
"github.com/Rhymen/go-whatsapp"
)
type ProfilePicInfo struct {
URL string `json:"eurl"`
Tag string `json:"tag"`
Status int16 `json:"status"`
}
func qrFromTerminal(invert bool) chan string {
qr := make(chan string)
go func() {
terminal := qrcodeTerminal.New()
if invert {
terminal = qrcodeTerminal.New2(qrcodeTerminal.ConsoleColors.BrightWhite, qrcodeTerminal.ConsoleColors.BrightBlack, qrcodeTerminal.QRCodeRecoveryLevels.Medium)
}
terminal.Get(<-qr).Print()
}()
return qr
}
func (b *Bwhatsapp) readSession() (whatsapp.Session, error) {
session := whatsapp.Session{}
sessionFile := b.Config.GetString(sessionFile)
if sessionFile == "" {
return session, errors.New("if you won't set SessionFile then you will need to scan QR code on every restart")
}
file, err := os.Open(sessionFile)
if err != nil {
return session, err
}
defer file.Close()
decoder := gob.NewDecoder(file)
return session, decoder.Decode(&session)
}
func (b *Bwhatsapp) writeSession(session whatsapp.Session) error {
sessionFile := b.Config.GetString(sessionFile)
if sessionFile == "" {
// we already sent a warning while starting the bridge, so let's be quiet here
return nil
}
file, err := os.Create(sessionFile)
if err != nil {
return err
}
defer file.Close()
encoder := gob.NewEncoder(file)
return encoder.Encode(session)
}
func (b *Bwhatsapp) restoreSession() (*whatsapp.Session, error) {
session, err := b.readSession()
if err != nil {
b.Log.Warn(err.Error())
}
b.Log.Debugln("Restoring WhatsApp session..")
session, err = b.conn.RestoreWithSession(session)
if err != nil {
// restore session connection timed out (I couldn't get over it without logging in again)
return nil, errors.New("failed to restore session: " + err.Error())
}
b.Log.Debugln("Session restored successfully!")
return &session, nil
}
func (b *Bwhatsapp) getSenderName(senderJid string) string {
if sender, exists := b.users[senderJid]; exists {
if sender.Name != "" {
return sender.Name
}
// if user is not in phone contacts
// it is the most obvious scenario unless you sync your phone contacts with some remote updated source
// users can change it in their WhatsApp settings -> profile -> click on Avatar
if sender.Notify != "" {
return sender.Notify
}
if sender.Short != "" {
return sender.Short
}
}
// try to reload this contact
_, err := b.conn.Contacts()
if err != nil {
b.Log.Errorf("error on update of contacts: %v", err)
}
if contact, exists := b.conn.Store.Contacts[senderJid]; exists {
// Add it to the user map
b.users[senderJid] = contact
if contact.Name != "" {
return contact.Name
}
// if user is not in phone contacts
// same as above
return contact.Notify
}
return ""
}
func (b *Bwhatsapp) getSenderNotify(senderJid string) string {
if sender, exists := b.users[senderJid]; exists {
return sender.Notify
}
return ""
}
func (b *Bwhatsapp) GetProfilePicThumb(jid string) (*ProfilePicInfo, error) {
data, err := b.conn.GetProfilePicThumb(jid)
if err != nil {
return nil, fmt.Errorf("failed to get avatar: %v", err)
}
content := <-data
info := &ProfilePicInfo{}
err = json.Unmarshal([]byte(content), info)
if err != nil {
return info, fmt.Errorf("failed to unmarshal avatar info: %v", err)
}
return info, nil
}
func isGroupJid(identifier string) bool {
return strings.HasSuffix(identifier, "@g.us") ||
strings.HasSuffix(identifier, "@temp") ||
strings.HasSuffix(identifier, "@broadcast")
}
| 42wim/matterbridge | bridge/whatsapp/helpers.go | GO | apache-2.0 | 3,689 |
'use strict';
var consoleBaseUrl = window.location.href;
consoleBaseUrl = consoleBaseUrl.substring(0, consoleBaseUrl.indexOf("/console"));
consoleBaseUrl = consoleBaseUrl + "/console";
var configUrl = consoleBaseUrl + "/config";
var auth = {};
var resourceBundle;
var locale = 'en';
var module = angular.module('keycloak', [ 'keycloak.services', 'keycloak.loaders', 'ui.bootstrap', 'ui.select2', 'angularFileUpload', 'angularTreeview', 'pascalprecht.translate', 'ngCookies', 'ngSanitize', 'ui.ace']);
var resourceRequests = 0;
var loadingTimer = -1;
angular.element(document).ready(function () {
var keycloakAuth = new Keycloak(configUrl);
function whoAmI(success, error) {
var req = new XMLHttpRequest();
req.open('GET', consoleBaseUrl + "/whoami", true);
req.setRequestHeader('Accept', 'application/json');
req.setRequestHeader('Authorization', 'bearer ' + keycloakAuth.token);
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
var data = JSON.parse(req.responseText);
success(data);
} else {
error();
}
}
}
req.send();
}
function loadResourceBundle(success, error) {
var req = new XMLHttpRequest();
req.open('GET', consoleBaseUrl + '/messages.json?lang=' + locale, true);
req.setRequestHeader('Accept', 'application/json');
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
var data = JSON.parse(req.responseText);
success && success(data);
} else {
error && error();
}
}
}
req.send();
}
function hasAnyAccess(user) {
return user && user['realm_access'];
}
keycloakAuth.onAuthLogout = function() {
location.reload();
}
keycloakAuth.init({ onLoad: 'login-required' }).success(function () {
auth.authz = keycloakAuth;
if (auth.authz.idTokenParsed.locale) {
locale = auth.authz.idTokenParsed.locale;
}
auth.refreshPermissions = function(success, error) {
whoAmI(function(data) {
auth.user = data;
auth.loggedIn = true;
auth.hasAnyAccess = hasAnyAccess(data);
success();
}, function() {
error();
});
};
loadResourceBundle(function(data) {
resourceBundle = data;
auth.refreshPermissions(function () {
module.factory('Auth', function () {
return auth;
});
var injector = angular.bootstrap(document, ["keycloak"]);
injector.get('$translate')('consoleTitle').then(function (consoleTitle) {
document.title = consoleTitle;
});
});
});
}).error(function () {
window.location.reload();
});
});
module.factory('authInterceptor', function($q, Auth) {
return {
request: function (config) {
if (!config.url.match(/.html$/)) {
var deferred = $q.defer();
if (Auth.authz.token) {
Auth.authz.updateToken(5).success(function () {
config.headers = config.headers || {};
config.headers.Authorization = 'Bearer ' + Auth.authz.token;
deferred.resolve(config);
}).error(function () {
location.reload();
});
}
return deferred.promise;
} else {
return config;
}
}
};
});
module.config(['$translateProvider', function($translateProvider) {
$translateProvider.useSanitizeValueStrategy('sanitizeParameters');
$translateProvider.preferredLanguage(locale);
$translateProvider.translations(locale, resourceBundle);
}]);
module.config([ '$routeProvider', function($routeProvider) {
$routeProvider
.when('/create/realm', {
templateUrl : resourceUrl + '/partials/realm-create.html',
resolve : {
},
controller : 'RealmCreateCtrl'
})
.when('/realms/:realm', {
templateUrl : resourceUrl + '/partials/realm-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmDetailCtrl'
})
.when('/realms/:realm/login-settings', {
templateUrl : resourceUrl + '/partials/realm-login-settings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfo) {
return ServerInfo.delay;
}
},
controller : 'RealmLoginSettingsCtrl'
})
.when('/realms/:realm/theme-settings', {
templateUrl : resourceUrl + '/partials/realm-theme-settings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmThemeCtrl'
})
.when('/realms/:realm/cache-settings', {
templateUrl : resourceUrl + '/partials/realm-cache-settings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmCacheCtrl'
})
.when('/realms', {
templateUrl : resourceUrl + '/partials/realm-list.html',
controller : 'RealmListCtrl'
})
.when('/realms/:realm/token-settings', {
templateUrl : resourceUrl + '/partials/realm-tokens.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmTokenDetailCtrl'
})
.when('/realms/:realm/client-initial-access', {
templateUrl : resourceUrl + '/partials/client-initial-access.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clientInitialAccess : function(ClientInitialAccessLoader) {
return ClientInitialAccessLoader();
},
clientRegTrustedHosts : function(ClientRegistrationTrustedHostListLoader) {
return ClientRegistrationTrustedHostListLoader();
}
},
controller : 'ClientInitialAccessCtrl'
})
.when('/realms/:realm/client-initial-access/create', {
templateUrl : resourceUrl + '/partials/client-initial-access-create.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'ClientInitialAccessCreateCtrl'
})
.when('/realms/:realm/client-reg-trusted-hosts/create', {
templateUrl : resourceUrl + '/partials/client-reg-trusted-host-create.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clientRegTrustedHost : function() {
return {};
}
},
controller : 'ClientRegistrationTrustedHostDetailCtrl'
})
.when('/realms/:realm/client-reg-trusted-hosts/:hostname', {
templateUrl : resourceUrl + '/partials/client-reg-trusted-host-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clientRegTrustedHost : function(ClientRegistrationTrustedHostLoader) {
return ClientRegistrationTrustedHostLoader();
}
},
controller : 'ClientRegistrationTrustedHostDetailCtrl'
})
.when('/realms/:realm/keys-settings', {
templateUrl : resourceUrl + '/partials/realm-keys.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmKeysDetailCtrl'
})
.when('/realms/:realm/identity-provider-settings', {
templateUrl : resourceUrl + '/partials/realm-identity-provider.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
instance : function(IdentityProviderLoader) {
return {};
},
providerFactory : function(IdentityProviderFactoryLoader) {
return {};
},
authFlows : function(AuthenticationFlowsLoader) {
return {};
}
},
controller : 'RealmIdentityProviderCtrl'
})
.when('/create/identity-provider/:realm/:provider_id', {
templateUrl : function(params){ return resourceUrl + '/partials/realm-identity-provider-' + params.provider_id + '.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
instance : function(IdentityProviderLoader) {
return {};
},
providerFactory : function(IdentityProviderFactoryLoader) {
return new IdentityProviderFactoryLoader();
},
authFlows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
}
},
controller : 'RealmIdentityProviderCtrl'
})
.when('/realms/:realm/identity-provider-settings/provider/:provider_id/:alias', {
templateUrl : function(params){ return resourceUrl + '/partials/realm-identity-provider-' + params.provider_id + '.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
instance : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
providerFactory : function(IdentityProviderFactoryLoader) {
return IdentityProviderFactoryLoader();
},
authFlows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
}
},
controller : 'RealmIdentityProviderCtrl'
})
.when('/realms/:realm/identity-provider-settings/provider/:provider_id/:alias/export', {
templateUrl : resourceUrl + '/partials/realm-identity-provider-export.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
identityProvider : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
providerFactory : function(IdentityProviderFactoryLoader) {
return IdentityProviderFactoryLoader();
}
},
controller : 'RealmIdentityProviderExportCtrl'
})
.when('/realms/:realm/identity-provider-mappers/:alias/mappers', {
templateUrl : function(params){ return resourceUrl + '/partials/identity-provider-mappers.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
identityProvider : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
mapperTypes : function(IdentityProviderMapperTypesLoader) {
return IdentityProviderMapperTypesLoader();
},
mappers : function(IdentityProviderMappersLoader) {
return IdentityProviderMappersLoader();
}
},
controller : 'IdentityProviderMapperListCtrl'
})
.when('/realms/:realm/identity-provider-mappers/:alias/mappers/:mapperId', {
templateUrl : function(params){ return resourceUrl + '/partials/identity-provider-mapper-detail.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
identityProvider : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
mapperTypes : function(IdentityProviderMapperTypesLoader) {
return IdentityProviderMapperTypesLoader();
},
mapper : function(IdentityProviderMapperLoader) {
return IdentityProviderMapperLoader();
}
},
controller : 'IdentityProviderMapperCtrl'
})
.when('/create/identity-provider-mappers/:realm/:alias', {
templateUrl : function(params){ return resourceUrl + '/partials/identity-provider-mapper-detail.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
identityProvider : function(IdentityProviderLoader) {
return IdentityProviderLoader();
},
mapperTypes : function(IdentityProviderMapperTypesLoader) {
return IdentityProviderMapperTypesLoader();
}
},
controller : 'IdentityProviderMapperCreateCtrl'
})
.when('/realms/:realm/default-roles', {
templateUrl : resourceUrl + '/partials/realm-default-roles.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
roles : function(RoleListLoader) {
return RoleListLoader();
}
},
controller : 'RealmDefaultRolesCtrl'
})
.when('/realms/:realm/smtp-settings', {
templateUrl : resourceUrl + '/partials/realm-smtp.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmSMTPSettingsCtrl'
})
.when('/realms/:realm/events', {
templateUrl : resourceUrl + '/partials/realm-events.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmEventsCtrl'
})
.when('/realms/:realm/admin-events', {
templateUrl : resourceUrl + '/partials/realm-events-admin.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmAdminEventsCtrl'
})
.when('/realms/:realm/events-settings', {
templateUrl : resourceUrl + '/partials/realm-events-config.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
eventsConfig : function(RealmEventsConfigLoader) {
return RealmEventsConfigLoader();
}
},
controller : 'RealmEventsConfigCtrl'
})
.when('/realms/:realm/partial-import', {
templateUrl : resourceUrl + '/partials/partial-import.html',
resolve : {
resourceName : function() { return 'users'},
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmImportCtrl'
})
.when('/create/user/:realm', {
templateUrl : resourceUrl + '/partials/user-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function() {
return {};
}
},
controller : 'UserDetailCtrl'
})
.when('/realms/:realm/users/:user', {
templateUrl : resourceUrl + '/partials/user-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
}
},
controller : 'UserDetailCtrl'
})
.when('/realms/:realm/users/:user/user-attributes', {
templateUrl : resourceUrl + '/partials/user-attributes.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
}
},
controller : 'UserDetailCtrl'
})
.when('/realms/:realm/users/:user/user-credentials', {
templateUrl : resourceUrl + '/partials/user-credentials.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
}
},
controller : 'UserCredentialsCtrl'
})
.when('/realms/:realm/users/:user/role-mappings', {
templateUrl : resourceUrl + '/partials/role-mappings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function() {
return {};
}
},
controller : 'UserRoleMappingCtrl'
})
.when('/realms/:realm/users/:user/groups', {
templateUrl : resourceUrl + '/partials/user-group-membership.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
groups : function(GroupListLoader) {
return GroupListLoader();
}
},
controller : 'UserGroupMembershipCtrl'
})
.when('/realms/:realm/users/:user/sessions', {
templateUrl : resourceUrl + '/partials/user-sessions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
sessions : function(UserSessionsLoader) {
return UserSessionsLoader();
}
},
controller : 'UserSessionsCtrl'
})
.when('/realms/:realm/users/:user/federated-identity', {
templateUrl : resourceUrl + '/partials/user-federated-identity-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
federatedIdentities : function(UserFederatedIdentityLoader) {
return UserFederatedIdentityLoader();
}
},
controller : 'UserFederatedIdentityCtrl'
})
.when('/create/federated-identity/:realm/:user', {
templateUrl : resourceUrl + '/partials/user-federated-identity-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
federatedIdentities : function(UserFederatedIdentityLoader) {
return UserFederatedIdentityLoader();
}
},
controller : 'UserFederatedIdentityAddCtrl'
})
.when('/realms/:realm/users/:user/consents', {
templateUrl : resourceUrl + '/partials/user-consents.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
userConsents : function(UserConsentsLoader) {
return UserConsentsLoader();
}
},
controller : 'UserConsentsCtrl'
})
.when('/realms/:realm/users/:user/offline-sessions/:client', {
templateUrl : resourceUrl + '/partials/user-offline-sessions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(UserLoader) {
return UserLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
offlineSessions : function(UserOfflineSessionsLoader) {
return UserOfflineSessionsLoader();
}
},
controller : 'UserOfflineSessionsCtrl'
})
.when('/realms/:realm/users', {
templateUrl : resourceUrl + '/partials/user-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'UserListCtrl'
})
.when('/create/role/:realm', {
templateUrl : resourceUrl + '/partials/role-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
role : function() {
return {};
},
roles : function(RoleListLoader) {
return RoleListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'RoleDetailCtrl'
})
.when('/realms/:realm/roles/:role', {
templateUrl : resourceUrl + '/partials/role-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
role : function(RoleLoader) {
return RoleLoader();
},
roles : function(RoleListLoader) {
return RoleListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'RoleDetailCtrl'
})
.when('/realms/:realm/roles', {
templateUrl : resourceUrl + '/partials/role-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
roles : function(RoleListLoader) {
return RoleListLoader();
}
},
controller : 'RoleListCtrl'
})
.when('/realms/:realm/groups', {
templateUrl : resourceUrl + '/partials/group-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
groups : function(GroupListLoader) {
return GroupListLoader();
}
},
controller : 'GroupListCtrl'
})
.when('/create/group/:realm/parent/:parentId', {
templateUrl : resourceUrl + '/partials/create-group.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
parentId : function($route) {
return $route.current.params.parentId;
}
},
controller : 'GroupCreateCtrl'
})
.when('/realms/:realm/groups/:group', {
templateUrl : resourceUrl + '/partials/group-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
group : function(GroupLoader) {
return GroupLoader();
}
},
controller : 'GroupDetailCtrl'
})
.when('/realms/:realm/groups/:group/attributes', {
templateUrl : resourceUrl + '/partials/group-attributes.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
group : function(GroupLoader) {
return GroupLoader();
}
},
controller : 'GroupDetailCtrl'
})
.when('/realms/:realm/groups/:group/members', {
templateUrl : resourceUrl + '/partials/group-members.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
group : function(GroupLoader) {
return GroupLoader();
}
},
controller : 'GroupMembersCtrl'
})
.when('/realms/:realm/groups/:group/role-mappings', {
templateUrl : resourceUrl + '/partials/group-role-mappings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
group : function(GroupLoader) {
return GroupLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function() {
return {};
}
},
controller : 'GroupRoleMappingCtrl'
})
.when('/realms/:realm/default-groups', {
templateUrl : resourceUrl + '/partials/default-groups.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
groups : function(GroupListLoader) {
return GroupListLoader();
}
},
controller : 'DefaultGroupsCtrl'
})
.when('/create/role/:realm/clients/:client', {
templateUrl : resourceUrl + '/partials/client-role-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
role : function() {
return {};
},
roles : function(RoleListLoader) {
return RoleListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'ClientRoleDetailCtrl'
})
.when('/realms/:realm/clients/:client/roles/:role', {
templateUrl : resourceUrl + '/partials/client-role-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
role : function(ClientRoleLoader) {
return ClientRoleLoader();
},
roles : function(RoleListLoader) {
return RoleListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'ClientRoleDetailCtrl'
})
.when('/realms/:realm/clients/:client/mappers', {
templateUrl : resourceUrl + '/partials/client-mappers.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientProtocolMapperListCtrl'
})
.when('/realms/:realm/clients/:client/add-mappers', {
templateUrl : resourceUrl + '/partials/client-mappers-add.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'AddBuiltinProtocolMapperCtrl'
})
.when('/realms/:realm/clients/:client/mappers/:id', {
templateUrl : resourceUrl + '/partials/client-protocol-mapper-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
mapper : function(ClientProtocolMapperLoader) {
return ClientProtocolMapperLoader();
}
},
controller : 'ClientProtocolMapperCtrl'
})
.when('/create/client/:realm/:client/mappers', {
templateUrl : resourceUrl + '/partials/client-protocol-mapper-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientProtocolMapperCreateCtrl'
})
.when('/realms/:realm/client-templates/:template/mappers', {
templateUrl : resourceUrl + '/partials/client-template-mappers.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateProtocolMapperListCtrl'
})
.when('/realms/:realm/client-templates/:template/add-mappers', {
templateUrl : resourceUrl + '/partials/client-template-mappers-add.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateAddBuiltinProtocolMapperCtrl'
})
.when('/realms/:realm/client-templates/:template/mappers/:id', {
templateUrl : resourceUrl + '/partials/client-template-protocol-mapper-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
mapper : function(ClientTemplateProtocolMapperLoader) {
return ClientTemplateProtocolMapperLoader();
}
},
controller : 'ClientTemplateProtocolMapperCtrl'
})
.when('/create/client-template/:realm/:template/mappers', {
templateUrl : resourceUrl + '/partials/client-template-protocol-mapper-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
}
},
controller : 'ClientTemplateProtocolMapperCreateCtrl'
})
.when('/realms/:realm/clients/:client/sessions', {
templateUrl : resourceUrl + '/partials/client-sessions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
sessionCount : function(ClientSessionCountLoader) {
return ClientSessionCountLoader();
}
},
controller : 'ClientSessionsCtrl'
})
.when('/realms/:realm/clients/:client/offline-access', {
templateUrl : resourceUrl + '/partials/client-offline-sessions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
offlineSessionCount : function(ClientOfflineSessionCountLoader) {
return ClientOfflineSessionCountLoader();
}
},
controller : 'ClientOfflineSessionsCtrl'
})
.when('/realms/:realm/clients/:client/credentials', {
templateUrl : resourceUrl + '/partials/client-credentials.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
clientAuthenticatorProviders : function(ClientAuthenticatorProvidersLoader) {
return ClientAuthenticatorProvidersLoader();
},
clientConfigProperties: function(PerClientAuthenticationConfigDescriptionLoader) {
return PerClientAuthenticationConfigDescriptionLoader();
}
},
controller : 'ClientCredentialsCtrl'
})
.when('/realms/:realm/clients/:client/credentials/client-jwt/:keyType/import/:attribute', {
templateUrl : resourceUrl + '/partials/client-credentials-jwt-key-import.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
callingContext : function() {
return "jwt-credentials";
}
},
controller : 'ClientCertificateImportCtrl'
})
.when('/realms/:realm/clients/:client/credentials/client-jwt/:keyType/export/:attribute', {
templateUrl : resourceUrl + '/partials/client-credentials-jwt-key-export.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
callingContext : function() {
return "jwt-credentials";
}
},
controller : 'ClientCertificateExportCtrl'
})
.when('/realms/:realm/clients/:client/identity-provider', {
templateUrl : resourceUrl + '/partials/client-identity-provider.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientIdentityProviderCtrl'
})
.when('/realms/:realm/clients/:client/clustering', {
templateUrl : resourceUrl + '/partials/client-clustering.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientClusteringCtrl'
})
.when('/register-node/realms/:realm/clients/:client/clustering', {
templateUrl : resourceUrl + '/partials/client-clustering-node.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientClusteringNodeCtrl'
})
.when('/realms/:realm/clients/:client/clustering/:node', {
templateUrl : resourceUrl + '/partials/client-clustering-node.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientClusteringNodeCtrl'
})
.when('/realms/:realm/clients/:client/saml/keys', {
templateUrl : resourceUrl + '/partials/client-saml-keys.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientSamlKeyCtrl'
})
.when('/realms/:realm/clients/:client/saml/:keyType/import/:attribute', {
templateUrl : resourceUrl + '/partials/client-saml-key-import.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
callingContext : function() {
return "saml";
}
},
controller : 'ClientCertificateImportCtrl'
})
.when('/realms/:realm/clients/:client/saml/:keyType/export/:attribute', {
templateUrl : resourceUrl + '/partials/client-saml-key-export.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
callingContext : function() {
return "saml";
}
},
controller : 'ClientCertificateExportCtrl'
})
.when('/realms/:realm/clients/:client/roles', {
templateUrl : resourceUrl + '/partials/client-role-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
roles : function(ClientRoleListLoader) {
return ClientRoleListLoader();
}
},
controller : 'ClientRoleListCtrl'
})
.when('/realms/:realm/clients/:client/revocation', {
templateUrl : resourceUrl + '/partials/client-revocation.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'ClientRevocationCtrl'
})
.when('/realms/:realm/clients/:client/scope-mappings', {
templateUrl : resourceUrl + '/partials/client-scope-mappings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'ClientScopeMappingCtrl'
})
.when('/realms/:realm/clients/:client/installation', {
templateUrl : resourceUrl + '/partials/client-installation.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientInstallationCtrl'
})
.when('/realms/:realm/clients/:client/service-account-roles', {
templateUrl : resourceUrl + '/partials/client-service-account-roles.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
user : function(ClientServiceAccountUserLoader) {
return ClientServiceAccountUserLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function(ClientLoader) {
return ClientLoader();
}
},
controller : 'UserRoleMappingCtrl'
})
.when('/create/client/:realm', {
templateUrl : resourceUrl + '/partials/create-client.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function() {
return {};
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'CreateClientCtrl'
})
.when('/realms/:realm/clients/:client', {
templateUrl : resourceUrl + '/partials/client-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
client : function(ClientLoader) {
return ClientLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientDetailCtrl'
})
.when('/create/client-template/:realm', {
templateUrl : resourceUrl + '/partials/client-template-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
template : function() {
return {};
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateDetailCtrl'
})
.when('/realms/:realm/client-templates/:template', {
templateUrl : resourceUrl + '/partials/client-template-detail.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateDetailCtrl'
})
.when('/realms/:realm/client-templates/:template/scope-mappings', {
templateUrl : resourceUrl + '/partials/client-template-scope-mappings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
template : function(ClientTemplateLoader) {
return ClientTemplateLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'ClientTemplateScopeMappingCtrl'
})
.when('/realms/:realm/clients', {
templateUrl : resourceUrl + '/partials/client-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientListCtrl'
})
.when('/realms/:realm/client-templates', {
templateUrl : resourceUrl + '/partials/client-template-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
templates : function(ClientTemplateListLoader) {
return ClientTemplateListLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientTemplateListCtrl'
})
.when('/import/client/:realm', {
templateUrl : resourceUrl + '/partials/client-import.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ClientImportCtrl'
})
.when('/', {
templateUrl : resourceUrl + '/partials/home.html',
controller : 'HomeCtrl'
})
.when('/mocks/:realm', {
templateUrl : resourceUrl + '/partials/realm-detail_mock.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmDetailCtrl'
})
.when('/realms/:realm/sessions/revocation', {
templateUrl : resourceUrl + '/partials/session-revocation.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmRevocationCtrl'
})
.when('/realms/:realm/sessions/realm', {
templateUrl : resourceUrl + '/partials/session-realm.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
stats : function(RealmClientSessionStatsLoader) {
return RealmClientSessionStatsLoader();
}
},
controller : 'RealmSessionStatsCtrl'
})
.when('/create/user-storage/:realm/providers/:provider', {
templateUrl : resourceUrl + '/partials/user-storage-generic.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function() {
return {
};
},
providerId : function($route) {
return $route.current.params.provider;
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'GenericUserStorageCtrl'
})
.when('/realms/:realm/user-storage/providers/:provider/:componentId', {
templateUrl : resourceUrl + '/partials/user-storage-generic.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function(ComponentLoader) {
return ComponentLoader();
},
providerId : function($route) {
return $route.current.params.provider;
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'GenericUserStorageCtrl'
})
.when('/realms/:realm/user-federation', {
templateUrl : resourceUrl + '/partials/user-federation.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'UserFederationCtrl'
})
.when('/realms/:realm/user-federation/providers/ldap/:instance', {
templateUrl : resourceUrl + '/partials/federated-ldap.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
}
},
controller : 'LDAPCtrl'
})
.when('/create/user-federation/:realm/providers/ldap', {
templateUrl : resourceUrl + '/partials/federated-ldap.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function() {
return {};
}
},
controller : 'LDAPCtrl'
})
.when('/realms/:realm/user-federation/providers/kerberos/:instance', {
templateUrl : resourceUrl + '/partials/federated-kerberos.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
providerFactory : function() {
return { id: "kerberos" };
}
},
controller : 'GenericUserFederationCtrl'
})
.when('/create/user-federation/:realm/providers/kerberos', {
templateUrl : resourceUrl + '/partials/federated-kerberos.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function() {
return {};
},
providerFactory : function() {
return { id: "kerberos" };
}
},
controller : 'GenericUserFederationCtrl'
})
.when('/create/user-federation/:realm/providers/:provider', {
templateUrl : resourceUrl + '/partials/federated-generic.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function() {
return {
};
},
providerFactory : function(UserFederationFactoryLoader) {
return UserFederationFactoryLoader();
}
},
controller : 'GenericUserFederationCtrl'
})
.when('/realms/:realm/user-federation/providers/:provider/:instance', {
templateUrl : resourceUrl + '/partials/federated-generic.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
instance : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
providerFactory : function(UserFederationFactoryLoader) {
return UserFederationFactoryLoader();
}
},
controller : 'GenericUserFederationCtrl'
})
.when('/realms/:realm/user-federation/providers/:provider/:instance/mappers', {
templateUrl : function(params){ return resourceUrl + '/partials/federated-mappers.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
provider : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
mapperTypes : function(UserFederationMapperTypesLoader) {
return UserFederationMapperTypesLoader();
},
mappers : function(UserFederationMappersLoader) {
return UserFederationMappersLoader();
}
},
controller : 'UserFederationMapperListCtrl'
})
.when('/realms/:realm/user-federation/providers/:provider/:instance/mappers/:mapperId', {
templateUrl : function(params){ return resourceUrl + '/partials/federated-mapper-detail.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
provider : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
mapperTypes : function(UserFederationMapperTypesLoader) {
return UserFederationMapperTypesLoader();
},
mapper : function(UserFederationMapperLoader) {
return UserFederationMapperLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'UserFederationMapperCtrl'
})
.when('/create/user-federation-mappers/:realm/:provider/:instance', {
templateUrl : function(params){ return resourceUrl + '/partials/federated-mapper-detail.html'; },
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
provider : function(UserFederationInstanceLoader) {
return UserFederationInstanceLoader();
},
mapperTypes : function(UserFederationMapperTypesLoader) {
return UserFederationMapperTypesLoader();
},
clients : function(ClientListLoader) {
return ClientListLoader();
}
},
controller : 'UserFederationMapperCreateCtrl'
})
.when('/realms/:realm/defense/headers', {
templateUrl : resourceUrl + '/partials/defense-headers.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'DefenseHeadersCtrl'
})
.when('/realms/:realm/defense/brute-force', {
templateUrl : resourceUrl + '/partials/brute-force.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'RealmBruteForceCtrl'
})
.when('/realms/:realm/protocols', {
templateUrl : resourceUrl + '/partials/protocol-list.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ProtocolListCtrl'
})
.when('/realms/:realm/authentication/flows', {
templateUrl : resourceUrl + '/partials/authentication-flows.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
},
selectedFlow : function() {
return null;
}
},
controller : 'AuthenticationFlowsCtrl'
})
.when('/realms/:realm/authentication/flow-bindings', {
templateUrl : resourceUrl + '/partials/authentication-flow-bindings.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
},
serverInfo : function(ServerInfo) {
return ServerInfo.delay;
}
},
controller : 'RealmFlowBindingCtrl'
})
.when('/realms/:realm/authentication/flows/:flow', {
templateUrl : resourceUrl + '/partials/authentication-flows.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flows : function(AuthenticationFlowsLoader) {
return AuthenticationFlowsLoader();
},
selectedFlow : function($route) {
return $route.current.params.flow;
}
},
controller : 'AuthenticationFlowsCtrl'
})
.when('/realms/:realm/authentication/flows/:flow/create/execution/:topFlow', {
templateUrl : resourceUrl + '/partials/create-execution.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
topFlow: function($route) {
return $route.current.params.topFlow;
},
parentFlow : function(AuthenticationFlowLoader) {
return AuthenticationFlowLoader();
},
formActionProviders : function(AuthenticationFormActionProvidersLoader) {
return AuthenticationFormActionProvidersLoader();
},
authenticatorProviders : function(AuthenticatorProvidersLoader) {
return AuthenticatorProvidersLoader();
},
clientAuthenticatorProviders : function(ClientAuthenticatorProvidersLoader) {
return ClientAuthenticatorProvidersLoader();
}
},
controller : 'CreateExecutionCtrl'
})
.when('/realms/:realm/authentication/flows/:flow/create/flow/execution/:topFlow', {
templateUrl : resourceUrl + '/partials/create-flow-execution.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
topFlow: function($route) {
return $route.current.params.topFlow;
},
parentFlow : function(AuthenticationFlowLoader) {
return AuthenticationFlowLoader();
},
formProviders : function(AuthenticationFormProvidersLoader) {
return AuthenticationFormProvidersLoader();
}
},
controller : 'CreateExecutionFlowCtrl'
})
.when('/realms/:realm/authentication/create/flow', {
templateUrl : resourceUrl + '/partials/create-flow.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
}
},
controller : 'CreateFlowCtrl'
})
.when('/realms/:realm/authentication/required-actions', {
templateUrl : resourceUrl + '/partials/required-actions.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
unregisteredRequiredActions : function(UnregisteredRequiredActionsListLoader) {
return UnregisteredRequiredActionsListLoader();
}
},
controller : 'RequiredActionsCtrl'
})
.when('/realms/:realm/authentication/password-policy', {
templateUrl : resourceUrl + '/partials/password-policy.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'RealmPasswordPolicyCtrl'
})
.when('/realms/:realm/authentication/otp-policy', {
templateUrl : resourceUrl + '/partials/otp-policy.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
serverInfo : function(ServerInfo) {
return ServerInfo.delay;
}
},
controller : 'RealmOtpPolicyCtrl'
})
.when('/realms/:realm/authentication/flows/:flow/config/:provider/:config', {
templateUrl : resourceUrl + '/partials/authenticator-config.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flow : function(AuthenticationFlowLoader) {
return AuthenticationFlowLoader();
},
configType : function(AuthenticationConfigDescriptionLoader) {
return AuthenticationConfigDescriptionLoader();
},
config : function(AuthenticationConfigLoader) {
return AuthenticationConfigLoader();
}
},
controller : 'AuthenticationConfigCtrl'
})
.when('/create/authentication/:realm/flows/:flow/execution/:executionId/provider/:provider', {
templateUrl : resourceUrl + '/partials/authenticator-config.html',
resolve : {
realm : function(RealmLoader) {
return RealmLoader();
},
flow : function(AuthenticationFlowLoader) {
return AuthenticationFlowLoader();
},
configType : function(AuthenticationConfigDescriptionLoader) {
return AuthenticationConfigDescriptionLoader();
},
execution : function(ExecutionIdLoader) {
return ExecutionIdLoader();
}
},
controller : 'AuthenticationConfigCreateCtrl'
})
.when('/server-info', {
templateUrl : resourceUrl + '/partials/server-info.html',
resolve : {
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ServerInfoCtrl'
})
.when('/server-info/providers', {
templateUrl : resourceUrl + '/partials/server-info-providers.html',
resolve : {
serverInfo : function(ServerInfoLoader) {
return ServerInfoLoader();
}
},
controller : 'ServerInfoCtrl'
})
.when('/logout', {
templateUrl : resourceUrl + '/partials/home.html',
controller : 'LogoutCtrl'
})
.when('/notfound', {
templateUrl : resourceUrl + '/partials/notfound.html'
})
.when('/forbidden', {
templateUrl : resourceUrl + '/partials/forbidden.html'
})
.otherwise({
templateUrl : resourceUrl + '/partials/pagenotfound.html'
});
} ]);
module.config(function($httpProvider) {
$httpProvider.interceptors.push('errorInterceptor');
var spinnerFunction = function(data, headersGetter) {
if (resourceRequests == 0) {
loadingTimer = window.setTimeout(function() {
$('#loading').show();
loadingTimer = -1;
}, 500);
}
resourceRequests++;
return data;
};
$httpProvider.defaults.transformRequest.push(spinnerFunction);
$httpProvider.interceptors.push('spinnerInterceptor');
$httpProvider.interceptors.push('authInterceptor');
});
module.factory('spinnerInterceptor', function($q, $window, $rootScope, $location) {
return {
response: function(response) {
resourceRequests--;
if (resourceRequests == 0) {
if(loadingTimer != -1) {
window.clearTimeout(loadingTimer);
loadingTimer = -1;
}
$('#loading').hide();
}
return response;
},
responseError: function(response) {
resourceRequests--;
if (resourceRequests == 0) {
if(loadingTimer != -1) {
window.clearTimeout(loadingTimer);
loadingTimer = -1;
}
$('#loading').hide();
}
return $q.reject(response);
}
};
});
module.factory('errorInterceptor', function($q, $window, $rootScope, $location, Notifications, Auth) {
return {
response: function(response) {
return response;
},
responseError: function(response) {
if (response.status == 401) {
Auth.authz.logout();
} else if (response.status == 403) {
$location.path('/forbidden');
} else if (response.status == 404) {
$location.path('/notfound');
} else if (response.status) {
if (response.data && response.data.errorMessage) {
Notifications.error(response.data.errorMessage);
} else {
Notifications.error("An unexpected server error has occurred");
}
}
return $q.reject(response);
}
};
});
// collapsable form fieldsets
module.directive('collapsable', function() {
return function(scope, element, attrs) {
element.click(function() {
$(this).toggleClass('collapsed');
$(this).find('.toggle-icons').toggleClass('kc-icon-collapse').toggleClass('kc-icon-expand');
$(this).find('.toggle-icons').text($(this).text() == "Icon: expand" ? "Icon: collapse" : "Icon: expand");
$(this).parent().find('.form-group').toggleClass('hidden');
});
}
});
// collapsable form fieldsets
module.directive('uncollapsed', function() {
return function(scope, element, attrs) {
element.prepend('<i class="toggle-class fa fa-angle-down"></i> ');
element.click(function() {
$(this).find('.toggle-class').toggleClass('fa-angle-down').toggleClass('fa-angle-right');
$(this).parent().find('.form-group').toggleClass('hidden');
});
}
});
// collapsable form fieldsets
module.directive('collapsed', function() {
return function(scope, element, attrs) {
element.prepend('<i class="toggle-class fa fa-angle-right"></i> ');
element.parent().find('.form-group').toggleClass('hidden');
element.click(function() {
$(this).find('.toggle-class').toggleClass('fa-angle-down').toggleClass('fa-angle-right');
$(this).parent().find('.form-group').toggleClass('hidden');
});
}
});
/**
* Directive for presenting an ON-OFF switch for checkbox.
* Usage: <input ng-model="mmm" name="nnn" id="iii" onoffswitch [on-text="ooo" off-text="fff"] />
*/
module.directive('onoffswitch', function() {
return {
restrict: "EA",
replace: true,
scope: {
name: '@',
id: '@',
ngModel: '=',
ngDisabled: '=',
kcOnText: '@onText',
kcOffText: '@offText'
},
// TODO - The same code acts differently when put into the templateURL. Find why and move the code there.
//templateUrl: "templates/kc-switch.html",
template: "<span><div class='onoffswitch' tabindex='0'><input type='checkbox' ng-model='ngModel' ng-disabled='ngDisabled' class='onoffswitch-checkbox' name='{{name}}' id='{{id}}'><label for='{{id}}' class='onoffswitch-label'><span class='onoffswitch-inner'><span class='onoffswitch-active'>{{kcOnText}}</span><span class='onoffswitch-inactive'>{{kcOffText}}</span></span><span class='onoffswitch-switch'></span></label></div></span>",
compile: function(element, attrs) {
/*
We don't want to propagate basic attributes to the root element of directive. Id should be passed to the
input element only to achieve proper label binding (and validity).
*/
element.removeAttr('name');
element.removeAttr('id');
if (!attrs.onText) { attrs.onText = "ON"; }
if (!attrs.offText) { attrs.offText = "OFF"; }
element.bind('keydown', function(e){
var code = e.keyCode || e.which;
if (code === 32 || code === 13) {
e.stopImmediatePropagation();
e.preventDefault();
$(e.target).find('input').click();
}
});
}
}
});
/**
* Directive for presenting an ON-OFF switch for checkbox. The directive expects the value to be string 'true' or 'false', not boolean true/false
* This directive provides some additional capabilities to the default onoffswitch such as:
*
* - Dynamic values for id and name attributes. Useful if you need to use this directive inside a ng-repeat
* - Specific scope to specify the value. Instead of just true or false.
*
* Usage: <input ng-model="mmm" name="nnn" id="iii" kc-onoffswitch-model [on-text="ooo" off-text="fff"] />
*/
module.directive('onoffswitchstring', function() {
return {
restrict: "EA",
replace: true,
scope: {
name: '=',
id: '=',
value: '=',
ngModel: '=',
ngDisabled: '=',
kcOnText: '@onText',
kcOffText: '@offText'
},
// TODO - The same code acts differently when put into the templateURL. Find why and move the code there.
//templateUrl: "templates/kc-switch.html",
template: '<span><div class="onoffswitch" tabindex="0"><input type="checkbox" ng-true-value="\'true\'" ng-false-value="\'false\'" ng-model="ngModel" ng-disabled="ngDisabled" class="onoffswitch-checkbox" name="kc{{name}}" id="kc{{id}}"><label for="kc{{id}}" class="onoffswitch-label"><span class="onoffswitch-inner"><span class="onoffswitch-active">{{kcOnText}}</span><span class="onoffswitch-inactive">{{kcOffText}}</span></span><span class="onoffswitch-switch"></span></label></div></span>',
compile: function(element, attrs) {
if (!attrs.onText) { attrs.onText = "ON"; }
if (!attrs.offText) { attrs.offText = "OFF"; }
element.bind('keydown click', function(e){
var code = e.keyCode || e.which;
if (code === 32 || code === 13) {
e.stopImmediatePropagation();
e.preventDefault();
$(e.target).find('input').click();
}
});
}
}
});
/**
* Directive for presenting an ON-OFF switch for checkbox. The directive expects the true-value or false-value to be string like 'true' or 'false', not boolean true/false.
* This directive provides some additional capabilities to the default onoffswitch such as:
*
* - Specific scope to specify the value. Instead of just 'true' or 'false' you can use any other values. For example: true-value="'foo'" false-value="'bar'" .
* But 'true'/'false' are defaults if true-value and false-value are not specified
*
* Usage: <input ng-model="mmm" name="nnn" id="iii" onoffswitchvalue [ true-value="'true'" false-value="'false'" on-text="ooo" off-text="fff"] />
*/
module.directive('onoffswitchvalue', function() {
return {
restrict: "EA",
replace: true,
scope: {
name: '@',
id: '@',
trueValue: '@',
falseValue: '@',
ngModel: '=',
ngDisabled: '=',
kcOnText: '@onText',
kcOffText: '@offText'
},
// TODO - The same code acts differently when put into the templateURL. Find why and move the code there.
//templateUrl: "templates/kc-switch.html",
template: "<span><div class='onoffswitch' tabindex='0'><input type='checkbox' ng-true-value='{{trueValue}}' ng-false-value='{{falseValue}}' ng-model='ngModel' ng-disabled='ngDisabled' class='onoffswitch-checkbox' name='{{name}}' id='{{id}}'><label for='{{id}}' class='onoffswitch-label'><span class='onoffswitch-inner'><span class='onoffswitch-active'>{{kcOnText}}</span><span class='onoffswitch-inactive'>{{kcOffText}}</span></span><span class='onoffswitch-switch'></span></label></div></span>",
compile: function(element, attrs) {
/*
We don't want to propagate basic attributes to the root element of directive. Id should be passed to the
input element only to achieve proper label binding (and validity).
*/
element.removeAttr('name');
element.removeAttr('id');
if (!attrs.trueValue) { attrs.trueValue = "'true'"; }
if (!attrs.falseValue) { attrs.falseValue = "'false'"; }
if (!attrs.onText) { attrs.onText = "ON"; }
if (!attrs.offText) { attrs.offText = "OFF"; }
element.bind('keydown', function(e){
var code = e.keyCode || e.which;
if (code === 32 || code === 13) {
e.stopImmediatePropagation();
e.preventDefault();
$(e.target).find('input').click();
}
});
}
}
});
module.directive('kcInput', function() {
var d = {
scope : true,
replace : false,
link : function(scope, element, attrs) {
var form = element.children('form');
var label = element.children('label');
var input = element.children('input');
var id = form.attr('name') + '.' + input.attr('name');
element.attr('class', 'control-group');
label.attr('class', 'control-label');
label.attr('for', id);
input.wrap('<div class="controls"/>');
input.attr('id', id);
if (!input.attr('placeHolder')) {
input.attr('placeHolder', label.text());
}
if (input.attr('required')) {
label.append(' <span class="required">*</span>');
}
}
};
return d;
});
module.directive('kcEnter', function() {
return function(scope, element, attrs) {
element.bind("keydown keypress", function(event) {
if (event.which === 13) {
scope.$apply(function() {
scope.$eval(attrs.kcEnter);
});
event.preventDefault();
}
});
};
});
module.directive('kcSave', function ($compile, Notifications) {
return {
restrict: 'A',
link: function ($scope, elem, attr, ctrl) {
elem.addClass("btn btn-primary");
elem.attr("type","submit");
elem.bind('click', function() {
$scope.$apply(function() {
var form = elem.closest('form');
if (form && form.attr('name')) {
var ngValid = form.find('.ng-valid');
if ($scope[form.attr('name')].$valid) {
//ngValid.removeClass('error');
ngValid.parent().removeClass('has-error');
$scope['save']();
} else {
Notifications.error("Missing or invalid field(s). Please verify the fields in red.")
//ngValid.removeClass('error');
ngValid.parent().removeClass('has-error');
var ngInvalid = form.find('.ng-invalid');
//ngInvalid.addClass('error');
ngInvalid.parent().addClass('has-error');
}
}
});
})
}
}
});
module.directive('kcReset', function ($compile, Notifications) {
return {
restrict: 'A',
link: function ($scope, elem, attr, ctrl) {
elem.addClass("btn btn-default");
elem.attr("type","submit");
elem.bind('click', function() {
$scope.$apply(function() {
var form = elem.closest('form');
if (form && form.attr('name')) {
form.find('.ng-valid').removeClass('error');
form.find('.ng-invalid').removeClass('error');
$scope['reset']();
}
})
})
}
}
});
module.directive('kcCancel', function ($compile, Notifications) {
return {
restrict: 'A',
link: function ($scope, elem, attr, ctrl) {
elem.addClass("btn btn-default");
elem.attr("type","submit");
}
}
});
module.directive('kcDelete', function ($compile, Notifications) {
return {
restrict: 'A',
link: function ($scope, elem, attr, ctrl) {
elem.addClass("btn btn-danger");
elem.attr("type","submit");
}
}
});
module.directive('kcDropdown', function ($compile, Notifications) {
return {
scope: {
kcOptions: '=',
kcModel: '=',
id: "=",
kcPlaceholder: '@'
},
restrict: 'EA',
replace: true,
templateUrl: resourceUrl + '/templates/kc-select.html',
link: function(scope, element, attr) {
scope.updateModel = function(item) {
scope.kcModel = item;
};
}
}
});
module.directive('kcReadOnly', function() {
var disabled = {};
var d = {
replace : false,
link : function(scope, element, attrs) {
var disable = function(i, e) {
if (!e.disabled) {
disabled[e.tagName + i] = true;
e.disabled = true;
}
}
var enable = function(i, e) {
if (disabled[e.tagName + i]) {
e.disabled = false;
delete disabled[i];
}
}
var filterIgnored = function(i, e){
return !e.attributes['kc-read-only-ignore'];
}
scope.$watch(attrs.kcReadOnly, function(readOnly) {
if (readOnly) {
element.find('input').filter(filterIgnored).each(disable);
element.find('button').filter(filterIgnored).each(disable);
element.find('select').filter(filterIgnored).each(disable);
element.find('textarea').filter(filterIgnored).each(disable);
} else {
element.find('input').filter(filterIgnored).each(enable);
element.find('input').filter(filterIgnored).each(enable);
element.find('button').filter(filterIgnored).each(enable);
element.find('select').filter(filterIgnored).each(enable);
element.find('textarea').filter(filterIgnored).each(enable);
}
});
}
};
return d;
});
module.directive('kcMenu', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-menu.html'
}
});
module.directive('kcTabsRealm', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-realm.html'
}
});
module.directive('kcTabsAuthentication', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-authentication.html'
}
});
module.directive('kcTabsUser', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-user.html'
}
});
module.directive('kcTabsGroup', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-group.html'
}
});
module.directive('kcTabsGroupList', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-group-list.html'
}
});
module.directive('kcTabsClient', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-client.html'
}
});
module.directive('kcTabsClientTemplate', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-client-template.html'
}
});
module.directive('kcNavigationUser', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-navigation-user.html'
}
});
module.directive('kcTabsIdentityProvider', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-identity-provider.html'
}
});
module.directive('kcTabsUserFederation', function () {
return {
scope: true,
restrict: 'E',
replace: true,
templateUrl: resourceUrl + '/templates/kc-tabs-user-federation.html'
}
});
module.controller('RoleSelectorModalCtrl', function($scope, realm, config, configName, RealmRoles, Client, ClientRole, $modalInstance) {
$scope.selectedRealmRole = {
role: undefined
};
$scope.selectedClientRole = {
role: undefined
};
$scope.client = {
selected: undefined
};
$scope.selectRealmRole = function() {
config[configName] = $scope.selectedRealmRole.role.name;
$modalInstance.close();
}
$scope.selectClientRole = function() {
config[configName] = $scope.client.selected.clientId + "." + $scope.selectedClientRole.role.name;
$modalInstance.close();
}
$scope.cancel = function() {
$modalInstance.dismiss();
}
$scope.changeClient = function() {
if ($scope.client.selected) {
ClientRole.query({realm: realm.realm, client: $scope.client.selected.id}, function (data) {
$scope.clientRoles = data;
});
} else {
console.log('selected client was null');
$scope.clientRoles = null;
}
}
RealmRoles.query({realm: realm.realm}, function(data) {
$scope.realmRoles = data;
})
Client.query({realm: realm.realm}, function(data) {
$scope.clients = data;
if (data.length > 0) {
$scope.client.selected = data[0];
$scope.changeClient();
}
})
});
module.controller('ProviderConfigCtrl', function ($modal, $scope) {
$scope.openRoleSelector = function (configName, config) {
$modal.open({
templateUrl: resourceUrl + '/partials/modal/role-selector.html',
controller: 'RoleSelectorModalCtrl',
resolve: {
realm: function () {
return $scope.realm;
},
config: function () {
return config;
},
configName: function () {
return configName;
}
}
})
}
});
module.directive('kcProviderConfig', function ($modal) {
return {
scope: {
config: '=',
properties: '=',
realm: '=',
clients: '=',
configName: '='
},
restrict: 'E',
replace: true,
controller: 'ProviderConfigCtrl',
templateUrl: resourceUrl + '/templates/kc-provider-config.html'
}
});
module.controller('ComponentRoleSelectorModalCtrl', function($scope, realm, config, configName, RealmRoles, Client, ClientRole, $modalInstance) {
$scope.selectedRealmRole = {
role: undefined
};
$scope.selectedClientRole = {
role: undefined
};
$scope.client = {
selected: undefined
};
$scope.selectRealmRole = function() {
config[configName][0] = $scope.selectedRealmRole.role.name;
$modalInstance.close();
}
$scope.selectClientRole = function() {
config[configName][0] = $scope.client.selected.clientId + "." + $scope.selectedClientRole.role.name;
$modalInstance.close();
}
$scope.cancel = function() {
$modalInstance.dismiss();
}
$scope.changeClient = function() {
if ($scope.client.selected) {
ClientRole.query({realm: realm.realm, client: $scope.client.selected.id}, function (data) {
$scope.clientRoles = data;
});
} else {
console.log('selected client was null');
$scope.clientRoles = null;
}
}
RealmRoles.query({realm: realm.realm}, function(data) {
$scope.realmRoles = data;
})
Client.query({realm: realm.realm}, function(data) {
$scope.clients = data;
if (data.length > 0) {
$scope.client.selected = data[0];
$scope.changeClient();
}
})
});
module.controller('ComponentConfigCtrl', function ($modal, $scope) {
$scope.openRoleSelector = function (configName, config) {
$modal.open({
templateUrl: resourceUrl + '/partials/modal/component-role-selector.html',
controller: 'ComponentRoleSelectorModalCtrl',
resolve: {
realm: function () {
return $scope.realm;
},
config: function () {
return config;
},
configName: function () {
return configName;
}
}
})
}
});
module.directive('kcComponentConfig', function ($modal) {
return {
scope: {
config: '=',
properties: '=',
realm: '=',
clients: '=',
configName: '='
},
restrict: 'E',
replace: true,
controller: 'ComponentConfigCtrl',
templateUrl: resourceUrl + '/templates/kc-component-config.html'
}
});
/*
* Used to select the element (invoke $(elem).select()) on specified action list.
* Usages kc-select-action="click mouseover"
* When used in the textarea element, this will select/highlight the textarea content on specified action (i.e. click).
*/
module.directive('kcSelectAction', function ($compile, Notifications) {
return {
restrict: 'A',
compile: function (elem, attrs) {
var events = attrs.kcSelectAction.split(" ");
for(var i=0; i < events.length; i++){
elem.bind(events[i], function(){
elem.select();
});
}
}
}
});
module.filter('remove', function() {
return function(input, remove, attribute) {
if (!input || !remove) {
return input;
}
var out = [];
for ( var i = 0; i < input.length; i++) {
var e = input[i];
if (Array.isArray(remove)) {
for (var j = 0; j < remove.length; j++) {
if (attribute) {
if (remove[j][attribute] == e[attribute]) {
e = null;
break;
}
} else {
if (remove[j] == e) {
e = null;
break;
}
}
}
} else {
if (attribute) {
if (remove[attribute] == e[attribute]) {
e = null;
}
} else {
if (remove == e) {
e = null;
}
}
}
if (e != null) {
out.push(e);
}
}
return out;
};
});
module.filter('capitalize', function() {
return function(input) {
if (!input) {
return;
}
var splittedWords = input.split(/\s+/);
for (var i=0; i<splittedWords.length ; i++) {
splittedWords[i] = splittedWords[i].charAt(0).toUpperCase() + splittedWords[i].slice(1);
};
return splittedWords.join(" ");
};
});
/*
* Guarantees a deterministic property iteration order.
* See: http://www.2ality.com/2015/10/property-traversal-order-es6.html
*/
module.filter('toOrderedMapSortedByKey', function(){
return function(input){
if(!input){
return input;
}
var keys = Object.keys(input);
if(keys.length <= 1){
return input;
}
keys.sort();
var result = {};
for (var i = 0; i < keys.length; i++) {
result[keys[i]] = input[keys[i]];
}
return result;
};
});
module.directive('kcSidebarResize', function ($window) {
return function (scope, element) {
function resize() {
var navBar = angular.element(document.getElementsByClassName('navbar-pf')).height();
var container = angular.element(document.getElementById("view").getElementsByTagName("div")[0]).height();
var height = Math.max(container, window.innerHeight - navBar - 3);
element[0].style['min-height'] = height + 'px';
}
resize();
var w = angular.element($window);
scope.$watch(function () {
return {
'h': window.innerHeight,
'w': window.innerWidth
};
}, function () {
resize();
}, true);
w.bind('resize', function () {
scope.$apply();
});
}
});
module.directive('kcTooltip', function($compile) {
return {
restrict: 'E',
replace: false,
terminal: true,
priority: 1000,
link: function link(scope,element, attrs) {
var angularElement = angular.element(element[0]);
var tooltip = angularElement.text();
angularElement.text('');
element.addClass('hidden');
var label = angular.element(element.parent().children()[0]);
label.append(' <i class="fa fa-question-circle text-muted" tooltip="' + tooltip + '" tooltip-placement="right" tooltip-trigger="mouseover mouseout"></i>');
$compile(label)(scope);
}
};
});
module.directive( 'kcOpen', function ( $location ) {
return function ( scope, element, attrs ) {
var path;
attrs.$observe( 'kcOpen', function (val) {
path = val;
});
element.bind( 'click', function () {
scope.$apply( function () {
$location.path(path);
});
});
};
});
module.directive('kcOnReadFile', function ($parse) {
console.debug('kcOnReadFile');
return {
restrict: 'A',
scope: false,
link: function(scope, element, attrs) {
var fn = $parse(attrs.kcOnReadFile);
element.on('change', function(onChangeEvent) {
var reader = new FileReader();
reader.onload = function(onLoadEvent) {
scope.$apply(function() {
fn(scope, {$fileContent:onLoadEvent.target.result});
});
};
reader.readAsText((onChangeEvent.srcElement || onChangeEvent.target).files[0]);
});
}
};
});
| wildfly-security-incubator/keycloak | themes/src/main/resources/theme/base/admin/resources/js/app.js | JavaScript | apache-2.0 | 99,144 |
<html>
<head>
<title>RSEM-EVAL: A novel reference-free transcriptome assembly evaluation measure</title>
<!--This file is autogenerated. Edit the template instead.-->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$','$']]}
});
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_SVG" type="text/javascript"></script>
<style type="text/css">
body { max-width: 50em; }
body, td { font-family: sans-serif; }
dt { font-family: monospace; }
h1, h2 { color: #990000; }
</style>
</head>
<body>
<h1>RSEM-EVAL: A novel reference-free transcriptome assembly evaluation measure</h1>
<h2><a name="introduction"></a> Introduction</h2>
<p>RSEM-EVAL is built off of RSEM. It is a reference-free de novo transcriptome assembly evaluator.</p>
<h2><a name="compilation"></a> Compilation & Installation</h2>
<p>To compile RSEM-EVAL, simply run</p>
<pre><code>make
</code></pre>
<p>To install, simply put the rsem directory in your environment's PATH
variable.</p>
<h3>Prerequisites</h3>
<p>C++, Perl and R are required to be installed. </p>
<p>To take advantage of RSEM-EVAL's built-in support for the Bowtie alignment
program, you must have <a href="http://bowtie-bio.sourceforge.net">Bowtie</a> installed.</p>
<h2><a name="usage"></a> Usage</h2>
<h3>I. Build an assembly from the RNA-Seq data using an assembler</h3>
<p>Please note that the RNA-Seq data set used to build the assembly
should be exactly the same as the RNA-Seq data set for evaluating this
assembly. RSEM-EVAL supports both single-end and paired-end reads.</p>
<h3>II. Estimate Transcript Length Distribution Parameters</h3>
<p>RSEM-EVAL provides a script
'rsem-eval-estimate-transcript-length-distribution' to estimate
transcript length distribution from a set of transcript
sequences. Transcripts can be from a closely related species to the
orgaism whose transcriptome is sequenced. Its usage is:</p>
<pre><code>rsem-eval-estimate-transcript-length-distribution input.fasta parameter_file
</code></pre>
<p>__input.fasta__ is a multi-FASTA file contains all transcript sequences used to learn the true transcript length distribution's parameters. <br>
__parameter_file__ records the learned parameters--the estimated mean and standard deviation (separated by a tab character).</p>
<p>We have some learned paramter files stored at folder
'true_transcript_length_distribution'. Please refer to
'true_length_dist_mean_sd.txt' in the folder for more details.</p>
<h3>III. Calculate the RSEM-EVAL score</h3>
<p>To calculate the RSEM-EVAL score, you should use 'rsem-eval-calculate-score'. Run</p>
<pre><code>rsem-eval-calculate-score --help
</code></pre>
<p>to get usage information.</p>
<h3>IV. Outputs related to the evaluation score</h3>
<p>RSEM-EVAL produces the following three score related files:
'sample_name.score', 'sample_name.score.isoforms.results' and
'sample_name.score.genes.results'.</p>
<p>'sample_name.score' stores the evaluation score for the evaluated
assembly. It contains 13 lines and each line contains a name and a
value separated by a tab.</p>
<p>The first 6 lines provide: 'Score', the RSEM-EVAL score;
'BIC_penalty', the BIC penalty term; 'Prior_score_on_contig_lengths (f
function canceled)', the log score of priors of contig lengths, with f
function values excluded (f function is defined in equation (4) at
page 5 of Additional file 1, which is the supplementary methods,
tables and figures of our DETONATE paper);
'Prior_score_on_contig_sequences', the log score of priors of contig
sequence bases; 'Data_likelihood_in_log_space_without_correction', the
RSEM log data likelihood calculated with contig-level read generating
probabilities mentioned in section 4 of Additional file 1;
'Correction_term_(f_function_canceled)', the correction term, with f
function values excluded. Score = BIC_penalty +
Prior_score_on_contig_lengths + Prior_score_on_contig_sequences +
Data_likelihood_in_log_space_without_correction -
Correction_term. Because both 'Prior_score_on_contig_lengths' and
'Correction_term' share the same f function values for each contig,
the f function values can be canceled out. Then
'Prior_score_on_contig_lengths_(f_function_canceled)' is the sum of
log $c_{\lambda}(\ell)$ terms in equation (9) at page 5 of Additional
file 1. 'Correction_term_(f_function_canceled)' is the sum of log $(1
- p_{\lambda_i})$ terms in equation (23) at page 9 of Additional file
1. For the correction term, we use $\lambda_i$ instead of $\lambda'_i$
to make f function canceled out.</p>
<p>NOTE: Higher RSEM-EVAL scores are better than lower scores. This is
true despite the fact that the scores are always negative. For
example, a score of -80000 is better than a score of -200000, since
-80000 > -200000.</p>
<p>The next 7 lines provide statistics that may help users to understand
the RSEM-EVAL score better. They are: 'Number_of_contigs', the number
of contigs contained in the assembly;
'Expected_number_of_aligned_reads_given_the_data', the expected number
of reads assigned to each contig estimated using the contig-level read
generating probabilities mentioned in section 4 of Additional file 1;
'Number_of_contigs_smaller_than_expected_read/fragment_length', the
number of contigs whose length is smaller than the expected
read/fragment length; 'Number_of_contigs_with_no_read_aligned_to', the
number of contigs whose expected number of aligned reads is smaller
than 0.005; 'Maximum_data_likelihood_in_log_space', the maximum data
likelihood in log space calculated from RSEM by treating the assembly
as "true" transcripts; 'Number_of_alignable_reads', the number of
reads that have at least one alignment found by the aligner (Because
'rsem-calculate-expression' tries to use a very loose criteria to find
alignments, reads with only low quality alignments may also be counted
as alignable reads here); 'Number_of_alignments_in_total', the number
of total alignments found by the aligner.</p>
<p>'sample_name.score.isoforms.results' and
'sample_name.score.genes.results' output "corrected" expression levels
based on contig-level read generating probabilities mentioned in
section 4 of Additional file 1. Unlike 'sample_name.isoforms.results'
and 'sample_name.genes.results', which are calculated by treating the
contigs as true transcripts, calculating
'sample_name.score.isoforms.results' and
'sample_name.score.genes.results' involves first estimating expected
read coverage for each contig and then convert the expected read
coverage into contig-level read generating probabilities. This
procedure is aware of that provided sequences are contigs and gives
better expression estimates for very short contigs. In addtion, the
'TPM' field is changed to 'CPM' field, which stands for contig per
million.</p>
<p>For 'sample_name.score.isoforms.results', one additional
column is added. The additional column is named as
'contig_impact_score' and gives the contig impact score for each
contig as described in section 5 of Additional file 1.</p>
<h2><a name="example"></a> Example</h2>
<p>We have a toy example in the 'examples' folder of the detonate distribution. A
single true transcript is stored at file 'toy_ref.fa'. The single-end, 76bp
reads generated from this transcript are stored in file 'toy_SE.fq'. In
addition, we have three different assemblies based on the data:
'toy_assembly_1.fa', 'toy_assembly_2.fa' and 'toy_assembly_3.fa'. We also know
the true transcript is from mouse and thus use 'mouse.txt' under
'true_transcript_length_distribution' as our transcript length parameter file.</p>
<p>We run (assuming that we are in the rsem-eval directory)</p>
<pre><code>./rsem-eval-calculate-score -p 8 \
--transcript-length-parameters true_transcript_length_distribution/mouse.txt \
../examples/toy_SE.fq \
../examples/toy_assembly_1.fa \
toy_assembly_1
76
</code></pre>
<p>to obtain the RSEM-EVAL score. </p>
<p>The RSEM-EVAL score can be found in 'toy_assembly_1.score'. The
contig impact scores can be found in
'toy_assembly_1.score.isoforms.results'.</p>
<h2><a name="authors"></a> Authors</h2>
<p>RSEM-EVAL is developed by Bo Li, with substaintial technical input from Colin Dewey and Nate Fillmore.</p>
<h2><a name="acknowledgements"></a> Acknowledgements</h2>
<p>Please refer to the acknowledgements section in 'README_RSEM.md'.</p>
<h2><a name="license"></a> License</h2>
<p>RSEM-EVAL is licensed under the <a href="http://www.gnu.org/licenses/gpl-3.0.html">GNU General Public License
v3</a>.</p>
</body>
</html> | fmaguire/BayeHem | bayehem/rsem/detonate-1.11/html/rsem-eval.html | HTML | apache-2.0 | 8,616 |
/*
* AnyOf_test.cpp
*
* Created on: Jan 30, 2016
* Author: ljeff
*/
#include "AnyOf.h"
namespace algorithm {
} /* namespace algorithm */
| jidol/boost-algorithms | AnyOf_test.cpp | C++ | apache-2.0 | 151 |
/*
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.customers.persistence;
import static org.mifos.application.meeting.util.helpers.MeetingType.CUSTOMER_MEETING;
import static org.mifos.application.meeting.util.helpers.RecurrenceType.WEEKLY;
import static org.mifos.framework.util.helpers.TestObjectFactory.EVERY_WEEK;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import junit.framework.Assert;
import org.mifos.accounts.business.AccountActionDateEntity;
import org.mifos.accounts.business.AccountBO;
import org.mifos.accounts.business.AccountFeesEntity;
import org.mifos.accounts.business.AccountStateEntity;
import org.mifos.accounts.business.AccountTestUtils;
import org.mifos.accounts.exceptions.AccountException;
import org.mifos.accounts.fees.business.AmountFeeBO;
import org.mifos.accounts.fees.business.FeeBO;
import org.mifos.accounts.fees.util.helpers.FeeCategory;
import org.mifos.accounts.loan.business.LoanBO;
import org.mifos.accounts.productdefinition.business.LoanOfferingBO;
import org.mifos.accounts.productdefinition.business.SavingsOfferingBO;
import org.mifos.accounts.productdefinition.util.helpers.RecommendedAmountUnit;
import org.mifos.accounts.savings.business.SavingsBO;
import org.mifos.accounts.util.helpers.AccountState;
import org.mifos.accounts.util.helpers.AccountStateFlag;
import org.mifos.accounts.util.helpers.AccountTypes;
import org.mifos.application.master.business.MifosCurrency;
import org.mifos.application.meeting.business.MeetingBO;
import org.mifos.application.meeting.exceptions.MeetingException;
import org.mifos.application.meeting.persistence.MeetingPersistence;
import org.mifos.application.meeting.util.helpers.RecurrenceType;
import org.mifos.application.servicefacade.CollectionSheetCustomerDto;
import org.mifos.application.util.helpers.YesNoFlag;
import org.mifos.config.AccountingRulesConstants;
import org.mifos.config.ConfigurationManager;
import org.mifos.core.CurrencyMismatchException;
import org.mifos.customers.business.CustomerAccountBO;
import org.mifos.customers.business.CustomerBO;
import org.mifos.customers.business.CustomerBOTestUtils;
import org.mifos.customers.business.CustomerNoteEntity;
import org.mifos.customers.business.CustomerPerformanceHistoryView;
import org.mifos.customers.business.CustomerSearch;
import org.mifos.customers.business.CustomerStatusEntity;
import org.mifos.customers.business.CustomerView;
import org.mifos.customers.center.business.CenterBO;
import org.mifos.customers.checklist.business.CheckListBO;
import org.mifos.customers.checklist.business.CustomerCheckListBO;
import org.mifos.customers.checklist.util.helpers.CheckListConstants;
import org.mifos.customers.client.business.AttendanceType;
import org.mifos.customers.client.business.ClientBO;
import org.mifos.customers.client.util.helpers.ClientConstants;
import org.mifos.customers.group.BasicGroupInfo;
import org.mifos.customers.group.business.GroupBO;
import org.mifos.customers.personnel.business.PersonnelBO;
import org.mifos.customers.personnel.util.helpers.PersonnelConstants;
import org.mifos.customers.util.helpers.ChildrenStateType;
import org.mifos.customers.util.helpers.CustomerLevel;
import org.mifos.customers.util.helpers.CustomerStatus;
import org.mifos.customers.util.helpers.CustomerStatusFlag;
import org.mifos.framework.MifosIntegrationTestCase;
import org.mifos.framework.TestUtils;
import org.mifos.framework.exceptions.ApplicationException;
import org.mifos.framework.exceptions.PersistenceException;
import org.mifos.framework.exceptions.SystemException;
import org.mifos.framework.hibernate.helper.QueryResult;
import org.mifos.framework.hibernate.helper.StaticHibernateUtil;
import org.mifos.framework.util.helpers.Money;
import org.mifos.framework.util.helpers.TestObjectFactory;
import org.mifos.security.util.UserContext;
public class CustomerPersistenceIntegrationTest extends MifosIntegrationTestCase {
public CustomerPersistenceIntegrationTest() throws Exception {
super();
}
private MeetingBO meeting;
private CustomerBO center;
private ClientBO client;
private CustomerBO group2;
private CustomerBO group;
private AccountBO account;
private LoanBO groupAccount;
private LoanBO clientAccount;
private SavingsBO centerSavingsAccount;
private SavingsBO groupSavingsAccount;
private SavingsBO clientSavingsAccount;
private SavingsOfferingBO savingsOffering;
private final CustomerPersistence customerPersistence = new CustomerPersistence();
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
public void tearDown() throws Exception {
try {
TestObjectFactory.cleanUp(centerSavingsAccount);
TestObjectFactory.cleanUp(groupSavingsAccount);
TestObjectFactory.cleanUp(clientSavingsAccount);
TestObjectFactory.cleanUp(groupAccount);
TestObjectFactory.cleanUp(clientAccount);
TestObjectFactory.cleanUp(account);
TestObjectFactory.cleanUp(client);
TestObjectFactory.cleanUp(group2);
TestObjectFactory.cleanUp(group);
TestObjectFactory.cleanUp(center);
StaticHibernateUtil.closeSession();
} catch (Exception e) {
// Throwing from tearDown will tend to mask the real failure.
e.printStackTrace();
}
super.tearDown();
}
public void testGetTotalAmountForAllClientsOfGroupForSingleCurrency() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
AccountBO clientAccount1 = getLoanAccount(client, meeting, "fdbdhgsgh", "54hg", TestUtils.RUPEE);
AccountBO clientAccount2 = getLoanAccount(client, meeting, "fasdfdsfasdf", "1qwe", TestUtils.RUPEE);
Money amount = customerPersistence.getTotalAmountForAllClientsOfGroup(group.getOffice().getOfficeId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, group.getSearchId() + ".%");
Assert.assertEquals(new Money(TestUtils.RUPEE, "600"), amount);
TestObjectFactory.cleanUp(clientAccount1);
TestObjectFactory.cleanUp(clientAccount2);
}
/*
* When trying to sum amounts across loans with different currencies, we should get an exception
*/
public void testGetTotalAmountForAllClientsOfGroupForMultipleCurrencies() throws Exception {
ConfigurationManager configMgr = ConfigurationManager.getInstance();
configMgr.setProperty(AccountingRulesConstants.ADDITIONAL_CURRENCY_CODES, TestUtils.EURO.getCurrencyCode());
AccountBO clientAccount1;
AccountBO clientAccount2;
try {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
clientAccount1 = getLoanAccount(client, meeting, "fdbdhgsgh", "54hg", TestUtils.RUPEE);
clientAccount2 = getLoanAccount(client, meeting, "fasdfdsfasdf", "1qwe", TestUtils.EURO);
try {
customerPersistence.getTotalAmountForAllClientsOfGroup(group.getOffice().getOfficeId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, group.getSearchId() + ".%");
fail("didn't get the expected CurrencyMismatchException");
} catch (CurrencyMismatchException e) {
// if we got here then we got the exception we were expecting
assertNotNull(e);
} catch (Exception e) {
fail("didn't get the expected CurrencyMismatchException");
}
} finally {
configMgr.clearProperty(AccountingRulesConstants.ADDITIONAL_CURRENCY_CODES);
}
TestObjectFactory.cleanUp(clientAccount1);
TestObjectFactory.cleanUp(clientAccount2);
}
/*
* When trying to sum amounts across loans with different currencies, we should get an exception
*/
public void testGetTotalAmountForGroupForMultipleCurrencies() throws Exception {
ConfigurationManager configMgr = ConfigurationManager.getInstance();
configMgr.setProperty(AccountingRulesConstants.ADDITIONAL_CURRENCY_CODES, TestUtils.EURO.getCurrencyCode());
GroupBO group1;
AccountBO account1;
AccountBO account2;
try {
CustomerPersistence customerPersistence = new CustomerPersistence();
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
account1 = getLoanAccount(group1, meeting, "adsfdsfsd", "3saf", TestUtils.RUPEE);
account2 = getLoanAccount(group1, meeting, "adspp", "kkaf", TestUtils.EURO);
try {
customerPersistence.getTotalAmountForGroup(group1.getCustomerId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING);
fail("didn't get the expected CurrencyMismatchException");
} catch (CurrencyMismatchException e) {
// if we got here then we got the exception we were expecting
assertNotNull(e);
} catch (Exception e) {
fail("didn't get the expected CurrencyMismatchException");
}
} finally {
configMgr.clearProperty(AccountingRulesConstants.ADDITIONAL_CURRENCY_CODES);
}
TestObjectFactory.cleanUp(account1);
TestObjectFactory.cleanUp(account2);
TestObjectFactory.cleanUp(group1);
}
public void testGetTotalAmountForGroup() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
AccountBO account1 = getLoanAccount(group1, meeting, "adsfdsfsd", "3saf");
AccountBO account2 = getLoanAccount(group1, meeting, "adspp", "kkaf");
Money amount = customerPersistence.getTotalAmountForGroup(group1.getCustomerId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING);
Assert.assertEquals(new Money(getCurrency(), "600"), amount);
AccountBO account3 = getLoanAccountInActiveBadStanding(group1, meeting, "adsfdsfsd1", "4sa");
AccountBO account4 = getLoanAccountInActiveBadStanding(group1, meeting, "adspp2", "kaf5");
Money amount2 = customerPersistence.getTotalAmountForGroup(group1.getCustomerId(),
AccountState.LOAN_ACTIVE_IN_BAD_STANDING);
Assert.assertEquals(new Money(getCurrency(), "600"), amount2);
TestObjectFactory.cleanUp(account1);
TestObjectFactory.cleanUp(account2);
TestObjectFactory.cleanUp(account3);
TestObjectFactory.cleanUp(account4);
TestObjectFactory.cleanUp(group1);
}
public void testGetTotalAmountForAllClientsOfGroup() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
AccountBO clientAccount1 = getLoanAccount(client, meeting, "fdbdhgsgh", "54hg");
AccountBO clientAccount2 = getLoanAccount(client, meeting, "fasdfdsfasdf", "1qwe");
Money amount = customerPersistence.getTotalAmountForAllClientsOfGroup(group.getOffice().getOfficeId(),
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, group.getSearchId() + ".%");
Assert.assertEquals(new Money(getCurrency(), "600"), amount);
clientAccount1.changeStatus(AccountState.LOAN_ACTIVE_IN_BAD_STANDING.getValue(), null, "none");
clientAccount2.changeStatus(AccountState.LOAN_ACTIVE_IN_BAD_STANDING.getValue(), null, "none");
TestObjectFactory.updateObject(clientAccount1);
TestObjectFactory.updateObject(clientAccount2);
StaticHibernateUtil.commitTransaction();
Money amount2 = customerPersistence.getTotalAmountForAllClientsOfGroup(group.getOffice().getOfficeId(),
AccountState.LOAN_ACTIVE_IN_BAD_STANDING, group.getSearchId() + ".%");
Assert.assertEquals(new Money(getCurrency(), "600"), amount2);
TestObjectFactory.cleanUp(clientAccount1);
TestObjectFactory.cleanUp(clientAccount2);
}
public void testGetAllBasicGroupInfo() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
GroupBO newGroup = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup", CustomerStatus.GROUP_HOLD, center);
GroupBO newGroup2 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup2", CustomerStatus.GROUP_CANCELLED,
center);
GroupBO newGroup3 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup3", CustomerStatus.GROUP_CLOSED, center);
GroupBO newGroup4 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup4", CustomerStatus.GROUP_PARTIAL, center);
GroupBO newGroup5 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("newGroup5", CustomerStatus.GROUP_PENDING, center);
List<BasicGroupInfo> groupInfos = customerPersistence.getAllBasicGroupInfo();
Assert.assertEquals(2, groupInfos.size());
Assert.assertEquals(group.getDisplayName(), groupInfos.get(0).getGroupName());
Assert.assertEquals(group.getSearchId(), groupInfos.get(0).getSearchId());
Assert.assertEquals(group.getOffice().getOfficeId(), groupInfos.get(0).getBranchId());
Assert.assertEquals(group.getCustomerId(), groupInfos.get(0).getGroupId());
Assert.assertEquals(newGroup.getDisplayName(), groupInfos.get(1).getGroupName());
Assert.assertEquals(newGroup.getSearchId(), groupInfos.get(1).getSearchId());
Assert.assertEquals(newGroup.getOffice().getOfficeId(), groupInfos.get(1).getBranchId());
Assert.assertEquals(newGroup.getCustomerId(), groupInfos.get(1).getGroupId());
TestObjectFactory.cleanUp(newGroup);
TestObjectFactory.cleanUp(newGroup2);
TestObjectFactory.cleanUp(newGroup3);
TestObjectFactory.cleanUp(newGroup4);
TestObjectFactory.cleanUp(newGroup5);
}
public void testCustomersUnderLO() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center_Active", meeting);
List<CustomerView> customers = customerPersistence.getActiveParentList(Short.valueOf("1"), CustomerLevel.CENTER
.getValue(), Short.valueOf("3"));
Assert.assertEquals(1, customers.size());
}
public void testActiveCustomersUnderParent() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
List<CustomerView> customers = customerPersistence.getChildrenForParent(center.getCustomerId(), center
.getSearchId(), center.getOffice().getOfficeId());
Assert.assertEquals(2, customers.size());
}
public void testOnHoldCustomersUnderParent() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
createCustomers(CustomerStatus.GROUP_HOLD, CustomerStatus.CLIENT_HOLD);
List<CustomerView> customers = customerPersistence.getChildrenForParent(center.getCustomerId(), center
.getSearchId(), center.getOffice().getOfficeId());
Assert.assertEquals(2, customers.size());
}
public void testGetLastMeetingDateForCustomer() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
account = getLoanAccount(group, meeting, "adsfdsfsd", "3saf");
// Date actionDate = new Date(2006,03,13);
Date meetingDate = customerPersistence.getLastMeetingDateForCustomer(center.getCustomerId());
Assert.assertEquals(new Date(getMeetingDates(meeting).getTime()).toString(), meetingDate.toString());
}
public void testGetChildernOtherThanClosed() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group);
ClientBO client4 = TestObjectFactory.createClient("client4", CustomerStatus.CLIENT_PENDING, group);
List<CustomerBO> customerList = customerPersistence.getChildren(center.getSearchId(), center.getOffice()
.getOfficeId(), CustomerLevel.CLIENT, ChildrenStateType.OTHER_THAN_CLOSED);
Assert.assertEquals(new Integer("3").intValue(), customerList.size());
for (CustomerBO customer : customerList) {
if (customer.getCustomerId().intValue() == client3.getCustomerId().intValue()) {
Assert.assertTrue(true);
}
}
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client4);
}
public void testGetChildernActiveAndHold() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_PARTIAL, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_PENDING, group);
ClientBO client4 = TestObjectFactory.createClient("client4", CustomerStatus.CLIENT_HOLD, group);
List<CustomerBO> customerList = customerPersistence.getChildren(center.getSearchId(), center.getOffice()
.getOfficeId(), CustomerLevel.CLIENT, ChildrenStateType.ACTIVE_AND_ONHOLD);
Assert.assertEquals(new Integer("2").intValue(), customerList.size());
for (CustomerBO customer : customerList) {
if (customer.getCustomerId().intValue() == client.getCustomerId().intValue()) {
Assert.assertTrue(true);
}
if (customer.getCustomerId().intValue() == client4.getCustomerId().intValue()) {
Assert.assertTrue(true);
}
}
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client4);
}
public void testGetChildernOtherThanClosedAndCancelled() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group);
ClientBO client4 = TestObjectFactory.createClient("client4", CustomerStatus.CLIENT_PENDING, group);
List<CustomerBO> customerList = customerPersistence.getChildren(center.getSearchId(), center.getOffice()
.getOfficeId(), CustomerLevel.CLIENT, ChildrenStateType.OTHER_THAN_CANCELLED_AND_CLOSED);
Assert.assertEquals(new Integer("2").intValue(), customerList.size());
for (CustomerBO customer : customerList) {
if (customer.getCustomerId().equals(client4.getCustomerId())) {
Assert.assertTrue(true);
}
}
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client4);
}
public void testGetAllChildern() throws Exception {
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group);
ClientBO client4 = TestObjectFactory.createClient("client4", CustomerStatus.CLIENT_PENDING, group);
List<CustomerBO> customerList = customerPersistence.getChildren(center.getSearchId(), center.getOffice()
.getOfficeId(), CustomerLevel.CLIENT, ChildrenStateType.ALL);
Assert.assertEquals(new Integer("4").intValue(), customerList.size());
for (CustomerBO customer : customerList) {
if (customer.getCustomerId().equals(client2.getCustomerId())) {
Assert.assertTrue(true);
}
}
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client4);
}
public void testRetrieveSavingsAccountForCustomer() throws Exception {
java.util.Date currentDate = new java.util.Date();
CustomerPersistence customerPersistence = new CustomerPersistence();
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
savingsOffering = TestObjectFactory.createSavingsProduct("SavingPrd1", "S", currentDate, RecommendedAmountUnit.COMPLETE_GROUP);
UserContext user = new UserContext();
user.setId(PersonnelConstants.SYSTEM_USER);
account = TestObjectFactory.createSavingsAccount("000100000000020", group, AccountState.SAVINGS_ACTIVE,
currentDate, savingsOffering, user);
StaticHibernateUtil.closeSession();
List<SavingsBO> savingsList = customerPersistence.retrieveSavingsAccountForCustomer(group.getCustomerId());
Assert.assertEquals(1, savingsList.size());
account = savingsList.get(0);
group = account.getCustomer();
center = group.getParentCustomer();
}
public void testNumberOfMeetingsAttended() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client", CustomerStatus.CLIENT_ACTIVE, group);
client.handleAttendance(new Date(System.currentTimeMillis()), AttendanceType.ABSENT);
client.handleAttendance(new Date(System.currentTimeMillis()), AttendanceType.PRESENT);
Calendar currentDate = new GregorianCalendar();
currentDate.roll(Calendar.DATE, 1);
client.handleAttendance(new Date(currentDate.getTimeInMillis()), AttendanceType.LATE);
StaticHibernateUtil.commitTransaction();
CustomerPerformanceHistoryView customerPerformanceHistoryView = customerPersistence.numberOfMeetings(true,
client.getCustomerId());
Assert.assertEquals(2, customerPerformanceHistoryView.getMeetingsAttended().intValue());
StaticHibernateUtil.closeSession();
}
public void testNumberOfMeetingsMissed() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client", CustomerStatus.CLIENT_ACTIVE, group);
client.handleAttendance(new Date(System.currentTimeMillis()), AttendanceType.PRESENT);
client.handleAttendance(new Date(System.currentTimeMillis()), AttendanceType.ABSENT);
Calendar currentDate = new GregorianCalendar();
currentDate.roll(Calendar.DATE, 1);
client.handleAttendance(new Date(currentDate.getTimeInMillis()), AttendanceType.APPROVED_LEAVE);
StaticHibernateUtil.commitTransaction();
CustomerPerformanceHistoryView customerPerformanceHistoryView = customerPersistence.numberOfMeetings(false,
client.getCustomerId());
Assert.assertEquals(2, customerPerformanceHistoryView.getMeetingsMissed().intValue());
StaticHibernateUtil.closeSession();
}
public void testLastLoanAmount() throws PersistenceException, AccountException {
Date startDate = new Date(System.currentTimeMillis());
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client", CustomerStatus.CLIENT_ACTIVE, group);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(startDate, center.getCustomerMeeting()
.getMeeting());
LoanBO loanBO = TestObjectFactory.createLoanAccount("42423142341", client,
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, startDate, loanOffering);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
account = (AccountBO) StaticHibernateUtil.getSessionTL().get(LoanBO.class, loanBO.getAccountId());
AccountStateEntity accountStateEntity = new AccountStateEntity(AccountState.LOAN_CLOSED_OBLIGATIONS_MET);
account.setUserContext(TestObjectFactory.getContext());
account.changeStatus(accountStateEntity.getId(), null, "");
TestObjectFactory.updateObject(account);
CustomerPersistence customerPersistence = new CustomerPersistence();
CustomerPerformanceHistoryView customerPerformanceHistoryView = customerPersistence.getLastLoanAmount(client
.getCustomerId());
Assert.assertEquals("300.0", customerPerformanceHistoryView.getLastLoanAmount());
}
public void testFindBySystemId() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group_Active_test", CustomerStatus.GROUP_ACTIVE, center);
GroupBO groupBO = (GroupBO) customerPersistence.findBySystemId(group.getGlobalCustNum());
Assert.assertEquals(groupBO.getDisplayName(), group.getDisplayName());
}
public void testGetBySystemId() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group_Active_test", CustomerStatus.GROUP_ACTIVE, center);
GroupBO groupBO = (GroupBO) customerPersistence.findBySystemId(group.getGlobalCustNum(), group
.getCustomerLevel().getId());
Assert.assertEquals(groupBO.getDisplayName(), group.getDisplayName());
}
public void testOptionalCustomerStates() throws Exception {
Assert.assertEquals(Integer.valueOf(0).intValue(), customerPersistence.getCustomerStates(Short.valueOf("0"))
.size());
}
public void testCustomerStatesInUse() throws Exception {
Assert.assertEquals(Integer.valueOf(14).intValue(), customerPersistence.getCustomerStates(Short.valueOf("1"))
.size());
}
public void testGetCustomersWithUpdatedMeetings() throws Exception {
center = createCenter();
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center);
CustomerBOTestUtils.setUpdatedFlag(group.getCustomerMeeting(), YesNoFlag.YES.getValue());
TestObjectFactory.updateObject(group);
List<Integer> customerIds = customerPersistence.getCustomersWithUpdatedMeetings();
Assert.assertEquals(1, customerIds.size());
}
public void testRetrieveAllLoanAccountUnderCustomer() throws PersistenceException {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = createCenter("center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("center1");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_ACTIVE, group1);
account = getLoanAccount(group, meeting, "cdfggdfs", "1qdd");
AccountBO account1 = getLoanAccount(client, meeting, "fdbdhgsgh", "54hg");
AccountBO account2 = getLoanAccount(client2, meeting, "fasdfdsfasdf", "1qwe");
AccountBO account3 = getLoanAccount(client3, meeting, "fdsgdfgfd", "543g");
AccountBO account4 = getLoanAccount(group1, meeting, "fasdf23", "3fds");
CustomerBOTestUtils.setCustomerStatus(client2, new CustomerStatusEntity(CustomerStatus.CLIENT_CLOSED));
TestObjectFactory.updateObject(client2);
client2 = TestObjectFactory.getClient(client2.getCustomerId());
CustomerBOTestUtils.setCustomerStatus(client3, new CustomerStatusEntity(CustomerStatus.CLIENT_CANCELLED));
TestObjectFactory.updateObject(client3);
client3 = TestObjectFactory.getClient(client3.getCustomerId());
List<AccountBO> loansForCenter = customerPersistence.retrieveAccountsUnderCustomer(center.getSearchId(), Short
.valueOf("3"), Short.valueOf("1"));
Assert.assertEquals(3, loansForCenter.size());
List<AccountBO> loansForGroup = customerPersistence.retrieveAccountsUnderCustomer(group.getSearchId(), Short
.valueOf("3"), Short.valueOf("1"));
Assert.assertEquals(3, loansForGroup.size());
List<AccountBO> loansForClient = customerPersistence.retrieveAccountsUnderCustomer(client.getSearchId(), Short
.valueOf("3"), Short.valueOf("1"));
Assert.assertEquals(1, loansForClient.size());
TestObjectFactory.cleanUp(account4);
TestObjectFactory.cleanUp(account3);
TestObjectFactory.cleanUp(account2);
TestObjectFactory.cleanUp(account1);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(center1);
}
public void testRetrieveAllSavingsAccountUnderCustomer() throws Exception {
center = createCenter("new_center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("new_center1");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group1);
account = getSavingsAccount(center, "Savings Prd1", "Abc1");
AccountBO account1 = getSavingsAccount(client, "Savings Prd2", "Abc2");
AccountBO account2 = getSavingsAccount(client2, "Savings Prd3", "Abc3");
AccountBO account3 = getSavingsAccount(client3, "Savings Prd4", "Abc4");
AccountBO account4 = getSavingsAccount(group1, "Savings Prd5", "Abc5");
AccountBO account5 = getSavingsAccount(group, "Savings Prd6", "Abc6");
AccountBO account6 = getSavingsAccount(center1, "Savings Prd7", "Abc7");
List<AccountBO> savingsForCenter = customerPersistence.retrieveAccountsUnderCustomer(center.getSearchId(),
Short.valueOf("3"), Short.valueOf("2"));
Assert.assertEquals(4, savingsForCenter.size());
List<AccountBO> savingsForGroup = customerPersistence.retrieveAccountsUnderCustomer(group.getSearchId(), Short
.valueOf("3"), Short.valueOf("2"));
Assert.assertEquals(3, savingsForGroup.size());
List<AccountBO> savingsForClient = customerPersistence.retrieveAccountsUnderCustomer(client.getSearchId(),
Short.valueOf("3"), Short.valueOf("2"));
Assert.assertEquals(1, savingsForClient.size());
TestObjectFactory.cleanUp(account3);
TestObjectFactory.cleanUp(account2);
TestObjectFactory.cleanUp(account1);
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(account4);
TestObjectFactory.cleanUp(account5);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(account6);
TestObjectFactory.cleanUp(center1);
}
public void testGetAllChildrenForParent() throws NumberFormatException, PersistenceException {
center = createCenter("Center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("center11");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group1);
List<CustomerBO> customerList1 = customerPersistence.getAllChildrenForParent(center.getSearchId(), Short
.valueOf("3"), CustomerLevel.CENTER.getValue());
Assert.assertEquals(2, customerList1.size());
List<CustomerBO> customerList2 = customerPersistence.getAllChildrenForParent(center.getSearchId(), Short
.valueOf("3"), CustomerLevel.GROUP.getValue());
Assert.assertEquals(1, customerList2.size());
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(center1);
}
public void testGetChildrenForParent() throws NumberFormatException, SystemException, ApplicationException {
center = createCenter("center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("center1");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group1);
List<Integer> customerIds = customerPersistence.getChildrenForParent(center.getSearchId(), Short.valueOf("3"));
Assert.assertEquals(3, customerIds.size());
CustomerBO customer = TestObjectFactory.getCustomer(customerIds.get(0));
Assert.assertEquals("Group", customer.getDisplayName());
customer = TestObjectFactory.getCustomer(customerIds.get(1));
Assert.assertEquals("client1", customer.getDisplayName());
customer = TestObjectFactory.getCustomer(customerIds.get(2));
Assert.assertEquals("client2", customer.getDisplayName());
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(center1);
}
public void testGetCustomers() throws NumberFormatException, SystemException, ApplicationException {
center = createCenter("center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
CenterBO center1 = createCenter("center11");
GroupBO group1 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group1", CustomerStatus.GROUP_ACTIVE, center1);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
ClientBO client2 = TestObjectFactory.createClient("client2", CustomerStatus.CLIENT_CLOSED, group);
ClientBO client3 = TestObjectFactory.createClient("client3", CustomerStatus.CLIENT_CANCELLED, group1);
List<Integer> customerIds = customerPersistence.getCustomers(CustomerLevel.CENTER.getValue());
Assert.assertEquals(2, customerIds.size());
TestObjectFactory.cleanUp(client3);
TestObjectFactory.cleanUp(client2);
TestObjectFactory.cleanUp(group1);
TestObjectFactory.cleanUp(center1);
}
public void testGetCustomerChecklist() throws NumberFormatException, SystemException, ApplicationException,
Exception {
center = createCenter("center");
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("client1", CustomerStatus.CLIENT_ACTIVE, group);
CustomerCheckListBO checklistCenter = TestObjectFactory.createCustomerChecklist(center.getCustomerLevel()
.getId(), center.getCustomerStatus().getId(), CheckListConstants.STATUS_ACTIVE);
CustomerCheckListBO checklistClient = TestObjectFactory.createCustomerChecklist(client.getCustomerLevel()
.getId(), client.getCustomerStatus().getId(), CheckListConstants.STATUS_INACTIVE);
CustomerCheckListBO checklistGroup = TestObjectFactory.createCustomerChecklist(
group.getCustomerLevel().getId(), group.getCustomerStatus().getId(), CheckListConstants.STATUS_ACTIVE);
StaticHibernateUtil.closeSession();
Assert.assertEquals(1, customerPersistence.getStatusChecklist(center.getCustomerStatus().getId(),
center.getCustomerLevel().getId()).size());
client = (ClientBO) StaticHibernateUtil.getSessionTL().get(ClientBO.class,
Integer.valueOf(client.getCustomerId()));
group = (GroupBO) StaticHibernateUtil.getSessionTL().get(GroupBO.class, Integer.valueOf(group.getCustomerId()));
center = (CenterBO) StaticHibernateUtil.getSessionTL().get(CenterBO.class,
Integer.valueOf(center.getCustomerId()));
checklistCenter = (CustomerCheckListBO) StaticHibernateUtil.getSessionTL().get(CheckListBO.class,
new Short(checklistCenter.getChecklistId()));
checklistClient = (CustomerCheckListBO) StaticHibernateUtil.getSessionTL().get(CheckListBO.class,
new Short(checklistClient.getChecklistId()));
checklistGroup = (CustomerCheckListBO) StaticHibernateUtil.getSessionTL().get(CheckListBO.class,
new Short(checklistGroup.getChecklistId()));
TestObjectFactory.cleanUp(checklistCenter);
TestObjectFactory.cleanUp(checklistClient);
TestObjectFactory.cleanUp(checklistGroup);
}
public void testRetrieveAllCustomerStatusList() throws NumberFormatException, SystemException, ApplicationException {
center = createCenter();
Assert.assertEquals(2, customerPersistence.retrieveAllCustomerStatusList(center.getCustomerLevel().getId())
.size());
}
public void testCustomerCountByOffice() throws Exception {
int count = customerPersistence.getCustomerCountForOffice(CustomerLevel.CENTER, Short.valueOf("3"));
Assert.assertEquals(0, count);
center = createCenter();
count = customerPersistence.getCustomerCountForOffice(CustomerLevel.CENTER, Short.valueOf("3"));
Assert.assertEquals(1, count);
}
public void testGetAllCustomerNotes() throws Exception {
center = createCenter();
center.addCustomerNotes(TestObjectFactory.getCustomerNote("Test Note", center));
TestObjectFactory.updateObject(center);
Assert.assertEquals(1, customerPersistence.getAllCustomerNotes(center.getCustomerId()).getSize());
for (CustomerNoteEntity note : center.getCustomerNotes()) {
Assert.assertEquals("Test Note", note.getComment());
Assert.assertEquals(center.getPersonnel().getPersonnelId(), note.getPersonnel().getPersonnelId());
}
center = (CenterBO) StaticHibernateUtil.getSessionTL().get(CenterBO.class,
Integer.valueOf(center.getCustomerId()));
}
public void testGetAllCustomerNotesWithZeroNotes() throws Exception {
center = createCenter();
Assert.assertEquals(0, customerPersistence.getAllCustomerNotes(center.getCustomerId()).getSize());
Assert.assertEquals(0, center.getCustomerNotes().size());
}
public void testGetFormedByPersonnel() throws NumberFormatException, SystemException, ApplicationException {
center = createCenter();
Assert.assertEquals(1, customerPersistence.getFormedByPersonnel(ClientConstants.LOAN_OFFICER_LEVEL,
center.getOffice().getOfficeId()).size());
}
public void testGetAllClosedAccounts() throws Exception {
getCustomer();
groupAccount.changeStatus(AccountState.LOAN_CANCELLED.getValue(), AccountStateFlag.LOAN_WITHDRAW.getValue(),
"WITHDRAW LOAN ACCOUNT");
clientAccount.changeStatus(AccountState.LOAN_CLOSED_WRITTEN_OFF.getValue(), null, "WITHDRAW LOAN ACCOUNT");
clientSavingsAccount.changeStatus(AccountState.SAVINGS_CANCELLED.getValue(), AccountStateFlag.SAVINGS_REJECTED
.getValue(), "WITHDRAW LOAN ACCOUNT");
TestObjectFactory.updateObject(groupAccount);
TestObjectFactory.updateObject(clientAccount);
TestObjectFactory.updateObject(clientSavingsAccount);
StaticHibernateUtil.commitTransaction();
Assert.assertEquals(1, customerPersistence.getAllClosedAccount(client.getCustomerId(),
AccountTypes.LOAN_ACCOUNT.getValue()).size());
Assert.assertEquals(1, customerPersistence.getAllClosedAccount(group.getCustomerId(),
AccountTypes.LOAN_ACCOUNT.getValue()).size());
Assert.assertEquals(1, customerPersistence.getAllClosedAccount(client.getCustomerId(),
AccountTypes.SAVINGS_ACCOUNT.getValue()).size());
}
public void testGetAllClosedAccountsWhenNoAccountsClosed() throws Exception {
getCustomer();
Assert.assertEquals(0, customerPersistence.getAllClosedAccount(client.getCustomerId(),
AccountTypes.LOAN_ACCOUNT.getValue()).size());
Assert.assertEquals(0, customerPersistence.getAllClosedAccount(group.getCustomerId(),
AccountTypes.LOAN_ACCOUNT.getValue()).size());
Assert.assertEquals(0, customerPersistence.getAllClosedAccount(client.getCustomerId(),
AccountTypes.SAVINGS_ACCOUNT.getValue()).size());
}
public void testGetLOForCustomer() throws PersistenceException {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
Short LO = customerPersistence.getLoanOfficerForCustomer(center.getCustomerId());
Assert.assertEquals(center.getPersonnel().getPersonnelId(), LO);
}
public void testUpdateLOsForAllChildren() {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
Assert.assertEquals(center.getPersonnel().getPersonnelId(), group.getPersonnel().getPersonnelId());
Assert.assertEquals(center.getPersonnel().getPersonnelId(), client.getPersonnel().getPersonnelId());
StaticHibernateUtil.startTransaction();
PersonnelBO newLO = TestObjectFactory.getPersonnel(Short.valueOf("2"));
new CustomerPersistence().updateLOsForAllChildren(newLO.getPersonnelId(), center.getSearchId(), center
.getOffice().getOfficeId());
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
center = TestObjectFactory.getCenter(center.getCustomerId());
group = TestObjectFactory.getGroup(group.getCustomerId());
client = TestObjectFactory.getClient(client.getCustomerId());
Assert.assertEquals(newLO.getPersonnelId(), group.getPersonnel().getPersonnelId());
Assert.assertEquals(newLO.getPersonnelId(), client.getPersonnel().getPersonnelId());
}
public void testUpdateLOsForAllChildrenAccounts() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
Assert.assertEquals(center.getPersonnel().getPersonnelId(), group.getPersonnel().getPersonnelId());
Assert.assertEquals(center.getPersonnel().getPersonnelId(), client.getPersonnel().getPersonnelId());
StaticHibernateUtil.startTransaction();
PersonnelBO newLO = TestObjectFactory.getPersonnel(Short.valueOf("2"));
new CustomerPersistence().updateLOsForAllChildrenAccounts(newLO.getPersonnelId(), center.getSearchId(), center
.getOffice().getOfficeId());
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
client = TestObjectFactory.getClient(client.getCustomerId());
for (AccountBO account : client.getAccounts()) {
Assert.assertEquals(newLO.getPersonnelId(), account.getPersonnel().getPersonnelId());
}
}
public void testCustomerDeleteMeeting() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
client = TestObjectFactory.createClient("myClient", meeting, CustomerStatus.CLIENT_PENDING);
StaticHibernateUtil.closeSession();
client = TestObjectFactory.getClient(client.getCustomerId());
customerPersistence.deleteCustomerMeeting(client);
CustomerBOTestUtils.setCustomerMeeting(client, null);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
client = TestObjectFactory.getClient(client.getCustomerId());
Assert.assertNull(client.getCustomerMeeting());
}
public void testDeleteMeeting() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
StaticHibernateUtil.closeSession();
meeting = new MeetingPersistence().getMeeting(meeting.getMeetingId());
customerPersistence.deleteMeeting(meeting);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
meeting = new MeetingPersistence().getMeeting(meeting.getMeetingId());
Assert.assertNull(meeting);
}
public void testSearchWithOfficeId() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search("C", Short.valueOf("3"), Short.valueOf("1"), Short
.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(2, queryResult.getSize());
Assert.assertEquals(2, queryResult.get(0, 10).size());
}
public void testSearchWithoutOfficeId() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search("C", Short.valueOf("0"), Short.valueOf("1"), Short
.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(2, queryResult.getSize());
Assert.assertEquals(2, queryResult.get(0, 10).size());
}
public void testSearchWithGlobalNo() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search(group.getGlobalCustNum(), Short.valueOf("3"), Short
.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
public void testSearchWithGovernmentId() throws Exception {
createCustomersWithGovernmentId(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search("76346793216", Short.valueOf("3"), Short
.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
@SuppressWarnings("unchecked")
public void testSearchWithCancelLoanAccounts() throws Exception {
groupAccount = getLoanAccount();
groupAccount.changeStatus(AccountState.LOAN_CANCELLED.getValue(), AccountStateFlag.LOAN_WITHDRAW.getValue(),
"WITHDRAW LOAN ACCOUNT");
TestObjectFactory.updateObject(groupAccount);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
groupAccount = TestObjectFactory.getObject(LoanBO.class, groupAccount.getAccountId());
center = TestObjectFactory.getCustomer(center.getCustomerId());
group = TestObjectFactory.getCustomer(group.getCustomerId());
QueryResult queryResult = new CustomerPersistence().search(group.getGlobalCustNum(), Short.valueOf("3"), Short
.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
List results = queryResult.get(0, 10);
Assert.assertEquals(1, results.size());
CustomerSearch customerSearch = (CustomerSearch) results.get(0);
Assert.assertEquals(0, customerSearch.getLoanGlobalAccountNum().size());
}
public void testSearchWithAccountGlobalNo() throws Exception {
getCustomer();
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().search(groupAccount.getGlobalAccountNum(), Short
.valueOf("3"), Short.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
public void testSearchGropAndClient() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().searchGroupClient("C", Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
public void testSearchGropAndClientForLoNoResults() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting, Short.valueOf("3"), Short.valueOf("3"));
group = TestObjectFactory.createGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, "1234", true,
new java.util.Date(), null, null, null, Short.valueOf("3"), center);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().searchGroupClient("C", Short.valueOf("3"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(0, queryResult.getSize());
Assert.assertEquals(0, queryResult.get(0, 10).size());
}
public void testSearchGropAndClientForLo() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting, Short.valueOf("3"), Short.valueOf("3"));
group = TestObjectFactory.createGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, "1234", true,
new java.util.Date(), null, null, null, Short.valueOf("3"), center);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().searchGroupClient("G", Short.valueOf("3"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
Assert.assertEquals(1, queryResult.get(0, 10).size());
}
public void testSearchCustForSavings() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
QueryResult queryResult = new CustomerPersistence().searchCustForSavings("C", Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(2, queryResult.getSize());
Assert.assertEquals(2, queryResult.get(0, 10).size());
}
public void testGetCustomerAccountsForFee() throws Exception {
groupAccount = getLoanAccount();
FeeBO periodicFee = TestObjectFactory.createPeriodicAmountFee("ClientPeridoicFee", FeeCategory.CENTER, "5",
RecurrenceType.WEEKLY, Short.valueOf("1"));
AccountFeesEntity accountFee = new AccountFeesEntity(center.getCustomerAccount(), periodicFee,
((AmountFeeBO) periodicFee).getFeeAmount().getAmountDoubleValue());
CustomerAccountBO customerAccount = center.getCustomerAccount();
AccountTestUtils.addAccountFees(accountFee, customerAccount);
TestObjectFactory.updateObject(customerAccount);
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
// check for the account fee
List<AccountBO> accountList = new CustomerPersistence().getCustomerAccountsForFee(periodicFee.getFeeId());
Assert.assertNotNull(accountList);
Assert.assertEquals(1, accountList.size());
Assert.assertTrue(accountList.get(0) instanceof CustomerAccountBO);
// get all objects again
groupAccount = TestObjectFactory.getObject(LoanBO.class, groupAccount.getAccountId());
group = TestObjectFactory.getCustomer(group.getCustomerId());
center = TestObjectFactory.getCustomer(center.getCustomerId());
}
public void testRetrieveCustomerAccountActionDetails() throws Exception {
center = createCenter();
Assert.assertNotNull(center.getCustomerAccount());
List<AccountActionDateEntity> actionDates = new CustomerPersistence().retrieveCustomerAccountActionDetails(
center.getCustomerAccount().getAccountId(), new java.sql.Date(System.currentTimeMillis()));
Assert.assertEquals("The size of the due insallments is ", actionDates.size(), 1);
}
public void testGetActiveCentersUnderUser() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("center", meeting, Short.valueOf("1"), Short.valueOf("1"));
PersonnelBO personnel = TestObjectFactory.getPersonnel(Short.valueOf("1"));
List<CustomerBO> customers = new CustomerPersistence().getActiveCentersUnderUser(personnel);
Assert.assertNotNull(customers);
Assert.assertEquals(1, customers.size());
}
public void testgetGroupsUnderUser() throws Exception {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("center", meeting, Short.valueOf("1"), Short.valueOf("1"));
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
group2 = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group33", CustomerStatus.GROUP_CANCELLED, center);
PersonnelBO personnel = TestObjectFactory.getPersonnel(Short.valueOf("1"));
List<CustomerBO> customers = new CustomerPersistence().getGroupsUnderUser(personnel);
Assert.assertNotNull(customers);
Assert.assertEquals(1, customers.size());
}
@SuppressWarnings("unchecked")
public void testSearchForActiveInBadStandingLoanAccount() throws Exception {
groupAccount = getLoanAccount();
groupAccount.changeStatus(AccountState.LOAN_ACTIVE_IN_BAD_STANDING.getValue(), null, "Changing to badStanding");
TestObjectFactory.updateObject(groupAccount);
StaticHibernateUtil.closeSession();
groupAccount = TestObjectFactory.getObject(LoanBO.class, groupAccount.getAccountId());
center = TestObjectFactory.getCustomer(center.getCustomerId());
group = TestObjectFactory.getCustomer(group.getCustomerId());
QueryResult queryResult = new CustomerPersistence().search(group.getGlobalCustNum(), Short.valueOf("3"), Short
.valueOf("1"), Short.valueOf("1"));
Assert.assertNotNull(queryResult);
Assert.assertEquals(1, queryResult.getSize());
List results = queryResult.get(0, 10);
Assert.assertEquals(1, results.size());
CustomerSearch customerSearch = (CustomerSearch) results.get(0);
Assert.assertEquals(1, customerSearch.getLoanGlobalAccountNum().size());
}
public void testGetCustomersByLevelId() throws Exception {
createCustomers(CustomerStatus.GROUP_ACTIVE, CustomerStatus.CLIENT_ACTIVE);
StaticHibernateUtil.commitTransaction();
List<CustomerBO> client = new CustomerPersistence().getCustomersByLevelId(Short.parseShort("1"));
Assert.assertNotNull(client);
Assert.assertEquals(1, client.size());
List<CustomerBO> group = new CustomerPersistence().getCustomersByLevelId(Short.parseShort("2"));
Assert.assertNotNull(group);
Assert.assertEquals(1, group.size());
List<CustomerBO> center = new CustomerPersistence().getCustomersByLevelId(Short.parseShort("3"));
Assert.assertNotNull(center);
Assert.assertEquals(1, center.size());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsActiveCenter() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
verifyCustomerLoaded(center.getCustomerId(), center.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedDoesntReturnInactiveCenter() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Inactive Center", meeting);
center.changeStatus(CustomerStatus.CENTER_INACTIVE, CustomerStatusFlag.GROUP_CANCEL_BLACKLISTED, "Made Inactive");
StaticHibernateUtil.commitTransaction();
StaticHibernateUtil.closeSession();
center = (CenterBO) StaticHibernateUtil.getSessionTL().get(CenterBO.class, center.getCustomerId());
verifyCustomerNotLoaded(center.getCustomerId(), center.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsActiveGroup() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Active Group", CustomerStatus.GROUP_ACTIVE,
center);
verifyCustomerLoaded(group.getCustomerId(), group.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsHoldGroup() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Hold Group", CustomerStatus.GROUP_HOLD,
center);
verifyCustomerLoaded(group.getCustomerId(), group.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedDoesntReturnClosedGroup() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Closed Group", CustomerStatus.GROUP_CLOSED,
center);
verifyCustomerNotLoaded(group.getCustomerId(), group.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsActiveClient() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Active Group", CustomerStatus.GROUP_ACTIVE,
center);
client = TestObjectFactory.createClient("Active Client", CustomerStatus.CLIENT_ACTIVE, group);
verifyCustomerLoaded(client.getCustomerId(), client.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedReturnsHoldClient() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Active Group", CustomerStatus.GROUP_ACTIVE,
center);
client = TestObjectFactory.createClient("Hold Client", CustomerStatus.CLIENT_HOLD, group);
verifyCustomerLoaded(client.getCustomerId(), client.getDisplayName());
}
public void testFindCustomerWithNoAssocationsLoadedDoesntReturnClosedClient() throws Exception {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY,
EVERY_WEEK, CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Active Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Active Group", CustomerStatus.GROUP_ACTIVE,
center);
client = TestObjectFactory.createClient("Closed Client", CustomerStatus.CLIENT_CLOSED, group);
verifyCustomerNotLoaded(client.getCustomerId(), client.getDisplayName());
}
private void verifyCustomerLoaded(Integer customerId, String customerName) {
CollectionSheetCustomerDto collectionSheetCustomerDto = customerPersistence
.findCustomerWithNoAssocationsLoaded(customerId);
Assert.assertNotNull(customerName + " was not returned", collectionSheetCustomerDto);
Assert.assertEquals(collectionSheetCustomerDto.getCustomerId(), customerId);
}
private void verifyCustomerNotLoaded(Integer customerId, String customerName) {
CollectionSheetCustomerDto collectionSheetCustomerDto = customerPersistence
.findCustomerWithNoAssocationsLoaded(customerId);
Assert.assertNull(customerName + " was returned", collectionSheetCustomerDto);
}
private AccountBO getSavingsAccount(final CustomerBO customer, final String prdOfferingname, final String shortName)
throws Exception {
Date startDate = new Date(System.currentTimeMillis());
SavingsOfferingBO savingsOffering = TestObjectFactory.createSavingsProduct(prdOfferingname, shortName,
startDate, RecommendedAmountUnit.COMPLETE_GROUP);
return TestObjectFactory.createSavingsAccount("432434", customer, Short.valueOf("16"), startDate,
savingsOffering);
}
private void getCustomer() throws Exception {
Date startDate = new Date(System.currentTimeMillis());
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
client = TestObjectFactory.createClient("Client", CustomerStatus.CLIENT_ACTIVE, group);
LoanOfferingBO loanOffering1 = TestObjectFactory.createLoanOffering("Loanwer", "43fs", startDate, meeting);
LoanOfferingBO loanOffering2 = TestObjectFactory.createLoanOffering("Loancd123", "vfr", startDate, meeting);
groupAccount = TestObjectFactory.createLoanAccount("42423142341", group,
AccountState.LOAN_ACTIVE_IN_GOOD_STANDING, startDate, loanOffering1);
clientAccount = TestObjectFactory.createLoanAccount("3243", client, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
startDate, loanOffering2);
MeetingBO meetingIntCalc = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
MeetingBO meetingIntPost = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
SavingsOfferingBO savingsOffering = TestObjectFactory.createSavingsProduct("SavingPrd12", "abc1", startDate,
RecommendedAmountUnit.COMPLETE_GROUP, meetingIntCalc, meetingIntPost);
SavingsOfferingBO savingsOffering1 = TestObjectFactory.createSavingsProduct("SavingPrd11", "abc2", startDate,
RecommendedAmountUnit.COMPLETE_GROUP, meetingIntCalc, meetingIntPost);
centerSavingsAccount = TestObjectFactory.createSavingsAccount("432434", center, Short.valueOf("16"), startDate,
savingsOffering);
clientSavingsAccount = TestObjectFactory.createSavingsAccount("432434", client, Short.valueOf("16"), startDate,
savingsOffering1);
}
private void createCustomers(final CustomerStatus groupStatus, final CustomerStatus clientStatus) {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", groupStatus, center);
client = TestObjectFactory.createClient("Client", clientStatus, group);
}
private void createCustomersWithGovernmentId(final CustomerStatus groupStatus, final CustomerStatus clientStatus) {
meeting = TestObjectFactory.createMeeting(TestObjectFactory.getTypicalMeeting());
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", groupStatus, center);
client = TestObjectFactory.createClient("Client", clientStatus, group, TestObjectFactory.getFees(), "76346793216", new java.util.Date(1222333444000L));
}
private static java.util.Date getMeetingDates(final MeetingBO meeting) {
List<java.util.Date> dates = new ArrayList<java.util.Date>();
try {
dates = meeting.getAllDates(new java.util.Date(System.currentTimeMillis()));
} catch (MeetingException e) {
e.printStackTrace();
}
return dates.get(dates.size() - 1);
}
private CenterBO createCenter() {
return createCenter("Center_Active_test");
}
private CenterBO createCenter(final String name) {
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
return TestObjectFactory.createWeeklyFeeCenter(name, meeting);
}
private LoanBO getLoanAccount() {
Date startDate = new Date(System.currentTimeMillis());
MeetingBO meeting = TestObjectFactory.createMeeting(TestObjectFactory.getNewMeetingForToday(WEEKLY, EVERY_WEEK,
CUSTOMER_MEETING));
center = TestObjectFactory.createWeeklyFeeCenter("Center", meeting);
group = TestObjectFactory.createWeeklyFeeGroupUnderCenter("Group", CustomerStatus.GROUP_ACTIVE, center);
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(startDate, meeting);
return TestObjectFactory.createLoanAccount("42423142341", group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
startDate, loanOffering);
}
private AccountBO getLoanAccount(final CustomerBO group, final MeetingBO meeting, final String offeringName,
final String shortName) {
Date startDate = new Date(System.currentTimeMillis());
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(offeringName, shortName, startDate, meeting);
return TestObjectFactory.createLoanAccount("42423142341", group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
startDate, loanOffering);
}
private AccountBO getLoanAccount(final CustomerBO group, final MeetingBO meeting, final String offeringName,
final String shortName, MifosCurrency currency) {
Date startDate = new Date(System.currentTimeMillis());
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(offeringName, shortName, startDate, meeting, currency);
return TestObjectFactory.createLoanAccount("42423142341", group, AccountState.LOAN_ACTIVE_IN_GOOD_STANDING,
startDate, loanOffering);
}
private AccountBO getLoanAccountInActiveBadStanding(final CustomerBO group, final MeetingBO meeting,
final String offeringName, final String shortName) {
Date startDate = new Date(System.currentTimeMillis());
LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering(offeringName, shortName, startDate, meeting);
return TestObjectFactory.createLoanAccount("42423141111", group, AccountState.LOAN_ACTIVE_IN_BAD_STANDING,
startDate, loanOffering);
}
}
| mifos/1.5.x | application/src/test/java/org/mifos/customers/persistence/CustomerPersistenceIntegrationTest.java | Java | apache-2.0 | 73,142 |
/**
*
* @author Alex Karpov (mailto:[email protected])
* @version $Id$
* @since 0.1
*/
package ru.job4j.max; | AlekseyKarpov/akarpov | chapter_001/src/test/java/ru/job4j/max/package-info.java | Java | apache-2.0 | 113 |
package com.capgemini.resilience.employer.service;
public interface ErrorSimulationService {
void generateErrorDependingOnErrorPossibility();
}
| microservices-summit-2016/resilience-demo | employer-service/src/main/java/com/capgemini/resilience/employer/service/ErrorSimulationService.java | Java | apache-2.0 | 150 |
using UnityEngine;
using System.Collections;
public class blockGenerator : MonoBehaviour {
public int spawnRate = 1;
private float timeSinceLastSpawn = 0;
public GameObject oneCube;
public int count;
// Use this for initialization
void Start () {
//Debug.Log("ran cube creator");
count = 0;
}
// Update is called once per frame
void Update () {
//timeSinceLastSpawn += Time.realtimeSinceStartup;
//Debug.Log("running cube creator" + timeSinceLastSpawn );
// if ( timeSinceLastSpawn > spawnRate )
// {
//Clone the cubes and randomly place them
count = count + 1;
if (count.Equals(50)) {
GameObject newCube = (GameObject)GameObject.Instantiate (oneCube);
newCube.transform.position = new Vector3 (0, 0, 20.0f);
newCube.transform.Translate (Random.Range (-8, 8), Random.Range (0, 8), 1.0f);
timeSinceLastSpawn = 0;
//Debug.Log("cube created");
// }
count = 0;
}
}
} | josejlm2/HackTx2014 | Assets/Resources/Scripts/blockGenerator.cs | C# | apache-2.0 | 938 |
// -----------------------------------------------------------------------
// <copyright file="Health.cs" company="PlayFab Inc">
// Copyright 2015 PlayFab Inc.
//
// 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.
// </copyright>
// -----------------------------------------------------------------------
using System.Threading;
using System.Threading.Tasks;
namespace Consul
{
public interface IHealthEndpoint
{
Task<QueryResult<HealthCheck[]>> Checks(string service, CancellationToken ct = default(CancellationToken));
Task<QueryResult<HealthCheck[]>> Checks(string service, QueryOptions q, CancellationToken ct = default(CancellationToken));
Task<QueryResult<HealthCheck[]>> Node(string node, CancellationToken ct = default(CancellationToken));
Task<QueryResult<HealthCheck[]>> Node(string node, QueryOptions q, CancellationToken ct = default(CancellationToken));
Task<QueryResult<ServiceEntry[]>> Service(string service, CancellationToken ct = default(CancellationToken));
Task<QueryResult<ServiceEntry[]>> Service(string service, string tag, CancellationToken ct = default(CancellationToken));
Task<QueryResult<ServiceEntry[]>> Service(string service, string tag, bool passingOnly, CancellationToken ct = default(CancellationToken));
Task<QueryResult<ServiceEntry[]>> Service(string service, string tag, bool passingOnly, QueryOptions q, CancellationToken ct = default(CancellationToken));
Task<QueryResult<HealthCheck[]>> State(HealthStatus status, CancellationToken ct = default(CancellationToken));
Task<QueryResult<HealthCheck[]>> State(HealthStatus status, QueryOptions q, CancellationToken ct = default(CancellationToken));
}
} | PlayFab/consuldotnet | Consul/Interfaces/IHealthEndpoint.cs | C# | apache-2.0 | 2,271 |
////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
////////////////////////////////////////////////////////////////////////////////
#include "RestHandler.h"
#include "Basics/StringUtils.h"
#include "Dispatcher/Dispatcher.h"
#include "Logger/Logger.h"
#include "Rest/GeneralRequest.h"
using namespace arangodb;
using namespace arangodb::basics;
using namespace arangodb::rest;
namespace {
std::atomic_uint_fast64_t NEXT_HANDLER_ID(
static_cast<uint64_t>(TRI_microtime() * 100000.0));
}
RestHandler::RestHandler(GeneralRequest* request, GeneralResponse* response)
: _handlerId(NEXT_HANDLER_ID.fetch_add(1, std::memory_order_seq_cst)),
_taskId(0),
_request(request),
_response(response) {}
RestHandler::~RestHandler() {
delete _request;
delete _response;
}
void RestHandler::setTaskId(uint64_t id, EventLoop loop) {
_taskId = id;
_loop = loop;
}
RestHandler::status RestHandler::executeFull() {
RestHandler::status result = status::FAILED;
requestStatisticsAgentSetRequestStart();
#ifdef USE_DEV_TIMERS
TRI_request_statistics_t::STATS = _statistics;
#endif
try {
prepareExecute();
try {
result = execute();
} catch (Exception const& ex) {
requestStatisticsAgentSetExecuteError();
handleError(ex);
} catch (std::bad_alloc const& ex) {
requestStatisticsAgentSetExecuteError();
Exception err(TRI_ERROR_OUT_OF_MEMORY, ex.what(), __FILE__, __LINE__);
handleError(err);
} catch (std::exception const& ex) {
requestStatisticsAgentSetExecuteError();
Exception err(TRI_ERROR_INTERNAL, ex.what(), __FILE__, __LINE__);
handleError(err);
} catch (...) {
requestStatisticsAgentSetExecuteError();
Exception err(TRI_ERROR_INTERNAL, __FILE__, __LINE__);
handleError(err);
}
finalizeExecute();
if (result != status::ASYNC && _response == nullptr) {
Exception err(TRI_ERROR_INTERNAL, "no response received from handler",
__FILE__, __LINE__);
handleError(err);
}
} catch (Exception const& ex) {
result = status::FAILED;
requestStatisticsAgentSetExecuteError();
LOG(ERR) << "caught exception: " << DIAGNOSTIC_INFORMATION(ex);
} catch (std::exception const& ex) {
result = status::FAILED;
requestStatisticsAgentSetExecuteError();
LOG(ERR) << "caught exception: " << ex.what();
} catch (...) {
result = status::FAILED;
requestStatisticsAgentSetExecuteError();
LOG(ERR) << "caught exception";
}
requestStatisticsAgentSetRequestEnd();
#ifdef USE_DEV_TIMERS
TRI_request_statistics_t::STATS = nullptr;
#endif
return result;
}
GeneralRequest* RestHandler::stealRequest() {
GeneralRequest* tmp = _request;
_request = nullptr;
return tmp;
}
GeneralResponse* RestHandler::stealResponse() {
GeneralResponse* tmp = _response;
_response = nullptr;
return tmp;
}
void RestHandler::setResponseCode(GeneralResponse::ResponseCode code) {
TRI_ASSERT(_response != nullptr);
_response->reset(code);
}
| m0ppers/arangodb | arangod/GeneralServer/RestHandler.cpp | C++ | apache-2.0 | 3,855 |
package com.box.boxjavalibv2.responseparsers;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import junit.framework.Assert;
import org.apache.commons.io.IOUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicHttpResponse;
import org.easymock.EasyMock;
import org.junit.Before;
import org.junit.Test;
import com.box.boxjavalibv2.dao.BoxPreview;
import com.box.restclientv2.exceptions.BoxRestException;
import com.box.restclientv2.responses.DefaultBoxResponse;
public class PreviewResponseParserTest {
private final static String PREVIEW_MOCK_CONTENT = "arbitrary string";
private final static String LINK_VALUE = "<https://api.box.com/2.0/files/5000369410/preview.png?page=%d>; rel=\"first\", <https://api.box.com/2.0/files/5000369410/preview.png?page=%d>; rel=\"last\"";
private final static String LINK_NAME = "Link";
private final static int firstPage = 1;
private final static int lastPage = 2;
private final static double length = 213;
private BoxPreview preview;
private DefaultBoxResponse boxResponse;
private HttpResponse response;
private HttpEntity entity;
private InputStream inputStream;
private Header header;
@Before
public void setUp() {
preview = new BoxPreview();
preview.setFirstPage(firstPage);
preview.setLastPage(lastPage);
boxResponse = EasyMock.createMock(DefaultBoxResponse.class);
response = EasyMock.createMock(BasicHttpResponse.class);
entity = EasyMock.createMock(StringEntity.class);
header = new BasicHeader("Link", String.format(LINK_VALUE, firstPage, lastPage));
}
@Test
public void testCanParsePreview() throws IllegalStateException, IOException, BoxRestException {
EasyMock.reset(boxResponse, response, entity);
inputStream = new ByteArrayInputStream(PREVIEW_MOCK_CONTENT.getBytes());
EasyMock.expect(boxResponse.getHttpResponse()).andReturn(response);
EasyMock.expect(boxResponse.getContentLength()).andReturn(length);
EasyMock.expect(response.getEntity()).andReturn(entity);
EasyMock.expect(entity.getContent()).andReturn(inputStream);
EasyMock.expect(boxResponse.getHttpResponse()).andReturn(response);
EasyMock.expect(response.getFirstHeader("Link")).andReturn(header);
EasyMock.replay(boxResponse, response, entity);
PreviewResponseParser parser = new PreviewResponseParser();
Object object = parser.parse(boxResponse);
Assert.assertEquals(BoxPreview.class, object.getClass());
BoxPreview parsed = (BoxPreview) object;
Assert.assertEquals(length, parsed.getContentLength());
Assert.assertEquals(firstPage, parsed.getFirstPage().intValue());
Assert.assertEquals(lastPage, parsed.getLastPage().intValue());
Assert.assertEquals(PREVIEW_MOCK_CONTENT, IOUtils.toString(parsed.getContent()));
EasyMock.verify(boxResponse, response, entity);
}
}
| shelsonjava/box-java-sdk-v2 | BoxJavaLibraryV2/tst/com/box/boxjavalibv2/responseparsers/PreviewResponseParserTest.java | Java | apache-2.0 | 3,189 |
// Copyright (C) 2018 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.git.receive;
import com.google.common.collect.ImmutableList;
import com.google.gerrit.reviewdb.client.Change;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
/**
* Keeps track of the change IDs thus far updated by ReceiveCommit.
*
* <p>This class is thread-safe.
*/
public class ResultChangeIds {
public enum Key {
CREATED,
REPLACED,
AUTOCLOSED,
}
private boolean isMagicPush;
private final Map<Key, List<Change.Id>> ids;
ResultChangeIds() {
ids = new EnumMap<>(Key.class);
for (Key k : Key.values()) {
ids.put(k, new ArrayList<>());
}
}
/** Record a change ID update as having completed. Thread-safe. */
public synchronized void add(Key key, Change.Id id) {
ids.get(key).add(id);
}
/** Indicate that the ReceiveCommits call involved a magic branch. */
public synchronized void setMagicPush(boolean magic) {
isMagicPush = magic;
}
public synchronized boolean isMagicPush() {
return isMagicPush;
}
/**
* Returns change IDs of the given type for which the BatchUpdate succeeded, or empty list if
* there are none. Thread-safe.
*/
public synchronized List<Change.Id> get(Key key) {
return ImmutableList.copyOf(ids.get(key));
}
}
| qtproject/qtqa-gerrit | java/com/google/gerrit/server/git/receive/ResultChangeIds.java | Java | apache-2.0 | 1,920 |
# Copyright 2016 The Meson development team
# 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.
import os
import subprocess
import shutil
import argparse
from .. import mlog
from ..mesonlib import has_path_sep
from . import destdir_join
from .gettext import read_linguas
parser = argparse.ArgumentParser()
parser.add_argument('command')
parser.add_argument('--id', dest='project_id')
parser.add_argument('--subdir', dest='subdir')
parser.add_argument('--installdir', dest='install_dir')
parser.add_argument('--sources', dest='sources')
parser.add_argument('--media', dest='media', default='')
parser.add_argument('--langs', dest='langs', default='')
parser.add_argument('--symlinks', type=bool, dest='symlinks', default=False)
def build_pot(srcdir, project_id, sources):
# Must be relative paths
sources = [os.path.join('C', source) for source in sources]
outfile = os.path.join(srcdir, project_id + '.pot')
subprocess.call(['itstool', '-o', outfile] + sources)
def update_po(srcdir, project_id, langs):
potfile = os.path.join(srcdir, project_id + '.pot')
for lang in langs:
pofile = os.path.join(srcdir, lang, lang + '.po')
subprocess.call(['msgmerge', '-q', '-o', pofile, pofile, potfile])
def build_translations(srcdir, blddir, langs):
for lang in langs:
outdir = os.path.join(blddir, lang)
os.makedirs(outdir, exist_ok=True)
subprocess.call([
'msgfmt', os.path.join(srcdir, lang, lang + '.po'),
'-o', os.path.join(outdir, lang + '.gmo')
])
def merge_translations(blddir, sources, langs):
for lang in langs:
subprocess.call([
'itstool', '-m', os.path.join(blddir, lang, lang + '.gmo'),
'-o', os.path.join(blddir, lang)
] + sources)
def install_help(srcdir, blddir, sources, media, langs, install_dir, destdir, project_id, symlinks):
c_install_dir = os.path.join(install_dir, 'C', project_id)
for lang in langs + ['C']:
indir = destdir_join(destdir, os.path.join(install_dir, lang, project_id))
os.makedirs(indir, exist_ok=True)
for source in sources:
infile = os.path.join(srcdir if lang == 'C' else blddir, lang, source)
outfile = os.path.join(indir, source)
mlog.log('Installing %s to %s' % (infile, outfile))
shutil.copyfile(infile, outfile)
shutil.copystat(infile, outfile)
for m in media:
infile = os.path.join(srcdir, lang, m)
outfile = os.path.join(indir, m)
c_infile = os.path.join(srcdir, 'C', m)
if not os.path.exists(infile):
if not os.path.exists(c_infile):
mlog.warning('Media file "%s" did not exist in C directory' % m)
continue
elif symlinks:
srcfile = os.path.join(c_install_dir, m)
mlog.log('Symlinking %s to %s.' % (outfile, srcfile))
if has_path_sep(m):
os.makedirs(os.path.dirname(outfile), exist_ok=True)
try:
try:
os.symlink(srcfile, outfile)
except FileExistsError:
os.remove(outfile)
os.symlink(srcfile, outfile)
continue
except (NotImplementedError, OSError):
mlog.warning('Symlinking not supported, falling back to copying')
infile = c_infile
else:
# Lang doesn't have media file so copy it over 'C' one
infile = c_infile
mlog.log('Installing %s to %s' % (infile, outfile))
if has_path_sep(m):
os.makedirs(os.path.dirname(outfile), exist_ok=True)
shutil.copyfile(infile, outfile)
shutil.copystat(infile, outfile)
def run(args):
options = parser.parse_args(args)
langs = options.langs.split('@@') if options.langs else []
media = options.media.split('@@') if options.media else []
sources = options.sources.split('@@')
destdir = os.environ.get('DESTDIR', '')
src_subdir = os.path.join(os.environ['MESON_SOURCE_ROOT'], options.subdir)
build_subdir = os.path.join(os.environ['MESON_BUILD_ROOT'], options.subdir)
abs_sources = [os.path.join(src_subdir, 'C', source) for source in sources]
if not langs:
langs = read_linguas(src_subdir)
if options.command == 'pot':
build_pot(src_subdir, options.project_id, sources)
elif options.command == 'update-po':
build_pot(src_subdir, options.project_id, sources)
update_po(src_subdir, options.project_id, langs)
elif options.command == 'build':
if langs:
build_translations(src_subdir, build_subdir, langs)
elif options.command == 'install':
install_dir = os.path.join(os.environ['MESON_INSTALL_PREFIX'], options.install_dir)
if langs:
build_translations(src_subdir, build_subdir, langs)
merge_translations(build_subdir, abs_sources, langs)
install_help(src_subdir, build_subdir, sources, media, langs, install_dir,
destdir, options.project_id, options.symlinks)
| becm/meson | mesonbuild/scripts/yelphelper.py | Python | apache-2.0 | 5,816 |
package com.veneweather.android;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.veneweather.android.db.City;
import com.veneweather.android.db.County;
import com.veneweather.android.db.Province;
import com.veneweather.android.util.HttpUtil;
import com.veneweather.android.util.Utility;
import org.litepal.crud.DataSupport;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
/**
* Created by lenovo on 2017/4/10.
*/
public class ChooseAreaFragment extends Fragment {
public static final int LEVEL_PROVINCE = 0;
public static final int LEVEL_CITY = 1;
public static final int LEVEL_COUNTY = 2;
private ProgressDialog progressDialog;
private TextView titleText;
private Button btn_back;
private ListView listView;
private ArrayAdapter<String> adapter;
private List<String> dataList = new ArrayList<>();
/**
* 省列表
*/
private List<Province> provinceList;
/**
* 市列表
*/
private List<City> cityList;
/**
* 县列表
*/
private List<County> countyList;
/**
* 选中的省份
*/
private Province selectedProvince;
/**
* 选中的城市
*/
private City selectedCity;
/**
* 当前选中的级别
*/
private int currentLevel;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.choose_area, container, false);
titleText = (TextView) view.findViewById(R.id.title_text);
btn_back = (Button) view.findViewById(R.id.back_button);
listView = (ListView) view.findViewById(R.id.list_view);
adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
if (currentLevel == LEVEL_PROVINCE) {
selectedProvince = provinceList.get(position);
queryCities();
} else if (currentLevel == LEVEL_CITY) {
selectedCity = cityList.get(position);
queryCounties();
} else if (currentLevel == LEVEL_COUNTY) {
String weatherId = countyList.get(position).getWeatherId();
if (getActivity() instanceof MainActivity) {
Intent intent = new Intent(getActivity(), WeatherActivity.class);
intent.putExtra("weather_id", weatherId);
startActivity(intent);
getActivity().finish();
} else if (getActivity() instanceof WeatherActivity) {
WeatherActivity activity = (WeatherActivity) getActivity();
activity.drawerLayout.closeDrawers();
activity.swipeRefresh.setRefreshing(true);
activity.requestWeather(weatherId);
}
}
}
});
btn_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (currentLevel == LEVEL_CITY) {
queryProvinces();
} else if (currentLevel == LEVEL_COUNTY) {
queryCities();
}
}
});
queryProvinces();
}
/**
* 查询全国所有的省,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private void queryProvinces() {
titleText.setText("中国");
btn_back.setVisibility(View.GONE);
provinceList = DataSupport.findAll(Province.class);
if (provinceList.size() > 0) {
dataList.clear();
for (Province province : provinceList) {
dataList.add(province.getProvinceName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_PROVINCE;
} else {
String address = "http://guolin.tech/api/china";
queryFromServer(address, "province");
}
}
/**
* 查询选中省内所有市,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private void queryCities() {
titleText.setText(selectedProvince.getProvinceName());
btn_back.setVisibility(View.VISIBLE);
cityList = DataSupport.where("provinceid = ?", String.valueOf(selectedProvince.getId())).find(City.class);
if (cityList.size() > 0) {
dataList.clear();
for (City city : cityList) {
dataList.add(city.getCityName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_CITY;
} else {
int provinceCode = selectedProvince.getProvinceCode();
String address = "http://guolin.tech/api/china/" + provinceCode;
queryFromServer(address, "city");
}
}
/**
* 查询选中市内所有县,优先从数据库查询,如果没有查询到再去服务器上查询
*/
private void queryCounties() {
titleText.setText(selectedCity.getCityName());
btn_back.setVisibility(View.VISIBLE);
countyList = DataSupport.where("cityid = ?", String.valueOf(selectedCity.getId())).find(County.class);
if (countyList.size() > 0) {
dataList.clear();
for (County county : countyList) {
dataList.add(county.getCountyName());
}
adapter.notifyDataSetChanged();
listView.setSelection(0);
currentLevel = LEVEL_COUNTY;
} else {
int provinceCode = selectedProvince.getProvinceCode();
int cityCode = selectedCity.getCitycode();
String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode;
queryFromServer(address, "county");
}
}
/**
* 根据传入的地址和类型从服务器上查询省市县数据
*/
private void queryFromServer(String address, final String type) {
showProgressDialog();
HttpUtil.sendOkHttpRequest(address, new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
String responseText = response.body().string();
boolean result = false;
if ("province".equals(type)) {
result = Utility.handleProvinceResponse(responseText);
} else if ("city".equals(type)) {
result = Utility.handleCityResponse(responseText, selectedProvince.getId());
} else if ("county".equals(type)) {
result = Utility.handleCountyResponse(responseText, selectedCity.getId());
}
if (result) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
if ("province".equals(type)) {
queryProvinces();
} else if ("city".equals(type)) {
queryCities();
} else if ("county".equals(type)) {
queryCounties();
}
}
});
}
}
@Override
public void onFailure(Call call, IOException e) {
// 通过runOnUiThread()方法回到主线程处理逻辑
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
closeProgressDialog();
Toast.makeText(getContext(), "加载失败", Toast.LENGTH_SHORT).show();
}
});
}
});
}
/**
* 显示进度对话框
*/
private void showProgressDialog() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("正在加载...");
progressDialog.setCanceledOnTouchOutside(false);
}
progressDialog.show();
}
/**
* 关闭进度对话框
*/
private void closeProgressDialog() {
if (progressDialog != null) {
progressDialog.dismiss();
}
}
}
| Ackerm-Zed/veneweather | app/src/main/java/com/veneweather/android/ChooseAreaFragment.java | Java | apache-2.0 | 9,584 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_152-ea) on Sat Jul 29 21:49:13 PDT 2017 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.fasterxml.jackson.datatype.jsr310.ser.YearMonthSerializer (Jackson datatype: JSR310 2.9.0 API)</title>
<meta name="date" content="2017-07-29">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.fasterxml.jackson.datatype.jsr310.ser.YearMonthSerializer (Jackson datatype: JSR310 2.9.0 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html" title="class in com.fasterxml.jackson.datatype.jsr310.ser">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/fasterxml/jackson/datatype/jsr310/ser/class-use/YearMonthSerializer.html" target="_top">Frames</a></li>
<li><a href="YearMonthSerializer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.fasterxml.jackson.datatype.jsr310.ser.YearMonthSerializer" class="title">Uses of Class<br>com.fasterxml.jackson.datatype.jsr310.ser.YearMonthSerializer</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html" title="class in com.fasterxml.jackson.datatype.jsr310.ser">YearMonthSerializer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.fasterxml.jackson.datatype.jsr310.ser">com.fasterxml.jackson.datatype.jsr310.ser</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.fasterxml.jackson.datatype.jsr310.ser">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html" title="class in com.fasterxml.jackson.datatype.jsr310.ser">YearMonthSerializer</a> in <a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/package-summary.html">com.fasterxml.jackson.datatype.jsr310.ser</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation">
<caption><span>Fields in <a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/package-summary.html">com.fasterxml.jackson.datatype.jsr310.ser</a> declared as <a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html" title="class in com.fasterxml.jackson.datatype.jsr310.ser">YearMonthSerializer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html" title="class in com.fasterxml.jackson.datatype.jsr310.ser">YearMonthSerializer</a></code></td>
<td class="colLast"><span class="typeNameLabel">YearMonthSerializer.</span><code><span class="memberNameLink"><a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html#INSTANCE">INSTANCE</a></span></code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/package-summary.html">com.fasterxml.jackson.datatype.jsr310.ser</a> that return <a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html" title="class in com.fasterxml.jackson.datatype.jsr310.ser">YearMonthSerializer</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>protected <a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html" title="class in com.fasterxml.jackson.datatype.jsr310.ser">YearMonthSerializer</a></code></td>
<td class="colLast"><span class="typeNameLabel">YearMonthSerializer.</span><code><span class="memberNameLink"><a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html#withFormat-java.lang.Boolean-java.time.format.DateTimeFormatter-com.fasterxml.jackson.annotation.JsonFormat.Shape-">withFormat</a></span>(<a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html?is-external=true" title="class or interface in java.lang">Boolean</a> useTimestamp,
java.time.format.DateTimeFormatter formatter,
com.fasterxml.jackson.annotation.JsonFormat.Shape shape)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../com/fasterxml/jackson/datatype/jsr310/ser/YearMonthSerializer.html" title="class in com.fasterxml.jackson.datatype.jsr310.ser">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?com/fasterxml/jackson/datatype/jsr310/ser/class-use/YearMonthSerializer.html" target="_top">Frames</a></li>
<li><a href="YearMonthSerializer.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2017 <a href="http://fasterxml.com/">FasterXML</a>. All rights reserved.</small></p>
</body>
</html>
| FasterXML/jackson-modules-java8 | docs/javadoc/datetime/2.9/com/fasterxml/jackson/datatype/jsr310/ser/class-use/YearMonthSerializer.html | HTML | apache-2.0 | 8,998 |
#
#Programa Lista 4, questão 1;
#Felipe Henrique Bastos Costa - 1615310032;
#
#
#
#
lista = []#lista vazia;
cont1 = 0#contador do indice;
cont2 = 1#contador da posição do numero, se é o primeiro, segundo etc;
v = 5#representaria o len da lista;
while(cont1 < v):
x = int(input("Informe o %dº numero inteiro para colocar em sua lista:\n"%cont2))#x e a variavel que recebe
#o numero do usuario
lista.append(x)#o numero informado para x e colocado dentro da lista;
cont1+=1#Os contadores estao
cont2+=1#sendo incrementados;
print("A lista de informada foi:\n%s"%lista)
| any1m1c/ipc20161 | lista4/ipc_lista4.01.py | Python | apache-2.0 | 675 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.