repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
danieloostra/mean-charlie-workspace
|
scott/FULL_MEAN/Friends/server/models/friend.js
|
148
|
var mongoose = require('mongoose');
var FriendSchema = new mongoose.Schema({
name: String
})
var Friend = mongoose.model('Friend', FriendSchema);
|
unlicense
|
codeApeFromChina/resource
|
frame_packages/java_libs/spring-2.5.6-src/src/org/springframework/web/servlet/tags/form/InputTag.java
|
4652
|
/*
* Copyright 2002-2008 the original author or authors.
*
* 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.springframework.web.servlet.tags.form;
import javax.servlet.jsp.JspException;
/**
* Data-binding-aware JSP tag for rendering an HTML '<code>input</code>'
* element with a '<code>type</code>' of '<code>text</code>'.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 2.0
*/
public class InputTag extends AbstractHtmlInputElementTag {
public static final String SIZE_ATTRIBUTE = "size";
public static final String MAXLENGTH_ATTRIBUTE = "maxlength";
public static final String ALT_ATTRIBUTE = "alt";
public static final String ONSELECT_ATTRIBUTE = "onselect";
public static final String READONLY_ATTRIBUTE = "readonly";
public static final String AUTOCOMPLETE_ATTRIBUTE = "autocomplete";
private String size;
private String maxlength;
private String alt;
private String onselect;
private String autocomplete;
/**
* Set the value of the '<code>size</code>' attribute.
* May be a runtime expression.
*/
public void setSize(String size) {
this.size = size;
}
/**
* Get the value of the '<code>size</code>' attribute.
*/
protected String getSize() {
return this.size;
}
/**
* Set the value of the '<code>maxlength</code>' attribute.
* May be a runtime expression.
*/
public void setMaxlength(String maxlength) {
this.maxlength = maxlength;
}
/**
* Get the value of the '<code>maxlength</code>' attribute.
*/
protected String getMaxlength() {
return this.maxlength;
}
/**
* Set the value of the '<code>alt</code>' attribute.
* May be a runtime expression.
*/
public void setAlt(String alt) {
this.alt = alt;
}
/**
* Get the value of the '<code>alt</code>' attribute.
*/
protected String getAlt() {
return this.alt;
}
/**
* Set the value of the '<code>onselect</code>' attribute.
* May be a runtime expression.
*/
public void setOnselect(String onselect) {
this.onselect = onselect;
}
/**
* Get the value of the '<code>onselect</code>' attribute.
*/
protected String getOnselect() {
return this.onselect;
}
/**
* Set the value of the '<code>autocomplete</code>' attribute.
* May be a runtime expression.
*/
public void setAutocomplete(String autocomplete) {
this.autocomplete = autocomplete;
}
/**
* Get the value of the '<code>autocomplete</code>' attribute.
*/
protected String getAutocomplete() {
return this.autocomplete;
}
/**
* Writes the '<code>input</code>' tag to the supplied {@link TagWriter}.
* Uses the value returned by {@link #getType()} to determine which
* type of '<code>input</code>' element to render.
*/
protected int writeTagContent(TagWriter tagWriter) throws JspException {
tagWriter.startTag("input");
writeDefaultAttributes(tagWriter);
tagWriter.writeAttribute("type", getType());
writeValue(tagWriter);
// custom optional attributes
writeOptionalAttribute(tagWriter, SIZE_ATTRIBUTE, getSize());
writeOptionalAttribute(tagWriter, MAXLENGTH_ATTRIBUTE, getMaxlength());
writeOptionalAttribute(tagWriter, ALT_ATTRIBUTE, getAlt());
writeOptionalAttribute(tagWriter, ONSELECT_ATTRIBUTE, getOnselect());
writeOptionalAttribute(tagWriter, AUTOCOMPLETE_ATTRIBUTE, getAutocomplete());
tagWriter.endTag();
return SKIP_BODY;
}
/**
* Writes the '<code>value</code>' attribute to the supplied {@link TagWriter}.
* Subclasses may choose to override this implementation to control exactly
* when the value is written.
*/
protected void writeValue(TagWriter tagWriter) throws JspException {
tagWriter.writeAttribute("value", getDisplayString(getBoundValue(), getPropertyEditor()));
}
/**
* Get the value of the '<code>type</code>' attribute. Subclasses
* can override this to change the type of '<code>input</code>' element
* rendered. Default value is '<code>text</code>'.
*/
protected String getType() {
return "text";
}
}
|
unlicense
|
hernan940730/DrawingApplication
|
src/view/RectangleTool.java
|
539
|
package view;
import controller.App;
public class RectangleTool extends CreationTool {
private static RectangleTool instance = null;
private RectangleTool( ){
super( );
}
protected static synchronized RectangleTool getInstance( ){
if( instance == null ){
instance = new RectangleTool();
}
return instance;
}
@Override
protected void createFigure( ) {
App.getInstance().addRectangle( getP1(), getP2() );
}
@Override
protected void drawFigure() {
App.getInstance().drawRectangle( getP1(), getP2() );
}
}
|
unlicense
|
clilystudio/NetBook
|
allsrc/com/qq/e/comm/services/RetCodeService$1.java
|
240
|
package com.qq.e.comm.services;
class RetCodeService$1
{
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: com.qq.e.comm.services.RetCodeService.1
* JD-Core Version: 0.6.0
*/
|
unlicense
|
clilystudio/NetBook
|
workspace/app/src/main/java/com/clilystudio/netbook/ui/BookCategoryListActivity.java
|
12997
|
package com.clilystudio.netbook.ui;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import com.clilystudio.netbook.CachePathConst;
import com.clilystudio.netbook.IntentBuilder;
import com.clilystudio.netbook.R;
import com.clilystudio.netbook.model.CategoryLevelRoot;
import com.clilystudio.netbook.adapter.BasePagerAdapter;
import com.clilystudio.netbook.util.CommonUtil;
import java.util.ArrayList;
import java.util.List;
public class BookCategoryListActivity extends BaseTabActivity implements ViewPager.OnPageChangeListener,
TabHost.OnTabChangeListener,
TabHost.TabContentFactory {
private boolean b;
private String c;
private String e;
private PopupWindow f;
private BookCategoryAdapter g;
private boolean h;
private String[] i;
private List<BookCategoryFragment> j = new ArrayList<>();
private ViewPager k;
private avAdapter l;
public static Intent a(Context context, boolean bl, String string) {
return new IntentBuilder().put(context, BookCategoryListActivity.class).putSerializable("CATEGORY_GENDER", bl).put("CATEGORY_KEY", string).build();
}
static void a(BookCategoryListActivity bookCategoryListActivity) {
if (bookCategoryListActivity.f != null && bookCategoryListActivity.f.isShowing()) {
bookCategoryListActivity.i();
return;
}
if (bookCategoryListActivity.f != null && !bookCategoryListActivity.f.isShowing()) {
ActionBar actionBar = bookCategoryListActivity.getActionBar();
if (actionBar != null) {
View customView = actionBar.getCustomView();
TextView textView = (TextView) customView.findViewById(R.id.actionbar_custom_right_text);
bookCategoryListActivity.f.showAsDropDown(textView);
}
}
bookCategoryListActivity.e("收起");
}
static void a(BookCategoryListActivity bookCategoryListActivity, String string) {
if (!bookCategoryListActivity.e.equals(string)) {
bookCategoryListActivity.e = string;
bookCategoryListActivity.d(string);
bookCategoryListActivity.g.notifyDataSetChanged();
bookCategoryListActivity.j.get(bookCategoryListActivity.k.getCurrentItem()).a();
bookCategoryListActivity.j.get(bookCategoryListActivity.k.getCurrentItem()).b(bookCategoryListActivity.g());
}
bookCategoryListActivity.i();
}
private String[] a(CategoryLevelRoot categoryLevelRoot) {
CategoryLevelRoot.CategoryLevel[] categoryLevels = this.b ? categoryLevelRoot.getMale() : categoryLevelRoot.getFemale();
for (CategoryLevelRoot.CategoryLevel categoryLevel : categoryLevels) {
if (categoryLevel.getMajor().equals(this.c)) {
return categoryLevel.getMins();
}
}
return new String[0];
}
private void h() {
if (this.a.getTabWidget().getTabCount() > 0) {
this.a.setCurrentTab(0);
this.a.clearAllTabs();
}
LayoutInflater layoutInflater = this.getLayoutInflater();
int n = this.l.getCount();
for (int k = 0; k < n; ++k) {
TabHost.TabSpec tabSpec = this.a.newTabSpec("tab" + k);
tabSpec.setContent(this);
View view = layoutInflater.inflate(R.layout.home_tabhost_item, (ViewGroup) getWindow().getDecorView(), false);
((TextView) view.findViewById(R.id.text)).setText(this.l.getPageTitle(k));
tabSpec.setIndicator(view);
this.a.addTab(tabSpec);
}
}
private void i() {
if (this.f != null && this.f.isShowing()) {
this.f.dismiss();
}
this.e("筛选");
}
public final BookCategoryFragment a(String string) {
BookCategoryFragment bookCategoryFragment = (BookCategoryFragment) this.getSupportFragmentManager().findFragmentByTag(string);
if (bookCategoryFragment == null) {
bookCategoryFragment = BookCategoryFragment.a(string);
}
return bookCategoryFragment;
}
public final String b() {
if (this.b) {
return "male";
}
return "female";
}
@Override
public View createTabContent(String string) {
View view = new View(this);
view.setMinimumHeight(0);
view.setMinimumWidth(0);
return view;
}
public final String f() {
return this.c;
}
public final String g() {
if (this.e.equals(this.c)) {
return "";
}
return this.e;
}
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
this.setContentView(R.layout.activity_book_category_tabhost);
this.b = this.getIntent().getBooleanExtra("CATEGORY_GENDER", false);
this.e = this.c = this.getIntent().getStringExtra("CATEGORY_KEY");
this.i = this.getResources().getStringArray(R.array.book_category_tabs);
View view = LayoutInflater.from(this).inflate(R.layout.category_level_popupwindow, (ViewGroup) getWindow().getDecorView(), false);
PopupWindow popupWindow = new PopupWindow(view, -1, -1);
popupWindow.setFocusable(true);
popupWindow.setBackgroundDrawable(new ColorDrawable(0));
popupWindow.setOutsideTouchable(true);
popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
BookCategoryListActivity.this.e("筛选");
}
});
this.f = popupWindow;
String[] arrstring = new String[]{};
CategoryLevelRoot categoryLevelRoot = CommonUtil.loadObject(CachePathConst.CategoryLevel, "category_level.txt");
String[] arrstring2 = categoryLevelRoot != null ? this.a(categoryLevelRoot) : arrstring;
final String[] arrstring3 = new String[1 + arrstring2.length];
arrstring3[0] = this.c;
System.arraycopy(arrstring2, 0, arrstring3, 1, arrstring2.length);
final int n = arrstring3.length;
boolean bl = false;
if (n == 1) {
bl = true;
}
this.h = bl;
view.findViewById(R.id.back_view).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
BookCategoryListActivity.this.i();
}
});
ListView listView = (ListView) view.findViewById(R.id.min_category_list);
this.g = new BookCategoryAdapter(this, arrstring3);
listView.setAdapter(this.g);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
BookCategoryListActivity.a(BookCategoryListActivity.this, arrstring3[position]);
}
});
if (this.h) {
this.b(this.c);
} else {
this.a(this.c, "筛选", new BaseCallBack() {
@Override
public void a() {
BookCategoryListActivity.a(BookCategoryListActivity.this);
}
});
}
this.a = (TabHost) this.findViewById(R.id.host);
this.k = (ViewPager) this.findViewById(R.id.pager);
this.l = new avAdapter(this.getSupportFragmentManager());
this.k.setOffscreenPageLimit(4);
this.k.setAdapter(this.l);
this.k.addOnPageChangeListener(this);
this.a.setup();
this.a.setOnTabChangedListener(this);
this.h();
}
@Override
protected void onDestroy() {
this.k.removeOnPageChangeListener(this);
super.onDestroy();
}
@Override
public void onPageScrollStateChanged(int n) {
}
@Override
public void onPageScrolled(int n, float f2, int n2) {
this.a(n, n2);
}
@Override
public void onPageSelected(int n) {
TabWidget tabWidget = this.a.getTabWidget();
int n2 = tabWidget.getDescendantFocusability();
tabWidget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
this.a.setCurrentTab(n);
tabWidget.setDescendantFocusability(n2);
}
@Override
public void onPause() {
super.onPause();
if (!this.h) {
this.i();
}
}
@Override
public void onTabChanged(String string) {
int n = this.a.getCurrentTab();
if (n >= 0 && n < this.l.getCount()) {
this.k.setCurrentItem(n, true);
}
}
final class avAdapter extends BasePagerAdapter {
private String[] a;
public avAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
this.a = new String[]{"new", "hot", "reputation", "over"};
BookCategoryListActivity.this.j.add(0, BookCategoryListActivity.this.a(this.a[0]));
BookCategoryListActivity.this.j.add(1, BookCategoryListActivity.this.a(this.a[1]));
BookCategoryListActivity.this.j.add(2, BookCategoryListActivity.this.a(this.a[2]));
BookCategoryListActivity.this.j.add(3, BookCategoryListActivity.this.a(this.a[3]));
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
for (int i = 0; i < 4; ++i) {
Fragment fragment = BookCategoryListActivity.this.j.get(i);
if (fragment.isAdded()) continue;
fragmentTransaction.add(BookCategoryListActivity.this.k.getId(), fragment, this.a[i]);
}
if (!fragmentTransaction.isEmpty()) {
fragmentTransaction.commit();
fragmentManager.executePendingTransactions();
}
}
@Override
public final Fragment getFragment(int position) {
return BookCategoryListActivity.this.j.get(position);
}
@Override
protected final String getTag(int position) {
return this.a[position];
}
@Override
public final int getCount() {
return 4;
}
@Override
public final CharSequence getPageTitle(int n) {
return BookCategoryListActivity.this.i[n];
}
}
public final class BookCategoryAdapter extends BaseAdapter {
private LayoutInflater a;
private String[] b;
public BookCategoryAdapter(Context context, String[] arrstring) {
this.a = LayoutInflater.from(context);
this.b = arrstring;
}
@Override
public final int getCount() {
return this.b.length;
}
@Override
public final Object getItem(int n) {
return this.b[n];
}
@Override
public final long getItemId(int n) {
return n;
}
/*
* Enabled aggressive block sorting
*/
@Override
public final View getView(int n, View view, ViewGroup viewGroup) {
ax ax2;
View view2;
if (view == null) {
ax ax3 = new ax();
view2 = n == 0 ? this.a.inflate(R.layout.category_major_list_item, (ViewGroup) getWindow().getDecorView(), false) : this.a.inflate(R.layout.category_level_list_item, (ViewGroup) getWindow().getDecorView(), false);
ax3.a = (TextView) view2.findViewById(R.id.category_name);
ax3.b = (ImageView) view2.findViewById(R.id.category_selected);
view2.setTag(ax3);
ax2 = ax3;
} else {
ax2 = (ax) view.getTag();
view2 = view;
}
ax2.a.setText(this.b[n]);
if (BookCategoryListActivity.this.e.equals(this.b[n])) {
ax2.a.setTextColor(BookCategoryListActivity.this.getResources().getColor(R.color.primary_red));
ax2.b.setVisibility(View.VISIBLE);
return view2;
}
ax2.a.setTextColor(CommonUtil.getAttrColor(BookCategoryListActivity.this, android.R.attr.textColor));
ax2.b.setVisibility(View.GONE);
return view2;
}
public final class ax {
TextView a;
ImageView b;
}
}
}
|
unlicense
|
Grauenwolf/DotNet-ORM-Cookbook
|
ORM Cookbook/Recipes.LinqToDB/Entities/EmployeeDetail.cs
|
1097
|
using LinqToDB.Mapping;
namespace Recipes.LinqToDB.Entities
{
[Table("EmployeeDetail", Schema = "HR")]
public partial class EmployeeDetail
{
[Column]
public string? CellPhone { get; set; }
[Column]
public int EmployeeClassificationKey { get; set; }
[NotNull]
[Column]
public string? EmployeeClassificationName { get; set; }
[Column]
public int EmployeeKey { get; set; }
[NotNull]
[Column]
public string? FirstName { get; set; }
[Column]
public bool IsEmployee { get; set; }
[Column]
public bool IsExempt { get; set; }
[NotNull]
[Column]
public string? LastName { get; set; }
[Column]
public string? MiddleName { get; set; }
[Column]
public string? OfficePhone { get; set; }
[Column]
public string? Title { get; set; }
}
//Used for linking the entity to the test framework. Not part of the recipe.
partial class EmployeeDetail : IEmployeeDetail
{
}
}
|
unlicense
|
hyller/CodeLibrary
|
Visual C++ Example/第8章 文档-视图-框架体系/实例183——改变视图窗口的背景色/FaceControl1/FaceControl1View.cpp
|
3403
|
// FaceControl1View.cpp : implementation of the CFaceControl1View class
//
#include "stdafx.h"
#include "FaceControl1.h"
#include "FaceControl1Doc.h"
#include "FaceControl1View.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CFaceControl1View
IMPLEMENT_DYNCREATE(CFaceControl1View, CView)
BEGIN_MESSAGE_MAP(CFaceControl1View, CView)
//{{AFX_MSG_MAP(CFaceControl1View)
ON_COMMAND(ID_CHAGEVIEWBK, OnChageviewbk)
ON_WM_ERASEBKGND()
//}}AFX_MSG_MAP
// Standard printing commands
ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CFaceControl1View construction/destruction
CFaceControl1View::CFaceControl1View()
{
// TODO: add construction code here
m_rgbBack = RGB(128 , 128 , 128);
}
CFaceControl1View::~CFaceControl1View()
{
}
BOOL CFaceControl1View::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CView::PreCreateWindow(cs);
}
/////////////////////////////////////////////////////////////////////////////
// CFaceControl1View drawing
void CFaceControl1View::OnDraw(CDC* pDC)
{
CFaceControl1Doc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
// TODO: add draw code for native data here
}
/////////////////////////////////////////////////////////////////////////////
// CFaceControl1View printing
BOOL CFaceControl1View::OnPreparePrinting(CPrintInfo* pInfo)
{
// default preparation
return DoPreparePrinting(pInfo);
}
void CFaceControl1View::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add extra initialization before printing
}
void CFaceControl1View::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: add cleanup after printing
}
/////////////////////////////////////////////////////////////////////////////
// CFaceControl1View diagnostics
#ifdef _DEBUG
void CFaceControl1View::AssertValid() const
{
CView::AssertValid();
}
void CFaceControl1View::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
CFaceControl1Doc* CFaceControl1View::GetDocument() // non-debug version is inline
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CFaceControl1Doc)));
return (CFaceControl1Doc*)m_pDocument;
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CFaceControl1View message handlers
void CFaceControl1View::OnChageviewbk() //¸Ä±ä±³¾°É«
{
// TODO: Add your command handler code here
m_rgbBack=RGB(0,128,128);
Invalidate(true);
}
BOOL CFaceControl1View::OnEraseBkgnd(CDC* pDC)
{
// TODO: Add your message handler code here and/or call default
CBrush Brush (m_rgbBack); // ´´½¨Ò»¸öеÄË¢×Ó
CBrush* pOldBrush = pDC->SelectObject (&Brush); // °ÑË¢×ÓÑ¡ÈëÉ豸»·¾³
//»ñµÃÐèÒªéß³ý±³¾°µÄÇøÓò
CRect reClip;
GetClientRect(&reClip);
//ÖØ»æ¸ÃÇøÓò
pDC->PatBlt(reClip.left , reClip.top , reClip.Width () , reClip.Height() , PATCOPY);
//ÊÍ·ÅË¢×Ó
pDC->SelectObject (pOldBrush);
return TRUE;//±ØÐë·µ»ØTURE
//return CView::OnEraseBkgnd(pDC);
}
|
unlicense
|
rsmeral/pv243-jboss
|
project/project-et-ejb/src/test/java/cz/muni/fi/pv243/et/test/ExpenseTrackingTest.java
|
8127
|
package cz.muni.fi.pv243.et.test;
import cz.muni.fi.pv243.et.data.ExpenseReportListProducer;
import cz.muni.fi.pv243.et.data.PersonListProducer;
import cz.muni.fi.pv243.et.data.PurposeListProducer;
import cz.muni.fi.pv243.et.model.Currency;
import cz.muni.fi.pv243.et.model.ExpenseReport;
import cz.muni.fi.pv243.et.model.MoneyTransfer;
import cz.muni.fi.pv243.et.model.Payment;
import cz.muni.fi.pv243.et.model.Person;
import cz.muni.fi.pv243.et.model.PersonRole;
import cz.muni.fi.pv243.et.model.Purpose;
import cz.muni.fi.pv243.et.model.ReportStatus;
import cz.muni.fi.pv243.et.model.UserModel;
import cz.muni.fi.pv243.et.security.UserManager;
import cz.muni.fi.pv243.et.service.ExpenseReportService;
import cz.muni.fi.pv243.et.service.LoginService;
import cz.muni.fi.pv243.et.service.MoneyTransferService;
import cz.muni.fi.pv243.et.service.PaymentService;
import cz.muni.fi.pv243.et.service.PersonService;
import cz.muni.fi.pv243.et.service.PurposeService;
import cz.muni.fi.pv243.et.service.impl.ReportComputing;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import static org.junit.Assert.*;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.picketlink.Identity;
import org.picketlink.authentication.AuthenticationException;
@RunWith(Arquillian.class)
public class ExpenseTrackingTest {
@Inject
private LoginService loginService;
@Inject
private ExpenseReportService reportSvc;
@Inject
private Identity identity;
@Inject
private PersonService personSvc;
@Inject
private PurposeService purposeSvc;
@Inject
private MoneyTransferService mtSvc;
@Inject
private PaymentService paySvc;
@Inject
private UserManager usrMgr;
@Inject
private ReportComputing reportComputer;
@Inject
private ExpenseReportListProducer reportList;
@Inject
private PersonListProducer personList;
@Inject
private PurposeListProducer purpList;
private static final String ADMIN = "admin";
private static final String VERIFIER = "verifier";
private static final String SUBMITTER = "submitter";
@Deployment(testable = true)
public static EnterpriseArchive deployment() {
return Deployments.mainDeployment(ExpenseTrackingTest.class);
}
@Test
@InSequence(1)
public void testUserCreation() {
loginAs(ADMIN);
createUser(new UserModel("submitter", "Tester", "Submitter", "submitter@tester.com", "submitter", "123456789"), PersonRole.APPLICANT);
createUser(new UserModel("verifier", "Tester", "Verifier", "verifier@tester.com", "verifier", "123456789"), PersonRole.VERIFIER);
assertEquals(3, usrMgr.findAll().size()); // 2 + admin
}
@Test
@InSequence(2)
public void testCreateReport() {
loginAs(SUBMITTER);
ExpenseReport report = new ExpenseReport();
report.setName("Report1");
report.setDescription("Report1 desc");
report.setSubmitter(getPersonForUser(SUBMITTER));
report.setStatus(ReportStatus.OPEN);
reportSvc.save(report);
loginAs(VERIFIER);
assertEquals(1, reportSvc.findAll().size());
assertEquals(report, reportSvc.findAll().iterator().next());
}
@Test
@InSequence(3)
public void testPurposeSvc() {
loginAs(ADMIN);
Purpose purpose = new Purpose();
purpose.setName("Purp1");
purpose.setDescription("purpose 1");
purposeSvc.save(purpose);
Collection<Purpose> all = purposeSvc.findAll();
assertEquals(1, all.size());
assertEquals(purpose, all.iterator().next());
}
@Test
@InSequence(4)
public void testPaymentSvc() {
loginAs(SUBMITTER);
Payment payment = new Payment();
payment.setPurpose(purpList.getAll().iterator().next());
payment.setCurrency(Currency.CZK);
payment.setDate(new Date());
payment.setValue(BigDecimal.valueOf(100));
payment.setReport(getOnlyReport());
paySvc.save(payment);
Collection<Payment> payments = paySvc.findByPerson(getPersonForUser(SUBMITTER));
assertEquals(1, payments.size());
assertEquals(payment, payments.iterator().next());
}
@Test
@InSequence(5)
public void testMoneyTransferSvc() {
loginAs(VERIFIER);
MoneyTransfer mt = new MoneyTransfer();
mt.setCreator(getPersonForUser(VERIFIER));
mt.setCurrency(Currency.CZK);
mt.setDate(new Date());
mt.setValue(BigDecimal.valueOf(300));
mt.setReport(getOnlyReport());
mtSvc.save(mt);
Collection<MoneyTransfer> mts = mtSvc.findForReport(getOnlyReport());
assertEquals(1, mts.size());
assertEquals(mt, mts.iterator().next());
}
@Test
@InSequence(6)
public void testReportComputing() {
loginAs(SUBMITTER);
BigDecimal totalValue = reportComputer.getTotalValue(getOnlyReport());
assertEquals(BigDecimal.valueOf(200), totalValue);
}
@Test
@InSequence(7)
public void testSubmitReport() {
loginAs(SUBMITTER);
ExpenseReport report = getOnlyReport();
reportSvc.submit(report);
assertEquals(ReportStatus.SUBMITTED, report.getStatus());
}
@Test
@InSequence(8)
public void testFindUnassignedReports() {
loginAs(VERIFIER);
ExpenseReport report = getOnlyReport();
Collection<ExpenseReport> unassigned = reportSvc.findWithNoVerifierAssigned();
assertEquals(1, unassigned.size());
assertEquals(report, unassigned.iterator().next());
}
@Test
@InSequence(9)
public void testClaimReport() {
loginAs(VERIFIER);
ExpenseReport report = getOnlyReport();
Person verifierPerson = getPersonForUser(VERIFIER);
reportSvc.claim(report, verifierPerson);
Collection<ExpenseReport> reportsForVerifier = reportSvc.findForVerifier(verifierPerson);
assertTrue(reportsForVerifier.contains(report));
}
@Test
@InSequence(10)
public void testApproveReport() {
loginAs(VERIFIER);
ExpenseReport report = getOnlyReport();
reportSvc.approve(report);
Collection<ExpenseReport> allApproved = reportSvc.findByStatus(ReportStatus.APPROVED);
Collection<ExpenseReport> forVerifierWithStatusApproved = reportSvc.findForVerifierWithStatus(getPersonForUser(VERIFIER), ReportStatus.APPROVED);
assertEquals(allApproved, forVerifierWithStatusApproved);
}
@Test
@InSequence(11)
public void testSendMoney() {
loginAs(VERIFIER);
ExpenseReport report = getOnlyReport();
reportSvc.sendMoney(report);
assertEquals(ReportStatus.SETTLED, report.getStatus());
assertEquals(0, reportSvc.findForSubmitterWithStatus(getPersonForUser(SUBMITTER), ReportStatus.OPEN).size());
}
private void loginAs(String username) {
try {
if (identity.isLoggedIn()) {
identity.logout();
}
loginService.login(username, username);
} catch (AuthenticationException ex) {
fail(ex.getMessage());
}
}
private void createUser(UserModel userModel, PersonRole... roles) {
usrMgr.add(userModel);
for (PersonRole role : roles) {
usrMgr.grantRole(userModel.getUserName(), role);
}
usrMgr.changePassword(userModel.getUserName(), userModel.getUserName());
}
private Person getPersonForUser(String username) {
UserModel usr = usrMgr.get(username);
return personList.getPerson(usr.getId());
}
private ExpenseReport getOnlyReport() {
Collection<ExpenseReport> all = reportList.getAll();
assertFalse(all.isEmpty());
return all.iterator().next();
}
}
|
unlicense
|
cc14514/hq6
|
hq-util/src/main/java/org/hyperic/util/validator/InvalidPostalCodeForStateException.java
|
1370
|
/*
* NOTE: This copyright does *not* cover user programs that use HQ
* program services by normal system calls through the application
* program interfaces provided as part of the Hyperic Plug-in Development
* Kit or the Hyperic Client Development Kit - this is merely considered
* normal use of the program, and does *not* fall under the heading of
* "derived work".
*
* Copyright (C) [2004, 2005, 2006], Hyperic, Inc.
* This file is part of HQ.
*
* HQ is free software; you can redistribute it and/or modify
* it under the terms version 2 of the GNU General Public License as
* published by the Free Software Foundation. This program is distributed
* in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*/
package org.hyperic.util.validator;
public class InvalidPostalCodeForStateException extends InvalidPostalCodeException {
public InvalidPostalCodeForStateException(String state, String zip) {
super(zip + " is not a valid ZIP Code for " + state);
}
}
|
unlicense
|
joksnet/youtube-dl
|
youtube_dl/extractor/generic.py
|
8580
|
# encoding: utf-8
import os
import re
from .common import InfoExtractor
from ..utils import (
compat_urllib_error,
compat_urllib_parse,
compat_urllib_request,
compat_urlparse,
ExtractorError,
)
from .brightcove import BrightcoveIE
class GenericIE(InfoExtractor):
IE_DESC = u'Generic downloader that works on some sites'
_VALID_URL = r'.*'
IE_NAME = u'generic'
_TESTS = [
{
u'url': u'http://www.hodiho.fr/2013/02/regis-plante-sa-jeep.html',
u'file': u'13601338388002.mp4',
u'md5': u'85b90ccc9d73b4acd9138d3af4c27f89',
u'info_dict': {
u"uploader": u"www.hodiho.fr",
u"title": u"R\u00e9gis plante sa Jeep"
}
},
{
u'url': u'http://www.8tv.cat/8aldia/videos/xavier-sala-i-martin-aquesta-tarda-a-8-al-dia/',
u'file': u'2371591881001.mp4',
u'md5': u'9e80619e0a94663f0bdc849b4566af19',
u'note': u'Test Brightcove downloads and detection in GenericIE',
u'info_dict': {
u'title': u'Xavier Sala i Martín: “Un banc que no presta és un banc zombi que no serveix per a res”',
u'uploader': u'8TV',
u'description': u'md5:a950cc4285c43e44d763d036710cd9cd',
}
},
]
def report_download_webpage(self, video_id):
"""Report webpage download."""
if not self._downloader.params.get('test', False):
self._downloader.report_warning(u'Falling back on generic information extractor.')
super(GenericIE, self).report_download_webpage(video_id)
def report_following_redirect(self, new_url):
"""Report information extraction."""
self._downloader.to_screen(u'[redirect] Following redirect to %s' % new_url)
def _test_redirect(self, url):
"""Check if it is a redirect, like url shorteners, in case return the new url."""
class HeadRequest(compat_urllib_request.Request):
def get_method(self):
return "HEAD"
class HEADRedirectHandler(compat_urllib_request.HTTPRedirectHandler):
"""
Subclass the HTTPRedirectHandler to make it use our
HeadRequest also on the redirected URL
"""
def redirect_request(self, req, fp, code, msg, headers, newurl):
if code in (301, 302, 303, 307):
newurl = newurl.replace(' ', '%20')
newheaders = dict((k,v) for k,v in req.headers.items()
if k.lower() not in ("content-length", "content-type"))
return HeadRequest(newurl,
headers=newheaders,
origin_req_host=req.get_origin_req_host(),
unverifiable=True)
else:
raise compat_urllib_error.HTTPError(req.get_full_url(), code, msg, headers, fp)
class HTTPMethodFallback(compat_urllib_request.BaseHandler):
"""
Fallback to GET if HEAD is not allowed (405 HTTP error)
"""
def http_error_405(self, req, fp, code, msg, headers):
fp.read()
fp.close()
newheaders = dict((k,v) for k,v in req.headers.items()
if k.lower() not in ("content-length", "content-type"))
return self.parent.open(compat_urllib_request.Request(req.get_full_url(),
headers=newheaders,
origin_req_host=req.get_origin_req_host(),
unverifiable=True))
# Build our opener
opener = compat_urllib_request.OpenerDirector()
for handler in [compat_urllib_request.HTTPHandler, compat_urllib_request.HTTPDefaultErrorHandler,
HTTPMethodFallback, HEADRedirectHandler,
compat_urllib_request.HTTPErrorProcessor, compat_urllib_request.HTTPSHandler]:
opener.add_handler(handler())
response = opener.open(HeadRequest(url))
if response is None:
raise ExtractorError(u'Invalid URL protocol')
new_url = response.geturl()
if url == new_url:
return False
self.report_following_redirect(new_url)
return new_url
def _real_extract(self, url):
parsed_url = compat_urlparse.urlparse(url)
if not parsed_url.scheme:
self._downloader.report_warning('The url doesn\'t specify the protocol, trying with http')
return self.url_result('http://' + url)
try:
new_url = self._test_redirect(url)
if new_url:
return [self.url_result(new_url)]
except compat_urllib_error.HTTPError:
# This may be a stupid server that doesn't like HEAD, our UA, or so
pass
video_id = url.split('/')[-1]
try:
webpage = self._download_webpage(url, video_id)
except ValueError:
# since this is the last-resort InfoExtractor, if
# this error is thrown, it'll be thrown here
raise ExtractorError(u'Invalid URL: %s' % url)
self.report_extraction(video_id)
# Look for BrightCove:
m_brightcove = re.search(r'<object.+?class=([\'"]).*?BrightcoveExperience.*?\1.+?</object>', webpage, re.DOTALL)
if m_brightcove is not None:
self.to_screen(u'Brightcove video detected.')
bc_url = BrightcoveIE._build_brighcove_url(m_brightcove.group())
return self.url_result(bc_url, 'Brightcove')
# Start with something easy: JW Player in SWFObject
mobj = re.search(r'flashvars: [\'"](?:.*&)?file=(http[^\'"&]*)', webpage)
if mobj is None:
# Broaden the search a little bit
mobj = re.search(r'[^A-Za-z0-9]?(?:file|source)=(http[^\'"&]*)', webpage)
if mobj is None:
# Broaden the search a little bit: JWPlayer JS loader
mobj = re.search(r'[^A-Za-z0-9]?file["\']?:\s*["\'](http[^\'"&]*)', webpage)
if mobj is None:
# Try to find twitter cards info
mobj = re.search(r'<meta (?:property|name)="twitter:player:stream" (?:content|value)="(.+?)"', webpage)
if mobj is None:
# We look for Open Graph info:
# We have to match any number spaces between elements, some sites try to align them (eg.: statigr.am)
m_video_type = re.search(r'<meta.*?property="og:video:type".*?content="video/(.*?)"', webpage)
# We only look in og:video if the MIME type is a video, don't try if it's a Flash player:
if m_video_type is not None:
mobj = re.search(r'<meta.*?property="og:video".*?content="(.*?)"', webpage)
if mobj is None:
# HTML5 video
mobj = re.search(r'<video[^<]*(?:>.*?<source.*?)? src="([^"]+)"', webpage, flags=re.DOTALL)
if mobj is None:
raise ExtractorError(u'Invalid URL: %s' % url)
# It's possible that one of the regexes
# matched, but returned an empty group:
if mobj.group(1) is None:
raise ExtractorError(u'Invalid URL: %s' % url)
video_url = mobj.group(1)
video_url = compat_urlparse.urljoin(url, video_url)
video_id = compat_urllib_parse.unquote(os.path.basename(video_url))
# here's a fun little line of code for you:
video_extension = os.path.splitext(video_id)[1][1:]
video_id = os.path.splitext(video_id)[0]
# it's tempting to parse this further, but you would
# have to take into account all the variations like
# Video Title - Site Name
# Site Name | Video Title
# Video Title - Tagline | Site Name
# and so on and so forth; it's just not practical
video_title = self._html_search_regex(r'<title>(.*)</title>',
webpage, u'video title', default=u'video', flags=re.DOTALL)
# video uploader is domain name
video_uploader = self._search_regex(r'(?:https?://)?([^/]*)/.*',
url, u'video uploader')
return [{
'id': video_id,
'url': video_url,
'uploader': video_uploader,
'upload_date': None,
'title': video_title,
'ext': video_extension,
}]
|
unlicense
|
dawnsun/mijiaosys
|
dal/src/main/java/com/mijiaokj/sys/common/lang/ObjectUtil.java
|
14264
|
package com.mijiaokj.sys.common.lang;
import com.mijiaokj.sys.common.util.StringUtil;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* Created by sunchenguang on 2017/5/31.
*/
public class ObjectUtil {
/* ============================================================================ */
/* 常量和singleton。 */
/* ============================================================================ */
/**
* 用于表示<code>null</code>的常量。
*
* <p>
* 例如,<code>HashMap.get(Object)</code>方法返回<code>null</code>有两种可能:
* 值不存在或值为<code>null</code>。而这个singleton可用来区别这两种情形。
* </p>
*
* <p>
* 另一个例子是,<code>Hashtable</code>的值不能为<code>null</code>。
* </p>
*/
public static final Object NULL = new Serializable() {
private static final long serialVersionUID = 7092611880189329093L;
private Object readResolve() {
return NULL;
}
};
/* ============================================================================ */
/* 默认值函数。 */
/* */
/* 当对象为null时,将对象转换成指定的默认对象。 */
/* ============================================================================ */
/**
* 如果对象为<code>null</code>,则返回指定默认对象,否则返回对象本身。
* <pre>
* ObjectUtil.defaultIfNull(null, null) = null
* ObjectUtil.defaultIfNull(null, "") = ""
* ObjectUtil.defaultIfNull(null, "zz") = "zz"
* ObjectUtil.defaultIfNull("abc", *) = "abc"
* ObjectUtil.defaultIfNull(Boolean.TRUE, *) = Boolean.TRUE
* </pre>
*
* @param object 要测试的对象
* @param defaultValue 默认值
*
* @return 对象本身或默认对象
*/
public static Object defaultIfNull(Object object, Object defaultValue) {
return (object != null) ? object
: defaultValue;
}
/* ============================================================================ */
/* 比较函数。 */
/* */
/* 以下方法用来比较两个对象是否相同。 */
/* ============================================================================ */
/**
* 比较两个对象是否完全相等。
*
* <p>
* 此方法可以正确地比较多维数组。
* <pre>
* ObjectUtil.equals(null, null) = true
* ObjectUtil.equals(null, "") = false
* ObjectUtil.equals("", null) = false
* ObjectUtil.equals("", "") = true
* ObjectUtil.equals(Boolean.TRUE, null) = false
* ObjectUtil.equals(Boolean.TRUE, "true") = false
* ObjectUtil.equals(Boolean.TRUE, Boolean.TRUE) = true
* ObjectUtil.equals(Boolean.TRUE, Boolean.FALSE) = false
* </pre>
* </p>
*
* @param object1 对象1
* @param object2 对象2
*
* @return 如果相等, 则返回<code>true</code>
*/
public static boolean equals(Object object1, Object object2) {
return ArrayUtil.equals(object1, object2);
}
/* ============================================================================ */
/* Hashcode函数。 */
/* */
/* 以下方法用来取得对象的hash code。 */
/* ============================================================================ */
/**
* 取得对象的hash值, 如果对象为<code>null</code>, 则返回<code>0</code>。
*
* <p>
* 此方法可以正确地处理多维数组。
* </p>
*
* @param object 对象
*
* @return hash值
*/
public static int hashCode(Object object) {
return ArrayUtil.hashCode(object);
}
/**
* 取得对象的原始的hash值, 如果对象为<code>null</code>, 则返回<code>0</code>。
*
* <p>
* 该方法使用<code>System.identityHashCode</code>来取得hash值,该值不受对象本身的<code>hashCode</code>方法的影响。
* </p>
*
* @param object 对象
*
* @return hash值
*/
public static int identityHashCode(Object object) {
return (object == null) ? 0
: System.identityHashCode(object);
}
/* ============================================================================ */
/* 取得对象的identity。 */
/* ============================================================================ */
/**
* 取得对象自身的identity,如同对象没有覆盖<code>toString()</code>方法时,<code>Object.toString()</code>的原始输出。
* <pre>
* ObjectUtil.identityToString(null) = null
* ObjectUtil.identityToString("") = "java.lang.String@1e23"
* ObjectUtil.identityToString(Boolean.TRUE) = "java.lang.Boolean@7fa"
* ObjectUtil.identityToString(new int[0]) = "int[]@7fa"
* ObjectUtil.identityToString(new Object[0]) = "java.lang.Object[]@7fa"
* </pre>
*
* @param object 对象
*
* @return 对象的identity,如果对象是<code>null</code>,则返回<code>null</code>
*/
public static String identityToString(Object object) {
if (object == null) {
return null;
}
return appendIdentityToString(null, object).toString();
}
/**
* 取得对象自身的identity,如同对象没有覆盖<code>toString()</code>方法时,<code>Object.toString()</code>的原始输出。
* <pre>
* ObjectUtil.identityToString(null, "NULL") = "NULL"
* ObjectUtil.identityToString("", "NULL") = "java.lang.String@1e23"
* ObjectUtil.identityToString(Boolean.TRUE, "NULL") = "java.lang.Boolean@7fa"
* ObjectUtil.identityToString(new int[0], "NULL") = "int[]@7fa"
* ObjectUtil.identityToString(new Object[0], "NULL") = "java.lang.Object[]@7fa"
* </pre>
*
* @param object 对象
* @param nullStr 如果对象为<code>null</code>,则返回该字符串
*
* @return 对象的identity,如果对象是<code>null</code>,则返回指定字符串
*/
public static String identityToString(Object object, String nullStr) {
if (object == null) {
return nullStr;
}
return appendIdentityToString(null, object).toString();
}
/**
* 将对象自身的identity——如同对象没有覆盖<code>toString()</code>方法时,<code>Object.toString()</code>的原始输出——追加到<code>StringBuffer</code>中。
* <pre>
* ObjectUtil.appendIdentityToString(*, null) = null
* ObjectUtil.appendIdentityToString(null, "") = "java.lang.String@1e23"
* ObjectUtil.appendIdentityToString(null, Boolean.TRUE) = "java.lang.Boolean@7fa"
* ObjectUtil.appendIdentityToString(buf, Boolean.TRUE) = buf.append("java.lang.Boolean@7fa")
* ObjectUtil.appendIdentityToString(buf, new int[0]) = buf.append("int[]@7fa")
* ObjectUtil.appendIdentityToString(buf, new Object[0]) = buf.append("java.lang.Object[]@7fa")
* </pre>
*
* @param buffer <code>StringBuffer</code>对象,如果是<code>null</code>,则创建新的
* @param object 对象
*
* @return <code>StringBuffer</code>对象,如果对象为<code>null</code>,则返回<code>null</code>
*/
public static StringBuffer appendIdentityToString(StringBuffer buffer, Object object) {
if (object == null) {
return null;
}
if (buffer == null) {
buffer = new StringBuffer();
}
buffer.append(ClassUtil.getClassNameForObject(object));
return buffer.append('@').append(Integer.toHexString(identityHashCode(object)));
}
/* ============================================================================ */
/* Clone函数。 */
/* */
/* 以下方法调用Object.clone方法,默认是“浅复制”(shallow copy)。 */
/* ============================================================================ */
/**
* 复制一个对象。如果对象为<code>null</code>,则返回<code>null</code>。
*
* <p>
* 此方法调用<code>Object.clone</code>方法,默认只进行“浅复制”。 对于数组,调用<code>ArrayUtil.clone</code>方法更高效。
* </p>
*
* @param array 要复制的数组
*
* @return 数组的复本,如果原始数组为<code>null</code>,则返回<code>null</code>
*/
public static Object clone(Object array) {
if (array == null) {
return null;
}
// 对数组特殊处理
if (array instanceof Object[]) {
return ArrayUtil.clone((Object[]) array);
}
if (array instanceof long[]) {
return ArrayUtil.clone((long[]) array);
}
if (array instanceof int[]) {
return ArrayUtil.clone((int[]) array);
}
if (array instanceof short[]) {
return ArrayUtil.clone((short[]) array);
}
if (array instanceof byte[]) {
return ArrayUtil.clone((byte[]) array);
}
if (array instanceof double[]) {
return ArrayUtil.clone((double[]) array);
}
if (array instanceof float[]) {
return ArrayUtil.clone((float[]) array);
}
if (array instanceof boolean[]) {
return ArrayUtil.clone((boolean[]) array);
}
if (array instanceof char[]) {
return ArrayUtil.clone((char[]) array);
}
// Not cloneable
if (!(array instanceof Cloneable)) {
throw new CloneNotSupportedException("Object of class " + array.getClass().getName()
+ " is not Cloneable");
}
// 用reflection调用clone方法
Class clazz = array.getClass();
try {
Method cloneMethod = clazz.getMethod("clone", ArrayUtil.EMPTY_CLASS_ARRAY);
return cloneMethod.invoke(array, ArrayUtil.EMPTY_OBJECT_ARRAY);
} catch (NoSuchMethodException e) {
throw new CloneNotSupportedException(e);
} catch (IllegalArgumentException e) {
throw new CloneNotSupportedException(e);
} catch (IllegalAccessException e) {
throw new CloneNotSupportedException(e);
} catch (InvocationTargetException e) {
throw new CloneNotSupportedException(e);
}
}
/* ============================================================================ */
/* 比较对象的类型。 */
/* ============================================================================ */
/**
* 检查两个对象是否属于相同类型。<code>null</code>将被看作任意类型。
*
* @param object1 对象1
* @param object2 对象2
*
* @return 如果两个对象有相同的类型,则返回<code>true</code>
*/
public static boolean isSameType(Object object1, Object object2) {
if ((object1 == null) || (object2 == null)) {
return true;
}
return object1.getClass().equals(object2.getClass());
}
/* ============================================================================ */
/* toString方法。 */
/* ============================================================================ */
/**
* 取得对象的<code>toString()</code>的值,如果对象为<code>null</code>,则返回空字符串<code>""</code>。
* <pre>
* ObjectUtil.toString(null) = ""
* ObjectUtil.toString("") = ""
* ObjectUtil.toString("bat") = "bat"
* ObjectUtil.toString(Boolean.TRUE) = "true"
* ObjectUtil.toString([1, 2, 3]) = "[1, 2, 3]"
* </pre>
*
* @param object 对象
*
* @return 对象的<code>toString()</code>的返回值,或空字符串<code>""</code>
*/
public static String toString(Object object) {
return (object == null) ? StringUtil.EMPTY_STRING
: (object.getClass().isArray() ? ArrayUtil.toString(object)
: object.toString());
}
/**
* 取得对象的<code>toString()</code>的值,如果对象为<code>null</code>,则返回指定字符串。
* <pre>
* ObjectUtil.toString(null, null) = null
* ObjectUtil.toString(null, "null") = "null"
* ObjectUtil.toString("", "null") = ""
* ObjectUtil.toString("bat", "null") = "bat"
* ObjectUtil.toString(Boolean.TRUE, "null") = "true"
* ObjectUtil.toString([1, 2, 3], "null") = "[1, 2, 3]"
* </pre>
*
* @param object 对象
* @param nullStr 如果对象为<code>null</code>,则返回该字符串
*
* @return 对象的<code>toString()</code>的返回值,或指定字符串
*/
public static String toString(Object object, String nullStr) {
return (object == null) ? nullStr
: (object.getClass().isArray() ? ArrayUtil.toString(object)
: object.toString());
}
}
|
unlicense
|
SeanShubin/detangler
|
scanner/src/main/scala/com/seanshubin/detangler/scanner/DirectoryScanner.scala
|
130
|
package com.seanshubin.detangler.scanner
import java.nio.file.Path
trait DirectoryScanner {
def findFiles(): Iterable[Path]
}
|
unlicense
|
marwei/leetcode
|
problem/310.rb
|
753
|
# @param {Integer} n
# @param {Integer[][]} edges
# @return {Integer[]}
def find_min_height_trees(n, edges)
return [0] if n == 1
adjancency = Hash.new { |hash, key| hash[key] = Array.new }
# adjancency matrix
edges.each do |from, to|
adjancency[from].push to
adjancency[to].push from
end
# find all singles
leafs = adjancency.each_with_object([]) do |(key, val), memo|
memo.push key if val.size == 1
end
# trim leaves until there's 1 or 2 nodes left
while adjancency.size > 2
leafs = leafs.each_with_object([]) do |leaf, memo|
parent = adjancency[leaf].first
adjancency.delete leaf
adjancency[parent].delete leaf
memo.push parent if adjancency[parent].size == 1
end
end
leafs
end
|
unlicense
|
griffaurel/rss-bridge
|
bridges/OpenClassroomsBridge.php
|
1558
|
<?php
class OpenClassroomsBridge extends BridgeAbstract{
const MAINTAINER = "sebsauvage";
const NAME = "OpenClassrooms Bridge";
const URI = "https://openclassrooms.com/";
const CACHE_TIMEOUT = 21600; // 6h
const DESCRIPTION = "Returns latest tutorials from OpenClassrooms.";
const PARAMETERS = array( array(
'u'=>array(
'name'=>'Catégorie',
'type'=>'list',
'required'=>true,
'values'=>array(
'Arts & Culture'=>'arts',
'Code'=>'code',
'Design'=>'design',
'Entreprise'=>'business',
'Numérique'=>'digital',
'Sciences'=>'sciences',
'Sciences Humaines'=>'humainities',
'Systèmes d\'information'=>'it',
'Autres'=>'others'
)
)
));
public function getURI(){
return self::URI.'/courses?categories='.$this->getInput('u').'&'
.'title=&sort=updatedAt+desc';
}
public function collectData(){
$html = getSimpleHTMLDOM($this->getURI())
or returnServerError('Could not request OpenClassrooms.');
foreach($html->find('.courseListItem') as $element) {
$item = array();
$item['uri'] = self::URI.$element->find('a', 0)->href;
$item['title'] = $element->find('h3', 0)->plaintext;
$item['content'] = $element->find('slidingItem__descriptionContent', 0)->plaintext;
$this->items[] = $item;
}
}
}
|
unlicense
|
ERNICommunity/ERNI-Photo-Database
|
server/ERNI.PhotoDatabase.DataAccess/UnitOfWork/IUnitOfWork.cs
|
358
|
using System.Threading;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Storage;
namespace ERNI.PhotoDatabase.DataAccess.UnitOfWork
{
public interface IUnitOfWork
{
Task SaveChanges(CancellationToken cancellationToken);
Task<IDbContextTransaction> BeginTransaction(CancellationToken cancellationToken);
}
}
|
unlicense
|
SubhamSatyajeet/JavaRough
|
Liang/Chapter5/CheckPoint5_7_2.java
|
137
|
public class CheckPoint5_7_2
{
public static void main(String[] args)
{
for(int i = 1; i <= 100; i++)
System.out.println(i);
}
}
|
unlicense
|
bakstad/JavaSandbox
|
random/src/main/java/query/QueryBuilder.java
|
321
|
package query;
public class QueryBuilder
{
public void append(String str)
{
query.append(str);
query.append(" ");
}
public String getQuery()
{
return query.toString().substring(0, query.length()-1);
}
private StringBuilder query = new StringBuilder();
}
|
unlicense
|
miktemk/TextureCreator
|
src/gui/TexMenuBar.java
|
3574
|
package gui;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.undo.*;
import javax.swing.border.*;
import gui.AboutDialog;
import editor.*;
public class TexMenuBar extends JMenuBar implements ActionListener
{
TextureCreator tc;
JFileChooser fc;
AboutDialog abouts;
public TexMenuBar(TextureCreator tc)
{
this.tc = tc;
JMenu filemenu = new JMenu("File");
filemenu.add(getMenuItem("Open Source Image...", KeyEvent.VK_O));
filemenu.add(getMenuItem("Save Result", KeyEvent.VK_S));
filemenu.add(getMenuItem("Save As...", KeyEvent.VK_S));
filemenu.addSeparator();
filemenu.add(getMenuItem("Exit", KeyEvent.VK_Q));
add(filemenu);
JMenu editmenu = new JMenu("Edit");
editmenu.add(getMenuItem("Undo", KeyEvent.VK_Z));
editmenu.add(getMenuItem("Redo", KeyEvent.VK_Y));
editmenu.addSeparator();
editmenu.add(getMenuItem("Select All", KeyEvent.VK_A));
add(editmenu);
JMenu helpmenu = new JMenu("Help");
helpmenu.add(getMenuItem("About", KeyEvent.VK_F1));
add(helpmenu);
fc = new JFileChooser();
fc.addChoosableFileFilter(new ExtFilter("gif:GIF", "Graphics Interchange Format"));
fc.addChoosableFileFilter(new ExtFilter("jpg:jpeg:JPG:JPEG", "JPEG Images"));
abouts = new AboutDialog();
}
private JMenuItem getMenuItem(String name)
{
JMenuItem mi = new JMenuItem(name);
mi.addActionListener(this);
return mi;
}
private JMenuItem getMenuItem(String name, int key)
{
JMenuItem mi = new JMenuItem(name);
mi.addActionListener(this);
mi.setAccelerator(KeyStroke.getKeyStroke(key, InputEvent.CTRL_MASK));
return mi;
}
public JFileChooser getFileChooser()
{
return fc;
}
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
JMenuItem item = (JMenuItem)source;
if(item.getText() == "Open Source Image...")
{
int option = fc.showOpenDialog(this);
if(option == JFileChooser.APPROVE_OPTION)
{
String filename = fc.getSelectedFile().getPath();
BufferedImage newBI = Utils.loadImage(filename);
tc.setImage(newBI);
}
}
else if(item.getText() == "Save Result")
{
tc.save(false);
}
else if(item.getText() == "Save As...")
{
tc.save(true);
}
else if(item.getText() == "Exit")
{
tc.exitProgram();
}
else if(item.getText() == "Undo")
{
UndoManager und = tc.getUndoManager();
try
{
und.undo();
}
catch(Exception ex){}
tc.oh.callRepaint();
tc.man.refreshJustQuad();
}
else if(item.getText() == "Redo")
{
UndoManager und = tc.getUndoManager();
try
{
und.redo();
}
catch(Exception ex){}
tc.oh.callRepaint();
tc.man.refreshJustQuad();
}
else if(item.getText() == "Select All")
{
tc.oh.callSelectAll();
}
else if(item.getText() == "About")
{
abouts.popUp();
}
}
}
|
unlicense
|
yangjun2/android
|
changhong/ChanghongSmartHome/src/com/changhong/smarthome/phone/store/activity/OrderDetailActivity.java
|
18968
|
package com.changhong.smarthome.phone.store.activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.text.InputType;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import com.changhong.sdk.activity.SuperActivity;
import com.changhong.smarthome.phone.R;
import com.changhong.smarthome.phone.store.dialog.CustomCommonDialog;
import com.changhong.smarthome.phone.store.entity.StoreConstant;
import com.changhong.smarthome.phone.store.logic.OrderDetailLogic;
import com.changhong.smarthome.phone.store.logic.bean.GoodsDetailInfo;
import com.changhong.smarthome.phone.store.logic.bean.OrderInfoBean;
import com.lidroid.xutils.HttpUtils;
public class OrderDetailActivity extends SuperActivity implements OnClickListener
{
/**
* 提交订单按钮
*/
private Button order_button;
/**
* 提交订单布局
*/
private LinearLayout orderLayout;
// private String texeString;
/**
* 名称
*/
private OrderDetailItem orderNameItem;
/**
* 数量
*/
private OrderDetailItem orderQuantityItem;
/**
* 收件人地址
*/
private OrderDetailItem orderAddresseeItem;
/**
* 收件人电话
*/
private OrderDetailItem orderPhoneItem;
/**
* 送货地址
*/
private OrderDetailItem orderDeliveryAddressItem;
/**
* 订单备注
*/
private OrderDetailItem orderRemarkItem;
/**
* 订单日期
*/
private OrderDetailItem orderDateItem;
/**
* 订单编号
*/
private OrderDetailItem orderNumberItem;
/**
* 订单金额
*/
private OrderDetailItem orderMoneyItem;
private OrderInfoBean orderInfoBean;
private OrderDetailLogic orderDetailLogic;
private HttpUtils httpUtils;
/**
* 标题栏
*/
private StoreTitleItem titleItem;
/**
* 订单详情的类型 0 确认订单 1 显示订单
*/
private int orderType;
/**
* ordertype = 1 时候,从商品详情界面传过来的商品详情
*/
private GoodsDetailInfo goodsDetailInfo;
private void initListener()
{
titleItem.setBackListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
finish();
}
});
}
private void initView()
{
titleItem = (StoreTitleItem)findViewById(R.id.order_detail_title);
//背景设置边距
LinearLayout detail_1 = (LinearLayout)findViewById(R.id.detail_1);
RelativeLayout.LayoutParams detail_1Params = (LayoutParams) detail_1.getLayoutParams();
detail_1Params.setMargins(16 * orderDetailLogic.screenWidth / 720, 12 * orderDetailLogic.screenHeight / 1280, 16 * orderDetailLogic.screenWidth / 720, 0);
detail_1.setLayoutParams(detail_1Params);
LinearLayout detail_2 = (LinearLayout)findViewById(R.id.detail_2);
RelativeLayout.LayoutParams detail_2Params = (LayoutParams) detail_2.getLayoutParams();
detail_2Params.setMargins(16 * orderDetailLogic.screenWidth / 720, 12 * orderDetailLogic.screenHeight / 1280, 16 * orderDetailLogic.screenWidth / 720, 0);
detail_2.setLayoutParams(detail_2Params);
// orderNameItem = (OrderDetailItem)findViewById(R.id.order_shopping_name);
// orderNameItem.setValue(orderInfoBean.getGoodsName());
//
// orderQuantityItem = (OrderDetailItem)findViewById(R.id.order_quantity);
// orderQuantityItem.setValue(String.valueOf(orderInfoBean.getOrderQuantity()) + "件");
//
// orderAddresseeItem = (OrderDetailItem)findViewById(R.id.order_addressee);
// orderAddresseeItem.setValue(orderInfoBean.getAddress());
//
// orderPhoneItem = (OrderDetailItem)findViewById(R.id.order_phone);
// orderPhoneItem.setValue(orderInfoBean.getPhone());
//
// orderDeliveryAddressItem = (OrderDetailItem)findViewById(R.id.order_delivery_address);
// orderDeliveryAddressItem.setValue(orderInfoBean.getDeliveryAddress());
//
// orderRemarkItem = (OrderDetailItem)findViewById(R.id.order_remark);
// orderRemarkItem.setValue(orderInfoBean.getOrderRemark());
//
// orderMoneyItem = (OrderDetailItem)findViewById(R.id.order_money);
// orderMoneyItem.setValue(String.valueOf(orderInfoBean.getOrderMoney()) + "元");
if(orderType == StoreConstant.ORDER_CONFORM)
{
//订购按钮布局
orderLayout = (LinearLayout)findViewById(R.id.order_button_layout);
orderLayout.setVisibility(View.VISIBLE);
RelativeLayout.LayoutParams orderLayoutParams = (LayoutParams) orderLayout.getLayoutParams();
orderLayoutParams.width = RelativeLayout.LayoutParams.MATCH_PARENT;
orderLayoutParams.height = 168 * orderDetailLogic.screenHeight / 1280;
orderLayout.setLayoutParams(orderLayoutParams);
order_button = (Button) findViewById(R.id.order_button);
order_button.setOnClickListener(this);
LinearLayout.LayoutParams order_buttonParams = (android.widget.LinearLayout.LayoutParams) order_button.getLayoutParams();
order_buttonParams.height = orderDetailLogic.screenHeight * 82 / 1280;
order_buttonParams.width = (orderDetailLogic.screenWidth * 304) / 720;
order_button.setLayoutParams(order_buttonParams);
order_button.setPadding((orderDetailLogic.screenWidth * 78) / 720, orderDetailLogic.screenHeight * 22 / 1280, (orderDetailLogic.screenWidth * 78) / 720, orderDetailLogic.screenHeight * 22 / 1280);
order_button.setTextSize(TypedValue.COMPLEX_UNIT_PX,
(orderDetailLogic.screenWidth * 26) / 720);
//订购数量
orderQuantityItem.setEditImageViewVisibility(View.VISIBLE);
orderQuantityItem.setEditImageListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
showOrderQuantityDialog(getResources().getString(R.string.order_detail_quantity),InputType.TYPE_CLASS_NUMBER,orderQuantityItem.getValueTextView());
}
});
//收件人
orderAddresseeItem.setEditImageViewVisibility(View.VISIBLE);
orderAddresseeItem.setEditImageListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
showOtherDialog(getResources().getString(R.string.order_detail_addressee),InputType.TYPE_CLASS_TEXT,orderAddresseeItem.getValueTextView(),0);
}
});
//联系方式
orderPhoneItem.setEditImageViewVisibility(View.VISIBLE);
orderPhoneItem.setEditImageListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
showOtherDialog(getResources().getString(R.string.order_detail_phone),InputType.TYPE_CLASS_PHONE,orderPhoneItem.getValueTextView(),1);
}
});
//送货地址
orderDeliveryAddressItem.setEditImageViewVisibility(View.VISIBLE);
orderDeliveryAddressItem.setEditImageListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
showOtherDialog(getResources().getString(R.string.order_detail_delivery_address),InputType.TYPE_CLASS_TEXT,orderDeliveryAddressItem.getValueTextView(),2);
}
});
//备注
orderRemarkItem.setEditImageViewVisibility(View.VISIBLE);
orderRemarkItem.setEditImageListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
showOtherDialog(getResources().getString(R.string.order_detail_remark),InputType.TYPE_CLASS_TEXT,orderRemarkItem.getValueTextView(),3);
}
});
}
else
{
orderDateItem = (OrderDetailItem)findViewById(R.id.order_date);
orderDateItem.setVisibility(View.VISIBLE);
// orderDateItem.setValue(orderInfoBean.getOrderTime());
orderNumberItem = (OrderDetailItem)findViewById(R.id.order_number);
orderNumberItem.setVisibility(View.VISIBLE);
// orderNumberItem.setValue(orderInfoBean.getOrderNumber());
}
}
@Override
protected void onRestart()
{
// TODO Auto-generated method stub
super.onRestart();
}
@Override
protected void onResume()
{
// TODO Auto-generated method stub
super.onResume();
}
@Override
protected void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
switch (v.getId())
{
case R.id.btn_back:
finish();
break;
case R.id.order_button:
showConformDialog();
break;
default:
break;
}
}
/**
* [订购数量选择对话框]<BR>
* [功能详细描述]
* @param title
* @param editIputType
* @param textView
*/
public void showOrderQuantityDialog(String title,int editIputType,final TextView textView)
{
final CustomCommonDialog dialog = new CustomCommonDialog(
OrderDetailActivity.this);
dialog.setTitle(title);
dialog.setEdittext();
dialog.setEditInputType(editIputType);
dialog.setOnOkButton(getResources().getString(R.string.dialog_ok), new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
String value = dialog.editText.getText().toString().trim();
if(value != null && !value.equals(""))
{
//数量最多为9999
if(value.length() >= 5)
{
showToast(getResources().getString(R.string.order_detail_error2));
return;
}
int num = Integer.parseInt(value);
// if(num > goodsDetailInfo.getStock())
// {
// showToast(getResources().getString(R.string.order_detail_error4));
// return;
// }
textView.setText(String.valueOf(num) + getResources().getString(R.string.order_detail_jian));
// orderInfoBean.setOrderQuantity(num);
// double allMoney = orderInfoBean.getGoodsPrice() * orderInfoBean.getOrderQuantity();
// orderInfoBean.setOrderMoney(allMoney);
// orderMoneyItem.getValueTextView().setText(String.valueOf(allMoney)+ getResources().getString(R.string.order_detail_jian));
dialog.dismiss();
}
else
{
showToast(getResources().getString(R.string.order_detail_error1));
}
}
});
dialog.setOnCancelButton(getResources().getString(R.string.dialog_cancel), new OnClickListener()
{
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
dialog.dismiss();
}
});
dialog.show();
}
/**
* [订购数量选择对话框]<BR>
* [功能详细描述]
* @param title
* @param editIputType
* @param textView
*/
public void showOtherDialog(String title,int editIputType,final TextView textView,final int key)
{
// final CustomCommonDialog dialog = new CustomCommonDialog(
// OrderDetailActivity.this);
// dialog.setTitle(title);
// dialog.setEdittext();
// dialog.setEditInputType(editIputType);
// dialog.setOnOkButton(getResources().getString(R.string.dialog_ok), new OnClickListener()
// {
// @Override
// public void onClick(View v)
// {
// // TODO Auto-generated method stub
// String value = dialog.editText.getText().toString().trim();
// textView.setText(value);
// if(key == 0)
// {
// orderInfoBean.setAddress(value);
// }
// else if(key == 1)
// {
// //电话号码长度最多15位
// if(value.length() > 15)
// {
// orderPhoneItem.setValue(orderInfoBean.getPhone());
// showToast(getResources().getString(R.string.order_detail_error3));
// return;
// }
// orderInfoBean.setPhone(value);
// }
// else if(key == 2)
// {
// orderInfoBean.setDeliveryAddress(value);
// }
// else if(key == 3)
// {
// orderInfoBean.setOrderRemark(value);
// }
// dialog.dismiss();
// }
// });
// dialog.setOnCancelButton(getResources().getString(R.string.dialog_cancel), new OnClickListener()
// {
//
// @Override
// public void onClick(View v)
// {
// // TODO Auto-generated method stub
// dialog.dismiss();
// }
// });
// dialog.show();
}
/**
* [显示确认支付,选择 一卡通, 支付宝 的弹出框]<BR>
* [功能详细描述]
*/
public void showConformDialog()
{
// final CustomSingleChoiceListDialog dialog = new CustomSingleChoiceListDialog(
// OrderDetailActivity.this);
//
//// int[] i = { 0, 1 };
// //对收件人,电话,收货地址,购买数量检查
// if(StringUtil.isNullOrEmpty(orderInfoBean.getAddress()) || StringUtil.isNullOrEmpty(orderInfoBean.getDeliveryAddress())
// || StringUtil.isNullOrEmpty(orderInfoBean.getPhone())
// || (orderInfoBean.getOrderQuantity() == 0))
// {
// showToast(getResources().getString(R.string.order_detail_error));
// return;
// }
// String[] j = { "一卡通", "支付宝" };
// dialog.setSingleChoiceItems(j, 0);
// dialog.setOnOkButton(getResources().getString(R.string.dialog_ok),new OnClickListener()
// {
// @Override
// public void onClick(View v)
// {
// // TODO Auto-generated method stub
// addOrder();
// dialog.dismiss();
// }
// });
// dialog.setOnCancelButton(getResources().getString(R.string.dialog_cancel));
// dialog.show();
}
@Override
public void initData()
{
// TODO Auto-generated method stub
orderDetailLogic = OrderDetailLogic.getInstance(getApplicationContext());
orderDetailLogic.setData(mHandler);
httpUtils = new HttpUtils();
orderType = getIntent().getIntExtra(StoreConstant.ORDER_TYPE, StoreConstant.ORDER_CONFORM);
//确认订单
if(orderType == StoreConstant.ORDER_CONFORM)
{
goodsDetailInfo = (GoodsDetailInfo) getIntent().getSerializableExtra(StoreConstant.GOODSDETAIL);
orderInfoBean = new OrderInfoBean();
// orderInfoBean.setGoodsName(goodsDetailInfo.getName());
// orderInfoBean.setGoodsPrice(goodsDetailInfo.getSalePrice());
// //默认订购1件
// orderInfoBean.setOrderQuantity(1);
// double allMoney = orderInfoBean.getGoodsPrice() * orderInfoBean.getOrderQuantity();
// orderInfoBean.setOrderMoney(allMoney);
//
// orderInfoBean.setGoodsId(goodsDetailInfo.getId());
// orderInfoBean.setSpId(goodsDetailInfo.getsInfo().getSpid());
//
// orderInfoBean.setAddress(orderDetailLogic.reallyName);
// orderInfoBean.setDeliveryAddress(orderDetailLogic.deliveryAddress);
// orderInfoBean.setPhone(orderDetailLogic.phone);
}
//查看订单详情
else
{
orderInfoBean = (OrderInfoBean) getIntent().getSerializableExtra(StoreConstant.ORDER_DETAIL);
}
}
private void addOrder()
{
showProcessDialog(new DialogInterface.OnDismissListener()
{
@Override
public void onDismiss(DialogInterface dialog)
{
orderDetailLogic.stopRequest();
}
});
orderDetailLogic.sendAddOrderReq(orderInfoBean, httpUtils);
}
@Override
public void initLayout(Bundle paramBundle)
{
// TODO Auto-generated method stub
setContentView(R.layout.orderdetail);
// initData();
initView();
initListener();
}
@Override
public void clearData()
{
// TODO Auto-generated method stub
}
public void handleMsg(Message msg)
{
super.handleMsg(msg);
switch (msg.what)
{
case StoreConstant.GET_ADDORDER_SUCCESS:
showToast(getResources().getString(R.string.order_add_suessce));
break;
case StoreConstant.GET_ADDORDER_FAILED:
showToast(getResources().getString(R.string.error_1));
break;
}
};
}
|
unlicense
|
KalaiselvanS/codejam
|
Problems/src/com/problems/SortWords.java
|
5251
|
package com.problems;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
/**
*
Find word count and then sorting the words as per their count.
If count is same then sort the words with same count in alphabetical order.
Input: ["a", "a", "aa", "b", "a", "bb", "bbc", "ba", "ab", "b", "b", "aa", "am", "am" ]
Output:
[
a : 3 ,
b : 3 ,
aa : 2 ,
am : 2 ,
ab : 1 ,
ba : 1 ,
bb : 1 ,
bbc : 1 ]
*
*/
public class SortWords {
public static void main(String[] args) {
String[] words = new String[] { "a", "a", "aa", "b", "a", "bb", "bbc", "ba", "ab", "b", "b", "aa", "am", "am" };
WordsCounter counter = new WordsCounter(words);
counter.desending().sortCount().desending().sortWords().process().desending().sortCount().ascending()
.sortWords().process().ascending().sortCount().desending().sortWords().process().ascending().sortCount()
.ascending().sortWords().process().desending().sortWords().desending().sortCount().process().desending()
.sortWords().ascending().sortCount().process().ascending().sortWords().desending().sortCount().process()
.ascending().sortWords().ascending().sortCount().process().ascending().sortWords().process().desending()
.sortWords().process().ascending().sortCount().process().desending().sortCount().process();
System.out.println("Find word count and then sorting the words as per their count."
+ "\nIf count is same then sort the words with same count in alphabetical order.");
counter.desending().sortCount().ascending().sortWords().process();
}
}
class WordsCounter {
public WordsCounter process() {
List<Word> words = new ArrayList<>(wordsMap.values());
Collections.sort(words, comparatorChain);
System.out.println(words);
comparatorChain = new ComparatorChain(null);
return this;
}
private Comparator associateComparator;
private ComparatorChain comparatorChain;
private HashMap<String, Word> wordsMap = new HashMap<>();
private static final Comparator ASCENDING_ORDER = new Comparator() {
@Override
public int compare(Object front, Object back) {
return ((Comparable) front).compareTo(back);
}
public String toString() {
return "ASCENDING_ORDER";
}
};
private static final Comparator DESCENDING_ORDER = new Comparator() {
@Override
public int compare(Object front, Object back) {
return ((Comparable) back).compareTo(front);
}
public String toString() {
return "DESCENDING_ORDER";
}
};
public WordsCounter(String[] words) {
for (String w : words) {
addWord(w);
}
associateComparator = ASCENDING_ORDER;
comparatorChain = new ComparatorChain(null);
}
public void addWord(String w) {
Word word = wordsMap.get(w);
if (word == null) {
word = new Word(w);
wordsMap.put(w, word);
}
word.increase();
}
public WordsCounter ascending() {
associateComparator = ASCENDING_ORDER;
return this;
}
public WordsCounter desending() {
associateComparator = DESCENDING_ORDER;
return this;
}
public WordsCounter sortWords() {
WordComparator wordComparator = new WordComparator(associateComparator);
ComparatorChain chain = new ComparatorChain(wordComparator);
comparatorChain.addLeaf(chain);
return this;
}
public WordsCounter sortCount() {
comparatorChain.addLeaf(new ComparatorChain(new CountComparator(associateComparator)));
return this;
}
public static class CountComparator implements Comparator<Word> {
Comparator<Integer> comparator;
public CountComparator(Comparator<Integer> comparator) {
this.comparator = comparator;
}
public int compare(Word front, Word back) {
return comparator.compare(front.count, back.count);
}
public String toString() {
return "CountComparator";
}
}
public static class WordComparator implements Comparator<Word> {
Comparator<String> comparator;
public WordComparator(Comparator<String> comparator) {
this.comparator = comparator;
}
public int compare(Word front, Word back) {
return comparator.compare(front.word, back.word);
}
public String toString() {
return "WordComparator";
}
}
public static class ComparatorChain<T> implements Comparator<T> {
private ComparatorChain<T> next;
private Comparator<T> comparator;
public ComparatorChain(Comparator<T> comparator) {
this.comparator = comparator;
}
public void addLeaf(ComparatorChain<T> next) {
if (this.next != null) {
this.next.addLeaf(next);
} else {
this.next = next;
}
}
public int compare(T front, T back) {
int rs = 0;
if (comparator != null) {
rs = comparator.compare(front, back);
}
if (rs == 0 && next != null) {
rs = next.compare(front, back);
}
return rs;
}
}
public class Word {
private String word;
private Integer count;
public Word(String word) {
this.word = word;
count = 0;
}
public void increase() {
count++;
}
@Override
public String toString() {
return String.format("\n\t%s \t: %s\t", word, count);
}
}
}
|
unlicense
|
Kapusch/purchase_service
|
purchase_service/shop/Module/Tools/LoginBox.Designer.cs
|
6111
|
namespace Magasin
{
partial class LoginBox
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tbLogin = new System.Windows.Forms.TextBox();
this.tbPassword = new System.Windows.Forms.TextBox();
this.lblLogin = new System.Windows.Forms.Label();
this.lblPasssword = new System.Windows.Forms.Label();
this.btnOK = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// tbLogin
//
this.tbLogin.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tbLogin.Location = new System.Drawing.Point(120, 24);
this.tbLogin.Name = "tbLogin";
this.tbLogin.Size = new System.Drawing.Size(154, 20);
this.tbLogin.TabIndex = 0;
//
// tbPassword
//
this.tbPassword.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.tbPassword.Location = new System.Drawing.Point(120, 54);
this.tbPassword.Name = "tbPassword";
this.tbPassword.PasswordChar = '*';
this.tbPassword.Size = new System.Drawing.Size(154, 20);
this.tbPassword.TabIndex = 1;
this.tbPassword.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tbPassword_KeyDown);
//
// lblLogin
//
this.lblLogin.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblLogin.AutoSize = true;
this.lblLogin.Location = new System.Drawing.Point(75, 27);
this.lblLogin.Name = "lblLogin";
this.lblLogin.Size = new System.Drawing.Size(39, 13);
this.lblLogin.TabIndex = 2;
this.lblLogin.Text = "Login :";
//
// lblPasssword
//
this.lblPasssword.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblPasssword.AutoSize = true;
this.lblPasssword.Location = new System.Drawing.Point(37, 57);
this.lblPasssword.Name = "lblPasssword";
this.lblPasssword.Size = new System.Drawing.Size(77, 13);
this.lblPasssword.TabIndex = 3;
this.lblPasssword.Text = "Mot de passe :";
//
// btnOK
//
this.btnOK.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.btnOK.Location = new System.Drawing.Point(120, 83);
this.btnOK.Name = "btnOK";
this.btnOK.Size = new System.Drawing.Size(75, 23);
this.btnOK.TabIndex = 4;
this.btnOK.Text = "OK";
this.btnOK.UseVisualStyleBackColor = true;
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// btnCancel
//
this.btnCancel.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.No;
this.btnCancel.Location = new System.Drawing.Point(220, 83);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 23);
this.btnCancel.TabIndex = 5;
this.btnCancel.Text = "Annuler";
this.btnCancel.UseVisualStyleBackColor = true;
//
// LoginBox
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(339, 118);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.lblPasssword);
this.Controls.Add(this.lblLogin);
this.Controls.Add(this.tbPassword);
this.Controls.Add(this.tbLogin);
this.Name = "LoginBox";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Identification";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox tbLogin;
private System.Windows.Forms.TextBox tbPassword;
private System.Windows.Forms.Label lblLogin;
private System.Windows.Forms.Label lblPasssword;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnCancel;
}
}
|
unlicense
|
koulevprime/GeoLifeReader
|
get_subset.py
|
2341
|
# Run this code to load only a small subset of the PLT files into the database.
# This code should not be used for further research, but just to demonstrate
# the underlying code is fully functional.
import logging
logging.basicConfig(
level=logging.DEBUG,
filename='/tmp/geolife.log',
filemode='w'
)
logger = logging.getLogger("geolife")
stdout = logging.StreamHandler()
stdout.setLevel(logging.INFO)
logger.addHandler(stdout)
import geolife
import time
from datetime import timedelta
import tempfile
from raw import pltfile
import random
import os
import shutil
import sys
random.seed(0)
def make_subset_copy(src, dst):
pltfiles = pltfile.get_plt_files(src)
small_subset_of_pltfiles = random.sample(pltfiles, 100)
for f in small_subset_of_pltfiles:
logger.debug(f)
# Isolate the subdirectory that will need to be created in the temporary
# destination to preserve user information.
directory = os.path.dirname(f)
destination_subpath = directory.split(src+"/")[1]
logger.debug("{0} will be created in {1}".format(
destination_subpath, sample_dir
))
# Create subdirectories if not present, and copy file.
destination_path = os.path.join(dst, destination_subpath)
logger.debug("Create path {0} if non-existent".format(destination_path))
try:
os.makedirs(destination_path)
except:
pass
shutil.copy(f, destination_path)
if __name__ == "__main__":
start = time.time()
try:
# To lighten the load of demonstrating the underlying code works,
# the following code will copy only a small subset of the GeoLife
# dataset for loading into the database.
# Copy a subset of the actual GeoLife dataset into a temporary directory.
import sys
geolife_source = sys.argv[-1]
geolife_root_directory = geolife.find_geolife_root(geolife_source)
logger.info("PLT files will come from {0}".format(geolife_root_directory))
sample_dir = tempfile.mkdtemp()
logger.info("Selected PLT files will be copied to {0}".format(sample_dir))
make_subset_copy(src=geolife_root_directory, dst=sample_dir)
except:
logger.exception("Stuff didn't do")
duration = time.time() - start
duration_delta = timedelta(seconds=duration)
print("Total execution time: {0}".format(duration_delta))
|
unlicense
|
ksean/finmgr
|
lib/src/main/java/sh/kss/finmgrlib/parse/CsvFileParserImpl.java
|
4529
|
/*
finmgr - A financial transaction framework
Copyright (C) 2021 Kennedy Software Solutions Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package sh.kss.finmgrlib.parse;
import com.google.common.collect.ImmutableList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import sh.kss.finmgrlib.entity.transaction.InvestmentTransaction;
import sh.kss.finmgrlib.parse.brokerage.RbcCsv;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
/**
* This class provides common functionality for the processing of .csv files into finmgr InvestmentTransactions
*
*/
@Component
public class CsvFileParserImpl implements CsvFileParser {
// Log manager
private final Logger LOG = LoggerFactory.getLogger(CsvFileParserImpl.class);
// A list of the available Csv parsers
private final List<CsvParser> CSV_PARSERS = ImmutableList.of(new RbcCsv());
@Override
public List<InvestmentTransaction> parseCsv(File file) {
LOG.debug("Calling parseCsv()");
// Wrap in try catch due to opening file input stream
try (FileInputStream inputStream = new FileInputStream(file)) {
// Try to match against known row parsers
for (CsvParser csvParser : CSV_PARSERS) {
LOG.debug(String.format("Check CsvParser %s", csvParser));
// If the header matches, parse it
if (csvParser.isMatch(inputStream)) {
LOG.debug(String.format("Matched CsvParser %s", csvParser));
return parseLines(file, csvParser);
}
}
// If no Row Parsers matched, the file format is unknown and no transactions are parsed
return Collections.emptyList();
} catch (FileNotFoundException fnfe) {
LOG.error(String.format("FileNotFoundException occurred when creating FileInputStream for file %s", file.getAbsoluteFile()));
fnfe.printStackTrace();
} catch (IOException ioe) {
LOG.error(String.format("IOException occurred when creating FileInputStream for file %s", file.getAbsoluteFile()));
ioe.printStackTrace();
}
return Collections.emptyList();
}
private List<InvestmentTransaction> parseLines(File file, CsvParser csvParser) {
LOG.debug("Calling parseLines()");
// Wrap in try catch due to opening file input stream
try (FileInputStream inputStream = new FileInputStream(file)) {
// Instantiate the list to hold transactions
List<InvestmentTransaction> transactions = new ArrayList<>();
// Create a UTF-8 Scanner on the input stream
Scanner scanner = new Scanner(inputStream, StandardCharsets.UTF_8);
// While more lines exist
while (scanner.hasNextLine()) {
// Fetch the line
String line = scanner.nextLine();
LOG.debug(line);
// Parse the line and add to the list if a valid row was found
csvParser.parse(line)
.ifPresent(transactions::add);
}
return transactions;
} catch (FileNotFoundException fnfe) {
LOG.error(String.format("FileNotFoundException occurred when creating FileInputStream for file %s", file.getAbsoluteFile()));
fnfe.printStackTrace();
} catch (IOException ioe) {
LOG.error(String.format("IOException occurred when creating FileInputStream for file %s", file.getAbsoluteFile()));
ioe.printStackTrace();
}
return Collections.emptyList();
}
}
|
unlicense
|
marwei/leetcode
|
problem/226.rb
|
1236
|
# Definition for a binary tree node.
class TreeNode
attr_accessor :val, :left, :right
def initialize(val)
@val = val
@left = nil
@right = nil
end
end
# @param {TreeNode} root
# @return {TreeNode}
def invert_tree(root)
queue = []
queue.push root
until queue.empty?
curr = queue.shift
next if curr.nil?
queue.push curr.left
queue.push curr.right
curr.left, curr.right = curr.right, curr.left
end
root
end
# head = TreeNode.new(1)
# head.left = TreeNode.new(2)
# head.right = TreeNode.new(3)
# two = head.left
# two.left = TreeNode.new(4)
# two.right = TreeNode.new(5)
# three = head.right
# three.left = TreeNode.new(6)
# three.right = nil
# four = two.left
# four.left = TreeNode.new(7)
# four.right = TreeNode.new(8)
# five = two.right
# five.left = TreeNode.new(9)
# five.right = TreeNode.new(10)
# def print_tree(root)
# queue = []
# queue.push root
# until queue.empty?
# curr = queue.shift
# next if curr.nil?
# queue.push curr.left
# queue.push curr.right
# puts "#{curr.val}'s left is "+"#{curr.left.val}" if curr.left
# puts "#{curr.val}'s right is "+"#{curr.right.val}" if curr.right
# end
# end
# invert_tree head
# print_tree head
|
unlicense
|
jfellien/car-rental-event-handling
|
Handle-RentCar/index.js
|
268
|
module.exports = (context, event, sourceCar) => {
context.log.info(`EVENT: ${ JSON.stringify(event) }`);
context.log.info(`SOURCE CAR: ${ JSON.stringify(sourceCar) }`)
sourceCar.status = "rented";
context.bindings.sinkCar = sourceCar;
context.done();
}
|
unlicense
|
The-TTP-Project/Singular-Chests
|
Singular Chests/src/com/tterrag/singularChests/lib/Reference.java
|
440
|
package com.tterrag.singularChests.lib;
public class Reference {
public static final String MOD_ID = "singularChests";
public static final String MOD_NAME = "Singular Chests";
public static final String VERSION = "0.0.1";
public static final String CLIENT_PROXY_CLASS = "com.tterrag.singularChests.proxy.ClientProxy";
public static final String SERVER_PROXY_CLASS = "com.tterrag.singularChests.proxy.CommonProxy";
}
|
unlicense
|
codeApeFromChina/resource
|
frame_packages/java_libs/hibernate-distribution-3.6.10.Final/project/hibernate-testsuite/src/test/java/org/hibernate/test/annotations/onetoone/hhh4851/Hardware.java
|
1060
|
package org.hibernate.test.annotations.onetoone.hhh4851;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(discriminatorType = DiscriminatorType.STRING, name = "DeviceType", length = 1)
@DiscriminatorValue(value = "C")
public class Hardware extends BaseEntity {
private Hardware parent = null;
protected Hardware() {
}
public Hardware(Hardware parent) {
this.parent = parent;
}
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
public Hardware getParent() {
return this.parent;
}
public void setParent(Hardware parent) {
this.parent = parent;
}
}
|
unlicense
|
litesoft/ScarPlus
|
src/com/esotericsoftware/utils/FileSupport.java
|
7532
|
package com.esotericsoftware.utils;
import com.esotericsoftware.scar.*;
public class FileSupport
{
public static final String WINDOWS_UNC_PATH_PREFIX = "\\\\";
public static String getWindowsDriveIndicator( String path )
{
return ((path.length() > 1) && (path.charAt( 1 ) == ':')) ? path.substring( 0, 2 ).toUpperCase() : "";
}
public static String removeFromFront( String pToRemove, String path )
{
return (pToRemove.length() == 0) ? path : path.substring( pToRemove.length() );
}
public static String normalizePath( IFileSystem pFileSystem, String path )
{
path = path.trim();
String zPrefix = "";
if ( pFileSystem.isWindows() )
{
if ( path.startsWith( WINDOWS_UNC_PATH_PREFIX ) )
{
path = removeFromFront( zPrefix = WINDOWS_UNC_PATH_PREFIX, path ).trim();
}
else
{
path = removeFromFront( zPrefix = getWindowsDriveIndicator( path ), path ).trim(); // Handle Drive Letter
}
}
path = path.trim();
if ( '/' != pFileSystem.separatorChar() )
{
path = path.replace( '/', pFileSystem.separatorChar() );
}
int at = path.indexOf( pFileSystem.separatorChar() );
if ( at != -1 )
{
String zFileSeparator = "" + pFileSystem.separatorChar();
// remove white space around file Parts
StringBuilder sb = new StringBuilder( path.length() );
int from = 0;
do
{
sb.append( path.substring( from, at ).trim() ).append( pFileSystem.separatorChar() );
from = at + 1;
}
while ( -1 != (at = path.indexOf( pFileSystem.separatorChar(), from )) );
path = sb.append( path.substring( from ).trim() ).toString();
// Clean up silly middle nothings
path = Utils.replace( path, zFileSeparator + "." + zFileSeparator, zFileSeparator ); // "/./"
path = Utils.replace( path, zFileSeparator + zFileSeparator, zFileSeparator ); // "//"
// Remove ending "/."
while ( path.endsWith( zFileSeparator + "." ) )
{
path = path.substring( 0, path.length() - 2 );
}
// Remove leading "./"
while ( path.startsWith( "." + zFileSeparator ) )
{
path = path.substring( 2 );
}
// Process Funky ..
String zPrefixDotDotSlash = "";
String zDotDotSlash = ".." + zFileSeparator;
while ( path.startsWith( zDotDotSlash ) )
{
zPrefixDotDotSlash += zDotDotSlash;
path = path.substring( 3 );
}
String zUpLevel = zFileSeparator + "..";
if ( path.endsWith( zUpLevel ) )
{
path += zFileSeparator;
}
zUpLevel += zFileSeparator;
for ( at = path.indexOf( zUpLevel ); at > 0; at = path.indexOf( zUpLevel ) )
{
path = removeDotDot( path, at, pFileSystem.separatorChar() );
}
path = zPrefixDotDotSlash + path;
if ( (path.length() > 1) && path.endsWith( zFileSeparator ) )
{
path = path.substring( 0, path.length() - 1 );
}
}
if ( path.length() == 0 )
{
path = ".";
}
path = zPrefix + path;
return path;
}
private static String removeDotDot( String path, int pAt, char pSeparatorChar )
{
int zEnd = pAt + 4;
while ( path.charAt( --pAt ) != pSeparatorChar )
{
if ( pAt == 0 )
{
return path.substring( zEnd );
}
}
return path.substring( 0, pAt + 1 ) + path.substring( zEnd );
}
public static boolean isAbsoluteNormalizedPath( IFileSystem pFileSystem, String pCanonicalParentDirIfPathRelativeForWindowsDriveLetter, String path )
{
if ( pFileSystem.isWindows() )
{
if ( path.startsWith( WINDOWS_UNC_PATH_PREFIX ) )
{
return true;
}
String zDriveIndicator = getWindowsDriveIndicator( path );
if ( zDriveIndicator.length() != 0 ) // Handle Drive Letter
{
if ( !pCanonicalParentDirIfPathRelativeForWindowsDriveLetter.startsWith( zDriveIndicator ) || !pFileSystem.canonicalCurrentPath().startsWith( zDriveIndicator ) )
{
return true; // Has Drive Letter and it is NOT the same both the 'CanonicalDirForWindowDriveLetterSourceRelativeness' && pFileSystem.canonicalCurrentPath()
}
path = removeFromFront( zDriveIndicator, path );
}
}
return (path.length() > 0) && (path.charAt( 0 ) == pFileSystem.separatorChar());
}
public static String canonicalizeNormalizedPath( IFileSystem pFileSystem, String pCanonicalParentDirIfPathRelative, String path )
{
if ( !pFileSystem.isWindows() )
{
if ( !isAbsoluteNormalizedPath( pFileSystem, pCanonicalParentDirIfPathRelative, path ) )
{
path = normalizePath( pFileSystem, pCanonicalParentDirIfPathRelative + pFileSystem.separatorChar() + path );
}
return canonicalizeAbsoluteNormalizedPath( pFileSystem, path );
}
// Windows!
if ( path.startsWith( WINDOWS_UNC_PATH_PREFIX ) )
{
return canonicalizeAbsoluteNormalizedPath( pFileSystem, path );
}
String zDriveIndicator = getWindowsDriveIndicator( path );
if ( !isAbsoluteNormalizedPath( pFileSystem, pCanonicalParentDirIfPathRelative, path ) ) // Relative!
{
path = normalizePath( pFileSystem, pCanonicalParentDirIfPathRelative + pFileSystem.separatorChar() + removeFromFront( zDriveIndicator, path ) );
return canonicalizeAbsoluteNormalizedPath( pFileSystem, path );
}
// Absolute
if ( zDriveIndicator.length() == 0 ) // to "default" Drive
{
return canonicalizeAbsoluteNormalizedPath( pFileSystem, path );
}
// Windows path w/ DriveIndicator which 'might' actually be relative to the given DriveIndicator
if ( (path = removeFromFront( zDriveIndicator, path )).length() == 0 ) // Should NOT be possible!
{
path = ".";
}
if ( (path.charAt( 0 ) != pFileSystem.separatorChar()) && !path.startsWith( "." ) )
{
path = "." + pFileSystem.separatorChar() + path;
}
return canonicalizeAbsoluteNormalizedPath( pFileSystem, zDriveIndicator + path );
}
private static String canonicalizeAbsoluteNormalizedPath( IFileSystem pFileSystem, String path )
{
String origPath = path;
if ( !pFileSystem.exists( origPath ) )
{
String zEnd = "";
for ( int at; -1 != (at = path.lastIndexOf( pFileSystem.separatorChar() )); )
{
zEnd = path.substring( at ) + zEnd;
if ( pFileSystem.exists( path = path.substring( 0, at ) ) )
{
return pFileSystem.canonicalizeNormalizedExisting( path ) + zEnd;
}
}
}
return pFileSystem.canonicalizeNormalizedExisting( origPath );
}
}
|
unlicense
|
DeveloperXY/MyIMDB
|
app/src/main/java/com/developerxy/myimdb/ui/fragments/SecondFragment.java
|
3606
|
package com.developerxy.myimdb.ui.fragments;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import com.annimon.stream.Collectors;
import com.annimon.stream.Stream;
import com.developerxy.myimdb.R;
import com.developerxy.myimdb.adapters.GenreAdapter;
import com.developerxy.myimdb.models.Genre;
import com.developerxy.myimdb.models.Show;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
public class SecondFragment extends NavigableFragment {
private SecondFragmentListener mListener;
private GenreAdapter genreAdapter;
@Bind(R.id.genreListview)
ListView genreListview;
public SecondFragment() {
// Required empty public constructor
}
public static SecondFragment newInstance(Show show) {
SecondFragment fragment = new SecondFragment();
if (show != null) {
Bundle args = new Bundle();
List<String> genres = show.getGenres();
args.putStringArrayList("genres", new ArrayList<>(genres));
fragment.setArguments(args);
}
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_second, container, false);
ButterKnife.bind(this, view);
List<String> genres = new ArrayList<>();
Bundle args = getArguments();
if (args != null) {
genres = args.getStringArrayList("genres");
}
List<String> gList = Arrays.asList(
getActivity().getResources().getStringArray(R.array.genreArray));
List<Genre> genresList = Stream.of(gList).map(g -> new Genre(g, false)).collect(Collectors.toList());
Stream.of(genres)
.forEach(g -> {
int index = gList.indexOf(g);
genresList.get(index).setSelected(true);
});
System.out.println(genresList);
genreAdapter = new GenreAdapter(getActivity(), R.layout.genre_list_item, genresList);
genreListview.setAdapter(genreAdapter);
return view;
}
/* If the onAttach(Context context) version is used instead, the method does not get called on API 19 devices. */
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (SecondFragmentListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement SecondFragmentListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onNext() {
List<String> genres = genreAdapter.getSelectedGenres();
if (genres.size() == 0) {
Toast.makeText(getActivity(), "Please select at least 1 genre.", Toast.LENGTH_SHORT).show();
return;
}
if (mListener != null)
mListener.navigateToThirdFragment(genres);
else
Toast.makeText(getActivity(), "Listener is null.", Toast.LENGTH_SHORT).show();
}
public interface SecondFragmentListener {
void navigateToThirdFragment(List<String> genres);
}
}
|
unlicense
|
DarthMaulware/EquationGroupLeaks
|
Leak #5 - Lost In Translation/windows/Resources/Python/Core/Lib/__future__.py
|
3727
|
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: __future__.py
"""Record of phased-in incompatible language changes.
Each line is of the form:
FeatureName = "_Feature(" OptionalRelease "," MandatoryRelease ","
CompilerFlag ")"
where, normally, OptionalRelease < MandatoryRelease, and both are 5-tuples
of the same form as sys.version_info:
(PY_MAJOR_VERSION, # the 2 in 2.1.0a3; an int
PY_MINOR_VERSION, # the 1; an int
PY_MICRO_VERSION, # the 0; an int
PY_RELEASE_LEVEL, # "alpha", "beta", "candidate" or "final"; string
PY_RELEASE_SERIAL # the 3; an int
)
OptionalRelease records the first release in which
from __future__ import FeatureName
was accepted.
In the case of MandatoryReleases that have not yet occurred,
MandatoryRelease predicts the release in which the feature will become part
of the language.
Else MandatoryRelease records when the feature became part of the language;
in releases at or after that, modules no longer need
from __future__ import FeatureName
to use the feature in question, but may continue to use such imports.
MandatoryRelease may also be None, meaning that a planned feature got
dropped.
Instances of class _Feature have two corresponding methods,
.getOptionalRelease() and .getMandatoryRelease().
CompilerFlag is the (bitfield) flag that should be passed in the fourth
argument to the builtin function compile() to enable the feature in
dynamically compiled code. This flag is stored in the .compiler_flag
attribute on _Future instances. These values must match the appropriate
#defines of CO_xxx flags in Include/compile.h.
No feature line is ever to be deleted from this file.
"""
all_feature_names = [
'nested_scopes',
'generators',
'division',
'absolute_import',
'with_statement',
'print_function',
'unicode_literals']
__all__ = [
'all_feature_names'] + all_feature_names
CO_NESTED = 16
CO_GENERATOR_ALLOWED = 0
CO_FUTURE_DIVISION = 8192
CO_FUTURE_ABSOLUTE_IMPORT = 16384
CO_FUTURE_WITH_STATEMENT = 32768
CO_FUTURE_PRINT_FUNCTION = 65536
CO_FUTURE_UNICODE_LITERALS = 131072
class _Feature:
def __init__(self, optionalRelease, mandatoryRelease, compiler_flag):
self.optional = optionalRelease
self.mandatory = mandatoryRelease
self.compiler_flag = compiler_flag
def getOptionalRelease(self):
"""Return first release in which this feature was recognized.
This is a 5-tuple, of the same form as sys.version_info.
"""
return self.optional
def getMandatoryRelease(self):
"""Return release in which this feature will become mandatory.
This is a 5-tuple, of the same form as sys.version_info, or, if
the feature was dropped, is None.
"""
return self.mandatory
def __repr__(self):
return '_Feature' + repr((self.optional,
self.mandatory,
self.compiler_flag))
nested_scopes = _Feature((2, 1, 0, 'beta', 1), (2, 2, 0, 'alpha', 0), CO_NESTED)
generators = _Feature((2, 2, 0, 'alpha', 1), (2, 3, 0, 'final', 0), CO_GENERATOR_ALLOWED)
division = _Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), CO_FUTURE_DIVISION)
absolute_import = _Feature((2, 5, 0, 'alpha', 1), (2, 7, 0, 'alpha', 0), CO_FUTURE_ABSOLUTE_IMPORT)
with_statement = _Feature((2, 5, 0, 'alpha', 1), (2, 6, 0, 'alpha', 0), CO_FUTURE_WITH_STATEMENT)
print_function = _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), CO_FUTURE_PRINT_FUNCTION)
unicode_literals = _Feature((2, 6, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), CO_FUTURE_UNICODE_LITERALS)
|
unlicense
|
Grauenwolf/DotNet-ORM-Cookbook
|
ORM Cookbook/Recipes.LinqToDB/RowCount/RowCountScenario.cs
|
1017
|
using LinqToDB;
using Recipes.LinqToDB.Entities;
using Recipes.RowCount;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Recipes.LinqToDB.RowCount
{
public class RowCountScenario : IRowCountScenario<Employee>
{
public int EmployeeCount(string lastName)
{
using (var db = new OrmCookbook())
return db.Employee.Where(e => e.LastName == lastName).Count();
}
public int EmployeeCount()
{
using (var db = new OrmCookbook())
return db.Employee.Count();
}
public void InsertBatch(IList<Employee> employees)
{
if (employees == null || employees.Count == 0)
throw new ArgumentException($"{nameof(employees)} is null or empty.", nameof(employees));
using (var db = new OrmCookbook())
{
foreach (var employee in employees)
db.Insert(employee);
}
}
}
}
|
unlicense
|
jlaura/isis3
|
isis/src/base/objs/IsisAml/IsisXMLGroup.cpp
|
2895
|
/** This is free and unencumbered software released into the public domain.
The authors of ISIS do not claim copyright on the contents of this file.
For more details about the LICENSE terms and the AUTHORS, you will
find files of those names at the top level of this repository. **/
/* SPDX-License-Identifier: CC0-1.0 */
#include <string>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/sax2/SAX2XMLReader.hpp>
#include <xercesc/sax2/Attributes.hpp>
#include "IsisXMLGroup.h"
#include "IsisXMLChTrans.h"
#include "IString.h"
using namespace std;
namespace XERCES = XERCES_CPP_NAMESPACE;
// Constructors
IsisXMLGroup::IsisXMLGroup(char *PencodingName,
bool &PexpandNamespaces,
XERCES::SAX2XMLReader* &Pparser,
IsisGroupData *Pgroup) {
encodingName = PencodingName;
expandNamespaces = PexpandNamespaces;
parser = Pparser;
group = Pgroup;
prevDocHandler = parser->getContentHandler();
prevErrorHandler = parser->getErrorHandler();
parser->setContentHandler(this);
parser->setErrorHandler(this);
parameterHandler = NULL;
ignoreHandler = NULL;
}
IsisXMLGroup::~IsisXMLGroup() {
if(parameterHandler != NULL) delete parameterHandler;
if(ignoreHandler != NULL) delete ignoreHandler;
}
// IsisXMLGroup: Overrides of the SAX DocumentHandler interface
void IsisXMLGroup::characters(const XMLCh *const chars,
const XMLSize_t length) {
}
void IsisXMLGroup::endElement(const XMLCh *const uri,
const XMLCh *const localname,
const XMLCh *const qname) {
parser->setContentHandler(prevDocHandler);
parser->setErrorHandler(prevErrorHandler);
}
void IsisXMLGroup::startElement(const XMLCh *const uri,
const XMLCh *const localname,
const XMLCh *const qname,
const XERCES::Attributes &attributes) {
if((string)XERCES::XMLString::transcode(localname) == (string)"parameter") {
if(parameterHandler != NULL) {
delete parameterHandler;
parameterHandler = NULL;
}
unsigned int index = group->parameters.size();
group->parameters.resize(index + 1);
QString name = XERCES::XMLString::transcode(attributes.getValue((XMLSize_t)0));
// Taken out after PVL refactor name.UpCase();
group->parameters[index].name = name;
parameterHandler = new IsisXMLParameter(encodingName, expandNamespaces,
parser, &group->parameters[index]);
}
else {
if(ignoreHandler != NULL) {
delete ignoreHandler;
ignoreHandler = NULL;
}
ignoreHandler = new IsisXMLIgnore(encodingName, expandNamespaces, parser,
(string)XERCES::XMLString::transcode(localname));
}
}
|
unlicense
|
cartman300/Vulkan.NET
|
Test/Properties/AssemblyInfo.cs
|
1384
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Test")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5acf8106-7e8d-44a3-ae67-45b59c2dded4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
unlicense
|
taujago/birojasa
|
application/modules/bj_serah_dealer/views/bj_serah_dealer_view_js.php
|
6457
|
<script type="text/javascript">
function modal_dealer(){
$('#dealer').modal('show');
}
// $("#tombolsubmitsimpan").click(function(){
// console.log('tests');
// $.ajax({
// url:'<?php echo site_url("$this->controller/simpan"); ?>',
// data : $('#form_data').serialize(),
// type : 'post',
// dataType : 'json',
// success : function(obj){
// console.log(obj.error);
// if(obj.error == false) { // berhasil
// // alert('hooooo.. error false');
// BootstrapDialog.alert({
// type: BootstrapDialog.TYPE_PRIMARY,
// title: 'Informasi',
// message: obj.message
// });
// $('#form_data').data('bootstrapValidator').resetForm(true);
// }
// else {
// BootstrapDialog.alert({
// type: BootstrapDialog.TYPE_DANGER,
// title: 'Error',
// message: obj.message
// });
// }
// }
// });
// $('#biro_jasa').DataTable().ajax.reload();
// // $('#tombolsubmitsimpan').click();
// return false;
// });
function serah_dealer_simpan(){
$.ajax({
url:'<?php echo site_url("$this->controller/simpan"); ?>',
data : $('#form_data').serialize(),
type : 'post',
dataType : 'json',
success : function(obj){
console.log(obj.error);
if(obj.error == false) { // berhasil
// alert('hooooo.. error false');
BootstrapDialog.alert({
type: BootstrapDialog.TYPE_PRIMARY,
title: 'Informasi',
message: obj.message
});
// $('#form_data').data('bootstrapValidator').resetForm(true);
}
else {
BootstrapDialog.alert({
type: BootstrapDialog.TYPE_DANGER,
title: 'Error',
message: obj.message
});
}
}
});
$('#bj_bbn_satu').DataTable().ajax.reload();
$('#dealer').modal('hide');
return false;
}
$(document).ready(function(){
$(".tanggal").datepicker().on('changeDate', function(ev){
$('.tanggal').datepicker('hide');
});
// });
$("#cetak").click(function() {
var tanggal_awal;
var tanggal_akhir;
var kode_dealer;
tanggal_awal = $("#tanggal_awal").val();
tanggal_akhir = $("#tanggal_akhir").val();
kode_dealer = $("#kode_dealer").val();
// window.alert(desa);
open('<?php echo site_url("$this->controller/cetak_serah_dealer?"); ?>'+'tanggal_awal='+ tanggal_awal +'&tanggal_akhir='+tanggal_akhir+'&kode_dealer='+ kode_dealer);
});
var dt = $("#bj_bbn_satu").DataTable(
{
// "order": [[ 0, "desc" ]],
// "iDisplayLength": 50,
"columnDefs": [ { "targets": 0, "orderable": false } ],
"processing": true,
"serverSide": true,
"ajax": '<?php echo site_url($this->controller."/get_data") ?>'
});
$("#bj_bbn_satu_filter").css("display","none");
$("#btn_submit").click(function(){
// alert('hello');
dt.column(1).search($("#tanggal_awal").val())
.column(2).search($("#tanggal_akhir").val())
.column(3).search($("#no_rangka").val())
.column(4).search($("#kode_dealer").val())
.draw();
return false;
});
$("#btn_reset").click(function(){
$("#tanggal_awal").val('');
$("#tanggal_akhir").val('');
$("#no_rangka").val('');
$("#kode_dealer").val('');
$("#btn_submit").click();
});
});
function printkwitansi(id){
open('<?php echo site_url("$this->controller/printkwitansi?"); ?>'+'id='+ id);
}
function hapus(id){
BootstrapDialog.show({
message : 'ANDA AKAN MENGHAPUS DATA BIRO JASA. ANDA YAKIN ? ',
title: 'KONFIRMASI HAPUS DATA BIRO JASA',
draggable: true,
buttons : [
{
label : 'YA',
cssClass : 'btn-primary',
hotkey: 13,
action : function(dialogItself){
dialogItself.close();
$('#myPleaseWait').modal('show');
$.ajax({
url : '<?php echo site_url("$this->controller/hapusdata") ?>',
type : 'post',
data : {id : id},
dataType : 'json',
success : function(obj) {
$('#myPleaseWait').modal('hide');
if(obj.error==false) {
BootstrapDialog.alert({
type: BootstrapDialog.TYPE_PRIMARY,
title: 'Informasi',
message: obj.message,
});
$('#bj_bbn_satu').DataTable().ajax.reload();
}
else {
BootstrapDialog.alert({
type: BootstrapDialog.TYPE_DANGER,
title: 'Error',
message: obj.message,
});
}
}
});
}
},
{
label : 'TIDAK',
cssClass : 'btn-danger',
action: function(dialogItself){
dialogItself.close();
}
}
]
});
}
</script>
|
unlicense
|
seckcoder/lang-learn
|
python/functools_user.py
|
1878
|
#!/usr/bin/env python
#-*- coding=utf-8 -*-
#
# Copyright 2013 Jike Inc. All Rights Reserved.
# Author: liwei@jike.com
"""
Provides demos for function in functools
"""
import functools
def demo_update_wrapper():
def decorator(f):
def wrapper(*args, **kwargs):
'''wrapper func'''
print 'Calling wrapper'
return f(*args, **kwargs)
return wrapper
def example():
'''Demo for update_wrapper'''
print "Called example function"
example_wrapper = decorator(example)
# NOTE(by seckcoder) : what update_wrapper does here is to overwrite the __name__,
# __module__, __doc__ attribute of wrapper(ie, example_wrapper) with wrapped's(ie example)
# and update wrapper(ie, example_wrapper)'s __dict__ with wrapped's(ie, example) __dict__
# it's just like the wrapper has wrapped in some attributes of wrapped
functools.update_wrapper(wrapper=example_wrapper,
wrapped=example)
example = example_wrapper
example()
print "example_wrapper name:\'{0.__name__}\', doc: \'{0.__doc__}\'".format(example)
def demo_wraps():
def decorator(f):
# NOTE(by seckcoder) : what wraps does here is to overwrite the __name__, __module__,
# __doc__ attribute of wrapper with f's, and update wrapper's __dict__ with
# f'__dict__, it's just like wrapper has wrapped in some attributes of f
@functools.wraps(f)
def wrapper(*args, **kwargs):
'''wrapper func'''
print 'Calling wrapper'
return f(*args, **kwargs)
return wrapper
@decorator
def example():
'''Demo for update_wrapper'''
print "Called example function"
example()
print "example_wrapper name:\'{0.__name__}\', doc: \'{0.__doc__}\'".format(example)
demo_wraps()
#demo_update_wrapper()
|
unlicense
|
sangshub/55231
|
Client/CubeEffect.cpp
|
3511
|
#include "StdAfx.h"
#include "CubeEffect.h"
#include "BufferMgr.h"
#include "Device.h"
#include "Pipeline.h"
#include "CamMgr.h"
#include "Rand.h"
#include "TextureMgr.h"
#include "TimeMgr.h"
CCubeEffect::CCubeEffect(void)
{
}
CCubeEffect::~CCubeEffect(void)
{
}
HRESULT CCubeEffect::Initialize(void)
{
m_dwVtxCnt = 8;
m_dwIndexCnt = 12;
m_pCubeTex = new VTXCUBE[m_dwVtxCnt];
m_pConvertCubeTex = new VTXCUBE[m_dwVtxCnt];
m_pIndex = new INDEX[m_dwIndexCnt];
m_pBufferMgr->GetVtxInfo(TEXT("CubeTex"), m_pCubeTex);
m_pBufferMgr->GetIndex(TEXT("CubeTex"), m_pIndex);
ZeroMemory(m_fAngle, sizeof(float)*3);
ZeroMemory(&m_tCube, sizeof(m_tCube));
m_eObjId = OBJ_ETC;
return S_OK;
}
const int CCubeEffect::Progress(void)
{
SetActive();
SetMatrix();
m_fTime += GETTIME;
m_fGravityTime += GETTIME;
if(m_fTime > m_fMaxTime)
return 1;
return 0;
}
void CCubeEffect::Render(void)
{
m_pDevice->GetDevice()->SetTexture(0, m_pCubeTexture);
m_pBufferMgr->SetVtxInfo(TEXT("CubeTex"), m_pConvertCubeTex);
m_pBufferMgr->RenderBuffer(TEXT("CubeTex"));
m_pDevice->GetDevice()->SetTexture(0, NULL);
}
void CCubeEffect::SetMatrix(const float fScale)
{
D3DXMATRIX matView;
D3DXMATRIX matProj;
CPipeline::MakeWorldMatrix(m_tInfo.matWorld, D3DXVECTOR3(m_fScale, m_fScale, m_fScale), m_fAngle, m_tInfo.vPos);
m_pCamMgr->GetMatrix(D3DTS_VIEW, matView);
m_pCamMgr->GetMatrix(D3DTS_PROJECTION, matProj);
memcpy(m_pConvertCubeTex, m_pCubeTex, sizeof(VTXCUBE) * m_dwVtxCnt);
for(size_t i = 0; i < m_dwVtxCnt; ++i)
{
CPipeline::MyTransformCoord(m_pConvertCubeTex[i].vPos, m_pConvertCubeTex[i].vPos, m_tInfo.matWorld);
CPipeline::MyTransformCoord(m_pConvertCubeTex[i].vPos, m_pConvertCubeTex[i].vPos, matView);
if(m_pConvertCubeTex[i].vPos.z < 1.f)
m_pConvertCubeTex[i].vPos.z = 1.f;
CPipeline::MyTransformCoord(m_pConvertCubeTex[i].vPos, m_pConvertCubeTex[i].vPos, matProj);
}
}
void CCubeEffect::CubeSetting(const D3DXVECTOR3& vPos
, const float fScale
, const int iSpeed //ÀÔÀÚ ¼Óµµ
, const int iMaxSpeed //ÀÔÀÚ ÃÖ´ë ¼Óµµ
, const float fElasticity
, const float fTime
, const float fUpPower
, const int iDrawId
, const D3DXVECTOR3& vDamageDir // µ¥¹ÌÁö ¹ÞÀº ¹æÇâ
, const bool bGravity
, const bool bSizeRnd // Å©±â·£´ý
)
{
m_tInfo.vPos = vPos;
m_tInfo.vDir = D3DXVECTOR3((float)CRand::Random(-10, 10), (float)CRand::Random(-10, 10), (float)CRand::Random(-10, 10));
D3DXVec3Normalize(&m_tInfo.vDir, &m_tInfo.vDir);
m_fSpeed = CRand::Random(iSpeed,iMaxSpeed) * 0.1f;
m_fElasticity = fElasticity;
m_fUpPower = fUpPower;
m_fTime = 0.f;
m_fMaxTime = fTime;
m_fGravityTime = 0.f;
m_pCubeTexture = m_pTextureMgr->GetCubeTex(iDrawId);
m_vDamageDir = vDamageDir;
m_bGravity = bGravity;
m_bDown = false;
if(bSizeRnd)
m_fScale = CRand::Random(0, int(fScale * 100.f)) * 0.01f;
else
m_fScale = fScale;
}
void CCubeEffect::SetActive()
{
float fGravitySpeed = 0.f;
m_tInfo.vPos += m_tInfo.vDir * (m_fSpeed * GETTIME);
if(m_bGravity)
{
fGravitySpeed = m_fUpPower + (-5.f * m_fGravityTime);
m_tInfo.vPos.y += fGravitySpeed;
m_tInfo.vPos += m_vDamageDir * 0.3f;
if(fGravitySpeed < 0)
m_bDown = true;
if(m_bDown && m_tInfo.vPos.y <= 0.1f)
{
m_fSpeed *= m_fElasticity;
m_fUpPower *= m_fElasticity;
if(m_fUpPower < 0.01f)
m_tInfo.vPos.y = 0.1f;
m_fGravityTime = 0.f;
m_bDown = false;
}
else
m_tInfo.vPos += m_vDamageDir * 0.15f;
}
}
|
unlicense
|
EpitaJS/js-class-2016
|
jspm_packages/npm/async@0.9.2/lib/async.js
|
28776
|
/* */
"format cjs";
(function(process) {
(function() {
var async = {};
var root,
previous_async;
root = this;
if (root != null) {
previous_async = root.async;
}
async.noConflict = function() {
root.async = previous_async;
return async;
};
function only_once(fn) {
var called = false;
return function() {
if (called)
throw new Error("Callback was already called.");
called = true;
fn.apply(root, arguments);
};
}
var _toString = Object.prototype.toString;
var _isArray = Array.isArray || function(obj) {
return _toString.call(obj) === '[object Array]';
};
var _each = function(arr, iterator) {
for (var i = 0; i < arr.length; i += 1) {
iterator(arr[i], i, arr);
}
};
var _map = function(arr, iterator) {
if (arr.map) {
return arr.map(iterator);
}
var results = [];
_each(arr, function(x, i, a) {
results.push(iterator(x, i, a));
});
return results;
};
var _reduce = function(arr, iterator, memo) {
if (arr.reduce) {
return arr.reduce(iterator, memo);
}
_each(arr, function(x, i, a) {
memo = iterator(memo, x, i, a);
});
return memo;
};
var _keys = function(obj) {
if (Object.keys) {
return Object.keys(obj);
}
var keys = [];
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
keys.push(k);
}
}
return keys;
};
if (typeof process === 'undefined' || !(process.nextTick)) {
if (typeof setImmediate === 'function') {
async.nextTick = function(fn) {
setImmediate(fn);
};
async.setImmediate = async.nextTick;
} else {
async.nextTick = function(fn) {
setTimeout(fn, 0);
};
async.setImmediate = async.nextTick;
}
} else {
async.nextTick = process.nextTick;
if (typeof setImmediate !== 'undefined') {
async.setImmediate = function(fn) {
setImmediate(fn);
};
} else {
async.setImmediate = async.nextTick;
}
}
async.each = function(arr, iterator, callback) {
callback = callback || function() {};
if (!arr.length) {
return callback();
}
var completed = 0;
_each(arr, function(x) {
iterator(x, only_once(done));
});
function done(err) {
if (err) {
callback(err);
callback = function() {};
} else {
completed += 1;
if (completed >= arr.length) {
callback();
}
}
}
};
async.forEach = async.each;
async.eachSeries = function(arr, iterator, callback) {
callback = callback || function() {};
if (!arr.length) {
return callback();
}
var completed = 0;
var iterate = function() {
iterator(arr[completed], function(err) {
if (err) {
callback(err);
callback = function() {};
} else {
completed += 1;
if (completed >= arr.length) {
callback();
} else {
iterate();
}
}
});
};
iterate();
};
async.forEachSeries = async.eachSeries;
async.eachLimit = function(arr, limit, iterator, callback) {
var fn = _eachLimit(limit);
fn.apply(null, [arr, iterator, callback]);
};
async.forEachLimit = async.eachLimit;
var _eachLimit = function(limit) {
return function(arr, iterator, callback) {
callback = callback || function() {};
if (!arr.length || limit <= 0) {
return callback();
}
var completed = 0;
var started = 0;
var running = 0;
(function replenish() {
if (completed >= arr.length) {
return callback();
}
while (running < limit && started < arr.length) {
started += 1;
running += 1;
iterator(arr[started - 1], function(err) {
if (err) {
callback(err);
callback = function() {};
} else {
completed += 1;
running -= 1;
if (completed >= arr.length) {
callback();
} else {
replenish();
}
}
});
}
})();
};
};
var doParallel = function(fn) {
return function() {
var args = Array.prototype.slice.call(arguments);
return fn.apply(null, [async.each].concat(args));
};
};
var doParallelLimit = function(limit, fn) {
return function() {
var args = Array.prototype.slice.call(arguments);
return fn.apply(null, [_eachLimit(limit)].concat(args));
};
};
var doSeries = function(fn) {
return function() {
var args = Array.prototype.slice.call(arguments);
return fn.apply(null, [async.eachSeries].concat(args));
};
};
var _asyncMap = function(eachfn, arr, iterator, callback) {
arr = _map(arr, function(x, i) {
return {
index: i,
value: x
};
});
if (!callback) {
eachfn(arr, function(x, callback) {
iterator(x.value, function(err) {
callback(err);
});
});
} else {
var results = [];
eachfn(arr, function(x, callback) {
iterator(x.value, function(err, v) {
results[x.index] = v;
callback(err);
});
}, function(err) {
callback(err, results);
});
}
};
async.map = doParallel(_asyncMap);
async.mapSeries = doSeries(_asyncMap);
async.mapLimit = function(arr, limit, iterator, callback) {
return _mapLimit(limit)(arr, iterator, callback);
};
var _mapLimit = function(limit) {
return doParallelLimit(limit, _asyncMap);
};
async.reduce = function(arr, memo, iterator, callback) {
async.eachSeries(arr, function(x, callback) {
iterator(memo, x, function(err, v) {
memo = v;
callback(err);
});
}, function(err) {
callback(err, memo);
});
};
async.inject = async.reduce;
async.foldl = async.reduce;
async.reduceRight = function(arr, memo, iterator, callback) {
var reversed = _map(arr, function(x) {
return x;
}).reverse();
async.reduce(reversed, memo, iterator, callback);
};
async.foldr = async.reduceRight;
var _filter = function(eachfn, arr, iterator, callback) {
var results = [];
arr = _map(arr, function(x, i) {
return {
index: i,
value: x
};
});
eachfn(arr, function(x, callback) {
iterator(x.value, function(v) {
if (v) {
results.push(x);
}
callback();
});
}, function(err) {
callback(_map(results.sort(function(a, b) {
return a.index - b.index;
}), function(x) {
return x.value;
}));
});
};
async.filter = doParallel(_filter);
async.filterSeries = doSeries(_filter);
async.select = async.filter;
async.selectSeries = async.filterSeries;
var _reject = function(eachfn, arr, iterator, callback) {
var results = [];
arr = _map(arr, function(x, i) {
return {
index: i,
value: x
};
});
eachfn(arr, function(x, callback) {
iterator(x.value, function(v) {
if (!v) {
results.push(x);
}
callback();
});
}, function(err) {
callback(_map(results.sort(function(a, b) {
return a.index - b.index;
}), function(x) {
return x.value;
}));
});
};
async.reject = doParallel(_reject);
async.rejectSeries = doSeries(_reject);
var _detect = function(eachfn, arr, iterator, main_callback) {
eachfn(arr, function(x, callback) {
iterator(x, function(result) {
if (result) {
main_callback(x);
main_callback = function() {};
} else {
callback();
}
});
}, function(err) {
main_callback();
});
};
async.detect = doParallel(_detect);
async.detectSeries = doSeries(_detect);
async.some = function(arr, iterator, main_callback) {
async.each(arr, function(x, callback) {
iterator(x, function(v) {
if (v) {
main_callback(true);
main_callback = function() {};
}
callback();
});
}, function(err) {
main_callback(false);
});
};
async.any = async.some;
async.every = function(arr, iterator, main_callback) {
async.each(arr, function(x, callback) {
iterator(x, function(v) {
if (!v) {
main_callback(false);
main_callback = function() {};
}
callback();
});
}, function(err) {
main_callback(true);
});
};
async.all = async.every;
async.sortBy = function(arr, iterator, callback) {
async.map(arr, function(x, callback) {
iterator(x, function(err, criteria) {
if (err) {
callback(err);
} else {
callback(null, {
value: x,
criteria: criteria
});
}
});
}, function(err, results) {
if (err) {
return callback(err);
} else {
var fn = function(left, right) {
var a = left.criteria,
b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
};
callback(null, _map(results.sort(fn), function(x) {
return x.value;
}));
}
});
};
async.auto = function(tasks, callback) {
callback = callback || function() {};
var keys = _keys(tasks);
var remainingTasks = keys.length;
if (!remainingTasks) {
return callback();
}
var results = {};
var listeners = [];
var addListener = function(fn) {
listeners.unshift(fn);
};
var removeListener = function(fn) {
for (var i = 0; i < listeners.length; i += 1) {
if (listeners[i] === fn) {
listeners.splice(i, 1);
return;
}
}
};
var taskComplete = function() {
remainingTasks--;
_each(listeners.slice(0), function(fn) {
fn();
});
};
addListener(function() {
if (!remainingTasks) {
var theCallback = callback;
callback = function() {};
theCallback(null, results);
}
});
_each(keys, function(k) {
var task = _isArray(tasks[k]) ? tasks[k] : [tasks[k]];
var taskCallback = function(err) {
var args = Array.prototype.slice.call(arguments, 1);
if (args.length <= 1) {
args = args[0];
}
if (err) {
var safeResults = {};
_each(_keys(results), function(rkey) {
safeResults[rkey] = results[rkey];
});
safeResults[k] = args;
callback(err, safeResults);
callback = function() {};
} else {
results[k] = args;
async.setImmediate(taskComplete);
}
};
var requires = task.slice(0, Math.abs(task.length - 1)) || [];
var ready = function() {
return _reduce(requires, function(a, x) {
return (a && results.hasOwnProperty(x));
}, true) && !results.hasOwnProperty(k);
};
if (ready()) {
task[task.length - 1](taskCallback, results);
} else {
var listener = function() {
if (ready()) {
removeListener(listener);
task[task.length - 1](taskCallback, results);
}
};
addListener(listener);
}
});
};
async.retry = function(times, task, callback) {
var DEFAULT_TIMES = 5;
var attempts = [];
if (typeof times === 'function') {
callback = task;
task = times;
times = DEFAULT_TIMES;
}
times = parseInt(times, 10) || DEFAULT_TIMES;
var wrappedTask = function(wrappedCallback, wrappedResults) {
var retryAttempt = function(task, finalAttempt) {
return function(seriesCallback) {
task(function(err, result) {
seriesCallback(!err || finalAttempt, {
err: err,
result: result
});
}, wrappedResults);
};
};
while (times) {
attempts.push(retryAttempt(task, !(times -= 1)));
}
async.series(attempts, function(done, data) {
data = data[data.length - 1];
(wrappedCallback || callback)(data.err, data.result);
});
};
return callback ? wrappedTask() : wrappedTask;
};
async.waterfall = function(tasks, callback) {
callback = callback || function() {};
if (!_isArray(tasks)) {
var err = new Error('First argument to waterfall must be an array of functions');
return callback(err);
}
if (!tasks.length) {
return callback();
}
var wrapIterator = function(iterator) {
return function(err) {
if (err) {
callback.apply(null, arguments);
callback = function() {};
} else {
var args = Array.prototype.slice.call(arguments, 1);
var next = iterator.next();
if (next) {
args.push(wrapIterator(next));
} else {
args.push(callback);
}
async.setImmediate(function() {
iterator.apply(null, args);
});
}
};
};
wrapIterator(async.iterator(tasks))();
};
var _parallel = function(eachfn, tasks, callback) {
callback = callback || function() {};
if (_isArray(tasks)) {
eachfn.map(tasks, function(fn, callback) {
if (fn) {
fn(function(err) {
var args = Array.prototype.slice.call(arguments, 1);
if (args.length <= 1) {
args = args[0];
}
callback.call(null, err, args);
});
}
}, callback);
} else {
var results = {};
eachfn.each(_keys(tasks), function(k, callback) {
tasks[k](function(err) {
var args = Array.prototype.slice.call(arguments, 1);
if (args.length <= 1) {
args = args[0];
}
results[k] = args;
callback(err);
});
}, function(err) {
callback(err, results);
});
}
};
async.parallel = function(tasks, callback) {
_parallel({
map: async.map,
each: async.each
}, tasks, callback);
};
async.parallelLimit = function(tasks, limit, callback) {
_parallel({
map: _mapLimit(limit),
each: _eachLimit(limit)
}, tasks, callback);
};
async.series = function(tasks, callback) {
callback = callback || function() {};
if (_isArray(tasks)) {
async.mapSeries(tasks, function(fn, callback) {
if (fn) {
fn(function(err) {
var args = Array.prototype.slice.call(arguments, 1);
if (args.length <= 1) {
args = args[0];
}
callback.call(null, err, args);
});
}
}, callback);
} else {
var results = {};
async.eachSeries(_keys(tasks), function(k, callback) {
tasks[k](function(err) {
var args = Array.prototype.slice.call(arguments, 1);
if (args.length <= 1) {
args = args[0];
}
results[k] = args;
callback(err);
});
}, function(err) {
callback(err, results);
});
}
};
async.iterator = function(tasks) {
var makeCallback = function(index) {
var fn = function() {
if (tasks.length) {
tasks[index].apply(null, arguments);
}
return fn.next();
};
fn.next = function() {
return (index < tasks.length - 1) ? makeCallback(index + 1) : null;
};
return fn;
};
return makeCallback(0);
};
async.apply = function(fn) {
var args = Array.prototype.slice.call(arguments, 1);
return function() {
return fn.apply(null, args.concat(Array.prototype.slice.call(arguments)));
};
};
var _concat = function(eachfn, arr, fn, callback) {
var r = [];
eachfn(arr, function(x, cb) {
fn(x, function(err, y) {
r = r.concat(y || []);
cb(err);
});
}, function(err) {
callback(err, r);
});
};
async.concat = doParallel(_concat);
async.concatSeries = doSeries(_concat);
async.whilst = function(test, iterator, callback) {
if (test()) {
iterator(function(err) {
if (err) {
return callback(err);
}
async.whilst(test, iterator, callback);
});
} else {
callback();
}
};
async.doWhilst = function(iterator, test, callback) {
iterator(function(err) {
if (err) {
return callback(err);
}
var args = Array.prototype.slice.call(arguments, 1);
if (test.apply(null, args)) {
async.doWhilst(iterator, test, callback);
} else {
callback();
}
});
};
async.until = function(test, iterator, callback) {
if (!test()) {
iterator(function(err) {
if (err) {
return callback(err);
}
async.until(test, iterator, callback);
});
} else {
callback();
}
};
async.doUntil = function(iterator, test, callback) {
iterator(function(err) {
if (err) {
return callback(err);
}
var args = Array.prototype.slice.call(arguments, 1);
if (!test.apply(null, args)) {
async.doUntil(iterator, test, callback);
} else {
callback();
}
});
};
async.queue = function(worker, concurrency) {
if (concurrency === undefined) {
concurrency = 1;
}
function _insert(q, data, pos, callback) {
if (!q.started) {
q.started = true;
}
if (!_isArray(data)) {
data = [data];
}
if (data.length == 0) {
return async.setImmediate(function() {
if (q.drain) {
q.drain();
}
});
}
_each(data, function(task) {
var item = {
data: task,
callback: typeof callback === 'function' ? callback : null
};
if (pos) {
q.tasks.unshift(item);
} else {
q.tasks.push(item);
}
if (q.saturated && q.tasks.length === q.concurrency) {
q.saturated();
}
async.setImmediate(q.process);
});
}
var workers = 0;
var q = {
tasks: [],
concurrency: concurrency,
saturated: null,
empty: null,
drain: null,
started: false,
paused: false,
push: function(data, callback) {
_insert(q, data, false, callback);
},
kill: function() {
q.drain = null;
q.tasks = [];
},
unshift: function(data, callback) {
_insert(q, data, true, callback);
},
process: function() {
if (!q.paused && workers < q.concurrency && q.tasks.length) {
var task = q.tasks.shift();
if (q.empty && q.tasks.length === 0) {
q.empty();
}
workers += 1;
var next = function() {
workers -= 1;
if (task.callback) {
task.callback.apply(task, arguments);
}
if (q.drain && q.tasks.length + workers === 0) {
q.drain();
}
q.process();
};
var cb = only_once(next);
worker(task.data, cb);
}
},
length: function() {
return q.tasks.length;
},
running: function() {
return workers;
},
idle: function() {
return q.tasks.length + workers === 0;
},
pause: function() {
if (q.paused === true) {
return;
}
q.paused = true;
},
resume: function() {
if (q.paused === false) {
return;
}
q.paused = false;
for (var w = 1; w <= q.concurrency; w++) {
async.setImmediate(q.process);
}
}
};
return q;
};
async.priorityQueue = function(worker, concurrency) {
function _compareTasks(a, b) {
return a.priority - b.priority;
}
;
function _binarySearch(sequence, item, compare) {
var beg = -1,
end = sequence.length - 1;
while (beg < end) {
var mid = beg + ((end - beg + 1) >>> 1);
if (compare(item, sequence[mid]) >= 0) {
beg = mid;
} else {
end = mid - 1;
}
}
return beg;
}
function _insert(q, data, priority, callback) {
if (!q.started) {
q.started = true;
}
if (!_isArray(data)) {
data = [data];
}
if (data.length == 0) {
return async.setImmediate(function() {
if (q.drain) {
q.drain();
}
});
}
_each(data, function(task) {
var item = {
data: task,
priority: priority,
callback: typeof callback === 'function' ? callback : null
};
q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
if (q.saturated && q.tasks.length === q.concurrency) {
q.saturated();
}
async.setImmediate(q.process);
});
}
var q = async.queue(worker, concurrency);
q.push = function(data, priority, callback) {
_insert(q, data, priority, callback);
};
delete q.unshift;
return q;
};
async.cargo = function(worker, payload) {
var working = false,
tasks = [];
var cargo = {
tasks: tasks,
payload: payload,
saturated: null,
empty: null,
drain: null,
drained: true,
push: function(data, callback) {
if (!_isArray(data)) {
data = [data];
}
_each(data, function(task) {
tasks.push({
data: task,
callback: typeof callback === 'function' ? callback : null
});
cargo.drained = false;
if (cargo.saturated && tasks.length === payload) {
cargo.saturated();
}
});
async.setImmediate(cargo.process);
},
process: function process() {
if (working)
return;
if (tasks.length === 0) {
if (cargo.drain && !cargo.drained)
cargo.drain();
cargo.drained = true;
return;
}
var ts = typeof payload === 'number' ? tasks.splice(0, payload) : tasks.splice(0, tasks.length);
var ds = _map(ts, function(task) {
return task.data;
});
if (cargo.empty)
cargo.empty();
working = true;
worker(ds, function() {
working = false;
var args = arguments;
_each(ts, function(data) {
if (data.callback) {
data.callback.apply(null, args);
}
});
process();
});
},
length: function() {
return tasks.length;
},
running: function() {
return working;
}
};
return cargo;
};
var _console_fn = function(name) {
return function(fn) {
var args = Array.prototype.slice.call(arguments, 1);
fn.apply(null, args.concat([function(err) {
var args = Array.prototype.slice.call(arguments, 1);
if (typeof console !== 'undefined') {
if (err) {
if (console.error) {
console.error(err);
}
} else if (console[name]) {
_each(args, function(x) {
console[name](x);
});
}
}
}]));
};
};
async.log = _console_fn('log');
async.dir = _console_fn('dir');
async.memoize = function(fn, hasher) {
var memo = {};
var queues = {};
hasher = hasher || function(x) {
return x;
};
var memoized = function() {
var args = Array.prototype.slice.call(arguments);
var callback = args.pop();
var key = hasher.apply(null, args);
if (key in memo) {
async.nextTick(function() {
callback.apply(null, memo[key]);
});
} else if (key in queues) {
queues[key].push(callback);
} else {
queues[key] = [callback];
fn.apply(null, args.concat([function() {
memo[key] = arguments;
var q = queues[key];
delete queues[key];
for (var i = 0,
l = q.length; i < l; i++) {
q[i].apply(null, arguments);
}
}]));
}
};
memoized.memo = memo;
memoized.unmemoized = fn;
return memoized;
};
async.unmemoize = function(fn) {
return function() {
return (fn.unmemoized || fn).apply(null, arguments);
};
};
async.times = function(count, iterator, callback) {
var counter = [];
for (var i = 0; i < count; i++) {
counter.push(i);
}
return async.map(counter, iterator, callback);
};
async.timesSeries = function(count, iterator, callback) {
var counter = [];
for (var i = 0; i < count; i++) {
counter.push(i);
}
return async.mapSeries(counter, iterator, callback);
};
async.seq = function() {
var fns = arguments;
return function() {
var that = this;
var args = Array.prototype.slice.call(arguments);
var callback = args.pop();
async.reduce(fns, args, function(newargs, fn, cb) {
fn.apply(that, newargs.concat([function() {
var err = arguments[0];
var nextargs = Array.prototype.slice.call(arguments, 1);
cb(err, nextargs);
}]));
}, function(err, results) {
callback.apply(that, [err].concat(results));
});
};
};
async.compose = function() {
return async.seq.apply(null, Array.prototype.reverse.call(arguments));
};
var _applyEach = function(eachfn, fns) {
var go = function() {
var that = this;
var args = Array.prototype.slice.call(arguments);
var callback = args.pop();
return eachfn(fns, function(fn, cb) {
fn.apply(that, args.concat([cb]));
}, callback);
};
if (arguments.length > 2) {
var args = Array.prototype.slice.call(arguments, 2);
return go.apply(this, args);
} else {
return go;
}
};
async.applyEach = doParallel(_applyEach);
async.applyEachSeries = doSeries(_applyEach);
async.forever = function(fn, callback) {
function next(err) {
if (err) {
if (callback) {
return callback(err);
}
throw err;
}
fn(next);
}
next();
};
if (typeof module !== 'undefined' && module.exports) {
module.exports = async;
} else if (typeof define !== 'undefined' && define.amd) {
define([], function() {
return async;
});
} else {
root.async = async;
}
}());
})(require('process'));
|
unlicense
|
jeffrey-io/wall-of-shame
|
2007/JovianSuite/JovianTools/Styles/XML.cs
|
1899
|
using System;
using System.Collections;
using JovianTools.Support;
namespace JovianTools.Styles
{
/// <summary>
/// Summary description for HTML.
/// </summary>
public class XMLExport : StyleExp
{
public bool inTag;
public bool inStr;
public bool encounterWS;
public XMLExport()
{
inTag = false;
inStr = false;
encounterWS = false;
}
public XMLExport copy()
{
XMLExport exp = new XMLExport();
exp.inTag = inTag;
exp.inStr = inStr;
return exp;
}
public bool diff(StyleExp e)
{
XMLExport Ex = e as XMLExport;
if(inTag != Ex.inTag) return true;
if(inStr != Ex.inStr) return true;
return false;
}
}
public class XML : StyleEng
{
public StyleExp StyleFirstLine(rtfLine l)
{
XMLExport exp = new XMLExport();
return StyleSuccLine(exp,l);;
}
public StyleExp StyleSuccLine(StyleExp P, rtfLine l)
{
XMLExport exp = (P as XMLExport).copy();
for(int k = 0; k < l.Length(); k++)
{
rtfChar C = l.charAt(k);
if(exp.inTag)
{
if(exp.inStr)
{
C.s = 3;
if(C.v == '\\')
{
k++;
if(k < l.Length())
{
l.charAt(k).s = 3;
}
}
else if(C.v == '"')
{
exp.inStr = false;
}
}
else
{
C.s = 1;
if(exp.encounterWS)
{
C.s = 2;
}
else
{
exp.encounterWS = Char.IsWhiteSpace(C.v);
if(exp.encounterWS) C.s = 2;
}
if(C.v == '"')
{
C.s = 3;
exp.inStr = true;
}
if(C.v == '>')
{
exp.inTag = false;
C.s = 1;
}
}
}
else
{
C.s = 0;
if(C.v == '<')
{
exp.encounterWS = false;
exp.inTag = true;
C.s = 1;
}
}
}
return exp;
}
}
}
|
unlicense
|
NxtChg/pieces
|
js/vue/vs-notify/vs-notify.js
|
4011
|
/*=============================================================================
Created by NxtChg (admin@nxtchg.com), 2017. License: Public Domain.
=============================================================================*/
var s = document.createElement("style"); s.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(s);
s.innerHTML =
'.vs-notify{ position:fixed; width:300px; z-index:9999; }'+
'.vs-notify .ntf{ font-size:14px; padding:10px; margin:0 5px 5px; color:#fff; background:#44A4FC; border-left:5px solid #187FE7; box-sizing:border-box; text-align:left; cursor:pointer; }'+
'.vs-notify .warn { background:#ffb648; border-left-color:#f48a06; }'+
'.vs-notify .error { background:#E54D42; border-left-color:#B82E24; }'+
'.vs-notify .success{ background:#68CD86; border-left-color:#42A85F; }'+
'.ntf-left-enter-active, .ntf-left-leave-active, .ntf-right-enter-active, .ntf-right-leave-active, .ntf-top-enter-active, .ntf-top-leave-active,'+
'.ntf-bottom-enter-active, .ntf-bottom-leave-active{ transition: all 0.3s; }'+
'.ntf-left-enter, .ntf-left-leave-to { opacity:0; transform:translateX(-300px); }'+
'.ntf-right-enter, .ntf-right-leave-to{ opacity:0; transform:translateX(300px); }'+
'.ntf-fade-enter-active, .ntf-fade-leave-active{ transition: opacity 0.5s; }'+
'.ntf-fade-enter, .ntf-fade-leave-to{ opacity: 0; }'+
'.ntf-top-enter, .ntf-top-leave-to{ opacity:0; transform: translateY(-120px); }'+
'.ntf-bottom-enter, .ntf-bottom-leave-to{ opacity:0; transform: translateY(120px); }';
//_____________________________________________________________________________
var VsNotify =
{
install: function(Vue)
{
var self = this; this.g = {};
var $notify = function(group, text, type, time){ if(self.g[group]) self.g[group](text, type, time); };
Object.defineProperty(Vue.prototype, '$notify', { get: function(){ return $notify; } });
}
};
Vue.use(VsNotify);
Vue.component('vs-notify',
{
template:
'<div :class="[\'vs-notify\', group]" :style="styles"><transition-group :name="trans" mode="out-in">'+
'<div :class="it.type" v-for="it in list" :key="it.id">'+
'<slot name="body" :class="it.type" :item="it" :close="function(){ end(it) }">'+
'<div @click.stop="end(it)" v-html="it.text"></div>'+
'</slot>'+
'</div>'+
'</transition-group></div>',
props:
{
group: String, transition: String,
position: { type: String, default: 'top right' },
duration: { type: Number, default: 3000 },
reverse: { type: Boolean, default: false }
},
data: function()
{
var d = !this.reverse, p = this.position, t = this.transition;
if(p.indexOf('bottom')+1) d = !d;
if(!t && p.indexOf('left' )+1) t = 'ntf-left';
if(!t && p.indexOf('right')+1) t = 'ntf-right';
return{ dir:d, trans: t, list:[] }
},
created: function()
{
var ids = 1, self = this;
VsNotify.g[this.group] = function(text, type, time)
{
if(text === undefined){ self.end(); return; }
var it = { id: ids++, text: text, type: 'ntf' + (type ? ' '+type : '') };
time = (time !== undefined ? time : self.duration);
if(time > 0){ it.timer = setTimeout(function(){ self.end(it); }, time); }
self.dir ? self.list.push(it) : self.list.unshift(it);
};
},
//destroyed: function(){ }, // do we need it? if so - remove group from VsNotify
computed:
{
styles: function()
{
var s = {}, pa = this.position.split(' ');
for(var i = 0; i < pa.length; i++)
{
if(pa[i] == 'center'){ s.left = s.right = 0; s.margin = 'auto'; } else if(pa[i] != '') s[pa[i]] = 0;
}
return s;
}
},
methods:
{
find: function(id){ for(var i = 0; i < this.list.length; i++) if(this.list[i].id == id) return i; return -1; },
end_no: function(n){ if(n+1){ clearTimeout(this.list[n].timer); this.list.splice(n, 1); } },
end: function(it)
{
if(it === undefined){ while(this.list.length) this.end_no(0); return; } // kill all
this.end_no(this.find(it.id));
}
}
});
|
unlicense
|
bkmeneguello/surveillance
|
surveillance/__init__.py
|
131
|
from .frame import Frame
from .queue import Queue, QueueFan
from .reader import Reader
from .writer import Writer, PeriodicWriter
|
unlicense
|
StarTrackDevKL/athena
|
src/main/webapp/scripts/app/account/settings/settings.js
|
665
|
'use strict';
angular.module('athenaApp')
.config(function ($stateProvider) {
$stateProvider
.state('settings', {
parent: 'account',
url: '/settings',
data: {
roles: ['ROLE_USER'],
pageTitle: 'Settings'
},
views: {
'content@': {
templateUrl: 'scripts/app/account/settings/settings.html',
controller: 'SettingsController'
}
},
resolve: {
}
});
});
|
unlicense
|
shilin-he/spa-northwind
|
src/Northwind.UI/Scripts/app/common/router.js
|
1114
|
define(function () {
return kendo.Router.extend({
init: function (options) {
this.namedRoutes = {};
kendo.Router.fn.init.call(this, options);
},
route: function (name, route, callback) {
if (arguments.length == 2) {
callback = route;
route = name;
name = 'catchall';
}
this.namedRoutes[name] = { route: route, callback: callback };
kendo.Router.fn.route.call(this, route, callback);
},
routeFor: function (name, params) {
var model, op, id, temp;
if (this.namedRoutes[name]) {
return this.namedRoutes[name]['route'].replace(/\:(\w+)/g, function(_, param) {
return params[param];
});
} else {
temp = name.split('-');
model = temp[1];
op = temp[0];
id = params && params['id'];
return '/' + model + '/' + op + (id ? '/' + id : '');
}
}
});
});
|
unlicense
|
devacfr/spring-restlet
|
restlet.ext.xstream/src/test/java/com/pmi/restlet/ext/xstream/impl/AnnotedCustomer.java
|
2481
|
package com.pmi.restlet.ext.xstream.impl;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
@XStreamAlias("customer")
public class AnnotedCustomer implements ICustomer {
@XStreamAlias("firstName")
@XStreamAsAttribute
private String firstName;
@XStreamAlias("lastName")
@XStreamAsAttribute
private String lastName;
@XStreamImplicit(itemFieldName="city")
private List<String> addresses;
@XStreamAlias("modificationDate")
private Date modificationDate;
@Override
public boolean equals(Object obj) {
return EqualsBuilder.reflectionEquals(this, obj);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
public Date getModificationDate() {
return modificationDate;
}
public void setModificationDate(Date modificationDate) {
this.modificationDate = modificationDate;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<String> getAddresses() {
return addresses;
}
/* (non-Javadoc)
* @see com.pmi.restlet.serialization.ICustomer#setAddresses(java.util.List)
*/
public void setAddresses(List<String> addresses) {
this.addresses = addresses;
}
@SuppressWarnings("deprecation")
public static ICustomer createCustomer() {
ICustomer customer = new AnnotedCustomer();
customer.setFirstName("Bernard");
customer.setLastName("Lefevre");
customer.setModificationDate(new Date(2010,2,10));
customer.setAddresses(new ArrayList<String>());
customer.getAddresses().addAll(Arrays.asList("Lyon", "Paris", "Marseille"));
return customer;
}
public static final ICustomer customer = createCustomer();
}
|
unlicense
|
GuoJianghui/SpringMVC
|
src/main/java/rip/springmvc/dao/user/UserDaoImpl.java
|
660
|
package rip.springmvc.dao.user;
import java.util.List;
import org.springframework.stereotype.Repository;
import rip.springmvc.common.dao.BaseDaoImpl;
import rip.springmvc.entity.User;
@Repository("userMapper")
public class UserDaoImpl extends BaseDaoImpl implements UserMapper {
public User getUser(String userId) {
return sqlSession().selectOne("rip.springmvc.dao.user.UserMapper.getUser", userId);
}
@Override
public void insert(User user) {
sqlSession().insert("rip.springmvc.dao.user.UserMapper.insert", user);
}
@Override
public List<User> users() {
return sqlSession().selectList("rip.springmvc.dao.user.UserMapper.users");
}
}
|
unlicense
|
kyle8998/Practice-Coding-Questions
|
leetcode/125-Easy-Valid-Palindrome/answer.py
|
380
|
#!/usr/bin/env python3
#-------------------------------------------------------------------------------
import re
class Solution:
def isPalindrome(self, s):
"""
:type s: str
:rtype: bool
"""
s = re.sub(r'\W*', '', s).lower()
return s == s[::-1]
#-------------------------------------------------------------------------------
|
unlicense
|
ncguy2/MOD003263
|
Mod003263/Mod003263/events/ui/InterviewToTemplateEvent.cs
|
257
|
namespace Mod003263.events.ui {
public class InterviewToTemplateEvent : AbstractEvent {
public interface InterviewToTemplateListener {
[Event]
void OnInterviewToTemplate(InterviewToTemplateEvent e);
}
}
}
|
unlicense
|
Krusen/ErgastApi.Net
|
src/ErgastApi/Serialization/JsonPropertyExtensions.cs
|
537
|
using System.Linq;
using Newtonsoft.Json.Serialization;
namespace ErgastApi.Serialization
{
public static class JsonPropertyExtensions
{
public static bool HasAttribute<T>(this JsonProperty property)
{
return property.AttributeProvider.GetAttributes(typeof(T), true).Any();
}
public static T GetAttribute<T>(this JsonProperty property) where T : class
{
return property.AttributeProvider.GetAttributes(typeof(T), true).FirstOrDefault() as T;
}
}
}
|
unlicense
|
boujam/jbulletin
|
src/main/java/com/fwb/jbulletin/dao/StudentDao.java
|
944
|
package com.fwb.jbulletin.dao;
import java.util.List;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;
import com.fwb.jbulletin.model.Student;
@Repository
@SuppressWarnings("unchecked")
public class StudentDao extends BaseDao{
public StudentDao(){
System.out.println("create bean [studentDao] " + this.toString());
}
@Cacheable("studentsCache")
public List<Student> findall () {
System.out.println("loading students from table STUDENT");
List <Student> students = (List<Student>) em.createQuery("select s from Student s").getResultList();
return students;
}
public Student findStudentById (long id) {
System.out.println("loading student by id from table STUDENT");
Student student = (Student) em.createQuery("select s from Student s where s.id =:id")
.setParameter("id", id)
.getSingleResult();
return student;
}
}
|
unlicense
|
akiross/codedude
|
opencl/add_test_ochell.cpp
|
1774
|
// Compiled with
// g++ -std=c++11 add_test_ochell.cpp -o add_test_ochell -l pocl && ./add_test_ochell
// or
// g++ -std=c++11 add_test_ochell.cpp -o add_test_ochell -l OpenCL && ./add_test_ochell
#include <iostream>
#include <cstdlib>
#include "ochell.hh"
int main(int argc, char **argv) {
int len = 100;
int *A = new int[len];
int *B = new int[len];
int *C = new int[len];
for (int i = 0; i < len; ++i) {
A[i] = 10 + i;
B[i] = 100 + i;
}
// Create a context using the first device available
cl::Context context = create_context(CL_DEVICE_TYPE_CPU);
// Alocate buffers for I/O
cl::Buffer inA = create_buffer(context, "rh", len, A);
cl::Buffer inB = create_buffer(context, "rh", len, B);
cl::Buffer outC = create_buffer(context, "wh", len, C);
// Get a device handler
std::vector<cl::Device> devices = get_devices(context);
std::cout << "INFO: " << devices.size() << " devices available\n";
// Create the program
cl::Program program = load_and_build_program(
context, devices, "vector_add_kernel.cl"
);
// Create a kernel object for accessing kernel entry point
cl::Kernel ker_vec_add = load_kernel(program, "vector_add");
// Set the arguments for this kernel (variadic template)
set_kernel_args(ker_vec_add, inA, inB, outC, len);
// Create a Command Queue for the device (1-to-1)
cl::CommandQueue queue = create_command_queue(context, devices[0]);
// Enqueue the kernel and get an event to check results
cl::Event event = enqueue_nd_range_kernel(
queue, ker_vec_add, cl::NullRange, cl::NDRange(len), cl::NDRange(1, 1)
);
// Wait for the conclusion
event.wait();
blocking_read_buffer(queue, outC, 0, len, C);
for (int i = 0; i < len; ++i)
std::cout << C[i] << " ";
std::cout << std::endl;
exit(EXIT_SUCCESS);
}
|
unlicense
|
Derrick-/HackMaineIrcBotSvc
|
HackMaineIrcBotSvc_Tests/UrlHookTests.cs
|
2465
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using HackMaineIrcBot.Irc.Hooks;
using HackMaineIrcBot.Irc.Hooks.UrlResolvers;
namespace HackMaineIrcBotSvc_Tests
{
[TestClass]
public class UrlHookTests
{
[TestMethod]
public void TestCanHandle()
{
string urlOK1 = "http://hackmaine.org";
string urlOK1u = "HTtp://HACKMAINE.org";
string urlOK2 = "http://hackmaine.org/forums";
string urlOK3 = "http://hackmaine.org/forums/";
string urlOK4 = "http://hackmaine.org/forums?hello=there&id=55";
string urlOK5 = "https://msdn.microsoft.com/en-us/library/ms563775(v=office.14).aspx";
string urlOK6 = "https://msdn.microsoft.com:84/en-us/library/ms563775(v=office.14).aspx";
string MessageOK1 = "Guys, check out http://hackmaine.org/forums/, if you dare";
string urlBad1 = "ht://hello.org";
string urlBad2 = "http://hello";
string urlBad3 = "http://hackmaine. org/forums/";
string urlBad4 = "http://hackmaine/forums.org/";
//TODO: string urlBad5 = "http://hackmaine.org:80:80/forums";
var urlHook = new UrlHook();
Assert.IsTrue(urlHook.CanHandle(urlOK1));
Assert.IsTrue(urlHook.CanHandle(urlOK1u));
Assert.IsTrue(urlHook.CanHandle(urlOK2));
Assert.IsTrue(urlHook.CanHandle(urlOK3));
Assert.IsTrue(urlHook.CanHandle(urlOK4));
Assert.IsTrue(urlHook.CanHandle(urlOK5));
Assert.IsTrue(urlHook.CanHandle(urlOK6));
Assert.IsTrue(urlHook.CanHandle(MessageOK1));
Assert.IsFalse(urlHook.CanHandle(urlBad1));
Assert.IsFalse(urlHook.CanHandle(urlBad2));
Assert.IsFalse(urlHook.CanHandle(urlBad3));
Assert.IsFalse(urlHook.CanHandle(urlBad4));
// Assert.IsFalse(urlHook.CanHandle(urlBad5));
}
[TestMethod]
public void GetTitleTest()
{
string title = "Page Title";
var html = string.Format("<html><head><title>{0}</title></head><body>Body text</body></html>", title);
var doc = UrlResolver.ParseHtml(html);
var expected = title;
var actual = UrlResolver.GetDocumentTitle(doc);
Assert.AreEqual(expected, actual);
}
}
}
|
unlicense
|
yannlandry/DumbEdgeFinder
|
src/edges.hpp
|
124
|
#include <opencv2/core/core.hpp>
void findEdges(const cv::Mat&, cv::Mat&);
float edist(const cv::Vec3b&, const cv::Vec3b&);
|
unlicense
|
pablo-f-cargnelutti/algorithms
|
StringAndArrays/StringAndArraysTest.java
|
7724
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package codinginterviewproblems.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author pcargnel
*/
public class StringAndArraysTest {
public StringAndArraysTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
// TODO add test methods here.
// The methods must be annotated with annotation @Test. For example:
//
@Test
public void testUniqueCharsTrue() {
MyString myString = new MyString("abcde");
boolean hasUniqueChars = myString.hasUniqueChars2();
assertTrue(hasUniqueChars);
}
@Test
public void testUniqueCharsFalse() {
MyString myString = new MyString("abcdde");
boolean hasUniqueChars = myString.hasUniqueChars2();
assertFalse(hasUniqueChars);
}
@Test
public void testUniqueCharsTrueWithEmptyString() {
MyString myString = new MyString("");
boolean hasUniqueChars = myString.hasUniqueChars2();
assertTrue(hasUniqueChars);
}
@Test
public void testUniqueCharsTrueWithOneCharString() {
MyString myString = new MyString("a");
boolean hasUniqueChars = myString.hasUniqueChars2();
assertTrue(hasUniqueChars);
}
@Test
public void testOnlyRepeateds()
{
Integer[] array1 = {3,1,2,4};
Integer[] array2 = {1,4,8};
Integer[] result = getOnlyCommon(array1, array2);
assertEquals(result[0], Integer.valueOf(1));
assertEquals(result[1], Integer.valueOf(4));
assertEquals(result.length, 2);
}
@Test
public void testAnagramsCount() {
MyPrase myPrase = new MyPrase(new String[]{"cat", "cat", "rat", "tar", "art", "trap", "rapt", "univision", "act", "part", "trap", "part", "tarp", "rat", "face", "cafe"});
Map<MyPrase.Anagram, MyPrase.Counter> anagrams = myPrase.anagramsCount();
assertEquals(3, anagrams.get(new MyPrase.Anagram("cat")).get());
assertEquals(4, anagrams.get(new MyPrase.Anagram("rat")).get());
assertEquals(1, anagrams.get(new MyPrase.Anagram("univision")).get());
}
@Test
public void testIsThereTwoNumsThatGetsSum() {
MyArray myArray = new MyArray(new int[]{4, -6, 53, 4, 66, 8, 47});
boolean isThereTwoIntsToGetSum = myArray.isThereTwoIntsToGetSum(-2);
assertTrue(isThereTwoIntsToGetSum);
}
@Test
public void testSubArray() {
MyArray myArray = new MyArray(null);
int[] array = {1, 56, 45, 4, 7, 45};
int[] subArray = {4};
int actual = myArray.findArray(array, subArray);
assertEquals(2, actual);
}
private Integer[] getOnlyCommon(Integer[] array1, Integer[] array2) {
Map<Integer, Integer> map;
Integer[] longestArray = array1.length >= array2.length ? array1 : array2;
Integer[] shorterArray = array1.length >= array2.length ? array2 : array1;
map = getMapFrom(shorterArray);
List<Integer> commonValues = new ArrayList(shorterArray.length);
for (int value : longestArray) {
if(map.containsKey(value))
commonValues.add(value);
}
Integer[] temp = new Integer[commonValues.size()];
return commonValues.toArray(temp);
}
private Map<Integer, Integer> getMapFrom(Integer[] array) {
Map<Integer, Integer> map = new HashMap<>();
for (int i : array) {
map.put(i, i);
}
return map;
}
}
class MyPrase {
private List<String> words;
public MyPrase(final String[] words) {
this.words = Arrays.asList(words);
}
public Map<Anagram, Counter> anagramsCount() {
Map<Anagram, Counter> anagrams = new HashMap<>();
for (final String word : words) {
Anagram anagram = new Anagram(word);
Counter auxCounter = new Counter(1);
Counter oldCounter = anagrams.put(anagram, auxCounter);
if(oldCounter != null)
auxCounter.incrementBy(oldCounter.get());
}
return anagrams;
}
static class Counter {
int counter;
public Counter(int from) {
this.counter = from;
}
void incrementOne() {
++counter;
}
int get() {
return counter;
}
private void incrementBy(int aNumber) {
counter += aNumber;
}
}
static class Anagram {
private final String word;
private int hashCode;
public Anagram(final String word) {
this.word = word;
calculateHashCode();
}
public String get() {
return this.word;
}
public boolean isAnagramOf(final String otherWord) {
if (otherWord.length() != word.length()) {
return false;
}
char[] wordCharArray = word.toCharArray();
char[] otherWordCharArray = otherWord.toCharArray();
Arrays.sort(wordCharArray);
Arrays.sort(otherWordCharArray);
return Arrays.equals(otherWordCharArray, wordCharArray);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Anagram other = (Anagram) obj;
if (!Objects.equals(this.hashCode, other.hashCode)) {
return false;
}
return true;
}
public int hashCode()
{
return this.hashCode;
}
private void calculateHashCode() {
hashCode = 0;
for (Character character : word.toCharArray()) {
hashCode += character.hashCode();
}
}
}
}
class MyArray {
private int[] array;
public MyArray(int[] elements) {
array = elements;
}
public boolean isThereTwoIntsToGetSum(int sum) {
Map<Integer, Integer> nums = new HashMap<>();
for (int num : array) {
nums.put(num, num);
}
for (int num : array) {
int difference = sum - num;
if (nums.containsKey(difference)) {
return true;
}
}
return false;
}
int findArray(int[] array, int[] subArray) {
if (array.length == 0 || subArray.length == 0) {
return -1;
}
if (subArray.length > array.length) {
return -1;
}
int diff = array.length - subArray.length;
int[] auxArray = new int[subArray.length];
for (int i = 0; i <= diff; i++) {
System.arraycopy(array, i, auxArray, 0, subArray.length);
if (Arrays.equals(auxArray, subArray)) {
return i;
}
}
return -1;
}
private void fillMap(int[] array, Map<Integer, Integer> arrayValueIndexMap) {
for (int i = 0; i < array.length; i++) {
arrayValueIndexMap.put(array[i], i);
}
}
}
|
unlicense
|
magicmonty/dotfiles_dotbot
|
apps/qutebrowser/shortcuts.py
|
1118
|
# qutebrowser shortcuts
config.bind(';dd', 'set downloads.location.directory ~/Dokumente ;; hint links download')
config.bind(';dff', 'set downloads.location.directory ~/.dotfiles ;; hint links download')
config.bind(';dr', 'set downloads.location.directory ~/Dropbox ;; hint links download')
config.bind(';dl', 'set downloads.location.directory ~/Downloads ;; hint links download')
config.bind(';D', 'set downloads.location.directory ~/Downloads ;; hint links download')
config.bind(';m', 'set downloads.location.directory ~/Musik ;; hint links download')
config.bind(';pp', 'set downloads.location.directory ~/Bilder ;; hint links download')
config.bind(';pk', 'set downloads.location.directory ~/Bilder/Korea ;; hint links download')
config.bind(';vv', 'set downloads.location.directory ~/Videos ;; hint links download')
config.bind(';s', 'set downloads.location.directory ~/.dotfiles/scripts ;; hint links download')
config.bind(';cf', 'set downloads.location.directory ~/.config ;; hint links download')
config.bind(';re', 'set downloads.location.directory ~/Dropbox/Haushalt/Steuer2018/ ;; hint links download')
|
unlicense
|
obshtestvo/sledi-parlamenta
|
website/config/deploy.rb
|
653
|
lock '3.2.1'
server 'parliament.obshtestvo.bg:2203', user: 'www-data', roles: %w(app web db)
set :application, 'parliament.obshtestvo.bg'
set :deploy_to, '/var/www/parliament.obshtestvo.bg'
set :repo_url, 'https://github.com/obshtestvo/open-parliament.git'
set :linked_files, %w(config/database.yml)
set :linked_dirs, %w(bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system)
set :keep_releases, 20
set :rails_env, 'production'
set :git_strategy, Capistrano::GitSubfolderStrategy
set :git_subfolder, '/website'
set :puma_threads, [15, 15]
set :puma_workers, 3
set :puma_init_active_record, true
|
unlicense
|
dhcmrlchtdj/toolkit
|
javascript/deferred.js
|
283
|
// https://github.com/tj/deferred.js/blob/master/index.js
export default function Deferred() {
const p = new Promise((resolve, reject) => {
this.resolve = resolve;
this.reject = reject;
});
this.then = p.then.bind(p);
this.catch = p.catch.bind(p);
}
|
unlicense
|
gsanchezc/proyectoAnalisis
|
Codigo Fuente/frmPrincipal/frm_CxC_CxP_CatalogoProveedores.Designer.cs
|
11215
|
namespace frmPrincipal
{
partial class frm_CxC_CxP_CatalogoProveedores
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frm_CxC_CxP_CatalogoProveedores));
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.btn_agregar = new System.Windows.Forms.Button();
this.btn_cerrar = new System.Windows.Forms.Button();
this.dtg_CatalogoProveedor = new System.Windows.Forms.DataGridView();
this.Id_Proveedor = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Identificacion = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Nombre_Proveedor = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Direccion = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Telefono = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.Eliminar = new System.Windows.Forms.DataGridViewButtonColumn();
this.label1 = new System.Windows.Forms.Label();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dtg_CatalogoProveedor)).BeginInit();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.pictureBox2);
this.groupBox1.Controls.Add(this.groupBox2);
this.groupBox1.Controls.Add(this.dtg_CatalogoProveedor);
this.groupBox1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.groupBox1.ForeColor = System.Drawing.SystemColors.ControlDarkDark;
this.groupBox1.Location = new System.Drawing.Point(0, 0);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(1263, 520);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Catalogo Proveedores";
//
// pictureBox2
//
this.pictureBox2.BackgroundImage = global::frmPrincipal.Properties.Resources.imagen_proveedor_255x250;
this.pictureBox2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;
this.pictureBox2.Location = new System.Drawing.Point(1063, 238);
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.Size = new System.Drawing.Size(178, 200);
this.pictureBox2.TabIndex = 31;
this.pictureBox2.TabStop = false;
//
// groupBox2
//
this.groupBox2.Controls.Add(this.btn_agregar);
this.groupBox2.Controls.Add(this.btn_cerrar);
this.groupBox2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.groupBox2.ForeColor = System.Drawing.SystemColors.ControlDarkDark;
this.groupBox2.Location = new System.Drawing.Point(1038, 21);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(219, 154);
this.groupBox2.TabIndex = 7;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Opciones";
//
// btn_agregar
//
this.btn_agregar.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btn_agregar.ForeColor = System.Drawing.SystemColors.ControlDarkDark;
this.btn_agregar.Location = new System.Drawing.Point(16, 41);
this.btn_agregar.Name = "btn_agregar";
this.btn_agregar.Size = new System.Drawing.Size(187, 33);
this.btn_agregar.TabIndex = 1;
this.btn_agregar.Text = "&Nuevo Proveedor";
this.btn_agregar.UseVisualStyleBackColor = true;
this.btn_agregar.Click += new System.EventHandler(this.btn_agregar_Click);
//
// btn_cerrar
//
this.btn_cerrar.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.btn_cerrar.ForeColor = System.Drawing.SystemColors.ControlDarkDark;
this.btn_cerrar.Location = new System.Drawing.Point(16, 95);
this.btn_cerrar.Name = "btn_cerrar";
this.btn_cerrar.Size = new System.Drawing.Size(187, 33);
this.btn_cerrar.TabIndex = 2;
this.btn_cerrar.Text = "&Cerrar";
this.btn_cerrar.UseVisualStyleBackColor = true;
this.btn_cerrar.Click += new System.EventHandler(this.btn_cerrar_Click);
//
// dtg_CatalogoProveedor
//
this.dtg_CatalogoProveedor.AllowUserToAddRows = false;
this.dtg_CatalogoProveedor.AllowUserToDeleteRows = false;
this.dtg_CatalogoProveedor.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dtg_CatalogoProveedor.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.Id_Proveedor,
this.Identificacion,
this.Nombre_Proveedor,
this.Direccion,
this.Telefono,
this.Eliminar});
this.dtg_CatalogoProveedor.Location = new System.Drawing.Point(12, 45);
this.dtg_CatalogoProveedor.Name = "dtg_CatalogoProveedor";
this.dtg_CatalogoProveedor.Size = new System.Drawing.Size(1020, 469);
this.dtg_CatalogoProveedor.TabIndex = 0;
//
// Id_Proveedor
//
this.Id_Proveedor.DataPropertyName = "idProveedor";
this.Id_Proveedor.HeaderText = "Id Proveedor";
this.Id_Proveedor.Name = "Id_Proveedor";
this.Id_Proveedor.Width = 150;
//
// Identificacion
//
this.Identificacion.DataPropertyName = "identificacion";
this.Identificacion.HeaderText = "Identificacion";
this.Identificacion.Name = "Identificacion";
this.Identificacion.Width = 150;
//
// Nombre_Proveedor
//
this.Nombre_Proveedor.DataPropertyName = "nombre";
this.Nombre_Proveedor.HeaderText = "Nombre Proveedor";
this.Nombre_Proveedor.Name = "Nombre_Proveedor";
this.Nombre_Proveedor.Width = 200;
//
// Direccion
//
this.Direccion.DataPropertyName = "direccion";
this.Direccion.HeaderText = "Direccion";
this.Direccion.Name = "Direccion";
this.Direccion.Width = 225;
//
// Telefono
//
this.Telefono.DataPropertyName = "telefono";
this.Telefono.HeaderText = "Telefono";
this.Telefono.Name = "Telefono";
this.Telefono.Width = 150;
//
// Eliminar
//
this.Eliminar.HeaderText = "Eliminar";
this.Eliminar.Name = "Eliminar";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(380, 18);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(319, 24);
this.label1.TabIndex = 49;
this.label1.Text = "CATALOGO DE PROVEEDORES";
//
// frm_CxC_CxP_CatalogoProveedores
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1264, 518);
this.Controls.Add(this.groupBox1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Name = "frm_CxC_CxP_CatalogoProveedores";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "Catalogo Proveedores";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frm_CxC_CxP_CatalogoProveedores_FormClosing);
this.Load += new System.EventHandler(this.frm_CxC_CxP_CatalogoProveedores_Load);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
this.groupBox2.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.dtg_CatalogoProveedor)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.DataGridView dtg_CatalogoProveedor;
private System.Windows.Forms.Button btn_agregar;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Button btn_cerrar;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.DataGridViewTextBoxColumn Id_Proveedor;
private System.Windows.Forms.DataGridViewTextBoxColumn Identificacion;
private System.Windows.Forms.DataGridViewTextBoxColumn Nombre_Proveedor;
private System.Windows.Forms.DataGridViewTextBoxColumn Direccion;
private System.Windows.Forms.DataGridViewTextBoxColumn Telefono;
private System.Windows.Forms.DataGridViewButtonColumn Eliminar;
private System.Windows.Forms.Label label1;
}
}
|
unlicense
|
ksean/finmgr
|
core/src/test/java/sh/kss/finmgrcore/FinmgrCoreApplicationTests.java
|
1575
|
/*
finmgr - A financial transaction framework
Copyright (C) 2021 Kennedy Software Solutions Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package sh.kss.finmgrcore;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for the correctness of the finmgr core API
*
*/
@SpringBootTest
public class FinmgrCoreApplicationTests {
private static final Logger LOG = LoggerFactory.getLogger(FinmgrCoreApplicationTests.class);
@Autowired
private FileUploadController fileUploadController;
/**
* Test that the Spring context can load
*
*/
@Test
public void contextLoads() {
LOG.info("Spring context loaded");
assertThat(fileUploadController).isNotNull();
}
}
|
unlicense
|
MikailBag/gen-io
|
example/base.js
|
2602
|
'use strict';
var genio = require('../lib');
var util = require('util');
var fs = require('fs');
var ansi = require('ansi');
var cursor = ansi(process.stdout);
var assert = require('assert');
var sample = __dirname + '/sample.txt';
function part(part) {
cursor
.green()
.bg.grey()
.write(` ----------${part}----------\n`)
.reset()
}
function apiFn(name, signature, desc) {
cursor
.write('\t- ')
.blue()
.write(name.toString())
.green()
.write(signature+'\n')
.yellow()
.write(`\t\t${desc}\n`)
.reset();
}
genio(function* (io) {
//intro
debugger;
var fd;
console.log(['this is example of some features of gen-io',
'install: npm i gen-io -S',
'usage: genfs(function* (io){generator, using io () objects? containing async calls? supported by gen-io})']
.join('\n'));
part('fs');
console.log(`lets open file ${sample}`);
var fd = yield io.fs.open(sample, 'r+');
yield io.fs.write(fd,'just sample');
console.log('fd of sample.txt is %d\n lets now read its content',fd);
var content = yield io.fs.readFile(sample);
console.log('content of \'./sample.txt\' is %s',content);
part('dns');
console.log('Only one example. Lets see at ips of google.com');
var ports = yield io.dns.resolve('google.com', 'A');
console.log('Google is running on following ports:');
cursor.yellow();
for (var port in ports) {
cursor.write(`\t${ports[port]}\n`)
}
cursor.reset();
part('utilities');
apiFn('read', '(stream)', 'Returns one chunk of stream');
apiFn('wait', '(eventEmitter,eventName)', `Waits for emiiting "eventName" by "eventEmitter
\t\treturns first arg, passed to cb`);
console.log('lets now know fd of sample by event "open" and its first chunk');
var stream = fs.createReadStream(sample);
fd = yield io.util.wait(stream, 'open');
var filepart = yield io.util.read(stream);
console.log('first chunk of sample is %s, its fd is %s',filepart,fd);
part('plugin API');
console.log('now it isn\'t very big (consists of 1 function), but it can be useful. Example:\n'+
'new io component:foo foo()->\'bar\'');
io = genio.ctx({
foojs: {
foo: function foo(cb) {
process.nextTick(function () {
cb(null, 'bar')
}
);
}
}
});
var bar = yield io.foojs.foo();
assert.equal('bar', bar);
console.log('and bar is %s',bar)
});
|
unlicense
|
danidemi/tutorial-front-end
|
webpack/01-project-with-configuration/webpack.config.js
|
648
|
const path = require('path');
module.exports = {
// entry tells Webpack which files are the entry points of your application.
// Those are your main files, that sit at the top of your dependency tree.
entry: './client/js/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'build')
},
module: {
loaders: [
{
// only files ending with .js
test: /\.js/,
loader: 'babel-loader',
// only files in client
include: path.resolve(__dirname + '/client')
}
]
}
};
|
unlicense
|
nature-track/wenCollege-CSharp
|
Model/supplier.cs
|
2953
|
/** 版本信息模板在安装目录下,可自行修改。
* supplier.cs
*
* 功 能: N/A
* 类 名: supplier
*
* Ver 变更日期 负责人 变更内容
* ───────────────────────────────────
* V0.01 2016-12-21 14:42:52 N/A 初版
*
* Copyright (c) 2012 Maticsoft Corporation. All rights reserved.
*┌──────────────────────────────────┐
*│ 此技术信息为本公司机密信息,未经本公司书面同意禁止向第三方披露. │
*│ 版权所有:动软卓越(北京)科技有限公司 │
*└──────────────────────────────────┘
*/
using System;
namespace Maticsoft.Model
{
/// <summary>
/// supplier:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
[Serializable]
public partial class supplier
{
public supplier()
{}
#region Model
private int _id;
private string _name;
private string _person;
private string _phone;
private string _phone2;
private string _bank;
private string _bank_num;
private string _address;
private int? _style;
private int? _leibie;
private string _wuzi;
private string _beizhu;
private string _beizhu2;
/// <summary>
///
/// </summary>
public int id
{
set{ _id=value;}
get{return _id;}
}
/// <summary>
///
/// </summary>
public string name
{
set{ _name=value;}
get{return _name;}
}
/// <summary>
///
/// </summary>
public string person
{
set{ _person=value;}
get{return _person;}
}
/// <summary>
///
/// </summary>
public string phone
{
set{ _phone=value;}
get{return _phone;}
}
/// <summary>
///
/// </summary>
public string phone2
{
set{ _phone2=value;}
get{return _phone2;}
}
/// <summary>
///
/// </summary>
public string bank
{
set{ _bank=value;}
get{return _bank;}
}
/// <summary>
///
/// </summary>
public string bank_num
{
set{ _bank_num=value;}
get{return _bank_num;}
}
/// <summary>
///
/// </summary>
public string address
{
set{ _address=value;}
get{return _address;}
}
/// <summary>
///
/// </summary>
public int? style
{
set{ _style=value;}
get{return _style;}
}
/// <summary>
///
/// </summary>
public int? leibie
{
set{ _leibie=value;}
get{return _leibie;}
}
/// <summary>
///
/// </summary>
public string wuzi
{
set{ _wuzi=value;}
get{return _wuzi;}
}
/// <summary>
///
/// </summary>
public string beizhu
{
set{ _beizhu=value;}
get{return _beizhu;}
}
/// <summary>
///
/// </summary>
public string beizhu2
{
set{ _beizhu2=value;}
get{return _beizhu2;}
}
#endregion Model
}
}
|
unlicense
|
boujam/jbulletin
|
src/main/java/com/fwb/jbulletin/model/Teacher.java
|
1086
|
package com.fwb.jbulletin.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.ManyToMany;
@Entity
public class Teacher extends BaseEntity {
/**
*
*/
private static final long serialVersionUID = 8136368761173410404L;
private String firstName;
private String lastName;
@ManyToMany(mappedBy="teachers")
List<Course> courses = new ArrayList<Course>();
public Teacher() {
System.out.println("inside constructor of Class Teacher : " + this.toString());
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<Course> getCourses() {
return courses;
}
public void setCourses(List<Course> courses) {
this.courses = courses;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
|
unlicense
|
SelvorWhim/competitive
|
LeetCode/MinimumValueToGetPositiveStepByStepSum.py
|
384
|
# convoluted description, but seems like you can just calculate the minimum partial sum (left to right), negate and add 1 to that
class Solution:
def minStartValue(self, nums: List[int]) -> int:
sum_so_far = 0
min_so_far = 0
for num in nums:
sum_so_far += num
min_so_far = min(min_so_far, sum_so_far)
return 1 - min_so_far
|
unlicense
|
satyriasizz/simple-scala-rest-example
|
src/main/scala/com/sysgears/example/domain/Customer.scala
|
1687
|
package com.sysgears.example.domain
import scala.slick.driver.MySQLDriver.simple._
import spray.http.{HttpCharsets, HttpEntity}
import net.liftweb.json.{DateFormat, Formats, Serialization}
import java.text.SimpleDateFormat
import java.util.Date
/**
* Customer entity.
*
* @param id unique id
* @param firstName first name
* @param lastName last name
* @param birthday date of birth
*/
case class Customer(id: Option[Long], firstName: String, lastName: String, birthday: Option[java.util.Date])
/**
* Mapped customers table object.
*/
object Customers extends Table[Customer]("customers") {
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def firstName = column[String]("first_name")
def lastName = column[String]("last_name")
def birthday = column[java.util.Date]("birthday", O.Nullable)
def * = id.? ~ firstName ~ lastName ~ birthday.? <>(Customer, Customer.unapply _)
implicit val dateTypeMapper = MappedTypeMapper.base[java.util.Date, java.sql.Date](
{
ud => new java.sql.Date(ud.getTime)
}, {
sd => new java.util.Date(sd.getTime)
})
val findById = for {
id <- Parameters[Long]
c <- this if c.id is id
} yield c
}
object CustomerConversions {
implicit val liftJsonFormats = new Formats {
val dateFormat = new DateFormat {
val sdf = new SimpleDateFormat("yyyy-MM-dd")
def parse(s: String): Option[Date] = try {
Some(sdf.parse(s))
} catch {
case e: Exception => None
}
def format(d: Date): String = sdf.format(d)
}
}
implicit def HttpEntityToCustomer(httpEntity: HttpEntity) = Serialization.read[Customer](httpEntity.asString(HttpCharsets.`UTF-8`))
}
|
unlicense
|
minagisyu/SmartAudioPlayerFx
|
SmartAudioPlayer Fx/__Primitives__/[Windows]/WinAPI/COM/IWMSyncReader2.cs
|
3305
|
using System;
using System.Runtime.InteropServices;
using System.Security;
namespace __Primitives__
{
partial class WinAPI
{
partial class COM
{
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("faed3d21-1b6b-4af7-8cb6-3e189bbc187b")]
[SuppressUnmanagedCodeSecurity]
public interface IWMSyncReader2
{
// IWMSyncReader
void Open(string pwszFilename);
void Close();
void SetRange(ulong cnsStartTime, long cnsDuration);
void SetRangeByFrame(
ushort wStreamNum,
ulong qwFrameNumber,
long cFramesToRead);
void GetNextSample(
ushort wStreamNum,
out INSSBuffer ppSample,
out ulong pcnsSampleTime,
out ulong pcnsDuration,
out uint pdwFlags,
out uint pdwOutputNum,
out ushort pwStreamNum);
void SetStreamsSelected(
ushort cStreamCount,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]
ushort[] pwStreamNumbers,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]
WMT_STREAM_SELECTION[] pSelections);
void GetStreamSelected(
ushort wStreamNum,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]
out WMT_STREAM_SELECTION[] pSelection);
void SetReadStreamSamples(ushort wStreamNum, bool fCompressed);
void GetReadStreamSamples(ushort wStreamNum, out bool pfCompressed);
void GetOutputSetting(
uint dwOutputNum,
string pszName,
out WMT_ATTR_DATATYPE pType,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)]
byte[] pValue,
ref ushort pcbLength);
void SetOutputSetting(
uint dwOutputNum,
string pszName,
WMT_ATTR_DATATYPE Type,
[MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 4)]
byte[] pValue,
ushort cbLength);
void GetOutputCount(out uint pcOutputs);
void GetOutputProps(uint dwOutputNum, out IWMOutputMediaProps ppOutput);
void SetOutputProps(uint dwOutputNum, IWMOutputMediaProps pOutput);
void GetOutputFormatCount(uint dwOutputNum, out uint pcFormats);
void GetOutputFormat(uint dwOutputNum, uint dwFormatNum, out IWMOutputMediaProps ppProps);
void GetOutputNumberForStream(ushort wStreamNum, out uint pdwOutputNum);
void GetStreamNumberForOutput(uint dwOutputNum, out ushort pwStreamNum);
void GetMaxOutputSampleSize(uint dwOutput, out uint pcbMax);
void GetMaxStreamSampleSize(ushort wStream, out uint pcbMax);
void OpenStream(IStream pStream);
// IWMSyncReader2
void SetRangeByTimecode(
ushort wStreamNum,
ref WMT_TIMECODE_EXTENSION_DATA pStart,
ref WMT_TIMECODE_EXTENSION_DATA pEnd);
void SetRangeByFrameEx(
ushort wStreamNum,
ulong qwFrameNumber,
long cFramesToRead,
out ulong pcnsStartTime);
void SetAllocateForOutput(uint dwOutputNum, IWMReaderAllocatorEx pAllocator);
void GetAllocateForOutput(uint dwOutputNum, out IWMReaderAllocatorEx ppAllocator);
void SetAllocateForStream(ushort wStreamNum, IWMReaderAllocatorEx pAllocator);
void GetAllocateForStream(ushort dwSreamNum, out IWMReaderAllocatorEx ppAllocator);
}
[StructLayout(LayoutKind.Sequential, Pack = 2)]
public struct WMT_TIMECODE_EXTENSION_DATA
{
public ushort wRange;
public uint dwTimecode;
public uint dwUserbits;
public uint dwAmFlags;
}
}
}
}
|
unlicense
|
bpmericle/gluecon2017-spring-boot
|
src/main/java/com/wistful/widgets/api/services/SearchService.java
|
624
|
package com.wistful.widgets.api.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.wistful.widgets.api.data.WidgetRepository;
import com.wistful.widgets.api.models.Widget;
/**
*
* @author brian.mericle
*
*/
@Service
public class SearchService {
@Autowired
private WidgetRepository repository;
/**
*
* @return
*/
public List<Widget> findAll() {
return repository.findAll();
}
/**
*
* @param id
* @return
*/
public Widget findById(String id) {
return repository.findById(id);
}
}
|
unlicense
|
igorgoroun/FTNW
|
Controller/PointController.php
|
5548
|
<?php
namespace IgorGoroun\FTNWBundle\Controller;
use Doctrine\Common\Cache\ApcuCache;
use IgorGoroun\FTNWBundle\Entity\reCaptcha;
use IgorGoroun\FTNWBundle\Form\RegistrationType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use IgorGoroun\FTNWBundle\Entity\Point;
use IgorGoroun\FTNWBundle\Form\SettingsType;
class PointController extends Controller
{
public function settingsAction(Request $request){
$user = $this->getUser();
$form = $this->createForm(SettingsType::class,$user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->addFlash('notice','Ваши данные сохранены.');
return $this->redirectToRoute('point_settings');
}
return $this->render(
'FTNWBundle:Point:settings.html.twig',
array(
'form' => $form->createView(),
'point_num' => $user->getNum(),
)
);
}
public function registerAction(Request $request)
{
$user = new Point();
$form = $this->createForm(RegistrationType::class,$user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid() && $this->reCaptchaValid($request)) {
$password = $this->get('security.password_encoder')->encodePassword($user,$user->getPlainPassword());
$user->setPassword($password);
$user->setActive(false);
$user->setNum($this->genFreeNum());
$user->setFtnaddr($this->genFTNAddr($user->getNum()));
$user->setIfaddr($this->genIfAddr($user->getFtnaddr()));
$user->setIfname($this->genIfName($user->getUsername()));
$user->setOrigin($this->getParameter('point_default_origin'));
$user->setSubscription($this->getParameter('point_default_subscription').$user->getUsername().', '.$user->getFtnaddr());
$user->setCreated(new \DateTime());
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
$this->addFlash('notice','Ваша учетная запись будет активирована через несколько минут.');
if ($user->getClassic()) {
return $this->redirectToRoute('point_classic_info',['num'=>$user->getNum()]);
/*
return $this->render('FTNWBundle:Point:classic.html.twig',
array(
'point' => $user,
)
);*/
} else {
return $this->redirectToRoute('point_web_info',['num'=>$user->getNum()]);
/*
return $this->render('FTNWBundle:Point:confirmweb.html.twig',
array(
'point' => $user,
)
);*/
}
}
return $this->render(
'FTNWBundle:Point:registration.html.twig',
array(
'form' => $form->createView()
)
);
}
private function reCaptchaValid(Request $request) {
$cap = $request->request->get('g-recaptcha-response');
$re = new reCaptcha($cap,$secret=$this->getParameter('recaptcha_secret_key'),$url=$this->getParameter('recaptcha_verify_host'));
return $re->verifyResponse();
}
private function genIfName($name) {
return mb_strtolower(preg_replace('/\ /','_',$name));
}
private function genIfAddr($ftn) {
preg_match('/(\d{1})\:(\d{1,4})\/(\d{1,4})\.(\d{1,4})/',$ftn,$data);
$ifaddr = 'p'.$data[4].'.f'.$data[3].'.n'.$data[2].'.z'.$data[1].'.fidonet.org';
return $ifaddr;
}
private function genFTNAddr($num) {
$node = $this->getParameter('node_ftn_address');
$point = $num;
return $node.'.'.$point;
}
private function genFreeNum() {
$qb = $this->getDoctrine()->getManager()->createQueryBuilder();
$qb->select($qb->expr()->max('p.num'))
->from('FTNWBundle:Point','p');
$max_num = $qb->getQuery()->getSingleScalarResult();
if (is_null($max_num)) {
return 1;
} else {
return $max_num+1;
}
}
public function loginAction(Request $request)
{
$authenticationUtils = $this->get('security.authentication_utils');
$error = $authenticationUtils->getLastAuthenticationError();
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render(
'FTNWBundle:Point:login.html.twig',
array(
// last username entered by the user
'last_username' => $lastUsername,
'error' => $error,
'ftnw_ver' => $this->getParameter('ftnw_ver'),
)
);
}
public function logoutAction() {
return $this->redirectToRoute('point_login');
}
public function classicAction($num) {
return $this->render('FTNWBundle:Point:classic.html.twig',array('num'=>$num));
}
public function webbsAction($num) {
return $this->render('FTNWBundle:Point:confirmweb.html.twig',array('num'=>$num));
}
public function faqAction() {
return $this->render('FTNWBundle:Point:faq.html.twig');
}
}
|
unlicense
|
hivaids2512/myresume
|
config/db/config.go
|
132
|
package db
const (
DB_HOST = "ds023438.mlab.com:23438"
DB_NAME = "myresume"
DB_USER = "tranquy2512"
DB_PASS = "@Quy@%!@!((#"
)
|
unlicense
|
orlenko/bccf
|
src/pybb/admin.py
|
6921
|
# -*- coding: utf-8
from copy import deepcopy
from django.utils.translation import ugettext_lazy as _
from django.contrib import admin
from django.core.urlresolvers import reverse
from bccf.admin import make_featured, make_unfeatured
from mezzanine.core.admin import DisplayableAdmin
from pybb.models import Category, Forum, Topic, Post, Profile, Attachment, PollAnswer
from pybb import util
username_field = util.get_username_field()
class ForumInlineAdmin(admin.TabularInline):
model = Forum
fields = ['name', 'hidden', 'position']
extra = 0
class CategoryAdmin(admin.ModelAdmin):
list_display = ['name', 'position', 'hidden', 'forum_count']
list_per_page = 20
ordering = ['position']
search_fields = ['name']
list_editable = ['position']
inlines = [ForumInlineAdmin]
class ForumAdmin(admin.ModelAdmin):
list_display = ['name', 'category', 'hidden', 'position', 'topic_count', ]
list_per_page = 20
raw_id_fields = ['moderators']
ordering = ['-category']
search_fields = ['name', 'category__name']
list_editable = ['position', 'hidden']
fieldsets = (
(None, {
'fields': ('category', 'name', 'hidden', 'position', )
}
),
(_('Additional options'), {
'classes': ('collapse',),
'fields': ('updated', 'description', 'headline', 'post_count', 'moderators')
}
),
)
class PollAnswerAdmin(admin.TabularInline):
model = PollAnswer
fields = ['text', ]
extra = 0
class TopicAdmin(admin.ModelAdmin):
list_display = ['name', 'forum', 'created', 'head', 'post_count', 'poll_type',]
list_per_page = 20
raw_id_fields = ['user', 'subscribers']
ordering = ['-created']
date_hierarchy = 'created'
search_fields = ['name']
fieldsets = (
(None, {
'fields': ('forum', 'name', 'user', ('created', 'updated'), 'poll_type',)
}
),
(_('Additional options'), {
'classes': ('collapse',),
'fields': (('views', 'post_count'), ('sticky', 'closed'), 'subscribers')
}
),
)
inlines = [PollAnswerAdmin, ]
class BCCFTopicAdmin(DisplayableAdmin):
actions = [make_featured, make_unfeatured]
list_per_page = 20
raw_id_fields = ['user', 'subscribers']
ordering = ['-created']
date_hierarchy = 'created'
search_fields = ['name']
def __init__(self, *args, **kwargs):
super(BCCFTopicAdmin, self).__init__(*args, **kwargs)
if self.fieldsets == DisplayableAdmin.fieldsets:
self.fieldsets = deepcopy(self.fieldsets)
for field in reversed(['forum',
'name',
'user',
'closed',
'content',
'bccf_topic',
'featured',
'image',
'page_for']):
self.fieldsets[0][1]['fields'].insert(3, field)
if self.list_display == DisplayableAdmin.list_display:
self.list_display = list(deepcopy(self.list_display))
for fieldname in ['head', 'post_count', 'featured']:
self.list_display.insert(-1, fieldname)
if self.list_filter == DisplayableAdmin.list_filter:
self.list_filter = list(deepcopy(self.list_filter))
for fieldname in ['featured']:
self.list_filter.insert(-1, fieldname)
class TopicReadTrackerAdmin(admin.ModelAdmin):
list_display = ['topic', 'user', 'time_stamp']
search_fields = ['user__%s' % username_field]
class ForumReadTrackerAdmin(admin.ModelAdmin):
list_display = ['forum', 'user', 'time_stamp']
search_fields = ['user__%s' % username_field]
class PostAdmin(admin.ModelAdmin):
list_display = ['topic', 'user', 'created', 'updated', 'on_moderation', 'summary']
list_editable = ['on_moderation']
list_per_page = 20
actions = ['make_approve', 'make_unapprove']
raw_id_fields = ['user', 'topic']
ordering = ['-created']
date_hierarchy = 'created'
search_fields = ['body']
fieldsets = (
(None, {
'fields': ('topic', 'user')
}
),
(_('Additional options'), {
'classes': ('collapse',),
'fields' : (('created', 'updated'), 'user_ip')
}
),
(_('Message'), {
'fields': ('body', 'body_html', 'body_text', 'on_moderation')
}
),
)
def make_approve(self, request, queryset):
num_rows = queryset.update(on_moderation=False)
if num_rows == 1:
message_bit = '1 post approved'
else:
message_bit = '%s posts approved' % num_rows
make_approve.short_description = "Approve selected posts"
def make_unapprove(self, request, queryset):
num_rows = queryset.update(on_moderation=True)
if num_rows == 1:
message_bit = '1 post disapproved'
else:
message_bit = '%s posts disapproved' % num_rows
make_unapprove.short_description = "Disapprove selected posts"
class ProfileAdmin(admin.ModelAdmin):
list_display = ['user', 'time_zone', 'language', 'post_count']
list_per_page = 20
ordering = ['-user']
search_fields = ['user__%s' % username_field]
fieldsets = (
(None, {
'fields': ('user', 'time_zone', 'language')
}
),
(_('Additional options'), {
'classes': ('collapse',),
'fields' : ('avatar', 'signature', 'show_signatures')
}
),
)
class AttachmentAdmin(admin.ModelAdmin):
list_display = ['file', 'size', 'admin_view_post', 'admin_edit_post']
def admin_view_post(self, obj):
return u'<a href="%s">view</a>' % obj.post.get_absolute_url()
admin_view_post.allow_tags = True
admin_view_post.short_description = _('View post')
def admin_edit_post(self, obj):
return u'<a href="%s">edit</a>' % reverse('admin:pybb_post_change', args=[obj.post.pk])
admin_edit_post.allow_tags = True
admin_edit_post.short_description = _('Edit post')
#admin.site.register(Category, CategoryAdmin)
admin.site.register(Forum, ForumAdmin)
admin.site.register(Topic, BCCFTopicAdmin)
admin.site.register(Post, PostAdmin)
#admin.site.register(Attachment, AttachmentAdmin)
if util.get_pybb_profile_model() == Profile:
admin.site.register(Profile, ProfileAdmin)
# This can be used to debug read/unread trackers
#admin.site.register(TopicReadTracker, TopicReadTrackerAdmin)
#admin.site.register(ForumReadTracker, ForumReadTrackerAdmin)
|
unlicense
|
JoseJimeniz/BankItems
|
localization-ruRU.lua
|
9970
|
-- BankItems ruRU Locale File (Credits: StingerSoft)
-- THE CONTENTS OF THIS FILE IS AUTO-GENERATED BY THE WOWACE PACKAGER
-- Please use the Localization App on WoWAce to update this
-- at http://www.wowace.com/projects/bank-items/localization/
if GetLocale() ~= "ruRU" then return end
local L = BANKITEMS_LOCALIZATION
L["All players' data have been cleared."] = "Данные о всех персонажах были очищены."
L["All Realms"] = "Все миры"
L["Bag %d Item %d:"] = "Сумка %d предмет %d:"
L["Bags"] = "В сумках"
L["Bank"] = "В банке"
L["Bank Item %d:"] = "Предмет в банке %d:"
L["BankItems Bindings"] = "Клавиши BankItems"
L["BANKITEMS_CAUTION_TEXT"] = [=[ВНИМАНИЕ: Некоторые предметы не были проанализированы / не отобразились в настоящем отчете, поскольку они не существуют в вашем локальном кэше WoW. Недавнее обновление WoW или меню запуска вызвало очищение локального кэша. Войдите за данного персонажа и посетите банк для исправления данного положения, или наведите курсор мыши на каждый предмет в каждой сумке для запроса информации с сервера (это может вызвать разрыв соединения с сервером).
]=]
L["BankItems Options"] = "Настройки BankItems"
L["-- /bi allbank : open BankItems and all bank bags only"] = "-- /bi allbank : открыть BankItems и все сумки банка"
L["-- /bi all : open BankItems and all bags"] = "-- /bi all : открыть BankItems и все сумки"
L["-- /bi charname : open bank of charname on the same server"] = "-- /bi charname : открыть банк персонажа на этом сервере"
L["-- /bi clearall : clear all players' info"] = "-- /bi clearall : очистить информацию о всех игроках"
L["-- /bi clear : clear currently selected player's info"] = "-- /bi clear : очистить информацию о выбранном игроке"
L["-- /bigb clear : clear currently selected guild's info"] = "-- /bigb clear : очистить информацию о выбранной гильдии"
L["-- /bigb : open BankItems guild bank"] = "-- /bigb : открыть гильдейский банк BankItems"
L["-- /bi hidebutton : hide the minimap button"] = "-- /bi hidebutton : скрыть кнопку у мини-карты"
L["-- /bi open charname : open bank of charname on the same server"] = "-- /bi open charname : открыть банк персонажа на этом сервере"
L["-- /bi search itemname : search for items"] = "-- /bi search itemname : поиск предметов"
L["-- /bi showbutton : show the minimap button"] = "-- /bi showbutton : показать кнопку у мини-карты"
L["-- /bis itemname : search for items"] = "-- /bis itemname : поиск предметов"
L["|cffeda55fClick|r to toggle BankItems"] = "|cffeda55fКлик|r открывает/закрывает окно BankItems"
L["|cffeda55fShift-Click|r to toggle BankItems Guild Bank"] = "|cffeda55fShift-Клик|r открывает/закрывает окно гильдейского банка BankItems"
L["Check to show all saved characters, regardless of realm or faction."] = "Просмотр всех сохранённых персонажей, независимо от сервера или фракции."
L["Check to show characters from the opposite faction (includes BankItems tooltips)."] = "Просмотр персонажей обоих фракций (добавляет информацию в подсказки BankItems)."
L["Contents of:"] = "Содержимое:"
L["%dg %ds %dc"] = "%dз %dс %dм"
L["%d guild bank(s) selected"] = "%d гильд. банк(а) выбран(о)"
L["Equipped"] = "Экипировка"
L["Equipped Items"] = "Экипировка"
L["Export BankItems..."] = "Экспорт..."
L["Group similar items"] = "Подобные предметы"
L["GuildBank"] = "Гильдейский банк"
L["has"] = "имеет"
L["Ignore unstackable soulbound items"] = "Игнорировать именные не объединяющиеся предметы"
L["Include the following guild banks:"] = "Включая следующие гильдейские банки:"
L["Items in Mailbox"] = "Почтовый ящик"
L["Left-click to open BankItems."] = "[Левый-клик] открывает/закрывает окно BankItems."
L["Lock main window from being moved"] = "Зафиксировать главное окно от перемещения"
L["Mailbox data not found. Please visit the mailbox on this character once to record it."] = "Данные о предметах в почтовом ящике не найдены. Пожалуйста, посетите почтовый ящик для их осмотра."
L["Minimap Button Position %d"] = "Позиция кнопки у мини-карты %d"
L["Minimap Button Radius %d"] = "Радиус кнопки у мини-карты %d"
L["Money:"] = "Деньги:"
L["Money (cumulative)"] = "Деньги (всего)"
L["No Guild Bank Data"] = "Нет данных о гильдейском банке"
L["No Guild Bank Tabs"] = "Нет сейфов гильдейского банка"
L["Note - Blizzard frames doesn't like it if your scale isn't 100% when using this option."] = "Заметка - Открытие окна банка Blizzard при использовании данной опции не рекомендуется, если не установлен масштаб 100%."
L["(Not seen before)"] = "(Не осмотрено)"
L["of"] = "-"
L["OfflineBank"] = "Автономный банк"
L["On the command \"/bi\":"] = "По команде \"/bi\":"
L["Open bank bags"] = "Сумки банка"
L["Open BankItems and..."] = "Открыть BankItems и..."
L["Open BankItems bags with Blizzard bags"] = "Открывать сумки BankItems рядом с сумками персонажа"
L["Open BankItems with Blizzard windows"] = "Открыть BankItems рядом со стандартными окнами"
L["Open currency bag"] = "Сумку валюты"
L["Open equipped bag"] = "Сумку экипировки"
L["Open inventory bags"] = "Сумки инвентаря"
L["Open keyring"] = "Связку ключей"
L["Open mail bag"] = "Почтовую сумку"
L["Options..."] = "Настройки..."
L["Right-click and drag to move this button."] = "[Правый-клик + тянуть] перемещает эту кнопку."
L["Scaling %d%%"] = "Масштаб %d%%"
L["%s data not found. Please log on this character once to record it."] = "Данные %s не найдены. Пожалуйста, зайдите за данного персонажа для получения информации о них."
L["Search bank and bank bags"] = "Поиск в банке и сумках банка"
L["Search BankItems..."] = "Поиск..."
L["Search equipped gear"] = "Поиск в экипировке"
L["Search for \"%s\" complete."] = "Поиск \"%s\" закончен."
L["Search guild banks"] = "Поиск в гильдейских банках"
L["Search inventory bags"] = "Поиск в сумках инвентаря"
L["Search mailbox"] = "Поиск в почтовом ящике"
L["Search these bags..."] = "Поиск в сумках..."
L["Show All Realms"] = "Все сервера"
L["Show bag prefix"] = "Показать префикс сумки"
L["Show extra item tooltip information"] = "Показать дополнительную информацию в подсказке предмета"
L["Show Opposite Faction"] = "Обе фракции"
L["Show the minimap button"] = "Показать кнопку у мини-карты"
L["<%s>'s guild bank has not purchased any guild bank tabs."] = "В гильдейском банке <%s> не приобретено ни одного сейфа."
L["Tab %d Item %d:"] = "Раздел %d предмет %d:"
L["Toggle BankItems"] = "Открыть/Закрыть BankItems"
L["Toggle BankItems and all Bags"] = "Открыть/Закрыть BankItems и все сумки"
L["Toggle BankItems and all Bank Bags"] = "Открыть/Закрыть BankItems и все сумки банка"
L["Toggle BankItems Guild Bank"] = "Открыть/Закрыть гильдейский банк BankItems"
L["Total"] = "Всего"
L["Total: %d"] = "Всего: %d"
L["Transparency %d%%"] = "Прозрачность %d%%"
L["Type /bi or /bankitems to open BankItems"] = "Для открытия BankItems введите: /bi или /bankitems"
L["View bank/inventory/mail contents from anywhere!"] = "Просмотр содержимого банка/инвентаря/почты в любое время!"
L["View Guild Bank contents from anywhere!"] = "Просмотр содержимого гильдейского банка в любой момент!"
L["Void Storage data not found. Please visit the Void Storage NPC on this character once to record it."] = "Данные Хранилища Бездны не найдены. Пожалуйста посетите Смотрителя Хранилища этим персонажем для осмотра содержимого Хранилища."
L["You do not have any guild bank data to display."] = "У вас нет никаких данных о гильдейском банке для отображения."
L["You have not seen the contents of \"%s\" before"] = "Вы раньше не осматривали содержимое \"%s\""
|
unlicense
|
dankozitza/mechanizm
|
src/mechanizm_game.cpp
|
76005
|
//
// mechanizm_game.cpp
//
// Asteroid mining and block building game.
//
// Created by Daniel Kozitza
//
#include <chrono>
#include <csignal>
#include <cstdlib>
#include <dirent.h>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <sys/wait.h>
#include <unistd.h>
#include "commands.hpp"
#include "mechanizm.hpp"
#include "options.hpp"
#include "tools.hpp"
#include <GL/glu.h>
#include <GL/glut.h>
//#include <glm/detail/type_vec4.hpp>
#include "Camera.hpp"
#include "Group.hpp" // includes Vertex, Tetrahedron, & Object
#include "Sphere.hpp"
using namespace tools;
void
animation(void),
setMatrix(int w, int h),
generate_map(void),
pricion(void),
mech_idle(void),
help(string prog_name),
menu(int choice),
resize(int w, int h),
mouse(int button, int state, int x, int y),
mouse_motion(int x, int y),
keyboard(unsigned char c, int x, int y),
keyboard_up(unsigned char c, int x, int y),
special_input(int key, int x, int y),
motion(int x, int y),
drawScene(void),
drawWireframe(int objs_index, int face),
drawVisibleTriangles(string gsid, string obid, Tetrahedron& tetra),
draw_glut_menu(),
draw_circle(float cx, float cy, float r, int num_segments),
draw_cam_spheres(),
draw_sphere(Sphere& s),
draw_spheres(),
reset_sphere_distance();
tools::Error random_motion(double t, Object &self);
tools::Error player_gravity(double t, Object &self);
tools::Error gobj_physics(double t, Object &self);
Tetrahedron generate_tetra_from_side(Tetrahedron& source, int source_face);
tools::Error save_map(string mapname);
tools::Error load_map(string mapname);
unordered_map<string, Group> GS;
vector<Sphere> SPHRS;
string select_gobj = "none";
string select_obj = "none";
int select_face;
long unsigned int gen_obj_cnt = 0;
long unsigned int gen_map_cnt = 1;
string selector_function = "select";
int draw_x_vertices = 0;
bool highlight_enabled = false;
int menu_depth = 0;
int timed_menu_display = 0;
int draw_menu_lines = 10;
string menu_input;
vector<string> menu_output;
vector<string> menu_history;
size_t mhinc;
int block_count = 1;
int mouse_left_state = 1;
int WIN = -1;
// X Y Z theta (ax) psi (ay) rotationSpeed translationSpeed
static Camera CAM(2.0, 2.0, 3.5, 0.0, 0.0, 0.6, 0.0022);
static mechanizm MECH;
int PO = 0;
int count = 1; // cycles through 1/60th of a second
commands GAME_CMDS;
map<string, string> CMDS_ENV;
int IGCMD_MOUT_SCROLL = 0;
map<string, unsigned long> GAME_STATS;
GLfloat SD; // current distance of the selection sphere
bool SD_DONE = true;
bool DRAW_GLUT_MENU = false;
GLfloat BRTNS = 0.0;
// menu options
bool MAP_GEN = false;
bool PHYSICS = false;
bool MOUSE_GRAB = false;
// commands for the in-game cli
void
cmd_help(vector<string>& argv),
cmd_tp(vector<string>& argv),
cmd_set(vector<string>& argv),
cmd_grow(vector<string>& argv),
cmd_stat(vector<string>& argv),
cmd_load(vector<string>& argv),
cmd_save_map(vector<string>& argv),
cmd_load_map(vector<string>& argv),
cmd_reseed(vector<string>& argv),
cmd_info(vector<string>& argv),
cmd_physics(vector<string>& argv),
cmd_foreach(vector<string>& argv),
cmd_controls(vector<string>& argv);
int main(int argc, char *argv[]) {
char buf[100];
sprintf(buf, "%li", time(NULL));
CMDS_ENV["rng_seed"] = buf;
srand(as_double(CMDS_ENV["rng_seed"]));
string prog_name = string(argv[0]);
options opt;
bool quiet = false;
bool show_help = false;
bool file_given = false;
bool realtime = false;
bool time = false;
bool seed_b = false;
vector<string> seed_argv(1);
vector<string> file_path_av(1);
string m[5];
vector<string> args;
Error e = NULL;
Object tmp_player_obj("player_grav_obj", 1.0, player_gravity);
tmp_player_obj.setConstQ("v", {0.0, 0.0, 0.0});
tmp_player_obj.setConstQ("AGM_GRAVITY", 9.8);
tmp_player_obj.setConstQ("AGM_FALLING", 0.0);
tmp_player_obj.setConstQ("AGM_FSTARTT", 3.0);
tmp_player_obj.setConstQ("AGM_FSTARTY", 5.0);
tmp_player_obj.translate(10.0, 0.0, 10.0);
MECH.add_object(tmp_player_obj);
MECH.current_time = 0.0;
// build handler for glut window / game save
signal(SIGINT, signals_callback_handler);
opt.handle('q', quiet);
opt.handle('h', show_help);
opt.handle('f', file_given, file_path_av);
opt.handle('r', realtime);
opt.handle('s', seed_b, seed_argv);
for (int i = 1; i < argc; ++i)
args.push_back(argv[i]);
opt.evaluate(args);
if (pmatches(m, prog_name, "^.*/([^/]+)$"))
prog_name = m[1];
if (show_help) {
help(prog_name);
return 0;
}
if (seed_b) {
srand(as_double(seed_argv[0]));
CMDS_ENV["rng_seed"] = seed_argv[0];
}
// set up the in game command line
vector<string> cmd_argv;
CMDS_ENV["agm_climb_spd"] = "0.8";
CMDS_ENV["brightness"] = "0.0";
CMDS_ENV["n_click_speed"] = "0.25";
CMDS_ENV["n_click_max_distance"] = "6.0";
CMDS_ENV["n_click_distance"] = "0.6";
CMDS_ENV["map_name"] = "map.json";
CMDS_ENV["mapgen_rndmns"] = "0.0002";
CMDS_ENV["mapgen_g_opt"] = "r";
CMDS_ENV["mapgen_size"] = "600";
CMDS_ENV["hotkey_g"] = "grow 1";
CMDS_ENV["hotkey_G"] = "grow 500";
CMDS_ENV["igcmd_mout_max_size"] = "100";
CMDS_ENV["igcmd_scroll_speed"] = "5";
CMDS_ENV["block_color"] = "0.25 0.3 0.3";
CMDS_ENV["player_move_speed"] = "0.001";
CMDS_ENV["phys_max_work"] = "200";
CMDS_ENV["phys_highlight"] = "false";
// X Y Z theta (ax) psi (ay) rotationSpeed translationSpeed
CAM = Camera(CAM.getX(), CAM.getY(), CAM.getZ(), 0.0, 0.0, 0.5,
as_double(CMDS_ENV["player_move_speed"]));
SD = as_double(CMDS_ENV["n_click_distance"]);
Sphere selector_sphere_1(0.0, 0.0, 0.0, 0.025, 0.4, 0.8, 0.6);
SPHRS.push_back(selector_sphere_1);
GAME_CMDS.handle(
"help",
cmd_help,
"\nThis is the in-game command line interface.",
"help [command]");
GAME_CMDS.handle(
"tp",
cmd_tp,
"Teleport to the given coordinates.",
"tp x y z",
"",
true);
GAME_CMDS.handle(
"set",
cmd_set,
"Set a value in CMDS_ENV.",
"set [key [value]]",
"This command can be called in 3 ways:\n"
" 0 args - - Print all values in the map.\n"
" 1 args - <key> - Print the value for key.\n"
" 2 args - <key> <value> - Write the value to the map.",
true);
GAME_CMDS.handle(
"save_map",
cmd_save_map,
"Save the map.",
"save_map [mapname]");
GAME_CMDS.handle(
"grow",
cmd_grow,
"Generate x tetrahedrons from selected object.",
"grow [x]",
"",
true);
GAME_CMDS.handle(
"stat",
cmd_stat,
"Display game stats.",
"stat");
GAME_CMDS.handle(
"load",
cmd_load,
"Load an object into the game.",
"load [name] [x] [y] [z]",
"Options:\n -m [sizex] [sizey] [sizez] [randomness]\n Load a matrix of objects centered at x,y,z with dimentions\n sizex, sizey, sizez. randomness is a float from\n 0 to 1 that describes the likelyhood of an object being loaded.\n -s [unit_size]\n Sets the unit size of the 3d grid. default: 1.0\n -g [count]\n Grow each object count new blocks. `-g r` selects a\n random count from 0 to 1000.",
true);
GAME_CMDS.handle(
"load_map",
cmd_load_map,
"Load a saved map from the given json file.",
"load_map [file_name.json]");
GAME_CMDS.handle(
"reseed",
cmd_reseed,
"Re-set the rng seed.",
"reseed [double]",
"Reseed sets the stored seed to the given double and runs srand.",
true);
GAME_CMDS.handle(
"info",
cmd_info,
"Print information about selected object(s).",
"info");
GAME_CMDS.handle(
"physics",
cmd_physics,
"Enable or disable physics simulation for selected object.",
"physics [enable/disable]",
"This command can be called in 3 ways:\n"
" 0 args - - Toggle physics simulation.\n"
" 1 args - enable/disable - Turn physics on/off.\n"
" 4 args - <key> <floatx> <floaty> <floatz>\n"
" - Set quantity <key> to floatn.",
true);
GAME_CMDS.handle(
"foreach",
cmd_foreach,
"Iterate over a list and execute given command.",
"foreach <group> <command> [argn...]");
GAME_CMDS.handle(
"controls",
cmd_controls,
"Enter 'help controls' for a list of controls.",
"help controls",
"Controls:\n e Open console.\n"
" w a s d space c Movement.\n"
" r Toggle PHYSICS.\n"
" x Toggle AGM. (physics must be enabled)\n"
" Esc Grab/ungrab mouse, exit console.\n"
" b Spawn a block.\n"
" i j k l h n Move selected block.\n"
" +/- Add or subtract number of points drawn.\n"
" 1 Set mouse left click mode to 'select'.\n"
" 2 Set mouse left click mode to 'remove'.\n"
" 3 Set mouse left click mode to 'build'.\n"
" 4 Set mouse left click mode to 'paint'.\n"
" t Hold t and click in paint mode to copy color.\n");
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
int glinit = 0;
char** glinit2;
glutInit(&glinit, glinit2);
glutInitWindowSize(800, 600);
glutInitDisplayMode(GLUT_RGB | GLUT_STENCIL | GLUT_DOUBLE | GLUT_DEPTH);
WIN = glutCreateWindow("Mechanizm");
glutIdleFunc(mech_idle);
glutDisplayFunc(drawScene);
glutMouseFunc(mouse);
glutMotionFunc(mouse_motion);
glutPassiveMotionFunc(mouse_motion);
glutReshapeFunc(resize);
glutCreateMenu(menu);
draw_glut_menu();
glutAttachMenu(GLUT_RIGHT_BUTTON);
glutKeyboardFunc(keyboard);
glutKeyboardUpFunc(keyboard_up);
glutSpecialFunc(special_input);
glutMainLoop();
return 0;
}
void cmd_help(vector<string>& argv) {
GAME_CMDS.better_default_help(argv);
for (int i = 0; i < argv.size(); i++) {;
menu_output.push_back(argv[i]);
}
}
void cmd_tp(vector<string>& argv) {
CAM.setX(as_double(argv[0]));
CAM.setY(as_double(argv[1]));
CAM.setZ(as_double(argv[2]));
}
void cmd_set(vector<string>& argv) {
string msg;
map<string, string>::iterator it;
if (argv.size() == 0) {
for (it = CMDS_ENV.begin(); it != CMDS_ENV.end(); it++) {
msg = it->first;
msg += ": ";
msg += it->second;
menu_output.push_back(msg);
}
}
else if (argv.size() == 1) {
it = CMDS_ENV.find(argv[0]);
if (it != CMDS_ENV.end()) {
msg = it->first;
msg += ": ";
msg += it->second;
menu_output.push_back(msg);
}
}
else if (argv.size() >= 2) {
for (int i = 2; i < argv.size(); i++) {
argv[1] += " " + argv[i];
}
CMDS_ENV[argv[0]] = argv[1];
msg = "setting ";
msg += argv[0];
msg += ": ";
msg += CMDS_ENV[argv[0]];
menu_output.push_back(msg);
if (argv[0] == "brightness") {BRTNS = as_double(argv[1]);}
if (argv[0] == "phys_max_work") {
unsigned int mw = as_uint(CMDS_ENV[argv[0]]);
for (auto gsit = GS.begin(); gsit != GS.end(); gsit++) {
if (gsit->second.phys_obj != NULL) {
gsit->second.phys_obj->maxwork = mw;
}
}
}
if (argv[0] == "phys_highlight" && argv[1] == "true") {
highlight_enabled = true;
}
else {highlight_enabled = false;}
}
// update cam in case settings are modified
CAM = Camera(CAM.getX(), CAM.getY(), CAM.getZ(), CAM.getAX(), CAM.getAY(),
0.5, as_double(CMDS_ENV["player_move_speed"]));
}
void cmd_save_map(vector<string>& argv) {
if (argv.size() > 0) {
CMDS_ENV["map_name"] = argv[0];
}
menu_output.push_back("saving map: " + CMDS_ENV["map_name"]);
save_map(CMDS_ENV["map_name"]);
}
void cmd_grow(vector<string>& argv) {
if (argv.size() != 1) {
menu_output.push_back("invalid arguments: try 'help grow'");
return;
}
int arg = as_int(argv[0]);
while (arg-- > 0) {
string gi = select_gobj;
if (GS[gi].vis_objs.size() == 0) {
cout << "cmd_grow: gobj " << gi << " has 0 visible objects\n";
arg--;
continue;
}
char buffer[100];
sprintf(buffer, "generated_object_%li", gen_obj_cnt);
gen_obj_cnt++;
string id = buffer;
Object o(id);
string robjkey;
int robji = rand() % GS[gi].vis_objs.size();
robjkey = GS[gi].vis_objs[robji];
if (GS[gi].objs[robjkey].tetra.vis_faces.size() < 1) {
cout << "cmd_grow: ERROR random object "
<< robjkey << " has no vis faces\n";
return;
}
int rvfacei = rand() % GS[gi].objs[robjkey].tetra.vis_faces.size();
int rfacei = GS[gi].objs[robjkey].tetra.vis_faces[rvfacei];
o.tetra = generate_tetra_from_side(
GS[gi].objs[robjkey].tetra, rfacei);
select_obj = robjkey;
tools::Error e = GS[gi].attach(robjkey, rfacei, o);
if (e != NULL) {
cout << "cmd_grow: error generating tetrahedron from object "
<< robjkey << " face " << rfacei << ".\nERROR: " << e << endl;
cout << "cmd_grow: re-running attach_interior_sides.\n";
// run attach_interior_faces here to fix remaining interior sides
e = NULL;
e = GS[gi].attach_interior_sides(robjkey);
if (e != NULL) {
cout << "cmd_grow: error running attach_interior_sides("
<< robjkey << ").\nERROR: " << e << endl;
}
//TODO: fix remaining visible sides left over from grow cmd.
//GS[gi].objs[robjkey].tetra.remove_vis_face(rfacei);
//GS[gi].objs[robjkey].tetra.set_faceColors(Tetrahedron().fc_blue);
//GS[gi].objs[robjkey].tetra.faceColors[rfacei][0] = 0.8;
//GS[gi].objs[robjkey].tetra.faceColors[rfacei][2] = 0.2;
//if (GS[gi].objs[robjkey].tetra.vis_faces.size() == 0) {
// GS[gi].remove_vis_obj(robjkey);
//}
//cout << "cmd_grow::" << e << "\n";
//cout << "cmd_grow: removing face " << rfacei << " from "
// << "object (blue) " << robjkey << ".\n";
//return;
}
}
}
void cmd_stat(vector<string>& argv) {
// set GAME_STATS
GAME_STATS["total_bodies"] = GS.size();
GAME_STATS["total_blocks"] = 0;
GAME_STATS["visible_blocks"] = 0;
GAME_STATS["mapped_sections"] = M().size();
for (auto git = GS.begin(); git != GS.end(); git++) {
GAME_STATS["total_blocks"] += GS[git->first].objs.size();
GAME_STATS["visible_blocks"] += GS[git->first].vis_objs.size();
}
for (auto gsit = GAME_STATS.begin(); gsit != GAME_STATS.end(); gsit++) {
string msg = gsit->first;
char buffer[100];
sprintf(buffer, ": %li", GAME_STATS[gsit->first]);
msg += buffer;
menu_output.push_back(msg);
}
return;
}
void cmd_load(vector<string>& argv) {
bool matrix = false;
unsigned long sizex, sizey, sizez;
int grow_i = -1;
GLfloat gsc = 1.0; // grid scale
GLfloat rndmns;
string msg;
Vertex v;
vector<string> nargv(0);
for (int argi = 0; argi < argv.size(); argi++) {
if (argv[argi] == "-m") {
matrix = true;
if (argi+4 >= argv.size()) {
menu_output.push_back("invalid argument sequence.");
return;
}
sizex = as_double(argv[argi+1]);
sizey = as_double(argv[argi+2]);
sizez = as_double(argv[argi+3]);
rndmns = as_double(argv[argi+4]);
argi += 4;
}
else if (argv[argi] == "-s") {
gsc = as_double(argv[argi+1]);
argi++;
}
else if (argv[argi] == "-g") {
grow_i = argi+1;
argi++;
}
else {
nargv.push_back(argv[argi]);
}
}
if (nargv.size() != 4) {
menu_output.push_back("Invalid arguments. Try `help load`.");
return;
}
string name = nargv[0];
v.x = as_double(nargv[1]);
v.y = as_double(nargv[2]);
v.z = as_double(nargv[3]);
if (!matrix) {
// if name exists load or copy from gs, otherwise generate tetrahedron
msg = "loading new tetrahedron " + name;
Object obj(name + "_obj_0");
Group g(name, obj);
Vertex c = obj.tetra.center();
g.translate(-c.x, -c.y, -c.z);
g.translate(v.x, v.y, v.z);
GS[name] = g;
select_gobj = name;
if (grow_i > 0) {
vector<string> tmp(1);
tmp[0] = argv[grow_i];
cmd_grow(tmp);
}
menu_output.push_back(msg);
}
else {
// get points to generate blocks
//unsigned long int gen_obj_cnt = 1;
for (GLfloat xi = v.x - (sizex/2.0); xi < v.x+(sizex/2.0); xi += gsc) {
for (GLfloat yi = v.y-(sizey/2.0); yi < v.y+(sizey/2.0); yi += gsc) {
for (
GLfloat zi = v.z-(sizez/2.0); zi < v.z+(sizez/2.0); zi += gsc) {
if (10000.0 * rndmns > rand() % 10001) {
char buffer[100];
sprintf(buffer, "_matrix_g_obj_%li", gen_obj_cnt);
gen_obj_cnt++;
string g_obj_name = name + buffer;
cout << "generating block " << g_obj_name;
cout << " at (" << xi << " " << yi << " " << zi << ")\n";
Object obj(g_obj_name);
Group g(g_obj_name, obj);
Vertex c = g.objs[g_obj_name].tetra.center();
g.translate(-c.x, -c.y, -c.z);
g.translate(xi, yi, zi);
GS[g_obj_name] = g;
GS[g_obj_name].objs[g_obj_name].setConstQ(
"v", {0.0, 0.0, -0.05});
if (grow_i > 0) {
vector<string> tmp(1);
if (argv[grow_i][0] != 'r') {
tmp[0] = argv[grow_i];
}
else {
int rcnt = rand() % 1000;
sprintf(buffer, "%i", rcnt);
tmp[0] = buffer;
}
select_gobj = g_obj_name;
cmd_grow(tmp);
}
}
}
}
}
}
}
void cmd_load_map(vector<string>& argv) {
GS.clear();
M().clear();
gen_obj_cnt = 0;
gen_map_cnt = 1;
string mname = CMDS_ENV["map_name"];
if (argv.size() > 0) {
mname = argv[0];
}
menu_output.push_back("loading map: " + mname);
tools::Error e = load_map(mname);
if (e != NULL) {
menu_output.push_back("load_map: Error loading map '" + mname + "':");
menu_output.push_back(e);
}
return;
}
void cmd_reseed(vector<string>& argv) {
if (argv.size() >= 1) {
CMDS_ENV["rng_seed"] = argv[0];
}
srand(as_double(CMDS_ENV["rng_seed"]));
return;
}
void cmd_info(vector<string>& argv) {
if (select_gobj == "none") {
menu_output.push_back("No object selected.");
return;
}
string physics_s = "false";
if (GS[select_gobj].phys_obj != NULL) {
if (GS[select_gobj].phys_obj->physics_b) {physics_s = "true";}
}
char buf[1000];
sprintf(buf, "selected group: %s\nselected object: %s\nobjects: %li\nvis_objs: %li\nphysics enabled: %s\nphysics events: %i\nv- CQS -v\n",
select_gobj.c_str(), select_obj.c_str(),
GS[select_gobj].objs.size(), GS[select_gobj].vis_objs.size(),
physics_s.c_str(), 0);
string msg = buf;
if (GS[select_gobj].phys_obj != NULL) {
for (auto it = GS[select_gobj].phys_obj->c_qs.begin();
it != GS[select_gobj].phys_obj->c_qs.end(); it++) {
msg += it->first + ": ";
for (int i = 0; i < it->second.size(); i++) {
sprintf(buf, "%lf ", it->second[i]);
msg += buf;
}
msg += "\n";
}
}
menu_output.push_back(msg);
return;
}
Object build_physics_object() {
Object phobj("physics_object", 1.0, gobj_physics);
phobj.setCQ("v", {0.0, 0.0, 0.0});
phobj.setCQ("av", {0.0, 0.0, 0.0});
phobj.maxwork = as_uint(CMDS_ENV["phys_max_work"]);
tools::Error n = phobj.enable_physics();
if (n != NULL) {menu_output.push_back(n);}
return phobj;
}
void cmd_physics(vector<string>& argv) {
tools::Error n = NULL;
if (select_gobj == "none") {
menu_output.push_back("No object selected.");
return;
}
Object tobj = build_physics_object();
tobj.gid = select_gobj;
tobj.group = &GS[select_gobj];
Vertex c = GS[select_gobj].center();
tobj.c_qs["ipos"] = {c.x, c.y, c.z};
if (argv.size() == 0) {
if (GS[select_gobj].phys_obj == NULL) {
argv = {"enable"};
}
else if (GS[select_gobj].phys_obj->physics_b == false) {
argv = {"enable"};
}
else {
argv = {"disable"};
}
}
if (argv.size() == 1) {
if (argv[0] == "enable") {
if (GS[select_gobj].phys_obj != NULL) {
n = GS[select_gobj].phys_obj->enable_physics();
if (n != NULL) {menu_output.push_back(n);}
else {menu_output.push_back(select_gobj + ": physics enabled");}
}
else {
MECH.add_object(tobj);
GS[select_gobj].phys_obj = &MECH.objs[MECH.size-1];
menu_output.push_back(select_gobj + ": physics enabled");
}
}
else if (GS[select_gobj].phys_obj != NULL) {
n = GS[select_gobj].phys_obj->disable_physics();
if (n != NULL) {menu_output.push_back(n);}
else {menu_output.push_back(select_gobj + ": physics disabled");}
}
return;
}
if (argv.size() == 4) {
vector<GLfloat> tv;
tv.push_back(as_double(argv[1]));
tv.push_back(as_double(argv[2]));
tv.push_back(as_double(argv[3]));
vector<string> targ = {"enable"};
if (GS[select_gobj].phys_obj == NULL) {cmd_physics(targ);}
GS[select_gobj].phys_obj->setConstQ(argv[0], tv);
menu_output.push_back("cmd_physics: setting physics quantity");
return;
}
return;
}
void cmd_foreach(vector<string>& argv) {
if (argv.size() < 2) {
menu_output.push_back("foreach: Invalid argument sequence.");
return;
}
string cmd = argv[1];
vector<string> nargv = {};
for (int i = 2; i < argv.size(); i++) {nargv.push_back(argv[i]);}
string osgobj = select_gobj;
if (argv[0] == "group") {
for (auto it = GS.begin(); it != GS.end(); it++) {
vector<string> cargv(nargv.size());
for (int i = 0; i < nargv.size(); i++) {
cargv[i] = nargv[i];//eval_rand(nargv[i]);
}
select_gobj = it->second.id;
GAME_CMDS.run(cmd, cargv);
if (!GAME_CMDS.resolved()) {
menu_output.push_back("unknown command: " + cmd);
select_gobj = osgobj;
return;
}
}
}
select_gobj = osgobj;
return;
}
void cmd_controls(vector<string>& argv) {return;}
// a pointer to this function placed in the test_object_1 object. It sets the
// current position as a function of time.
tools::Error random_motion(double t, Object &self) {
GLfloat x = -0.007;
if (rand() % 2) {
x = 0.007;
}
GLfloat y = -0.007;
if (rand() % 2) {
y = 0.007;
}
GLfloat z = -0.007;
if (rand() % 2) {
z = 0.007;
}
self.translate(
x,
y,
z);
return NULL;
}
// gobj_physics MECH.obj motion function
//
// does work_n actions either running a physics event or checking for
// intersection. instances that do not check for collisions will
// work through physics events.
tools::Error gobj_physics(double t, Object &self) {
Group *g = (Group*)self.group;
bool br = false;
// do collision checks first and break when max work is reached
// collision checks will use a ->vector from the location of the tetrahedron
// points to their location one frame ahead for accuate collision
// detection.
//
// on group collision time of intersection is unknown. assume half a
// frame is when the collision takes place.
// move to 1/128 seconds ahead
// calculate the new velocities
// move to 1/128 seconds ahead
// return rather than breaking and moving a second time.
//
if (self.physics_b == true) {
if (self.work == self.maxwork && g->voit != g->vis_objs.begin()) {
g->voit = g->vis_objs.begin();
}
// skip if v and av are 0.0
Vertex sv = to_vert(self.getCQ("v"));
Vertex sav = to_vert(self.getCQ("av"));
if (sv.equals(Vertex(0, 0, 0)) && sav.equals(Vertex(0, 0, 0))) {
return NULL;
}
// check for intersection with second group
// loop through visible objects and check for second group
// in nearby sections
if (self.work != 0) {
for (g->voit; g->voit != g->vis_objs.end(); g->voit++) {
// get nearest sections
string v_obj_id = *g->voit;
// get visible tetrahedron final position
Tetrahedron vt = GS[self.gid].objs[v_obj_id].tetra;
Tetrahedron vtfin = vt;
vtfin.translate((GLfloat)(1.0/64.0) * sv.x,
(GLfloat)(1.0/64.0) * sv.y,
(GLfloat)(1.0/64.0) * sv.z);
vtfin.rotate_abt_vert(g->center(),
(GLfloat)(1.0/64.0) * sav.x,
(GLfloat)(1.0/64.0) * sav.y,
(GLfloat)(1.0/64.0) * sav.z);
// get nearby sections
string v_obj_skey = om_get_section_key(vtfin.center());
vector<string> sections;
om_get_nearby_sections(v_obj_skey, sections);
//GLfloat d[4] = {1000.0, 1000.0, 1000.0};
vector<string>::iterator secit = sections.begin();
map<string, vector<string>> n_objs;
for (secit; secit != sections.end(); secit++) {
vector<oinfo>::iterator n_it = M()[*secit].begin();
for (n_it; n_it != M()[*secit].end(); n_it++) {
if (n_it->gid != self.gid) {
Tetrahedron nt = GS[n_it->gid].objs[n_it->oid].tetra;
// get distance from initial position
GLfloat dis = vt.center().distance( nt.center());
// check against travel distance + approx object radius
if (dis < vt.center().distance( vtfin.center()) + 1.1) {
// use lines between vt and vtfin points to
// check for intersection with n_it->oid
Vertex tripnts[3];
Vertex lines[4][2];
for (int pi = 0; pi < 4; pi++) {
lines[pi][0] = vt.points[pi];
lines[pi][1] = vtfin.points[pi];
}
// loop over lines
for (int li = 0; li < 4; li++) {
for (int vfi = 0; vfi < nt.vis_faces.size();
vfi++) {
// get triptnts of second object
int fi = nt.vis_faces[vfi];
for (int tripti = 0; tripti < 3; tripti++) {
tripnts[tripti].x = *nt.face[fi].pnts[tripti][0];
tripnts[tripti].y = *nt.face[fi].pnts[tripti][1];
tripnts[tripti].z = *nt.face[fi].pnts[tripti][2];
}
// check for intersection
if (tools::line_intersects_triangle(lines[li],
tripnts,
NULL)) {
// move ahead half a frame
Object *obj = GS[self.gid].phys_obj;
if (GS[n_it->gid].phys_obj != NULL &&
GS[n_it->gid].phys_obj->physics_b) {
Object *vphobj = GS[self.gid].phys_obj;
Object *nphobj = GS[n_it->gid].phys_obj;
vector<GLfloat> tq(vphobj->getCQ("v"));
vphobj->setCQ("v", nphobj->getCQ("v"));
nphobj->setCQ("v", tq);
}
else {
Object *obj = GS[self.gid].phys_obj;
Vertex vc = GS[self.gid].center();
Vertex nc = GS[n_it->gid].center();
Vertex gn = nc - vc;
gn.normalize();
Vertex v = to_vert(obj->getCQ("v"));
v *= Vertex(-cos(gn.x - M_PI/2.0),
-sin(gn.y - M_PI/2.0),
-cos(gn.z - M_PI/2.0));
obj->setCQ("v", {v.x, v.y, v.z});
return NULL;
}
//move ahead second half of frame
}
}
}
n_objs[n_it->gid].push_back(n_it->oid);
}
}
}
}
if (highlight_enabled == true ) {
//cout << "n_obj size: " << n_objs.size() << endl;
for (auto it = n_objs.begin(); it != n_objs.end(); it++) {
for (int i = 0; i < it->second.size(); i++) {
GS[it->first].objs[it->second[i]].tetra.highlight_frames = 64;
}
}
}
self.work--;
if (self.work == 0) {
self.work = self.maxwork;
br = true;
break;
}
}
if (br == false) {
// g->voit is at end of list, reset it
g->voit = g->vis_objs.begin();
}
} // end of work scope
// collision detector hasn't returned so move group
if (self.getConstQ("v").size() == 3) {
//move group
vector<GLfloat>::iterator vit = self.c_qs["v"].begin();
GLfloat incx = (GLfloat)(1.0/64.0) * (*vit); vit++;
GLfloat incy = (GLfloat)(1.0/64.0) * (*vit); vit++;
GLfloat incz = (GLfloat)(1.0/64.0) * (*vit);
// 1/64th of a second x velocity = distance
g->translate(incx, incy, incz);
}
if (self.getConstQ("av").size() == 3) {
vector<GLfloat>::iterator avit = self.c_qs["av"].begin();
GLfloat incax = (GLfloat)(1.0/64.0) * (*avit); avit++;
GLfloat incay = (GLfloat)(1.0/64.0) * (*avit); avit++;
GLfloat incaz = (GLfloat)(1.0/64.0) * (*avit);
g->rotate_abt_center(incax, incay, incaz);
}
}
return NULL;
}
tools::Error player_gravity(double t, Object &self) {
// check for collision with object below cam, if collision is detected
// move player above point of intersection if detected
// loop through all visible sides, check if line intersects triangles
//if ((count + 1) % 2 == 0) {
//
GLfloat falling = self.getConstQ("AGM_FALLING")[0];
if (falling < 0.5) {
return NULL;
}
GLfloat incx, incz = 0.0;
vector<GLfloat> incr = {0.0, 0.0, 0.0};
// check if player object has velocity and calculate distance to travel
if (self.getConstQ("v").size() == 3) {
incx = (GLfloat)(1.0/64.0) * self.getConstQ("v")[0];
incz = (GLfloat)(1.0/64.0) * self.getConstQ("v")[2];
}
if (self.getConstQ("av").size() == 3) {
incr = self.getConstQ("av");
incr[0] *= (GLfloat)(1.0/64.0);
incr[1] *= (GLfloat)(1.0/64.0);
incr[2] *= (GLfloat)(1.0/64.0);
}
// intersecting group and object id's
string ig;
string io;
Vertex cc;
cc.x = CAM.getX();
cc.y = CAM.getY();
cc.z = CAM.getZ();
string cc_om_key = om_get_section_key(cc);
vector<string> sections;
om_get_nearby_sections(cc_om_key, sections);
for (int si = 0; si < sections.size(); si++) {
auto mit = M().find(sections[si]);
if (mit == M().end()) {continue;}
for (int omvi = 0; omvi < mit->second.size(); omvi++) {
ig = mit->second[omvi].gid;
io = mit->second[omvi].oid;
Vertex line[2];
line[0] = self.tetra.center();
line[0].y += 0.3;
line[1].x = self.tetra.center().x;
line[1].z = self.tetra.center().z;
line[1].y = self.tetra.center().y - 1.0;
// check each visable face
Tetrahedron tetra = GS[ig].objs[io].tetra;
for (int vfi = 0; vfi < tetra.vis_faces.size();
vfi++) {
int fi = tetra.vis_faces[vfi];
Vertex tripnts[3];
// get cam position above center of intersecting face.
Vertex c;
tetra.face[fi].center(c);
GLfloat new_cam_y = c.y + 0.85;
for (int tripti = 0; tripti < 3; tripti++) {
tripnts[tripti].x =
*tetra.face[fi].pnts[tripti][0];
tripnts[tripti].y =
*tetra.face[fi].pnts[tripti][1];
tripnts[tripti].z =
*tetra.face[fi].pnts[tripti][2];
}
if (tools::line_intersects_triangle(
line,
tripnts,
NULL)) {
self.translate(-self.tetra.center().x,
-self.tetra.center().y,
-self.tetra.center().z);
GLfloat climb_mv = as_double(CMDS_ENV["agm_climb_spd"]);
if (CAM.getY() + climb_mv < new_cam_y) {
self.translate(
CAM.getX() + incx, CAM.getY() + climb_mv,
CAM.getZ() + incz);
CAM.setY((CAM.getY() + climb_mv));
}
else {
self.translate(
CAM.getX() + incx, new_cam_y, CAM.getZ() + incz);
CAM.setY(new_cam_y);
}
Vertex gc = GS[ig].center();
self.rotate_abt_vert(gc, incr[0], incr[1], incr[2]);
CAM.setAX(CAM.getAX() - incr[1]);
//CAM.setAY(CAM.getAY() - incr[0]);
//CAM.setAZ(CAM.getAZ() + incr[2]);
CAM.setX(self.tetra.center().x);
CAM.setZ(self.tetra.center().z);
self.setConstQ("AGM_FSTARTT", MECH.current_time);
// if intersecting group has velocity copy x and z to this v
if (GS[ig].phys_obj == NULL) {
self.setCQ("v", {0.0, 0.0, 0.0});
self.setCQ("av", {0.0, 0.0, 0.0});
}
else if(GS[ig].phys_obj->physics_b == true) {
self.setCQ("v", GS[ig].phys_obj->getCQ("v"));
self.setCQ("av", GS[ig].phys_obj->getCQ("av"));
}
else {
self.setCQ("v", {0.0, 0.0, 0.0});
self.setCQ("av", {0.0, 0.0, 0.0});
}
return NULL;
}
}
}
}
// in keyboard change velocity of player object when animation is on
GLfloat gravity = self.getConstQ("AGM_GRAVITY")[0];
GLfloat fstartt = self.getConstQ("AGM_FSTARTT")[0];
GLfloat fstarty = self.getConstQ("AGM_FSTARTY")[0];
if (self.last_t < fstartt) {
self.last_t = fstartt;
}
// use AGM_FSTARTT to calculate fall distance
GLfloat tt = t - fstartt;
GLfloat tlast_t = self.last_t - fstartt;
GLfloat movement = 0.5*gravity*tt*tt -
0.5*gravity*tlast_t*tlast_t;
GLfloat camy = CAM.getY() - movement;
CAM.setX(CAM.getX() + incx);
CAM.setY(camy);
CAM.setZ(CAM.getZ() + incz);
self.translate(incx, -movement, incz);
self.last_t = t;
return NULL;
}
void help(string p_name) {
cout << "\n";
cout << fold(0, 80, p_name +
" is a frontend for the mechanizm object.");
cout << "\n\nUsage:\n\n " << p_name;
cout << " [-option]\n\n";
cout << "Options:\n\n";
cout << " r - Run the simulation in real time.\n";
cout << " q - Quiet mode. Nothing will be printed to stdout.";
cout << "\n f <file_name> - Load the objects from the given file name.\n";
cout << " h - Print this information.\n";
cout << " s <integer> - Set the random number generator seed.\n\n";
}
void drawVisibleTriangles(string gsid, string obid, Tetrahedron& tetra) {
int drawn = 0;
if (draw_x_vertices > 0) {
for (int pi = 0; pi < draw_x_vertices; pi++) {
Sphere new_sphere(tetra.points[pi].x,
tetra.points[pi].y,
tetra.points[pi].z,
0.0369, 0.4, 0.8, 0.6);
draw_sphere(new_sphere);
}
}
else if (draw_x_vertices < 0) {
Sphere new_sphere(MECH.objs[PO].tetra.center().x,
MECH.objs[PO].tetra.center().y - 0.8,
MECH.objs[PO].tetra.center().z,
0.1369, 0.4, 0.8, 0.6);
draw_sphere(new_sphere);
}
glBegin(GL_TRIANGLES);
for (int vfi = 0; vfi < tetra.vis_faces.size(); vfi++) {
int fi = tetra.vis_faces[vfi];
if (tetra.highlight_frames == 0) {
glColor3f(brtns(BRTNS, tetra.faceColors[fi][0]),
brtns(BRTNS, tetra.faceColors[fi][1]),
brtns(BRTNS, tetra.faceColors[fi][2]));
}
else {
//glColor3f(brtns(BRTNS, tetra.fc[tetra.highlight_color][fi][0]),
// brtns(BRTNS, tetra.fc[tetra.highlight_color][fi][1]),
// brtns(BRTNS, tetra.fc[tetra.highlight_color][fi][2]));
glColor3f(brtns(BRTNS, tetra.fc_green[fi][0]),
brtns(BRTNS, tetra.fc_green[fi][1]),
brtns(BRTNS, tetra.fc_green[fi][2]));
tetra.highlight_frames--;
}
//glColor3fv(tetra.faceColors[fi]);
for (int pi = 0; pi < 3; pi++) {
Vertex tmpv;
tmpv.x = *tetra.face[fi].pnts[pi][0];
tmpv.y = *tetra.face[fi].pnts[pi][1];
tmpv.z = *tetra.face[fi].pnts[pi][2];
glVertex3f(
tmpv.x,
tmpv.y,
tmpv.z);
drawn++;
}
if (gsid == select_gobj && obid == select_obj) {
glEnd();
glBegin(GL_LINE_LOOP);
glColor3f(0.0, 0.0, 0.0);
for (int pi = 0; pi < 3; pi++) {
Vertex tmpv;
tmpv.x = *tetra.face[fi].pnts[pi][0];
tmpv.y = *tetra.face[fi].pnts[pi][1];
tmpv.z = *tetra.face[fi].pnts[pi][2];
glVertex3f(
tmpv.x,
tmpv.y,
tmpv.z);
}
glEnd();
glBegin(GL_TRIANGLES);
}
}
glEnd();
}
// add bool haxis - true for x axis false for z
void draw_circle(float cx, float cy, float r, int num_segments, bool haxis) {
glBegin(GL_LINE_LOOP);
for (int ii = 0; ii < num_segments; ii++) {
//get the current angle
float theta = 2.0f * 3.1415926f * float(ii) / float(num_segments);
float x = r * cosf(theta);//calculate the x component
float y = r * sinf(theta);//calculate the y component
if (haxis = true) {
glVertex3f(x + cx, y + cy, 0.0);//output vertex
}
else {
glVertex3f(0.0, y + cy, x + cx);
}
}
glEnd();
}
void draw_cam_spheres() {
Error e = NULL;
if (menu_depth != 0) {return;}
// if left click is pressed calculate the distance
if (SD_DONE == false) {
GLfloat n_d = as_double(CMDS_ENV["n_click_distance"]);
GLfloat n_s = as_double(CMDS_ENV["n_click_speed"]);
GLfloat n_m_d = as_double(CMDS_ENV["n_click_max_distance"]);
GLfloat nsx, nsy, nsz;
if (SD > n_m_d) {
SD = n_d;
if (mouse_left_state == 1) SD_DONE = true;
}
else {
SD += n_s;
}
// get the new position in front of the camera
CAM.pos_in_los(SD, nsx, nsy, nsz);
// set the sphere position
SPHRS[0].center[0] = nsx;
SPHRS[0].center[1] = nsy;
SPHRS[0].center[2] = nsz;
int i = -1;
int sidx, sidy, sidz;
// check for collision with nearby objects
Vertex cc;
cc.x = nsx;
cc.y = nsy;
cc.z = nsz;
string cc_om_key = om_get_section_key(cc);
vector<string> sections;
om_get_nearby_sections(cc_om_key, sections);
for (int si = 0; si < sections.size(); si++) {
auto mit = M().find(sections[si]);
if (mit == M().end()) {continue;}
for (int omvi = 0; omvi < mit->second.size(); omvi++) {
string gi = mit->second[omvi].gid;
string j = mit->second[omvi].oid;
Tetrahedron tetra = GS[gi].objs[j].tetra;
if (GS[gi].objs[j].shape == "tetrahedron") {
// get line segment points
Vertex line[2];
line[0].x = nsx;
line[0].y = nsy;
line[0].z = nsz;
GLfloat tx, ty, tz;
CAM.pos_in_los(SD+n_s, tx, ty, tz);
line[1].x = tx;
line[1].y = ty;
line[1].z = tz;
glBegin(GL_LINE_LOOP);
glVertex3f(
line[0].x,
line[0].y,
line[0].z);
glVertex3f(
line[1].x,
line[1].y,
line[1].z);
glEnd();
// get triangle points of each visible face
for (int vfi = 0; vfi < tetra.vis_faces.size();
vfi++) {
Vertex tripnts[3];
int fi = tetra.vis_faces[vfi];
for (int tripti = 0; tripti < 3; tripti++) {
tripnts[tripti].x = *tetra.face[fi].pnts[tripti][0];
tripnts[tripti].y = *tetra.face[fi].pnts[tripti][1];
tripnts[tripti].z = *tetra.face[fi].pnts[tripti][2];
}
if (tools::line_intersects_triangle(
line,
tripnts,
NULL)) {
// group: gi object: j
if (selector_function == "select") {
select_gobj = gi;
select_obj = j;
string msg("selected group: " + gi + "\nobject: " + j);
char buffer[100];
sprintf(buffer,
", face %i, vis_faces: %li",
fi,
tetra.vis_faces.size());
msg += buffer;
menu_output.push_back(msg);
timed_menu_display = 150;
draw_menu_lines = 2;
reset_sphere_distance();
return;
}
else if (selector_function == "remove") {
GS[gi].detach(j);
SD = as_double(CMDS_ENV["n_click_distance"]);
SD_DONE = true;
menu_output.push_back(
"group: " + gi + ": removed object " + j);
timed_menu_display = 150;
draw_menu_lines = 1;
if (GS[gi].objs.size() == 0) {
auto it = GS.find(gi);
GS.erase(it);
}
return;
}
else if (selector_function == "build") {
select_gobj = gi;
char buffer[100];
sprintf(buffer, "generated_object_%li", gen_obj_cnt++);
select_obj = buffer;
Object o(buffer);
o.tetra = generate_tetra_from_side(tetra, fi);
vector<string> m(4);
if (pmatches(m,
CMDS_ENV["block_color"], "(.+) (.+) (.+)")) {
GLfloat os = (GLfloat)(rand() % 10) / 100.0;
for (int fi = 0; fi < 4; fi++) {
o.tetra.faceColors[fi][0] = as_double(m[1]) + os;
o.tetra.faceColors[fi][1] = as_double(m[2]) + os;
o.tetra.faceColors[fi][2] = as_double(m[3]) + os;
}
}
else {
cout << "build: block color does not match\n";
}
e = GS[gi].attach(j, fi, o);
if (e != NULL) {
cout << "draw_cam_spheres::" << e << "\n";
cout << "draw_cam_spheres: running "
<< "attach_interior_sides(" << j << ").\n";
e = NULL;
e = GS[gi].attach_interior_sides(j);
if (e != NULL) {
cout << "draw_cam_spheres::" << e << "\n";
}
}
SD = as_double(CMDS_ENV["n_click_distance"]);
SD_DONE = true;
return;
}
if (selector_function == "paint") {
select_gobj = gi;
select_obj = j;
vector<string> m(4);
if (pmatches(m,
CMDS_ENV["block_color"], "(.+) (.+) (.+)")) {
GLfloat os = (GLfloat)(rand() % 10) / 100.0;
if (CAM._keyboard['t'] == false) {
for (int i = 0; i < 4; i++) {
GS[gi].objs[j].tetra.faceColors[i][0] =
as_double(m[1]) + os;
GS[gi].objs[j].tetra.faceColors[i][1] =
as_double(m[2]) + os;
GS[gi].objs[j].tetra.faceColors[i][2] =
as_double(m[3]) + os;
}
} else {
char buf[100];
sprintf(buf, "%lf %lf %lf",
GS[gi].objs[j].tetra.faceColors[0][0],
GS[gi].objs[j].tetra.faceColors[0][1],
GS[gi].objs[j].tetra.faceColors[0][2]
);
CMDS_ENV["block_color"] = string(buf);
menu_output.push_back(
"copied color " + string(buf));
timed_menu_display = 150;
draw_menu_lines = 1;
}
}
SD = as_double(CMDS_ENV["n_click_distance"]);
SD_DONE = true;
return;
}
}
}
} // end of tetrahedron loop
} // end of obect loop
} // end of map section loop
}
else {
CAM.pos_in_los(SD,
SPHRS[0].center[0], SPHRS[0].center[1], SPHRS[0].center[2]);
}
// draw the sphere
glColor3f(SPHRS[0].color[0], SPHRS[0].color[1], SPHRS[0].color[2]);
glPushMatrix();
glTranslatef(SPHRS[0].center[0], SPHRS[0].center[1], SPHRS[0].center[2]);
glutWireSphere(SPHRS[0].r, 8, 6);
glPopMatrix();
}
void draw_spheres() {
for (int i = 1; i < SPHRS.size(); i++) {
draw_sphere(SPHRS[i]);
}
}
void draw_sphere(Sphere& s) {
glColor3f(s.color[0], s.color[1], s.color[2]);
glPushMatrix();
glTranslatef(s.center[0], s.center[1], s.center[2]);
//glutWireSphere(s.r, 36, 36);
glutWireSphere(s.r, 4, 4);
glPopMatrix();
}
void reset_sphere_distance() {
SD = as_double(CMDS_ENV["n_click_distance"]);
if (mouse_left_state == 1) SD_DONE = true;
}
void drawFilledTStrip() {
glBegin(GL_TRIANGLE_STRIP);
glColor3f(1, 0, 0); glVertex3f(0, 2, 0);
glColor3f(0, 1, 0); glVertex3f(-1, 0, 1);
glColor3f(0, 0, 1); glVertex3f(1, 0, 1);
glEnd();
}
void mouse(int button, int state, int x, int y) {
// left button down
if (button == 0 && state == 0) {
mouse_left_state = 0;
if (SD_DONE) {
SD_DONE = false;
}
else {
SD = as_double(CMDS_ENV["n_click_distance"]);
}
}
else if (button == 0 && state == 1) {
mouse_left_state = 1;
}
if (state == 0) {
int scroll_speed = as_int(CMDS_ENV["igcmd_scroll_speed"]);
if (button == 4) {
if (IGCMD_MOUT_SCROLL - scroll_speed < 0) {
IGCMD_MOUT_SCROLL = 0;
}
else {
IGCMD_MOUT_SCROLL = IGCMD_MOUT_SCROLL - scroll_speed;
}
}
if (button == 3) {
if (IGCMD_MOUT_SCROLL + scroll_speed >=
as_int(CMDS_ENV["igcmd_mout_max_size"])) {
IGCMD_MOUT_SCROLL = 0;
}
else {
IGCMD_MOUT_SCROLL += scroll_speed;
}
}
}
}
void mouse_motion(int x, int y) {
if (MOUSE_GRAB && !DRAW_GLUT_MENU) {
CAM.rotation(x, y);
}
}
void draw_bitmap_string(
float x, float y, float z, void *font, string& str) {
glColor3f(0.1, 0.99, 0.69);
glRasterPos3f(x, y, z);
for (int i = 0; i < str.size(); ++i) {
glutBitmapCharacter(font, str[i]);
}
}
void draw_menu_output(float x, float y, float z, void *font) {
int max_lines = as_int(CMDS_ENV["igcmd_mout_max_size"]);
newlines_to_indices(menu_output);
while (menu_output.size() > max_lines) {
menu_output.erase(menu_output.begin());
}
int dmli = menu_output.size() - draw_menu_lines;
while (dmli < 0) { dmli++; }
for (int i =
menu_output.size() - 1 - IGCMD_MOUT_SCROLL;
i >= dmli - IGCMD_MOUT_SCROLL && i > 0; i--) {
y += 0.0369;
glColor3f(0.1, 0.69, 0.99);
glRasterPos3f(x, y, z);
for (int j = 0; j < menu_output[i].size(); ++j) {
glutBitmapCharacter(font, menu_output[i][j]);
}
}
}
void drawScene(void) {
if (MOUSE_GRAB && !DRAW_GLUT_MENU) {
CAM.last_mouse_pos_x = 75;
CAM.last_mouse_pos_y = 75;
glutWarpPointer(75, 75);
}
glClearColor(0.0, 0.0, 0.025, 0.0); // background color
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
//// set up camera
glLoadIdentity();
CAM.translation();
glRotatef(180 * CAM.getAY() / 3.141592653, 1.0, 0.0, 0.0);
glRotatef(180 * CAM.getAX() / 3.141592653, 0.0, 1.0, 0.0);
glTranslated(-CAM.getX(), -CAM.getY(), -CAM.getZ());
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glBegin(GL_TRIANGLE_STRIP);
glColor3f(1, 0, 0); glVertex3f(0, 0, 0);
glColor3f(0, 1, 0); glVertex3f(-1, 0, 1);
glColor3f(0, 0, 1); glVertex3f(1, 0, 1);
glEnd();
draw_circle(0.0, 1.0, 3.0, 36, false);
draw_spheres();
draw_cam_spheres();
if (DRAW_GLUT_MENU) {
draw_glut_menu();
DRAW_GLUT_MENU = false;
}
glEnable(GL_STENCIL_TEST);
glClear(GL_STENCIL_BUFFER_BIT);
glStencilMask(1);
glStencilFunc(GL_ALWAYS, 0, 1);
glStencilOp(GL_INVERT, GL_INVERT, GL_INVERT);
glColor3f(1.0, 1.0, 0.0);
// draw visible triangles in group map
for (auto glit = GS.begin(); glit != GS.end(); glit++) {
string gid = glit->first;
for (int voit = 0; voit < GS[gid].vis_objs.size(); voit++) {
string oid = GS[gid].vis_objs[voit];
drawVisibleTriangles(gid, oid, GS[gid].objs[oid].tetra);
}
}
if (menu_depth != 0 || timed_menu_display-- > 0) {
// write character bitmaps
draw_bitmap_string(
// these calculate the location in front of the face
CAM.getX() + (cos(CAM.getAX() - 2*(M_PI/3)) * cos(-CAM.getAY()))*1.3,
//CAM.getY() + sin(-CAM.getAY())*1.3 - 0.5,
CAM.getY() - 0.5,
CAM.getZ() + (sin(CAM.getAX() - 2*(M_PI/3)) * cos(-CAM.getAY()))*1.3,
GLUT_BITMAP_9_BY_15,
menu_input);
// draw the output next
draw_menu_output(
// these calculate the location in front of the face
CAM.getX() + (cos(CAM.getAX() - 2*(M_PI/3)) * cos(-CAM.getAY()))*1.3,
CAM.getY() - 0.5,
CAM.getZ() + (sin(CAM.getAX() - 2*(M_PI/3)) * cos(-CAM.getAY()))*1.3,
GLUT_BITMAP_9_BY_15);
}
glPopMatrix();
glDisable(GL_STENCIL_TEST);
glutSwapBuffers();
}
void
setMatrix(int w, int h)
{
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// set the perspective
// (angle of sight, width/height ratio, clip near, depth)
gluPerspective(60, (GLfloat)w / (GLfloat)h, 0.1, 500.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void generate_map(void) {
char buffer[100];
sprintf(buffer, "initmapid%li", gen_map_cnt++);
string x, y, z;
x = as_string(CAM.getX());
y = as_string(CAM.getY());
z = as_string(CAM.getZ());
char size_y[100];
sprintf(size_y, "%lf",
(GLfloat)(as_double(CMDS_ENV["mapgen_size"]) / 6.0));
vector<string> targv = {buffer, x, y, z,
"-g", CMDS_ENV["mapgen_g_opt"], "-s", "10.0",
"-m", CMDS_ENV["mapgen_size"],
string(size_y),
CMDS_ENV["mapgen_size"],
CMDS_ENV["mapgen_rndmns"]};
cmd_load(targv);
}
void animation(void) {
tools::Error e = NULL;
// 1/64th of a second
e = MECH.run(0.015625, 0, 0.015625);
if (e != NULL) {
cout << "mechanizm_game::animation::" << e << endl;
return;
}
//cout << "count: " << count << " t: " << MECH.current_time << "\n";
if (count == 60) {
e = MECH.run(0.046875, 0, 0.046875);
//cout << "last t: " << MECH.current_time << "\n";
}
if (e != NULL) {
cout << e;
return;
}
// move the player object MECH.objs[PO] to cam position
MECH.objs[PO].translate(-MECH.objs[PO].tetra.center().x, -MECH.objs[PO].tetra.center().y, -MECH.objs[PO].tetra.center().z);
MECH.objs[PO].translate(CAM.getX(), CAM.getY(), CAM.getZ());
if (MECH.objs[PO].getConstQ("AGM_FALLING")[PO] < 0.5) {
MECH.objs[PO].setConstQ("AGM_FSTARTY", CAM.getY());
}
}
void mech_idle(void) {
if (MAP_GEN) {
MAP_GEN = false;
generate_map();
}
if (PHYSICS) {
animation();
}
glutPostRedisplay();
count++;
if (count > 60) {
count = 0;
}
}
void draw_glut_menu() {
while (glutGet(GLUT_MENU_NUM_ITEMS) > 0) {
glutRemoveMenuItem(1);
}
glutAddMenuEntry("Generate Map", 0);
glutAddMenuEntry("Physics", 1);
glutAddMenuEntry("Mouse", 2);
}
// mouse right click menu
void menu(int choice) {
switch (choice) {
case 0: // Map Generation
if (MAP_GEN) {
MAP_GEN = false;
}
else {
MAP_GEN = true;
}
break;
case 1: // Physics
count = 0;
if (PHYSICS) {
PHYSICS = false;
menu_output.push_back("PHYSICS Disabled");
timed_menu_display = 60;
draw_menu_lines = 1;
}
else {
PHYSICS = true;
menu_output.push_back("PHYSICS Enabled");
timed_menu_display = 60;
draw_menu_lines = 1;
}
break;
case 2: // Grab Mouse
if (MOUSE_GRAB) {
MOUSE_GRAB = false;
}
else {
MOUSE_GRAB = true;
CAM.last_mouse_pos_x = 75;
CAM.last_mouse_pos_y = 75;
glutWarpPointer(75, 75);
}
}
DRAW_GLUT_MENU = true;
glutPostRedisplay();
}
/* ARGSUSED1 */
void
keyboard(unsigned char c, int x, int y)
{
string prefix = "-> ";
for (int i = 0; i < menu_depth; ++i) {
prefix += " ";
}
if (menu_depth != 0) { // go into menu mode
if (menu_depth == 37) { // menu 37 is command line input
if (c != 13 && c != 8 && c != 27) { // 13 is Enter
menu_input += c;
}
else if (c == 8) { // backspace
if (menu_input.size() > 3) {
menu_input.resize(menu_input.size()-1);
}
}
else if (c == 27) { // Esc
menu_output.push_back("exiting menu");
menu_depth = 0;
timed_menu_display = 0;
draw_menu_lines = 20;
CAM.unlockAY();
return;
}
else {
menu_history.push_back(menu_input);
mhinc = menu_history.size();
menu_input[0] = ' ';
menu_input[1] = ' ';
// get the command and arguments from the menu_input
// space characters can be escaped with forwardslash
string cmd;
vector<string> cmd_argv;
string word;
menu_input += " ";
for (int z = 0; z < menu_input.size(); z++) {
if (menu_input[z] == '\\') {
word += ' ';
z++;
continue;
}
if (menu_input[z] == ' ') {
if (word.size() > 0) {
if (cmd.size() > 0) {
cmd_argv.push_back(word);
}
else {
cmd = word;
}
word.clear();
}
continue;
}
word += menu_input[z];
}
menu_input[0] = '\\';
menu_input[1] = '>';
menu_output.push_back(menu_input);
menu_input = "^> ";
string msg = "CMDS: Unknown command: `";
GAME_CMDS.run(cmd, cmd_argv);
if (cmd != "help" && cmd != "" && !GAME_CMDS.resolved()) {
msg += cmd;
msg += "`";
menu_output.push_back(msg);
}
}
return;
}
return;
}
// gameplay level controls
char m0_buffer[100];
if (c == 'e' || c == '`') {
menu_input = "^> ";
menu_depth = 37;
draw_menu_lines = 25;
CAM.lockAY(0);
mhinc = menu_history.size();
return;
}
if (c == 'b') {
string id ;
char n[100];
sprintf(n, "spawned_g_object_%li", GS.size());
id = n;
Object tmp(id);
Group spawn_group(id, tmp);
cout << prefix;
cout << "spawning group object: " << id << "\n";
string msg = prefix;
msg += "spawning group object: " + id + "\n";
menu_output.push_back(msg);
draw_menu_lines = 2;
timed_menu_display = 60;
select_gobj = id;
GLfloat nx, ny, nz;
CAM.pos_in_los(SD, nx, ny, nz);
spawn_group.translate(nx, ny, nz);
GS[spawn_group.id] = spawn_group;
return;
}
if (c == 'r' || c == 'R') {
if (PHYSICS) {
PHYSICS = false;
menu_output.push_back("Physics Disabled");
timed_menu_display = 60;
draw_menu_lines = 1;
}
else {
PHYSICS = true;
menu_output.push_back("Physics Enabled");
timed_menu_display = 60;
draw_menu_lines = 1;
}
}
if (c == 'x' || c == 'X') { // enable/disable artificial gravity module
GLfloat f = MECH.objs[PO].getConstQ("AGM_FALLING")[0];
if (f < 0.5) {
if (!PHYSICS) {
menu_output.push_back("Error: Enable Physics");
}
else {
MECH.objs[PO].setConstQ("AGM_FALLING", 1.0);
MECH.objs[PO].setConstQ("AGM_FSTARTT", MECH.current_time);
CAM.agm_enabled = true;
menu_output.push_back("AGM Enabled");
}
timed_menu_display = 60;
draw_menu_lines = 1;
}
else {
MECH.objs[PO].setConstQ("AGM_FALLING", 0.0);
MECH.objs[PO].setConstQ("v", {0.0, 0.0, 0.0});
CAM.agm_enabled = false;
menu_output.push_back("AGM Disabled");
timed_menu_display = 60;
draw_menu_lines = 1;
}
}
if (c == ' ') { // AGM jump
}
if (c == '+') { // add to draw_x_vertices
draw_x_vertices++;
sprintf(m0_buffer, "draw_x_vertices: %i", draw_x_vertices);
string msg = m0_buffer;
cout << msg << "\n";
menu_output.push_back(msg);
timed_menu_display = 60;
return;
}
if (c == '-') { // subtract from draw_x_vertices
if (draw_x_vertices > -1) draw_x_vertices--;
sprintf(m0_buffer, "draw_x_vertices: %i", draw_x_vertices);
string msg = m0_buffer;
cout << msg << "\n";
menu_output.push_back(msg);
timed_menu_display = 60;
return;
}
switch (c) {
case 27: // Esc
if (MOUSE_GRAB) {
MOUSE_GRAB = false;
}
else {
MOUSE_GRAB = true;
}
break;
case 'i':
if (select_gobj != "") {
if (GS[select_gobj].phys_obj != NULL && PHYSICS &&
GS[select_gobj].phys_obj->physics_b == true) {
vector<GLfloat> v = GS[select_gobj].phys_obj->getCQ("v");
v[0] += cos(CAM.getAX()-M_PI/2) * 0.25;
v[2] += sin(CAM.getAX()-M_PI/2) * 0.25;
GS[select_gobj].phys_obj->setCQ("v", v);
}
else {GS[select_gobj].translate(0, 0, -1.0);}
}
break;
case 'j':
if (select_gobj != "") {
if (GS[select_gobj].phys_obj != NULL && PHYSICS &&
GS[select_gobj].phys_obj->physics_b == true) {
vector<GLfloat> v = GS[select_gobj].phys_obj->getCQ("v");
v[0] -= cos(CAM.getAX()) * 0.25;
v[2] -= sin(CAM.getAX()) * 0.25;
GS[select_gobj].phys_obj->setCQ("v", v);
}
else {GS[select_gobj].translate(-1.0, 0, 0);}
}
break;
case 'k':
if (select_gobj != "none") {
if (GS[select_gobj].phys_obj != NULL && PHYSICS &&
GS[select_gobj].phys_obj->physics_b == true) {
vector<GLfloat> v = GS[select_gobj].phys_obj->getCQ("v");
v[0] -= cos(CAM.getAX()-M_PI/2) * 0.25;
v[2] -= sin(CAM.getAX()-M_PI/2) * 0.25;
GS[select_gobj].phys_obj->setCQ("v", v);
}
else {GS[select_gobj].translate(0, 0, 1.0);}
}
break;
case 'l':
if (select_gobj != "none") {
if (GS[select_gobj].phys_obj != NULL && PHYSICS &&
GS[select_gobj].phys_obj->physics_b == true) {
vector<GLfloat> v = GS[select_gobj].phys_obj->getCQ("v");
v[0] += cos(CAM.getAX()) * 0.25;
v[2] += sin(CAM.getAX()) * 0.25;
GS[select_gobj].phys_obj->setCQ("v", v);
}
else {GS[select_gobj].translate(1.0, 0, 0);}
}
break;
case 'h':
if (select_gobj != "none") {
if (GS[select_gobj].phys_obj != NULL && PHYSICS &&
GS[select_gobj].phys_obj->physics_b == true) {
vector<GLfloat> v = GS[select_gobj].phys_obj->getCQ("v");
v[1] += 0.25;
GS[select_gobj].phys_obj->setCQ("v", v);
}
else {GS[select_gobj].translate(0, 1.0, 0);}
}
break;
case 'n':
if (select_gobj != "none") {
if (GS[select_gobj].phys_obj != NULL && PHYSICS &&
GS[select_gobj].phys_obj->physics_b == true) {
vector<GLfloat> v = GS[select_gobj].phys_obj->getCQ("v");
v[1] -= 0.25;
GS[select_gobj].phys_obj->setCQ("v", v);
}
else {GS[select_gobj].translate(0, -1.0, 0);}
}
break;
case 'o':
// GS[select_gobj].scale_by(1.1, 1.1, 1.1);
break;
case 'u':
// GS[select_gobj].scale_by(0.9, 0.9, 0.9);
break;
case 'I':
if (select_gobj != "none") {
if (GS[select_gobj].phys_obj != NULL && PHYSICS &&
GS[select_gobj].phys_obj->physics_b == true) {
vector<GLfloat> av = GS[select_gobj].phys_obj->getCQ("av");
av[0] -= cos(CAM.getAX()) * 0.1;
av[2] -= sin(CAM.getAX()) * 0.1;
GS[select_gobj].phys_obj->setCQ("av", av);
}
else {
GS[select_gobj].rotate_abt_center(7.0*(M_PI/4.0), 0.0, 0.0);
}
}
break;
case 'J':
if (select_gobj != "none") {
if (GS[select_gobj].phys_obj != NULL && PHYSICS &&
GS[select_gobj].phys_obj->physics_b == true) {
vector<GLfloat> av = GS[select_gobj].phys_obj->getCQ("av");
av[1] += 0.1;
GS[select_gobj].phys_obj->setCQ("av", av);
}
else {
GS[select_gobj].rotate_abt_center(0.0, M_PI/4.0, 0.0);
}
}
break;
case 'K':
if (select_gobj != "none") {
if (GS[select_gobj].phys_obj != NULL && PHYSICS &&
GS[select_gobj].phys_obj->physics_b == true) {
vector<GLfloat> av = GS[select_gobj].phys_obj->getCQ("av");
av[0] += cos(CAM.getAX()) * 0.1;
av[2] += sin(CAM.getAX()) * 0.1;
GS[select_gobj].phys_obj->setCQ("av", av);
}
else {
GS[select_gobj].rotate_abt_center(M_PI/4.0, 0.0, 0.0);
}
}
break;
case 'L':
if (select_gobj != "none") {
if (GS[select_gobj].phys_obj != NULL && PHYSICS &&
GS[select_gobj].phys_obj->physics_b == true) {
vector<GLfloat> av = GS[select_gobj].phys_obj->getCQ("av");
av[1] -= 0.1;
GS[select_gobj].phys_obj->setCQ("av", av);
}
else {
GS[select_gobj].rotate_abt_center(0.0, 7.0*(M_PI/4.0), 0.0);
}
}
break;
case 'U':
if (select_gobj != "none") {
if (GS[select_gobj].phys_obj != NULL && PHYSICS &&
GS[select_gobj].phys_obj->physics_b == true) {
vector<GLfloat> av = GS[select_gobj].phys_obj->getCQ("av");
av[0] -= cos(CAM.getAX()-M_PI/2.0) * 0.1;
av[2] -= sin(CAM.getAX()-M_PI/2.0) * 0.1;
//av[2] += 0.05;
GS[select_gobj].phys_obj->setCQ("av", av);
}
else {
GS[select_gobj].rotate_abt_center(0.0, 0.0, M_PI/4.0);
}
}
break;
case 'O':
if (select_gobj != "none") {
if (GS[select_gobj].phys_obj != NULL && PHYSICS &&
GS[select_gobj].phys_obj->physics_b == true) {
vector<GLfloat> av = GS[select_gobj].phys_obj->getCQ("av");
av[0] += cos(CAM.getAX()-M_PI/2.0) * 0.1;
av[2] += sin(CAM.getAX()-M_PI/2.0) * 0.1;
//av[2] -= 0.05;
GS[select_gobj].phys_obj->setCQ("av", av);
}
else {
GS[select_gobj].rotate_abt_center(0.0, 0.0, 7.0*(M_PI/4.0));
}
}
break;
case '1':
selector_function = "select";
menu_output.push_back("mouse function: select");
draw_menu_lines = 1;
timed_menu_display = 50;
break;
case '2':
selector_function = "remove";
menu_output.push_back("mouse function: remove");
draw_menu_lines = 1;
timed_menu_display = 50;
break;
case '3':
selector_function = "build";
menu_output.push_back("mouse function: build");
draw_menu_lines = 1;
timed_menu_display = 50;
break;
case '4':
selector_function = "paint";
menu_output.push_back("mouse function: paint");
draw_menu_lines = 1;
timed_menu_display = 50;
break;
default: // hotkeys
if (CAM.pressKey(c)) {
glutPostRedisplay();
break;
}
// loop through config and find hotkey entries
for (auto it = CMDS_ENV.begin(); it != CMDS_ENV.end(); it++) {
string key = it->first;
if (key.size() == 8 && key.substr(0, 6) == "hotkey") {
string hkey = key.substr(7, 1);
if (hkey[0] == c) {
string cmd = CMDS_ENV[key];
if (cmd.substr(0, 4) == "grow") {
// run grow command
vector<string> cmd_argv;
cmd_argv.push_back(cmd.substr(5, 50));
GAME_CMDS.run("grow", cmd_argv);
}
}
}
}
break;
}
}
void keyboard_up(unsigned char c, int x, int y) {
CAM.setKeyboard(c, false);
glutPostRedisplay();
}
void special_input(int key, int x, int y) {
switch(key) {
case GLUT_KEY_UP:
if (mhinc > 0) {mhinc--;}
menu_input = menu_history[mhinc];
break;
case GLUT_KEY_DOWN:
if (mhinc < menu_history.size()-1) {mhinc++;}
menu_input = menu_history[mhinc];
break;
//case GLUT_KEY_LEFT:
//break;
//case GLUT_KEY_RIGHT:
//break;
}
return;
}
void
resize(int w, int h)
{
glViewport(0, 0, w, h);
setMatrix(w, h);
}
Tetrahedron generate_tetra_from_side(
Tetrahedron& source_tetra, int source_face) {
Tetrahedron new_tetra;
// reflect opposite point across selected side
// temporary vertex placed at position of opposite point
Vertex opp_v;
// get the index of the vertex that is reflected
int opp_v_i = 4;
if (source_face == 0) opp_v_i = 3;
if (source_face == 1) opp_v_i = 2;
if (source_face == 2) opp_v_i = 1;
if (source_face == 3) opp_v_i = 0;
opp_v = source_tetra.points[opp_v_i];
// use 2 lines from source face to reflect opp_v_i across plane
Vertex tnorm;
Vertex tpa = source_tetra.points[source_tetra.faceIndex[source_face][0]];
Vertex tpb = source_tetra.points[source_tetra.faceIndex[source_face][1]];
Vertex tpc = source_tetra.points[source_tetra.faceIndex[source_face][2]];
tnorm = ((tpb - tpa).cross(tpc - tpa)).normalize();
Vertex u;
u.x = (opp_v.dot(tnorm) - tnorm.dot(tpa)) * tnorm.x;
u.y = (opp_v.dot(tnorm) - tnorm.dot(tpa)) * tnorm.y;
u.z = (opp_v.dot(tnorm) - tnorm.dot(tpa)) * tnorm.z;
Vertex v = opp_v - u;
Vertex new_v = v - u;
// loop through source face indices copy points for each face
if (source_face == 0) {
new_tetra.points[0] =
source_tetra.points[source_tetra.faceIndex[source_face][1]];
new_tetra.points[1] =
source_tetra.points[source_tetra.faceIndex[source_face][0]];
new_tetra.points[2] =
source_tetra.points[source_tetra.faceIndex[source_face][2]];
new_tetra.points[3] = new_v;
}
if (source_face == 1) {
new_tetra.points[0] =
source_tetra.points[source_tetra.faceIndex[source_face][1]];
new_tetra.points[1] =
source_tetra.points[source_tetra.faceIndex[source_face][0]];
new_tetra.points[2] = new_v;
new_tetra.points[3] =
source_tetra.points[source_tetra.faceIndex[source_face][2]];
}
if (source_face == 2) {
new_tetra.points[0] = new_v;
new_tetra.points[1] =
source_tetra.points[source_tetra.faceIndex[source_face][0]];
new_tetra.points[2] =
source_tetra.points[source_tetra.faceIndex[source_face][1]];
new_tetra.points[3] =
source_tetra.points[source_tetra.faceIndex[source_face][2]];
}
if (source_face == 3) {
new_tetra.points[0] =
source_tetra.points[source_tetra.faceIndex[source_face][0]];
new_tetra.points[1] = new_v;
new_tetra.points[2] =
source_tetra.points[source_tetra.faceIndex[source_face][1]];
new_tetra.points[3] =
source_tetra.points[source_tetra.faceIndex[source_face][2]];
}
return new_tetra;
}
tools::Error save_map(string mapname) {
string jmap = "{\n";
unsigned long int i = 0;
for (auto it = GS.begin(); it != GS.end(); it++) {
jmap += "\"" + it->first + "\": " + it->second.getJSON();
if (i != GS.size()-1) {jmap += ",\n";}
i++;
}
jmap += "\n}";
return tools::write_file(mapname, jmap);
}
tools::Error load_map(string mapname) {
tools::Error e = NULL;
string msg = "load_map: ";
Json::Value jv;
e = load_json_value_from_file(jv, mapname);
if (e != NULL) {
msg += e;
return error(msg);
}
for (auto jvit = jv.begin(); jvit != jv.end(); jvit++) {
string gid = jvit.key().asString();
string ioid = jv[gid]["g_objs"].begin().key().asString();
Object obj(ioid);
Group nglb(gid, obj);
for (auto gobjit = jv[gid].begin(); gobjit != jv[gid].end(); gobjit++) {
string gobjkey = gobjit.key().asString();
if (gobjkey == "g_vis_objs") {
vector<string> vobjs;
for (int i = 0; i < jv[gid][gobjkey].size(); i++) {
vobjs.push_back(jv[gid][gobjkey][i].asString());
}
nglb.set_vis_objs(vobjs);
}
if (gobjkey == "g_objs") {
Json::Value g_objs = jv[gid][gobjkey];
for (auto g_objsit = g_objs.begin();
g_objsit != g_objs.end(); g_objsit++) {
string obj_id = g_objsit.key().asString();
vector<string> m(2);
if (pmatches(m,
obj_id, "(\\d+)$")) {
if (gen_obj_cnt <= as_int(m[1])) {
gen_obj_cnt = as_int(m[1]) + 1;
}
}
Json::Value objval = *g_objsit;
Object nobj(obj_id);
nobj.shape = objval["obj_shape"].asString();
nobj.gid = gid;
Json::Value tetraval = objval["obj_tetra"];
Json::Value pointsval = tetraval["points"];
for (int ii = 0; ii < 4; ii++) {
Json::Value vertval = pointsval[ii];
nobj.tetra.points[ii].x = vertval[0].asFloat();
nobj.tetra.points[ii].y = vertval[1].asFloat();
nobj.tetra.points[ii].z = vertval[2].asFloat();
}
vector<int> nvfaces;
Json::Value vfacesval = tetraval["vis_faces"];
for (int iii = 0; iii < vfacesval.size(); iii++) {
nvfaces.push_back(vfacesval[iii].asInt());
}
nobj.tetra.set_vis_faces(nvfaces);
Json::Value facecolorsval = tetraval["faceColors"];
for (int ii = 0; ii < 4; ii++) {
Json::Value fcval = facecolorsval[ii];
nobj.tetra.faceColors[ii][0] = fcval[0].asFloat();
nobj.tetra.faceColors[ii][1] = fcval[1].asFloat();
nobj.tetra.faceColors[ii][2] = fcval[2].asFloat();
}
// populate object map
nobj.om_tracking = true;
nobj.last_om_key = om_get_section_key(nobj.tetra.center());
om_add_obj(nobj.gid, nobj.id, nobj.last_om_key);
nglb.objs[obj_id] = nobj;
}
}
}
GS[gid] = nglb;
}
return NULL;
}
|
unlicense
|
codeApeFromChina/resource
|
frame_packages/java_libs/spring-2.5.6-src/src/org/springframework/mail/MailAuthenticationException.java
|
1498
|
/*
* Copyright 2002-2006 the original author or authors.
*
* 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.springframework.mail;
/**
* Exception thrown on failed authentication.
*
* @author Dmitriy Kopylenko
* @author Juergen Hoeller
*/
public class MailAuthenticationException extends MailException {
/**
* Constructor for MailAuthenticationException.
* @param msg message
*/
public MailAuthenticationException(String msg) {
super(msg);
}
/**
* Constructor for MailAuthenticationException.
* @param msg the detail message
* @param cause the root cause from the mail API in use
*/
public MailAuthenticationException(String msg, Throwable cause) {
super(msg, cause);
}
/**
* Constructor for MailAuthenticationException.
* @param cause the root cause from the mail API in use
*/
public MailAuthenticationException(Throwable cause) {
super("Authentication failed", cause);
}
}
|
unlicense
|
ch1huizong/dj
|
onlineshop/myshop/coupons/migrations/0001_initial.py
|
845
|
# Generated by Django 2.2.3 on 2019-09-07 12:50
import django.core.validators
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Coupon',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('code', models.CharField(max_length=50, unique=True)),
('valid_from', models.DateTimeField()),
('valid_to', models.DateTimeField()),
('discount', models.IntegerField(validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)])),
('active', models.BooleanField()),
],
),
]
|
unlicense
|
funkyDunks/Tracker
|
mobility-track-nodejs/config/database.js
|
448
|
module.exports = {
development: {
db: 'mongodb://localhost/mobilitytracker',
url: 'mongodb://localhost/mobilitytracker',
app: {
name: 'Nodejs Express Mongoose Demo'
}
},
test: {
db: 'mongodb://localhost/mobilitytracker',
app: {
name: 'Nodejs Express Mongoose Demo'
}
},
production: {
db: 'mongodb://localhost/mobilitytracker',
app: {
name: 'Nodejs Express Mongoose Demo'
}
}
};
|
apache-2.0
|
victor-smirnov/dumbo
|
tests/disruptor/wait_strategy_test.cc
|
15273
|
// Copyright (c) 2011-2015, Francois Saint-Jacques
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the disruptor-- nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL FRANCOIS SAINT-JACQUES BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE WaitStrategyTest
#include <boost/test/unit_test.hpp>
#include <dumbo/v1/disruptor/wait_strategy.h>
namespace dumbo {
namespace v1 {
namespace disruptor {
namespace test {
template <typename W>
struct StrategyFixture {
StrategyFixture() : alerted(false) {}
Sequence cursor;
Sequence sequence_1;
Sequence sequence_2;
Sequence sequence_3;
StdVector<Sequence*> dependents;
W strategy;
std::atomic<bool> alerted;
StdVector<Sequence*> allDependents() {
StdVector<Sequence*> d = {&sequence_1, &sequence_2, &sequence_3};
return d;
}
};
/* BusySpingStrategy */
using BusySpinStrategyFixture = StrategyFixture<BusySpinStrategy>;
BOOST_FIXTURE_TEST_SUITE(BusySpinStrategy, BusySpinStrategyFixture)
BOOST_AUTO_TEST_CASE(WaitForCursor) {
std::atomic<int64_t> return_value(kInitialCursorValue);
std::thread waiter([this, &return_value]() {
return_value.store(
strategy.WaitFor(kFirstSequenceValue, cursor, dependents, alerted));
});
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
std::thread([this]() {
cursor.IncrementAndGet(1L);
strategy.SignalAllWhenBlocking();
}).join();
waiter.join();
BOOST_CHECK_EQUAL(return_value.load(), kFirstSequenceValue);
}
BOOST_AUTO_TEST_CASE(SignalTimeoutWaitingOnCursor) {
std::atomic<int64_t> return_value(kInitialCursorValue);
std::thread waiter([this, &return_value]() {
return_value.store(strategy.WaitFor(kFirstSequenceValue, cursor, dependents,
alerted,
std::chrono::microseconds(1L)));
});
waiter.join();
BOOST_CHECK_EQUAL(return_value.load(), kTimeoutSignal);
std::thread waiter2([this, &return_value]() {
return_value.store(strategy.WaitFor(kFirstSequenceValue, cursor, dependents,
alerted, std::chrono::seconds(1L)));
});
cursor.IncrementAndGet(1L);
strategy.SignalAllWhenBlocking();
waiter2.join();
BOOST_CHECK_EQUAL(return_value.load(), kFirstSequenceValue);
}
BOOST_AUTO_TEST_CASE(WaitForDependents) {
std::atomic<int64_t> return_value(kInitialCursorValue);
std::thread waiter([this, &return_value]() {
return_value.store(strategy.WaitFor(kFirstSequenceValue, cursor,
allDependents(), alerted));
});
cursor.IncrementAndGet(1L);
strategy.SignalAllWhenBlocking();
// dependents haven't moved, WaitFor() should still block.
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_1.IncrementAndGet(1L);
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_2.IncrementAndGet(1L);
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_3.IncrementAndGet(1L);
waiter.join();
BOOST_CHECK_EQUAL(return_value.load(), kFirstSequenceValue);
}
BOOST_AUTO_TEST_CASE(SignalAlertWaitingOnDependents) {
std::atomic<int64_t> return_value(kInitialCursorValue);
std::thread waiter([this, &return_value]() {
return_value.store(strategy.WaitFor(kFirstSequenceValue, cursor,
allDependents(), alerted));
});
cursor.IncrementAndGet(1L);
strategy.SignalAllWhenBlocking();
// dependents haven't moved, WaitFor() should still block.
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_1.IncrementAndGet(1L);
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_2.IncrementAndGet(1L);
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
alerted.store(true);
waiter.join();
BOOST_CHECK_EQUAL(return_value.load(), kAlertedSignal);
}
BOOST_AUTO_TEST_SUITE_END() // BusySpinStrategy suite
/* YieldingStrategy */
using YieldingStrategyFixture = StrategyFixture<YieldingStrategy<>>;
BOOST_FIXTURE_TEST_SUITE(YieldingStrategy, YieldingStrategyFixture)
BOOST_AUTO_TEST_CASE(WaitForCursor) {
std::atomic<int64_t> return_value(kInitialCursorValue);
std::thread waiter([this, &return_value]() {
return_value.store(
strategy.WaitFor(kFirstSequenceValue, cursor, dependents, alerted));
});
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
std::thread([this]() {
cursor.IncrementAndGet(1L);
strategy.SignalAllWhenBlocking();
}).join();
waiter.join();
BOOST_CHECK_EQUAL(return_value.load(), kFirstSequenceValue);
}
BOOST_AUTO_TEST_CASE(SignalTimeoutWaitingOnCursor) {
std::atomic<int64_t> return_value(kInitialCursorValue);
std::thread waiter([this, &return_value]() {
return_value.store(strategy.WaitFor(kFirstSequenceValue, cursor, dependents,
alerted,
std::chrono::microseconds(1L)));
});
waiter.join();
BOOST_CHECK_EQUAL(return_value.load(), kTimeoutSignal);
std::thread waiter2([this, &return_value]() {
return_value.store(strategy.WaitFor(kFirstSequenceValue, cursor, dependents,
alerted, std::chrono::seconds(1L)));
});
cursor.IncrementAndGet(1L);
strategy.SignalAllWhenBlocking();
waiter2.join();
BOOST_CHECK_EQUAL(return_value.load(), kFirstSequenceValue);
}
BOOST_AUTO_TEST_CASE(WaitForDependents) {
std::atomic<int64_t> return_value(kInitialCursorValue);
std::thread waiter([this, &return_value]() {
return_value.store(strategy.WaitFor(kFirstSequenceValue, cursor,
allDependents(), alerted));
});
cursor.IncrementAndGet(1L);
strategy.SignalAllWhenBlocking();
// dependents haven't moved, WaitFor() should still block.
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_1.IncrementAndGet(1L);
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_2.IncrementAndGet(1L);
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_3.IncrementAndGet(1L);
waiter.join();
BOOST_CHECK_EQUAL(return_value.load(), kFirstSequenceValue);
}
BOOST_AUTO_TEST_CASE(SignalAlertWaitingOnDependents) {
std::atomic<int64_t> return_value(kInitialCursorValue);
std::thread waiter([this, &return_value]() {
return_value.store(strategy.WaitFor(kFirstSequenceValue, cursor,
allDependents(), alerted));
});
cursor.IncrementAndGet(1L);
strategy.SignalAllWhenBlocking();
// dependents haven't moved, WaitFor() should still block.
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_1.IncrementAndGet(1L);
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_2.IncrementAndGet(1L);
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
alerted.store(true);
waiter.join();
BOOST_CHECK_EQUAL(return_value.load(), kAlertedSignal);
}
BOOST_AUTO_TEST_SUITE_END() // YieldingStrategy suite
/* SleepingStrategy */
using SleepingStrategyFixture = StrategyFixture<SleepingStrategy<>>;
BOOST_FIXTURE_TEST_SUITE(SleepingStrategy, SleepingStrategyFixture)
BOOST_AUTO_TEST_CASE(WaitForCursor) {
std::atomic<int64_t> return_value(kInitialCursorValue);
std::thread waiter([this, &return_value]() {
return_value.store(
strategy.WaitFor(kFirstSequenceValue, cursor, dependents, alerted));
});
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
std::thread([this]() {
cursor.IncrementAndGet(1L);
strategy.SignalAllWhenBlocking();
}).join();
waiter.join();
BOOST_CHECK_EQUAL(return_value.load(), kFirstSequenceValue);
}
BOOST_AUTO_TEST_CASE(SignalTimeoutWaitingOnCursor) {
std::atomic<int64_t> return_value(kInitialCursorValue);
std::thread waiter([this, &return_value]() {
return_value.store(strategy.WaitFor(kFirstSequenceValue, cursor, dependents,
alerted,
std::chrono::microseconds(1L)));
});
waiter.join();
BOOST_CHECK_EQUAL(return_value.load(), kTimeoutSignal);
std::thread waiter2([this, &return_value]() {
return_value.store(strategy.WaitFor(kFirstSequenceValue, cursor, dependents,
alerted, std::chrono::seconds(1L)));
});
cursor.IncrementAndGet(1L);
strategy.SignalAllWhenBlocking();
waiter2.join();
BOOST_CHECK_EQUAL(return_value.load(), kFirstSequenceValue);
}
BOOST_AUTO_TEST_CASE(WaitForDependents) {
std::atomic<int64_t> return_value(kInitialCursorValue);
std::thread waiter([this, &return_value]() {
return_value.store(strategy.WaitFor(kFirstSequenceValue, cursor,
allDependents(), alerted));
});
cursor.IncrementAndGet(1L);
strategy.SignalAllWhenBlocking();
// dependents haven't moved, WaitFor() should still block.
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_1.IncrementAndGet(1L);
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_2.IncrementAndGet(1L);
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_3.IncrementAndGet(1L);
waiter.join();
BOOST_CHECK_EQUAL(return_value.load(), kFirstSequenceValue);
}
BOOST_AUTO_TEST_CASE(SignalAlertWaitingOnDependents) {
std::atomic<int64_t> return_value(kInitialCursorValue);
std::thread waiter([this, &return_value]() {
return_value.store(strategy.WaitFor(kFirstSequenceValue, cursor,
allDependents(), alerted));
});
cursor.IncrementAndGet(1L);
strategy.SignalAllWhenBlocking();
// dependents haven't moved, WaitFor() should still block.
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_1.IncrementAndGet(1L);
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_2.IncrementAndGet(1L);
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
alerted.store(true);
waiter.join();
BOOST_CHECK_EQUAL(return_value.load(), kAlertedSignal);
}
BOOST_AUTO_TEST_SUITE_END() // SleepingStrategy suite
/* BlockingStrategy */
using BlockingStrategyFixture = StrategyFixture<BlockingStrategy>;
BOOST_FIXTURE_TEST_SUITE(BlockingStrategy, BlockingStrategyFixture)
BOOST_AUTO_TEST_CASE(WaitForCursor) {
std::atomic<int64_t> return_value(kInitialCursorValue);
std::thread waiter([this, &return_value]() {
return_value.store(
strategy.WaitFor(kFirstSequenceValue, cursor, dependents, alerted));
});
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
std::thread([this]() {
cursor.IncrementAndGet(1L);
strategy.SignalAllWhenBlocking();
}).join();
waiter.join();
BOOST_CHECK_EQUAL(return_value.load(), kFirstSequenceValue);
}
BOOST_AUTO_TEST_CASE(SignalAlertWaitingOnCursor) {
std::atomic<int64_t> return_value(kInitialCursorValue);
std::thread waiter([this, &return_value]() {
return_value.store(
strategy.WaitFor(kFirstSequenceValue, cursor, dependents, alerted));
});
std::thread([this]() { strategy.SignalAllWhenBlocking(); }).join();
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
std::thread([this]() {
alerted.store(true);
strategy.SignalAllWhenBlocking();
}).join();
waiter.join();
BOOST_CHECK_EQUAL(return_value.load(), kAlertedSignal);
}
BOOST_AUTO_TEST_CASE(SignalTimeoutWaitingOnCursor) {
std::atomic<int64_t> return_value(kInitialCursorValue);
std::thread waiter([this, &return_value]() {
return_value.store(strategy.WaitFor(kFirstSequenceValue, cursor, dependents,
alerted,
std::chrono::microseconds(1L)));
});
waiter.join();
BOOST_CHECK_EQUAL(return_value.load(), kTimeoutSignal);
std::thread waiter2([this, &return_value]() {
return_value.store(strategy.WaitFor(kFirstSequenceValue, cursor, dependents,
alerted, std::chrono::seconds(1L)));
});
cursor.IncrementAndGet(1L);
strategy.SignalAllWhenBlocking();
waiter2.join();
BOOST_CHECK_EQUAL(return_value.load(), kFirstSequenceValue);
}
BOOST_AUTO_TEST_CASE(WaitForDependents) {
std::atomic<int64_t> return_value(kInitialCursorValue);
std::thread waiter([this, &return_value]() {
return_value.store(strategy.WaitFor(kFirstSequenceValue, cursor,
allDependents(), alerted));
});
cursor.IncrementAndGet(1L);
strategy.SignalAllWhenBlocking();
// dependents haven't moved, WaitFor() should still block.
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_1.IncrementAndGet(1L);
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_2.IncrementAndGet(1L);
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_3.IncrementAndGet(1L);
waiter.join();
BOOST_CHECK_EQUAL(return_value.load(), kFirstSequenceValue);
}
BOOST_AUTO_TEST_CASE(SignalAlertWaitingOnDependents) {
std::atomic<int64_t> return_value(kInitialCursorValue);
std::thread waiter([this, &return_value]() {
return_value.store(strategy.WaitFor(kFirstSequenceValue, cursor,
allDependents(), alerted));
});
cursor.IncrementAndGet(1L);
strategy.SignalAllWhenBlocking();
// dependents haven't moved, WaitFor() should still block.
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_1.IncrementAndGet(1L);
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
sequence_2.IncrementAndGet(1L);
BOOST_CHECK_EQUAL(return_value.load(), kInitialCursorValue);
alerted.store(true);
waiter.join();
BOOST_CHECK_EQUAL(return_value.load(), kAlertedSignal);
}
BOOST_AUTO_TEST_SUITE_END() // BlockingStrategy suite
}}}}
|
apache-2.0
|
jbazin30/coiffure
|
main/class/graph/inc/Label.class.php
|
11839
|
<?php
/*
* This work is hereby released into the Public Domain.
* To view a copy of the public domain dedication,
* visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
* Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
*
*/
require_once dirname(__FILE__) . "/../Graph.class.php";
/**
* Draw labels
*
* @package Artichow
*/
class awLabel implements awPositionable {
/**
* Label border
*
* @var int
*/
public $border;
/**
* Label texts
*
* @var array
*/
protected $texts;
/**
* Text font
*
* @var int
*/
protected $font;
/**
* Text angle
*
* @var int
*/
protected $angle = 0;
/**
* Text color
*
* @var Color
*/
protected $color;
/**
* Text background
*
* @var Color, Gradient
*/
private $background;
/**
* Callback function
*
* @var string
*/
private $function;
/**
* Padding
*
* @var int
*/
private $padding;
/**
* Move position from this vector
*
* @var Point
*/
protected $move;
/**
* Label interval
*
* @var int
*/
protected $interval = 1;
/**
* Horizontal align
*
* @var int
*/
protected $hAlign = awLabel::CENTER;
/**
* Vertical align
*
* @var int
*/
protected $vAlign = awLabel::MIDDLE;
/**
* Hide all labels ?
*
* @var bool
*/
protected $hide = FALSE;
/**
* Keys to hide
*
* @var array
*/
protected $hideKey = [];
/**
* Values to hide
*
* @var array
*/
protected $hideValue = [];
/**
* Hide first label
*
* @var bool
*/
protected $hideFirst = FALSE;
/**
* Hide last label
*
* @var bool
*/
protected $hideLast = FALSE;
/**
* Build the label
*
* @param string $label First label
*/
public function __construct($label = NULL, $font = NULL, $color = NULL, $angle = 0) {
if (is_array($label)) {
$this->set($label);
} elseif (is_string($label)) {
$this->set(array($label));
}
if ($font === NULL) {
$font = new awFont2;
}
$this->setFont($font);
$this->setAngle($angle);
if ($color instanceof awColor) {
$this->setColor($color);
} else {
$this->setColor(new awColor(0, 0, 0));
}
$this->move = new awPoint(0, 0);
$this->border = new awBorder;
$this->border->hide();
}
/**
* Get an element of the label from its key
*
* @param int $key Element key
* @return string A value
*/
public function get($key) {
return array_key_exists($key, $this->texts) ? $this->texts[$key] : NULL;
}
/**
* Get all labels
*
* @return array
*/
public function all() {
return $this->texts;
}
/**
* Set one or several labels
*
* @param array $labels Array of string or a string
*/
public function set($labels) {
if (is_array($labels)) {
$this->texts = $labels;
} else {
$this->texts = array((string) $labels);
}
}
/**
* Count number of texts in the label
*
* @return int
*/
public function count() {
return is_array($this->texts) ? count($this->texts) : 0;
}
/**
* Set a callback function for labels
*
* @param string $function
*/
public function setCallbackFunction($function) {
$this->function = is_null($function) ? $function : (string) $function;
}
/**
* Return the callback function for labels
*
* @return string
*/
public function getCallbackFunction() {
return $this->function;
}
/**
* Change labels format
*
* @param string $format New format (printf style: %.2f for example)
*/
public function setFormat($format) {
$function = 'label' . time() . '_' . (microtime() * 1000000);
eval('function ' . $function . '($value) {
return sprintf("' . addcslashes($format, '"') . '", $value);
}');
$this->setCallbackFunction($function);
}
/**
* Change font for label
*
* @param awFont $font New font
* @param awColor $color Font color (can be NULL)
*/
public function setFont(awFont $font, $color = NULL) {
$this->font = $font;
if ($color instanceof awColor) {
$this->setColor($color);
}
}
/**
* Change font angle
*
* @param int $angle New angle
*/
public function setAngle($angle) {
$this->angle = (int) $angle;
}
/**
* Change font color
*
* @param awColor $color
*/
public function setColor(awColor $color) {
$this->color = $color;
}
/**
* Change text background
*
* @param mixed $background
*/
public function setBackground($background) {
$this->background = $background;
}
/**
* Change text background color
*
* @param Color
*/
public function setBackgroundColor(awColor $color) {
$this->background = $color;
}
/**
* Change text background gradient
*
* @param Gradient
*/
public function setBackgroundGradient(awGradient $gradient) {
$this->background = $gradient;
}
/**
* Change padding
*
* @param int $left Left padding
* @param int $right Right padding
* @param int $top Top padding
* @param int $bottom Bottom padding
*/
public function setPadding($left, $right, $top, $bottom) {
$this->padding = array((int) $left, (int) $right, (int) $top, (int) $bottom);
}
/**
* Hide all labels ?
*
* @param bool $hide
*/
public function hide($hide = TRUE) {
$this->hide = (bool) $hide;
}
/**
* Show all labels ?
*
* @param bool $show
*/
public function show($show = TRUE) {
$this->hide = (bool) !$show;
}
/**
* Hide a key
*
* @param int $key The key to hide
*/
public function hideKey($key) {
$this->hideKey[$key] = TRUE;
}
/**
* Hide a value
*
* @param int $value The value to hide
*/
public function hideValue($value) {
$this->hideValue[] = $value;
}
/**
* Hide first label
*
* @param bool $hide
*/
public function hideFirst($hide) {
$this->hideFirst = (bool) $hide;
}
/**
* Hide last label
*
* @param bool $hide
*/
public function hideLast($hide) {
$this->hideLast = (bool) $hide;
}
/**
* Set label interval
*
* @param int
*/
public function setInterval($interval) {
$this->interval = (int) $interval;
}
/**
* Change label position
*
* @param int $x Add this interval to X coord
* @param int $y Add this interval to Y coord
*/
public function move($x, $y) {
$this->move = $this->move->move($x, $y);
}
/**
* Change alignment
*
* @param int $h Horizontal alignment
* @param int $v Vertical alignment
*/
public function setAlign($h = NULL, $v = NULL) {
if ($h !== NULL) {
$this->hAlign = (int) $h;
}
if ($v !== NULL) {
$this->vAlign = (int) $v;
}
}
/**
* Get a text from the labele
*
* @param mixed $key Key in the array text
* @return Text
*/
public function getText($key) {
if (is_array($this->texts) and array_key_exists($key, $this->texts)) {
$value = $this->texts[$key];
if (is_string($this->function)) {
$value = call_user_func($this->function, $value);
}
$text = new awText($value);
$text->setFont($this->font);
$text->setAngle($this->angle);
$text->setColor($this->color);
if ($this->background instanceof awColor) {
$text->setBackgroundColor($this->background);
} elseif ($this->background instanceof awGradient) {
$text->setBackgroundGradient($this->background);
}
$text->border = $this->border;
if ($this->padding !== NULL) {
call_user_func_array(array($text, 'setPadding'), $this->padding);
}
return $text;
} else {
return NULL;
}
}
/**
* Get max width of all texts
*
* @param awDriver $driver A driver
* @return int
*/
public function getMaxWidth(awDriver $driver) {
return $this->getMax($driver, 'getTextWidth');
}
/**
* Get max height of all texts
*
* @param awDriver $driver A driver
* @return int
*/
public function getMaxHeight(awDriver $driver) {
return $this->getMax($driver, 'getTextHeight');
}
/**
* Draw the label
*
* @param awDriver $driver
* @param awPoint $p Label center
* @param int $key Text position in the array of texts (default to zero)
*/
public function draw(awDriver $driver, awPoint $p, $key = 0) {
if (($key % $this->interval) !== 0) {
return;
}
// Hide all labels
if ($this->hide) {
return;
}
// Key is hidden
if (array_key_exists($key, $this->hideKey)) {
return;
}
// Hide first label
if ($key === 0 and $this->hideFirst) {
return;
}
// Hide last label
if ($key === count($this->texts) - 1 and $this->hideLast) {
return;
}
$text = $this->getText($key);
if ($text !== NULL) {
// Value must be hidden
if (in_array($text->getText(), $this->hideValue)) {
return;
}
$x = $p->x;
$y = $p->y;
// Get padding
list($left, $right, $top, $bottom) = $text->getPadding();
// $font = $text->getFont();
$width = $driver->getTextWidth($text);
$height = $driver->getTextHeight($text);
switch ($this->hAlign) {
case awLabel::RIGHT :
$x -= ( $width + $right);
break;
case awLabel::CENTER :
$x -= ( $width - $left + $right) / 2;
break;
case awLabel::LEFT :
$x += $left;
break;
}
switch ($this->vAlign) {
case awLabel::TOP :
$y -= ( $height + $bottom);
break;
case awLabel::MIDDLE :
$y -= ( $height - $top + $bottom) / 2;
break;
case awLabel::BOTTOM :
$y += $top;
break;
}
$driver->string($text, $this->move->move($x, $y));
}
}
protected function getMax(awDriver $driver, $function) {
$max = NULL;
foreach ($this->texts as $key => $text) {
$text = $this->getText($key);
$font = $text->getFont();
if (is_null($max)) {
$max = $font->{$function}($text);
} else {
$max = max($max, $font->{$function}($text));
}
}
return $max;
}
}
registerClass('Label');
?>
|
apache-2.0
|
vandewilly/git-flow-sample
|
config/initializers/secret_token.rb
|
504
|
# Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
GitFlowSample::Application.config.secret_token = '9f3edebb1bad90a049d6268fc1dd4c2f2be8605caf64bdfbd0f939780956314893ed91dfe3440c41fab4abaf4ef7888c53b9612d62e989ef14d65e06c6f542d0'
|
apache-2.0
|
drinkwithwater/floodlightplus
|
src/main/java/net/floodlightcontroller/staticflowentry/web/TestResource.java
|
2894
|
/**
* Copyright 2011, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* 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 net.floodlightcontroller.staticflowentry.web;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.floodlightcontroller.core.annotations.LogMessageCategory;
import net.floodlightcontroller.core.annotations.LogMessageDoc;
import net.floodlightcontroller.staticflowentry.StaticFlowEntries;
import net.floodlightcontroller.staticflowentry.StaticFlowEntryPusher;
import net.floodlightcontroller.storage.IStorageSourceService;
/**
* Pushes a static flow entry to the storage source
* @author alexreimers
*
*/
@LogMessageCategory("Static Flow Pusher")
public class TestResource extends ServerResource {
protected static Logger log = LoggerFactory.getLogger(TestResource.class);
@Get
public String test() {
IStorageSourceService storageSource =
(IStorageSourceService)getContext().getAttributes().
get(IStorageSourceService.class.getCanonicalName());
Map<String, Object> rowValues=new HashMap<String, Object>();
rowValues.put(StaticFlowEntryPusher.COLUMN_NAME,"1");
rowValues.put(StaticFlowEntryPusher.COLUMN_SWITCH, "00:00:00:00:00:00:02:00");
// rowValues.put(StaticFlowEntryPusher.COLUMN_ACTIONS, "output="+2);
rowValues.put(StaticFlowEntryPusher.COLUMN_INSTRUCTIONS, "not used");
rowValues.put(StaticFlowEntryPusher.COLUMN_PRIORITY,"3");
rowValues.put(StaticFlowEntryPusher.COLUMN_ACTIVE,"true");
rowValues.put(StaticFlowEntryPusher.COLUMN_IN_PORT,Integer.toString(1));
rowValues.put(StaticFlowEntryPusher.COLUMN_DL_TYPE,"0x0800");
//rowValues.put(StaticFlowEntryPusher.COLUMN_DL_SRC,"00:00:00:00:00:00:00:01");
//rowValues.put(StaticFlowEntryPusher.COLUMN_DL_DST,"00:00:00:00:00:00:00:02");
rowValues.put(StaticFlowEntryPusher.COLUMN_NW_SRC,"10.0.0.1");
rowValues.put(StaticFlowEntryPusher.COLUMN_NW_DST,"10.0.0.2");
storageSource.insertRowAsync(StaticFlowEntryPusher.TABLE_NAME, rowValues);
return rowValues.toString();
}
}
|
apache-2.0
|
yankee42/mustangproject
|
src/main/java/org/mustangproject/ZUGFeRD/model/TradeTaxType.java
|
9296
|
//
// Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 generiert
// Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// �nderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren.
// Generiert: 2015.10.16 um 06:16:03 PM CEST
//
package org.mustangproject.ZUGFeRD.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java-Klasse f�r TradeTaxType complex type.
*
* <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist.
*
* <pre>
* <complexType name="TradeTaxType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="CalculatedAmount" type="{urn:un:unece:uncefact:data:standard:UnqualifiedDataType:15}AmountType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="TypeCode" type="{urn:un:unece:uncefact:data:standard:QualifiedDataType:12}TaxTypeCodeType" minOccurs="0"/>
* <element name="ExemptionReason" type="{urn:un:unece:uncefact:data:standard:UnqualifiedDataType:15}TextType" minOccurs="0"/>
* <element name="BasisAmount" type="{urn:un:unece:uncefact:data:standard:UnqualifiedDataType:15}AmountType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="LineTotalBasisAmount" type="{urn:un:unece:uncefact:data:standard:UnqualifiedDataType:15}AmountType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="AllowanceChargeBasisAmount" type="{urn:un:unece:uncefact:data:standard:UnqualifiedDataType:15}AmountType" maxOccurs="unbounded" minOccurs="0"/>
* <element name="CategoryCode" type="{urn:un:unece:uncefact:data:standard:QualifiedDataType:12}TaxCategoryCodeType" minOccurs="0"/>
* <element name="ApplicablePercent" type="{urn:un:unece:uncefact:data:standard:UnqualifiedDataType:15}PercentType" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TradeTaxType", propOrder = {
"calculatedAmount",
"typeCode",
"exemptionReason",
"basisAmount",
"lineTotalBasisAmount",
"allowanceChargeBasisAmount",
"categoryCode",
"applicablePercent"
})
public class TradeTaxType {
@XmlElement(name = "CalculatedAmount")
protected List<AmountType> calculatedAmount;
@XmlElement(name = "TypeCode")
protected TaxTypeCodeType typeCode;
@XmlElement(name = "ExemptionReason")
protected TextType exemptionReason;
@XmlElement(name = "BasisAmount")
protected List<AmountType> basisAmount;
@XmlElement(name = "LineTotalBasisAmount")
protected List<AmountType> lineTotalBasisAmount;
@XmlElement(name = "AllowanceChargeBasisAmount")
protected List<AmountType> allowanceChargeBasisAmount;
@XmlElement(name = "CategoryCode")
protected TaxCategoryCodeType categoryCode;
@XmlElement(name = "ApplicablePercent")
protected PercentType applicablePercent;
/**
* Gets the value of the calculatedAmount property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the calculatedAmount property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCalculatedAmount().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AmountType }
*
*
*/
public List<AmountType> getCalculatedAmount() {
if (calculatedAmount == null) {
calculatedAmount = new ArrayList<AmountType>();
}
return this.calculatedAmount;
}
/**
* Ruft den Wert der typeCode-Eigenschaft ab.
*
* @return
* possible object is
* {@link TaxTypeCodeType }
*
*/
public TaxTypeCodeType getTypeCode() {
return typeCode;
}
/**
* Legt den Wert der typeCode-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link TaxTypeCodeType }
*
*/
public void setTypeCode(TaxTypeCodeType value) {
this.typeCode = value;
}
/**
* Ruft den Wert der exemptionReason-Eigenschaft ab.
*
* @return
* possible object is
* {@link TextType }
*
*/
public TextType getExemptionReason() {
return exemptionReason;
}
/**
* Legt den Wert der exemptionReason-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link TextType }
*
*/
public void setExemptionReason(TextType value) {
this.exemptionReason = value;
}
/**
* Gets the value of the basisAmount property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the basisAmount property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getBasisAmount().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AmountType }
*
*
*/
public List<AmountType> getBasisAmount() {
if (basisAmount == null) {
basisAmount = new ArrayList<AmountType>();
}
return this.basisAmount;
}
/**
* Gets the value of the lineTotalBasisAmount property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the lineTotalBasisAmount property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getLineTotalBasisAmount().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AmountType }
*
*
*/
public List<AmountType> getLineTotalBasisAmount() {
if (lineTotalBasisAmount == null) {
lineTotalBasisAmount = new ArrayList<AmountType>();
}
return this.lineTotalBasisAmount;
}
/**
* Gets the value of the allowanceChargeBasisAmount property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the allowanceChargeBasisAmount property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAllowanceChargeBasisAmount().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AmountType }
*
*
*/
public List<AmountType> getAllowanceChargeBasisAmount() {
if (allowanceChargeBasisAmount == null) {
allowanceChargeBasisAmount = new ArrayList<AmountType>();
}
return this.allowanceChargeBasisAmount;
}
/**
* Ruft den Wert der categoryCode-Eigenschaft ab.
*
* @return
* possible object is
* {@link TaxCategoryCodeType }
*
*/
public TaxCategoryCodeType getCategoryCode() {
return categoryCode;
}
/**
* Legt den Wert der categoryCode-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link TaxCategoryCodeType }
*
*/
public void setCategoryCode(TaxCategoryCodeType value) {
this.categoryCode = value;
}
/**
* Ruft den Wert der applicablePercent-Eigenschaft ab.
*
* @return
* possible object is
* {@link PercentType }
*
*/
public PercentType getApplicablePercent() {
return applicablePercent;
}
/**
* Legt den Wert der applicablePercent-Eigenschaft fest.
*
* @param value
* allowed object is
* {@link PercentType }
*
*/
public void setApplicablePercent(PercentType value) {
this.applicablePercent = value;
}
}
|
apache-2.0
|
aws/aws-sdk-java
|
aws-java-sdk-kafka/src/main/java/com/amazonaws/services/kafka/model/transform/ClusterInfoJsonUnmarshaller.java
|
7089
|
/*
* 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.kafka.model.transform;
import java.math.*;
import javax.annotation.Generated;
import com.amazonaws.services.kafka.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;
import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;
/**
* ClusterInfo JSON Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ClusterInfoJsonUnmarshaller implements Unmarshaller<ClusterInfo, JsonUnmarshallerContext> {
public ClusterInfo unmarshall(JsonUnmarshallerContext context) throws Exception {
ClusterInfo clusterInfo = new ClusterInfo();
int originalDepth = context.getCurrentDepth();
String currentParentElement = context.getCurrentParentElement();
int targetDepth = originalDepth + 1;
JsonToken token = context.getCurrentToken();
if (token == null)
token = context.nextToken();
if (token == VALUE_NULL) {
return null;
}
while (true) {
if (token == null)
break;
if (token == FIELD_NAME || token == START_OBJECT) {
if (context.testExpression("activeOperationArn", targetDepth)) {
context.nextToken();
clusterInfo.setActiveOperationArn(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("brokerNodeGroupInfo", targetDepth)) {
context.nextToken();
clusterInfo.setBrokerNodeGroupInfo(BrokerNodeGroupInfoJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("clientAuthentication", targetDepth)) {
context.nextToken();
clusterInfo.setClientAuthentication(ClientAuthenticationJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("clusterArn", targetDepth)) {
context.nextToken();
clusterInfo.setClusterArn(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("clusterName", targetDepth)) {
context.nextToken();
clusterInfo.setClusterName(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("creationTime", targetDepth)) {
context.nextToken();
clusterInfo.setCreationTime(DateJsonUnmarshallerFactory.getInstance("iso8601").unmarshall(context));
}
if (context.testExpression("currentBrokerSoftwareInfo", targetDepth)) {
context.nextToken();
clusterInfo.setCurrentBrokerSoftwareInfo(BrokerSoftwareInfoJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("currentVersion", targetDepth)) {
context.nextToken();
clusterInfo.setCurrentVersion(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("encryptionInfo", targetDepth)) {
context.nextToken();
clusterInfo.setEncryptionInfo(EncryptionInfoJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("enhancedMonitoring", targetDepth)) {
context.nextToken();
clusterInfo.setEnhancedMonitoring(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("openMonitoring", targetDepth)) {
context.nextToken();
clusterInfo.setOpenMonitoring(OpenMonitoringJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("loggingInfo", targetDepth)) {
context.nextToken();
clusterInfo.setLoggingInfo(LoggingInfoJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("numberOfBrokerNodes", targetDepth)) {
context.nextToken();
clusterInfo.setNumberOfBrokerNodes(context.getUnmarshaller(Integer.class).unmarshall(context));
}
if (context.testExpression("state", targetDepth)) {
context.nextToken();
clusterInfo.setState(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("stateInfo", targetDepth)) {
context.nextToken();
clusterInfo.setStateInfo(StateInfoJsonUnmarshaller.getInstance().unmarshall(context));
}
if (context.testExpression("tags", targetDepth)) {
context.nextToken();
clusterInfo.setTags(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class), context.getUnmarshaller(String.class))
.unmarshall(context));
}
if (context.testExpression("zookeeperConnectString", targetDepth)) {
context.nextToken();
clusterInfo.setZookeeperConnectString(context.getUnmarshaller(String.class).unmarshall(context));
}
if (context.testExpression("zookeeperConnectStringTls", targetDepth)) {
context.nextToken();
clusterInfo.setZookeeperConnectStringTls(context.getUnmarshaller(String.class).unmarshall(context));
}
} else if (token == END_ARRAY || token == END_OBJECT) {
if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
if (context.getCurrentDepth() <= originalDepth)
break;
}
}
token = context.nextToken();
}
return clusterInfo;
}
private static ClusterInfoJsonUnmarshaller instance;
public static ClusterInfoJsonUnmarshaller getInstance() {
if (instance == null)
instance = new ClusterInfoJsonUnmarshaller();
return instance;
}
}
|
apache-2.0
|
buildingenergy/buildingenergy-platform
|
seed/static/seed/js/services/user_service.js
|
7063
|
/**
* :copyright: (c) 2014 Building Energy Inc
* :license: see LICENSE for more details.
*/
// user services
angular.module('BE.seed.service.user', []).factory('user_service', [
'$http',
'$q',
'generated_urls',
function ($http, $q, generated_urls) {
var user_factory = {};
var urls = generated_urls;
var organization;
/**
* returns the current organization, set initially by a controller
* @return {obj} organization
*/
user_factory.get_organization = function() {
// yes this is a global, but otherwise we'll have to use a promise in
// front of every request that needs this. window.BE.initial_org_id is
// set in base.html via the seed.views.main home view
return organization || {
id: window.BE.initial_org_id,
name: window.BE.initial_org_name,
user_role: window.BE.initial_org_user_role
};
};
/**
* sets the current organization
* @param {obj} org
* @return {promise}
*/
user_factory.set_organization = function(org) {
organization = org;
var defer = $q.defer();
$http({
method: 'PUT',
'url': urls.accounts.set_default_organization,
'data': {
'organization': org
}
}).success(function(data) {
if (data.status === 'error') {
defer.reject(data);
}
defer.resolve(data);
}).error(function(data, status) {
defer.reject(data, status);
});
return defer.promise;
};
user_factory.get_users = function() {
var defer = $q.defer();
$http.get(urls.accounts.get_users).success(function(data) {
defer.resolve(data);
}).error(function(data, status) {
defer.reject(data, status);
});
return defer.promise;
};
user_factory.add = function(user) {
var defer = $q.defer();
var new_user_details = {'first_name': user.first_name,
'last_name': user.last_name,
'email': user.email,
'org_name': user.org_name,
'role': user.role
};
if (typeof user.organization !== "undefined") {
new_user_details.organization_id = user.organization.org_id;
}
$http({
method: 'POST',
'url': urls.accounts.add_user,
'data': new_user_details
}).success(function(data) {
if (data.status === 'error') {
defer.reject(data);
}
defer.resolve(data);
}).error(function(data, status) {
defer.reject(data, status);
});
return defer.promise;
};
user_factory.get_default_columns = function() {
var defer = $q.defer();
$http({
method: 'GET',
'url': urls.seed.get_default_columns
}).success(function(data) {
if (data.status === 'error') {
defer.reject(data);
}
defer.resolve(data);
}).error(function(data, status) {
defer.reject(data, status);
});
return defer.promise;
};
user_factory.get_shared_buildings = function() {
var defer = $q.defer();
$http({
method: 'GET',
'url': urls.accounts.get_shared_buildings
}).success(function(data) {
if (data.status === 'error') {
defer.reject(data);
}
defer.resolve(data);
}).error(function(data, status) {
defer.reject(data, status);
});
return defer.promise;
};
/**
* gets the user's first name, last name, email, and API key if exists
* @return {obj} object with keys: first_name, last_name, email, api_key
*/
user_factory.get_user_profile = function() {
var defer = $q.defer();
$http({
method: 'GET',
'url': urls.accounts.get_user_profile
}).success(function(data) {
if (data.status === 'error') {
defer.reject(data);
}
defer.resolve(data);
}).error(function(data, status) {
defer.reject(data, status);
});
return defer.promise;
};
/**
* asks the server to generate a new API key
* @return {obj} object with api_key
*/
user_factory.generate_api_key = function() {
var defer = $q.defer();
$http({
method: 'POST',
'url': urls.accounts.generate_api_key
}).success(function(data) {
if (data.status === 'error') {
defer.reject(data);
}
defer.resolve(data);
}).error(function(data, status) {
defer.reject(data, status);
});
return defer.promise;
};
user_factory.set_default_columns = function(columns, show_shared_buildings) {
var defer = $q.defer();
$http({
method: 'POST',
'url': urls.seed.set_default_columns,
'data': {'columns': columns, 'show_shared_buildings': show_shared_buildings}
}).success(function(data) {
if (data.status === 'error') {
defer.reject(data);
}
defer.resolve(data);
}).error(function(data, status) {
defer.reject(data, status);
});
return defer.promise;
};
/**
* updates the user's PR
* @param {obj} user
*/
user_factory.update_user = function(user) {
var defer = $q.defer();
$http({
method: 'PUT',
'url': urls.accounts.update_user,
'data': {user: user}
}).success(function(data) {
if (data.status === 'error') {
defer.reject(data);
}
defer.resolve(data);
}).error(function(data, status) {
defer.reject(data, status);
});
return defer.promise;
};
/**
* sets the user's password
* @param {string} current_password
* @param {string} password_1
* @param {string} password_2
*/
user_factory.set_password = function(current_password, password_1, password_2) {
var defer = $q.defer();
$http({
method: 'PUT',
'url': urls.accounts.set_password,
'data': {
'current_password': current_password,
'password_1': password_1,
'password_2': password_2
}
}).success(function(data) {
if (data.status === 'error') {
defer.reject(data);
}
defer.resolve(data);
}).error(function(data, status) {
defer.reject(data, status);
});
return defer.promise;
};
return user_factory;
}]);
|
apache-2.0
|
begla/Intrinsic
|
IntrinsicCore/src/IntrinsicCoreComponentsCamera.cpp
|
3713
|
// Copyright 2017 Benjamin Glatzel
//
// 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.
// Precompiled header file
#include "stdafx.h"
namespace Intrinsic
{
namespace Core
{
namespace Components
{
void CameraManager::init()
{
_INTR_LOG_INFO("Inititializing Camera Component Manager...");
Dod::Components::ComponentManagerBase<
CameraData, _INTR_MAX_CAMERA_COMPONENT_COUNT>::_initComponentManager();
Dod::Components::ComponentManagerEntry cameraEntry;
{
cameraEntry.createFunction = Components::CameraManager::createCamera;
cameraEntry.destroyFunction = Components::CameraManager::destroyCamera;
cameraEntry.resetToDefaultFunction =
Components::CameraManager::resetToDefault;
cameraEntry.getComponentForEntityFunction =
Components::CameraManager::getComponentForEntity;
Application::_componentManagerMapping[_N(Camera)] = cameraEntry;
Application::_orderedComponentManagers.push_back(cameraEntry);
}
Dod::PropertyCompilerEntry propCompilerCamera;
{
propCompilerCamera.compileFunction =
Components::CameraManager::compileDescriptor;
propCompilerCamera.initFunction =
Components::CameraManager::initFromDescriptor;
propCompilerCamera.ref = Dod::Ref();
Application::_componentPropertyCompilerMapping[_N(Camera)] =
propCompilerCamera;
}
}
// <-
void CameraManager::updateFrustumsAndMatrices(const CameraRefArray& p_Cameras)
{
_INTR_PROFILE_CPU("General", "Cam. Matrix Updt.");
for (uint32_t i = 0u; i < static_cast<uint32_t>(p_Cameras.size()); ++i)
{
CameraRef campCompRef = p_Cameras[i];
Entity::EntityRef entityRef = _entity(campCompRef);
Components::NodeRef nodeCompRef =
Components::NodeManager::getComponentForEntity(entityRef);
glm::vec3& forward = _forward(campCompRef);
glm::vec3& up = _up(campCompRef);
glm::vec3& camWorldPosition =
Components::NodeManager::_worldPosition(nodeCompRef);
forward = Components::NodeManager::_worldOrientation(nodeCompRef) *
glm::vec3(0.0f, 0.0f, 1.0f);
up = Components::NodeManager::_worldOrientation(nodeCompRef) *
glm::vec3(0.0f, 1.0f, 0.0f);
_prevViewMatrix(campCompRef) = _viewMatrix(campCompRef);
_viewMatrix(campCompRef) =
glm::lookAt(camWorldPosition, camWorldPosition + forward, up);
_projectionMatrix(campCompRef) = computeCustomProjMatrix(
campCompRef, _descNearPlane(campCompRef), _descFarPlane(campCompRef));
Resources::FrustumManager::_descNearFarPlaneDistances(
_frustum(campCompRef)) =
glm::vec2(_descNearPlane(campCompRef), _descFarPlane(campCompRef));
Resources::FrustumManager::_descProjectionType(_frustum(campCompRef)) =
Resources::ProjectionType::kPerspective;
}
}
// <-
glm::mat4 CameraManager::computeCustomProjMatrix(CameraRef p_Ref, float p_Near,
float p_Far)
{
const float aspectRatio = R::RenderSystem::_backbufferDimensions.x /
(float)R::RenderSystem::_backbufferDimensions.y;
return glm::scale(glm::vec3(1.0f, -1.0f, 1.0f)) *
glm::perspective(_descFov(p_Ref), aspectRatio, p_Near, p_Far);
}
}
}
}
|
apache-2.0
|
abuabdul/FourT
|
src/main/java/com/abuabdul/fourt/domain/Resource.java
|
2875
|
/*
* Copyright 2013-2016 abuabdul.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.abuabdul.fourt.domain;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* @author abuabdul
*
*/
@Entity
@Table(name = "RESOURCE")
public class Resource {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID")
private Long id;
@Column(name = "NAME", length = 50, nullable = false)
private String name;
@Column(name = "TASK_DATE", nullable = false)
private Date taskDate;
@Column(name = "CREATED_DATE", nullable = false)
private Date createdDate;
@Column(name = "CREATED_BY", length = 50, nullable = false)
private String createdBy;
@Column(name = "UPDATED_DATE", nullable = false)
private Date updatedDate;
@Column(name = "UPDATED_BY", length = 50, nullable = false)
private String updatedBy;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "resource")
private List<TaskDetail> taskDetailList;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getTaskDate() {
return taskDate;
}
public void setTaskDate(Date taskDate) {
this.taskDate = taskDate;
}
public List<TaskDetail> getTaskDetailList() {
return taskDetailList;
}
public void setTaskDetailList(List<TaskDetail> taskDetailList) {
this.taskDetailList = taskDetailList;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public Date getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(Date updatedDate) {
this.updatedDate = updatedDate;
}
public String getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
}
|
apache-2.0
|
McLeodMoores/starling
|
projects/financial/src/main/java/com/opengamma/financial/analytics/model/pnl/HistoricalValuationPnLFunction.java
|
9838
|
/**
* Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.model.pnl;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.schedule.ScheduleCalculatorFactory;
import com.opengamma.analytics.financial.schedule.TimeSeriesSamplingFunctionFactory;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.function.AbstractFunction;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.target.ComputationTargetType;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.financial.analytics.timeseries.DateConstraint;
import com.opengamma.financial.analytics.timeseries.HistoricalTimeSeriesFunctionUtils;
import com.opengamma.financial.analytics.timeseries.HistoricalValuationFunction;
import com.opengamma.financial.security.FinancialSecurityUtils;
import com.opengamma.timeseries.date.DateDoubleTimeSeries;
import com.opengamma.timeseries.date.localdate.ImmutableLocalDateDoubleTimeSeries;
import com.opengamma.timeseries.date.localdate.LocalDateDoubleTimeSeries;
import com.opengamma.util.async.AsynchronousExecution;
import com.opengamma.util.money.Currency;
/**
* Calculates a PnL series by performing a full historical valuation over the required period.
*/
public class HistoricalValuationPnLFunction extends AbstractFunction.NonCompiledInvoker {
@Override
public ComputationTargetType getTargetType() {
return ComputationTargetType.POSITION;
}
@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) {
return ImmutableSet.of(new ValueSpecification(ValueRequirementNames.PNL_SERIES, target.toSpecification(), ValueProperties.all()));
}
@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) {
final ValueProperties outputConstraints = desiredValue.getConstraints();
final Set<String> startDates = desiredValue.getConstraints().getValues(HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY);
if (startDates == null || startDates.size() != 1) {
return null;
}
final Set<String> endDates = desiredValue.getConstraints().getValues(HistoricalTimeSeriesFunctionUtils.END_DATE_PROPERTY);
if (endDates == null || endDates.size() != 1) {
return null;
}
Set<String> desiredCurrencies = desiredValue.getConstraints().getValues(ValuePropertyNames.CURRENCY);
if (desiredCurrencies == null || desiredCurrencies.isEmpty()) {
final Collection<Currency> targetCurrencies = FinancialSecurityUtils.getCurrencies(target.getPosition().getSecurity(), context.getSecuritySource());
// REVIEW jonathan 2013-03-12 -- should we pass through all the currencies and see what it wants to produce?
desiredCurrencies = ImmutableSet.of(Iterables.get(targetCurrencies, 0).getCode());
}
final String pnlSeriesStartDateProperty = ValueRequirementNames.PNL_SERIES + "_" + HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY;
final ValueProperties.Builder requirementConstraints = desiredValue.getConstraints().copy()
.withoutAny(ValuePropertyNames.CURRENCY)
.with(HistoricalValuationFunction.PASSTHROUGH_PREFIX + ValuePropertyNames.CURRENCY, desiredCurrencies)
.withoutAny(ValuePropertyNames.PROPERTY_PNL_CONTRIBUTIONS)
.withoutAny(ValuePropertyNames.SCHEDULE_CALCULATOR)
.withoutAny(ValuePropertyNames.SAMPLING_FUNCTION)
.withoutAny(HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY)
.with(pnlSeriesStartDateProperty, outputConstraints.getValues(HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY))
.withOptional(pnlSeriesStartDateProperty);
final String startDate = getPriceSeriesStart(outputConstraints);
if (startDate == null) {
return null;
}
requirementConstraints.with(HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY, startDate);
removeTransformationProperties(requirementConstraints);
return ImmutableSet.of(new ValueRequirement(ValueRequirementNames.HISTORICAL_TIME_SERIES, target.toSpecification(), requirementConstraints.get()));
}
@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target,
final Map<ValueSpecification, ValueRequirement> inputs) {
final Entry<ValueSpecification, ValueRequirement> tsInput = Iterables.getOnlyElement(inputs.entrySet());
final ValueSpecification tsSpec = tsInput.getKey();
final String pnlStartDate = tsInput.getValue()
.getConstraint(ValueRequirementNames.PNL_SERIES + "_" + HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY);
final ValueSpecification valueSpec = getResultSpec(target, tsSpec.getProperties(), pnlStartDate, null);
return ImmutableSet.of(valueSpec);
}
@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target,
final Set<ValueRequirement> desiredValues) throws AsynchronousExecution {
final ValueRequirement desiredValue = Iterables.getOnlyElement(desiredValues);
final ComputedValue priceTsComputedValue = inputs.getComputedValue(ValueRequirementNames.HISTORICAL_TIME_SERIES);
final LocalDateDoubleTimeSeries priceTs = (LocalDateDoubleTimeSeries) priceTsComputedValue.getValue();
if (priceTs.isEmpty()) {
return null;
}
final DateDoubleTimeSeries<?> pnlTs = calculatePnlSeries(priceTs, executionContext, desiredValue);
final String pnlStartDate = desiredValue.getConstraint(HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY);
final ValueSpecification valueSpec = getResultSpec(target, priceTsComputedValue.getSpecification().getProperties(), pnlStartDate, desiredValue);
return ImmutableSet.of(new ComputedValue(valueSpec, pnlTs));
}
// -------------------------------------------------------------------------
protected String getPriceSeriesStart(final ValueProperties outputConstraints) {
final Set<String> samplingPeriodValues = outputConstraints.getValues(ValuePropertyNames.SAMPLING_PERIOD);
if (samplingPeriodValues != null && !samplingPeriodValues.isEmpty()) {
return DateConstraint.VALUATION_TIME.minus(samplingPeriodValues.iterator().next()).toString();
}
final Set<String> startDates = outputConstraints.getValues(HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY);
if (startDates != null && !startDates.isEmpty()) {
return Iterables.getOnlyElement(startDates);
}
return null;
}
protected void removeTransformationProperties(final ValueProperties.Builder builder) {
builder.withoutAny(ValuePropertyNames.TRANSFORMATION_METHOD);
}
protected void addTransformationProperties(final ValueProperties.Builder builder, final ValueRequirement desiredValue) {
builder.with(ValuePropertyNames.TRANSFORMATION_METHOD, "None");
}
protected DateDoubleTimeSeries<?> calculatePnlSeries(final LocalDateDoubleTimeSeries priceSeries, final FunctionExecutionContext executionContext,
final ValueRequirement desiredValue) {
final int pnlVectorSize = priceSeries.size() - 1;
final double[] pnlValues = new double[pnlVectorSize];
for (int i = 0; i < pnlVectorSize; i++) {
pnlValues[i] = priceSeries.getValueAtIndex(i + 1) - priceSeries.getValueAtIndex(i);
}
final int[] pnlDates = new int[priceSeries.size() - 1];
System.arraycopy(priceSeries.timesArrayFast(), 1, pnlDates, 0, pnlDates.length);
final LocalDateDoubleTimeSeries pnlTs = ImmutableLocalDateDoubleTimeSeries.of(pnlDates, pnlValues);
return pnlTs;
}
// -------------------------------------------------------------------------
private ValueSpecification getResultSpec(final ComputationTarget target, final ValueProperties priceTsProperties, final String pnlStartDate,
final ValueRequirement desiredValue) {
final Set<String> currencies = priceTsProperties.getValues(HistoricalValuationFunction.PASSTHROUGH_PREFIX + ValuePropertyNames.CURRENCY);
if (currencies == null || currencies.size() != 1) {
throw new OpenGammaRuntimeException("Expected a single currency for historical valuation series but got " + currencies);
}
final ValueProperties.Builder builder = priceTsProperties.copy()
.withoutAny(ValuePropertyNames.FUNCTION)
.with(ValuePropertyNames.FUNCTION, getUniqueId())
.with(ValuePropertyNames.CURRENCY, currencies)
.with(ValuePropertyNames.PROPERTY_PNL_CONTRIBUTIONS, "Full")
.withoutAny(HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY)
.with(HistoricalTimeSeriesFunctionUtils.START_DATE_PROPERTY, pnlStartDate)
.with(ValuePropertyNames.SCHEDULE_CALCULATOR, ScheduleCalculatorFactory.DAILY)
.with(ValuePropertyNames.SAMPLING_FUNCTION, TimeSeriesSamplingFunctionFactory.NO_PADDING);
addTransformationProperties(builder, desiredValue);
return new ValueSpecification(ValueRequirementNames.PNL_SERIES, target.toSpecification(), builder.get());
}
}
|
apache-2.0
|
marshall/titanium
|
modules/ti.UI/ui_binding.cpp
|
9827
|
/**
* Appcelerator Titanium - licensed under the Apache Public License 2
* see LICENSE in the root folder for details on the license.
* Copyright (c) 2009 Appcelerator, Inc. All Rights Reserved.
*/
#include "ui_module.h"
#include <string>
#define GET_ARG_OR_RETURN(INDEX, TYPE, VAR) \
if ((int) args.size() < INDEX - 1 || !args.at(INDEX)->Is##TYPE()) \
return; \
VAR = args.at(INDEX)->To##TYPE();
#define GET_ARG(INDEX, TYPE, VAR) \
if ((int) args.size() > INDEX && args.at(INDEX)->Is##TYPE()) \
VAR = args.at(INDEX)->To##TYPE();
namespace ti
{
UIBinding* UIBinding::instance = NULL;
UIBinding::UIBinding(Host *host) : host(host)
{
instance = this;
/**
* @tiapi(method=True,name=UI.createMenu,version=0.2) Creates a MenuItem object
* @tiresult(for=UI.createMenu,type=object) a MenuItem object
*/
this->SetMethod("createMenu", &UIBinding::_CreateMenu);
/**
* @tiapi(method=True,name=UI.createTrayMenu,version=0.2) Creates a TrayItem object
* @tiresult(for=UI.createTrayMenu,type=object) a TrayItem object
*/
this->SetMethod("createTrayMenu", &UIBinding::_CreateTrayMenu);
/**
* @tiapi(method=True,name=UI.setMenu,version=0.2) Sets a menu for the application
* @tiarg(for=UI.setMenu,type=object,name=menu) a MenuItem object or null to unset
*/
this->SetMethod("setMenu", &UIBinding::_SetMenu);
/**
* @tiapi(method=True,name=UI.getMenu,version=0.2) Returns the application's main MenuItem
* @tiresult(for=UI.getMenu,type=object) the application's main MenuItem
*/
this->SetMethod("getMenu", &UIBinding::_GetMenu);
/**
* @tiapi(method=True,name=UI.setContextMenu,version=0.2) Sets the application's context menu
* @tiarg(for=UI.setContextMenu,type=object,name=menu) a MenuItem object or null to unset
*/
this->SetMethod("setContextMenu", &UIBinding::_SetContextMenu);
/**
* @tiapi(method=True,name=UI.getContextMenu,version=0.2) Returns the application context menu
* @tiresult(for=UI.getContextMenu,type=object) the application's context MenuItem object
*/
this->SetMethod("getContextMenu", &UIBinding::_GetContextMenu);
/**
* @tiapi(method=True,name=UI.setIcon,version=0.2) Sets the application's icon
* @tiarg(for=UI.setIcon,type=object,name=menu) path to the icon
*/
this->SetMethod("setIcon", &UIBinding::_SetIcon);
/**
* @tiapi(method=True,name=UI.addTray,version=0.2) Adds a tray menu
* @tiarg(for=UI.addTray,type=object,name=menu) a TrayItem to add
*/
this->SetMethod("addTray", &UIBinding::_AddTray);
/**
* @tiapi(method=True,name=UI.clearTray,version=0.2) Removes a tray menu
*/
this->SetMethod("clearTray", &UIBinding::_ClearTray);
/**
* @tiapi(method=True,name=UI.setDockIcon,version=0.2) Sets the dock icon
* @tiarg(for=UI.setDockIcon,type=string,name=icon) path to the icon
*/
this->SetMethod("setDockIcon", &UIBinding::_SetDockIcon);
/**
* @tiapi(method=True,name=UI.setDockMenu,version=0.2) Sets the dock menu
* @tiarg(for=UI.setDockMenu,type=object,name=menu) a MenuItem object
*/
this->SetMethod("setDockMenu", &UIBinding::_SetDockMenu);
/**
* @tiapi(method=True,name=UI.setBadge,version=0.2) Sets the application's badge value
* @tiarg(for=UI.setBadge,type=string,name=badge) badge value
*/
this->SetMethod("setBadge", &UIBinding::_SetBadge);
/**
* @tiapi(method=True,name=UI.setBadgeImage,version=0.2) Sets the application's badge image
* @tiarg(for=UI.setBadge,type=string,name=badge_image) path to badge image
*/
this->SetMethod("setBadgeImage", &UIBinding::_SetBadgeImage);
/**
* @tiapi(method=True,name=UI.getIdleTime,version=0.2) Returns the user's idle time (for the machine, not just the application)
* @tiresult(for=UI.getIdleTime,type=double) the idle time as a double
*/
this->SetMethod("getIdleTime", &UIBinding::_GetIdleTime);
this->openWindowList = new StaticBoundList();
/**
* @tiapi(method=True,name=UI.getOpenWindows,version=0.4) Returns the list of currently open windows
* @tiresult(for=UI.getOpenWindows,type=list) the list of open windows
*/
this->SetMethod("getOpenWindows", &UIBinding::_GetOpenWindows);
/**
* @tiapi(property=True,name=UI.windows,version=0.2) Returns a list of open user created windows
* @tideprecated(for=UI.windows,version=0.4)
*/
this->Set("windows", Value::NewList(this->openWindowList));
SharedKObject global = host->GetGlobalObject();
SharedValue ui_binding_val = Value::NewObject(this);
global->Set("UI", ui_binding_val);
}
void UIBinding::CreateMainWindow(WindowConfig* config)
{
SharedPtr<UserWindow> no_parent = NULL;
SharedUserWindow main_window = this->CreateWindow(config, no_parent);
SharedKObject global = host->GetGlobalObject();
/**
* @tiapi(property=True,name=UI.mainWindow) Returns the main window
*/
global->SetNS("UI.mainWindow", Value::NewObject(main_window));
main_window->Open();
}
void UIBinding::ErrorDialog(std::string msg)
{
std::cerr << msg << std::endl;
}
UIBinding::~UIBinding()
{
}
Host* UIBinding::GetHost()
{
return host;
}
std::vector<SharedUserWindow>& UIBinding::GetOpenWindows()
{
return this->openWindows;
}
void UIBinding::AddToOpenWindows(SharedUserWindow window)
{
this->openWindowList->Append(Value::NewObject(window));
this->openWindows.push_back(window);
}
void UIBinding::RemoveFromOpenWindows(SharedUserWindow window)
{
static Logger* logger = Logger::Get("UI");
std::vector<SharedUserWindow>::iterator w = openWindows.begin();
while (w != openWindows.end())
{
if ((*w).get() == window.get())
{
w = this->openWindows.erase(w);
return;
}
else
{
w++;
}
}
logger->Warn("Tried to remove a non-existant window: 0x%lx", (long int) window.get());
}
void UIBinding::_GetOpenWindows(const ValueList& args, SharedValue result)
{
result->SetList(this->openWindowList);
}
void UIBinding::_CreateMenu(const ValueList& args, SharedValue result)
{
SharedPtr<MenuItem> menu = this->CreateMenu(false);
result->SetList(menu);
}
void UIBinding::_CreateTrayMenu(const ValueList& args, SharedValue result)
{
SharedPtr<MenuItem> menu = this->CreateMenu(true);
result->SetList(menu);
}
void UIBinding::_SetMenu(const ValueList& args, SharedValue result)
{
SharedPtr<MenuItem> menu = NULL; // A NULL value is an unset
if (args.size() > 0 && args.at(0)->IsList())
{
menu = args.at(0)->ToList().cast<MenuItem>();
}
UIModule::SetMenu(menu);
this->SetMenu(menu);
}
void UIBinding::_GetMenu(const ValueList& args, SharedValue result)
{
SharedPtr<MenuItem> menu = UIModule::GetMenu();
if (menu.get() != NULL)
{
SharedKList list = menu;
result->SetList(list);
}
else
{
result->SetUndefined();
}
}
void UIBinding::_SetContextMenu(const ValueList& args, SharedValue result)
{
SharedPtr<MenuItem> menu = NULL; // A NULL value is an unset
if (args.size() > 0 && args.at(0)->IsList())
{
menu = args.at(0)->ToList().cast<MenuItem>();
}
UIModule::SetContextMenu(menu);
this->SetContextMenu(menu);
}
void UIBinding::_GetContextMenu(const ValueList& args, SharedValue result)
{
SharedPtr<MenuItem> menu = UIModule::GetContextMenu();
if (menu.get() != NULL)
{
SharedKList list = menu;
result->SetList(list);
}
else
{
result->SetUndefined();
}
}
void UIBinding::_SetIcon(const ValueList& args, SharedValue result)
{
SharedString icon_path = NULL; // a NULL value is an unset
if (args.size() > 0 && args.at(0)->IsString())
{
const char *icon_url = args.at(0)->ToString();
icon_path = UIModule::GetResourcePath(icon_url);
}
UIModule::SetIcon(icon_path);
this->SetIcon(icon_path);
}
void UIBinding::_AddTray(const ValueList& args, SharedValue result)
{
const char *icon_url;
GET_ARG_OR_RETURN(0, String, icon_url);
SharedString icon_path = UIModule::GetResourcePath(icon_url);
if (icon_path.isNull())
return;
SharedKMethod cb = SharedKMethod(NULL);
GET_ARG(1, Method, cb);
SharedPtr<TrayItem> item = this->AddTray(icon_path, cb);
UIModule::AddTrayItem(item);
result->SetObject(item);
}
void UIBinding::_ClearTray(const ValueList& args, SharedValue result)
{
UIModule::ClearTrayItems();
}
void UIBinding::_SetDockIcon(const ValueList& args, SharedValue result)
{
SharedString icon_path = NULL; // a NULL value is an unset
if (args.size() > 0 && args.at(0)->IsString())
{
const char *icon_url = args.at(0)->ToString();
icon_path = UIModule::GetResourcePath(icon_url);
}
this->SetDockIcon(icon_path);
}
void UIBinding::_SetDockMenu(const ValueList& args, SharedValue result)
{
SharedPtr<MenuItem> menu = NULL; // A NULL value is an unset
if (args.size() > 0 && args.at(0)->IsList())
{
menu = args.at(0)->ToList().cast<MenuItem>();
}
this->SetDockMenu(menu);
}
void UIBinding::_SetBadge(const ValueList& args, SharedValue result)
{
// badges are just labels right now
// we might want to support custom images too
SharedString badge_path = NULL; // a NULL value is an unset
if (args.size() > 0 && args.at(0)->IsString())
{
const char *badge_url = args.at(0)->ToString();
if (badge_url!=NULL)
{
badge_path = SharedString(new std::string(badge_url));
}
}
this->SetBadge(badge_path);
}
void UIBinding::_SetBadgeImage(const ValueList& args, SharedValue result)
{
SharedString image_path = NULL; // a NULL value is an unset
if (args.size() > 0 && args.at(0)->IsString())
{
const char *image_url = args.at(0)->ToString();
if (image_url!=NULL)
{
image_path = UIModule::GetResourcePath(image_url);
}
}
this->SetBadgeImage(image_path);
}
void UIBinding::_GetIdleTime(
const ValueList& args,
SharedValue result)
{
result->SetDouble(this->GetIdleTime());
}
}
|
apache-2.0
|
splink/pagelets-seed
|
app/controllers/HomeController.scala
|
5985
|
package controllers
import javax.inject._
import akka.stream.Materializer
import org.splink.pagelets._
import org.splink.pagelets.twirl.TwirlCombiners._
import play.api.data.Forms._
import play.api.data._
import play.api.i18n.{I18nSupport, Lang, Messages}
import play.api.mvc._
import play.api.{Configuration, Environment}
import service.{CarouselService, TeaserService, TextblockService}
import views.html.{error, wrapper}
/**
* A controller which shows Pagelets in async mode. Async mode renders everything on the server
* side before the complete page is actually sent to the client.
*/
@Singleton
class HomeController @Inject()(pagelets: Pagelets,
teaserService: TeaserService,
carouselService: CarouselService,
textblockService: TextblockService)(
implicit m: Materializer,
e: Environment,
conf: Configuration) extends InjectedController with I18nSupport {
val log = play.api.Logger(getClass).logger
implicit lazy val executionContext = defaultExecutionContext
import pagelets._
val supportedLanguages = conf.get[Seq[String]]("play.i18n.langs")
implicit def request2lang(implicit r: RequestHeader) = messagesApi.preferred(r).lang
// the page configuration
def tree(r: RequestHeader) = {
//make the request implicitly available to the sections combiner template
implicit val request: RequestHeader = r
val tree = Tree("home".id, Seq(
Leaf("header".id, () => header).
withJavascript(
Javascript("lib/bootstrap/js/dropdown.min.js"),
Javascript("lib/bootstrap/js/alert.min.js")
).withMetaTags(
MetaTag("description", Messages("metaTags.description"))
// the header is mandatory. If it fails, the user is redirected to an error page @see the index Action
).setMandatory(true),
Tree("content".id, Seq(
Leaf("carousel".id, () => carousel).
// the carousel pagelet depends on specific Javascripts
withJavascript(
Javascript("lib/bootstrap/js/transition.min.js"),
Javascript("lib/bootstrap/js/carousel.min.js")).
withFallback(fallback("Carousel") _),
// if the text pagelet fails, the fallback pagelet is rendered, if no fallback is defined, the pagelet is left out
Leaf("text".id, () => text).withFallback(fallback("Text") _),
Tree("teasers".id, Seq(
Leaf("teaserA".id, teaser("A") _),
Leaf("teaserB".id, teaser("B") _),
Leaf("teaserC".id, teaser("C") _),
Leaf("teaserD".id, teaser("D") _)
), results =>
// the usage of a combine template, which allows to control how the child pagelets are put together
combine(results)(views.html.pagelets.teasers.apply))
)),
Leaf("footer".id, () => footer).withCss(
// the footer pagelet depends on specific Javascripts
Css("stylesheets/footer.min.css")
)
), results =>
combine(results)(views.html.pagelets.sections.apply))
// output a different for users who prefer to view the page in german
request2lang.language match {
case "de" => tree.skip("text".id)
case _ => tree
}
}
def mainTemplate(implicit r: RequestHeader) = wrapper(routes.HomeController.resourceFor) _
val onError = routes.HomeController.errorPage
// action to send a combined resource (that is Javascript or Css) for a fingerprint
def resourceFor(fingerprint: String) = ResourceAction(fingerprint)
// the main Action which triggers the rendering of the page according to the tree
def index = PageAction.async(onError)(implicit r => Messages("title"), tree) { (request, page) =>
// uncomment to log a visualization of the tree
//log.info("\n" + visualize(tree(request)))
mainTemplate(request)(page)
}
// in case a mandatory pagelet produces an error, the user is redirected to the error page
def errorPage = Action { implicit request =>
val language = request.cookies.get(messagesApi.langCookieName).
map(_.value).getOrElse(supportedLanguages.head)
InternalServerError(error(language))
}
// render any part of the page tree. For instance just the footer, or the whole content
def pagelet(id: PageletId) = PageletAction.async(onError)(tree, id) { (request, page) =>
mainTemplate(request)(page)
}
val langForm = Form(single("language" -> nonEmptyText))
def changeLanguage = Action { implicit request =>
val target = request.headers.get(REFERER).getOrElse(routes.HomeController.index.path)
langForm.bindFromRequest().fold(
_ => BadRequest,
lang =>
if (supportedLanguages.contains(lang))
Redirect(target).
withLang(Lang(lang)).
flashing(Flash(Map("success" -> Messages("language.change.flash", Messages(lang)))))
else BadRequest
)
}
def header = Action { implicit request =>
Ok(views.html.pagelets.header())
}
// a pagelet is just a simple Play Action
def carousel = Action.async { implicit request =>
carouselService.carousel.map { teasers =>
Ok(views.html.pagelets.carousel(teasers)).
withCookies(Cookie("carouselCookie", "carouselValue"))
}
}
def teaser(typ: String)() = Action.async { implicit request =>
teaserService.teaser(typ).map { teaser =>
Ok(views.html.pagelets.teaser(teaser))
}.recover { case _ =>
Ok(views.html.pagelets.fallback(typ, "col-md-3"))
}
}
def text = Action.async { implicit request =>
textblockService.text.map { text =>
Ok(views.html.pagelets.text(text)).
withCookies(Cookie("textCookie", "textValue"))
}
}
def footer = Action { implicit request =>
Ok(views.html.pagelets.footer())
}
def fallback(name: String)() = Action {
Ok(views.html.pagelets.fallback(name, "col-md-12"))
}
}
|
apache-2.0
|
MICommunity/psi-jami
|
jami-core/src/main/java/psidev/psi/mi/jami/listener/PolymerChangeListener.java
|
749
|
package psidev.psi.mi.jami.listener;
import psidev.psi.mi.jami.model.Polymer;
/**
* Listener for changes in polymer
*
* @author Marine Dumousseau (marine@ebi.ac.uk)
* @version $Id$
* @since <pre>30/01/14</pre>
*/
public interface PolymerChangeListener<P extends Polymer> extends InteractorChangeListener<P> {
/**
* Listen to the event where the sequence of a protein has been changed.
* If oldSequence is null, it means that the sequence has been initialised.
* If the sequence of the protein is null, it means that the sequence of the protein has been reset
*
* @param protein : updated polymer
* @param oldSequence : old sequence
*/
public void onSequenceUpdate(P protein, String oldSequence);
}
|
apache-2.0
|
chbe89/mindstormer
|
src/edu/kit/mindstormer/program/AbstractProgram.java
|
642
|
package edu.kit.mindstormer.program;
public abstract class AbstractProgram implements Program {
private final String name;
protected AbstractProgram() {
this.name = this.getClass().getSimpleName();
}
protected AbstractProgram(String name) {
this.name = name;
}
@Override
public void initialize() {
quit.set(false);
}
@Override
public abstract void run();
public void startProgram() {
initialize();
run();
}
@Override
public final String getName() {
return name;
}
@Override
public void terminate() {
quit.set(true);
}
@Override
public String toString() {
return "Program [" + name + "]";
}
}
|
apache-2.0
|
nafae/developer
|
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201406/video/ReportErrorReason.java
|
1516
|
package com.google.api.ads.adwords.jaxws.v201406.video;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ReportError.Reason.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="ReportError.Reason">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="UNKNOWN"/>
* <enumeration value="CRITERIA_TYPE_NOT_SUPPORTED"/>
* <enumeration value="INVALID_TARGETING_GROUP_ID_COUNT"/>
* <enumeration value="NO_STATS_SELECTOR"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "ReportError.Reason")
@XmlEnum
public enum ReportErrorReason {
/**
*
* Default error.
*
*
*/
UNKNOWN,
/**
*
* Unsupported criteria type bundle.
*
*
*/
CRITERIA_TYPE_NOT_SUPPORTED,
/**
*
* Reporting at targeting group level requires exactly one targeting group.
*
*
*/
INVALID_TARGETING_GROUP_ID_COUNT,
/**
*
* Stats selector is required for reporting.
*
*
*/
NO_STATS_SELECTOR;
public String value() {
return name();
}
public static ReportErrorReason fromValue(String v) {
return valueOf(v);
}
}
|
apache-2.0
|
NationalSecurityAgency/ghidra
|
Ghidra/Features/Base/src/test/java/ghidra/program/database/RealProgramMTFModel.java
|
5594
|
/* ###
* IP: GHIDRA
* REVIEWED: YES
*
* 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 ghidra.program.database;
import ghidra.test.TestEnv;
import ghidra.util.TestUniversalIdGenerator;
import ghidra.util.exception.AssertException;
/**
* The non-preferred way of configuring tests for merge testing, which is to use real
* programs that are files on disk. You should try to use the
* {@link InMemoryProgramMTFModel} by using
* {@link MergeTestFacilitator#initialize(String, MergeProgramModifier)} when writing
* merge tests.
*/
// TODO rename--this is no longer using real programs
public class RealProgramMTFModel extends AbstractMTFModel {
/**
* We install our test ID generator to ensure that all datatypes we create will share the
* same ID across all versions of the programs we create. If we do not do this, then they will
* be different, which breaks many tests.
*/
private TestUniversalIdGenerator universalIdGenerator = new TestUniversalIdGenerator();
RealProgramMTFModel(TestEnv env) {
super(env);
}
@Override
public void initialize(String programName, ProgramModifierListener modifier) throws Exception {
cleanup();
MergeProgramGenerator programGenerator = createProgramGenerator(programName);
generatePrograms(programName, programGenerator);
disableAutoAnalysis();
makeIncomingChanges(modifier);
makeLocalChanges(modifier);
recordChanges();
clearChanges();
}
@Override
public void initialize(String programName, OriginalProgramModifierListener modifier)
throws Exception {
cleanup();
MergeProgramGenerator programGenerator = createProgramGenerator(programName);
generatePrograms(programName, programGenerator);
disableAutoAnalysis();
createCustomStartingProgram(modifier);
clearChanges();
makeIncomingChanges(modifier);
makeLocalChanges(modifier);
recordChanges();
clearChanges();
}
/**
* Tests that use this method are creating a new 'original' program, rather than using
* a pre-fabricated one from a program builder.
*/
private void createCustomStartingProgram(OriginalProgramModifierListener modifier)
throws Exception {
universalIdGenerator.checkpoint();
modifier.modifyOriginal(originalProgram);
universalIdGenerator.restore();
modifier.modifyOriginal(privateProgram);
universalIdGenerator.restore();
modifier.modifyOriginal(latestProgram);
universalIdGenerator.restore();
modifier.modifyOriginal(resultProgram);
}
private MergeProgramGenerator createProgramGenerator(String programName) {
if (programName.toLowerCase().contains("notepad")) {
return new MergeProgramGenerator_Notepads(this);
}
else if (programName.toLowerCase().contains("calc")) {
return new MergeProgramGenerator_Calcs(this);
}
else if (programName.toLowerCase().contains("difftest")) {
return new MergeProgramGenerator_DiffTestPrograms(this);
}
else if (programName.toLowerCase().contains("r4000")) {
return new MergeProgramGenerator_Mips(this);
}
else if (programName.toLowerCase().contains("wallace")) {
return new MergeProgramGenerator_Wallace(this);
}
throw new AssertException("Add new program generator for program: " + programName);
}
@Override
public void initialize(String programName, MergeProgramModifier modifier) {
throw new UnsupportedOperationException();
}
private void disableAutoAnalysis() {
disableAutoAnalysis(privateProgram);
disableAutoAnalysis(resultProgram);
disableAutoAnalysis(latestProgram);
}
private void makeLocalChanges(ProgramModifierListener modifier) throws Exception {
modifier.modifyPrivate(privateProgram);
}
private void makeIncomingChanges(ProgramModifierListener modifier) throws Exception {
universalIdGenerator.checkpoint();
modifier.modifyLatest(latestProgram);
universalIdGenerator.restore();
modifier.modifyLatest(resultProgram);
}
private void generatePrograms(String programName, MergeProgramGenerator programGenerator)
throws Exception {
universalIdGenerator.checkpoint();
privateProgram = programGenerator.generateProgram(programName);
universalIdGenerator.restore();
originalProgram = programGenerator.generateProgram(programName);
universalIdGenerator.restore();
resultProgram = programGenerator.generateProgram(programName);
universalIdGenerator.restore();
latestProgram = programGenerator.generateProgram(programName);
}
private void recordChanges() {
// ...keep track of the changes we've made
latestChangeSet = latestProgram.getChanges();
privateChangeSet = privateProgram.getChanges();
}
private void clearChanges() {
// trick each program to think that it hasn't been changed so that the merge process
// ignores all the work done so far
latestProgram.setChangeSet(new ProgramDBChangeSet(resultProgram.getAddressMap(), 20));
resultProgram.setChangeSet(new ProgramDBChangeSet(resultProgram.getAddressMap(), 20));
privateProgram.setChangeSet(new ProgramDBChangeSet(resultProgram.getAddressMap(), 20));
originalProgram.setChangeSet(new ProgramDBChangeSet(resultProgram.getAddressMap(), 20));
}
}
|
apache-2.0
|
Loofer/BaseNetWork
|
app/src/main/java/org/loofer/retrofit/account/AccountProvider.java
|
565
|
package org.loofer.retrofit.account;
/**
* ============================================================
* 版权: xx有限公司 版权所有(c)2016
* <p>
* 作者:Loofer
* 版本:1.0
* 创建日期 :2017/2/26 11:42.
* 描述:
* <p>
* 注:如果您修改了本类请填写以下内容作为记录,如非本人操作劳烦通知,谢谢!!!
* Modified Date Modify Content:
* <p>
* ==========================================================
*/
public interface AccountProvider {
Account provideAccount(String accountJson);
}
|
apache-2.0
|
crate/crate
|
server/src/testFixtures/java/org/elasticsearch/cluster/ESAllocationTestCase.java
|
11333
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.elasticsearch.cluster;
import static java.util.Collections.emptyMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodeRole;
import org.elasticsearch.cluster.routing.RoutingNode;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.cluster.routing.allocation.allocator.BalancedShardsAllocator;
import org.elasticsearch.cluster.routing.allocation.allocator.ShardsAllocator;
import org.elasticsearch.cluster.routing.allocation.decider.AllocationDecider;
import org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders;
import org.elasticsearch.cluster.routing.allocation.decider.Decision;
import org.elasticsearch.cluster.routing.allocation.decider.SameShardAllocationDecider;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.gateway.GatewayAllocator;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.gateway.TestGatewayAllocator;
import static org.elasticsearch.cluster.routing.ShardRoutingState.INITIALIZING;
public abstract class ESAllocationTestCase extends ESTestCase {
private static final ClusterSettings EMPTY_CLUSTER_SETTINGS =
new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS);
public static MockAllocationService createAllocationService() {
return createAllocationService(Settings.Builder.EMPTY_SETTINGS);
}
public static MockAllocationService createAllocationService(Settings settings) {
return createAllocationService(settings, random());
}
public static MockAllocationService createAllocationService(Settings settings, Random random) {
return createAllocationService(settings, EMPTY_CLUSTER_SETTINGS, random);
}
public static MockAllocationService createAllocationService(Settings settings, ClusterSettings clusterSettings, Random random) {
return new MockAllocationService(
randomAllocationDeciders(settings, clusterSettings, random),
new TestGatewayAllocator(),
new BalancedShardsAllocator(settings),
EmptyClusterInfoService.INSTANCE);
}
public static AllocationDeciders randomAllocationDeciders(Settings settings, ClusterSettings clusterSettings, Random random) {
List<AllocationDecider> deciders = new ArrayList<>(
ClusterModule.createAllocationDeciders(settings, clusterSettings, Collections.emptyList()));
Collections.shuffle(deciders, random);
return new AllocationDeciders(deciders);
}
protected static Set<DiscoveryNodeRole> MASTER_DATA_ROLES =
Collections.unmodifiableSet(Set.of(DiscoveryNodeRole.MASTER_ROLE, DiscoveryNodeRole.DATA_ROLE));
protected static DiscoveryNode newNode(String nodeId) {
return newNode(nodeId, Version.CURRENT);
}
protected static DiscoveryNode newNode(String nodeName, String nodeId, Map<String, String> attributes) {
return new DiscoveryNode(nodeName, nodeId, buildNewFakeTransportAddress(), attributes, MASTER_DATA_ROLES, Version.CURRENT);
}
protected static DiscoveryNode newNode(String nodeId, Map<String, String> attributes) {
return new DiscoveryNode(nodeId, buildNewFakeTransportAddress(), attributes, MASTER_DATA_ROLES, Version.CURRENT);
}
protected static DiscoveryNode newNode(String nodeId, Set<DiscoveryNodeRole> roles) {
return new DiscoveryNode(nodeId, buildNewFakeTransportAddress(), emptyMap(), roles, Version.CURRENT);
}
protected static DiscoveryNode newNode(String nodeId, Version version) {
return new DiscoveryNode(nodeId, buildNewFakeTransportAddress(), emptyMap(), MASTER_DATA_ROLES, version);
}
protected static ClusterState startRandomInitializingShard(ClusterState clusterState, AllocationService strategy) {
List<ShardRouting> initializingShards = clusterState.getRoutingNodes().shardsWithState(INITIALIZING);
if (initializingShards.isEmpty()) {
return clusterState;
}
return startShardsAndReroute(strategy, clusterState, randomFrom(initializingShards));
}
protected static AllocationDeciders yesAllocationDeciders() {
return new AllocationDeciders(Arrays.asList(
new TestAllocateDecision(Decision.YES),
new SameShardAllocationDecider(
Settings.EMPTY,
new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS)
)
));
}
protected static AllocationDeciders noAllocationDeciders() {
return new AllocationDeciders(Collections.singleton(new TestAllocateDecision(Decision.NO)));
}
protected static AllocationDeciders throttleAllocationDeciders() {
return new AllocationDeciders(Arrays.asList(
new TestAllocateDecision(Decision.THROTTLE),
new SameShardAllocationDecider(
Settings.EMPTY,
new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS)
)
));
}
protected ClusterState applyStartedShardsUntilNoChange(ClusterState clusterState, AllocationService service) {
ClusterState lastClusterState;
do {
lastClusterState = clusterState;
logger.debug("ClusterState: {}", clusterState.getRoutingNodes());
clusterState = startInitializingShardsAndReroute(service, clusterState);
} while (lastClusterState.equals(clusterState) == false);
return clusterState;
}
/**
* Mark all initializing shards as started, then perform a reroute (which may start some other shards initializing).
*
* @return the cluster state after completing the reroute.
*/
public static ClusterState startInitializingShardsAndReroute(AllocationService allocationService, ClusterState clusterState) {
return startShardsAndReroute(allocationService, clusterState, clusterState.routingTable().shardsWithState(INITIALIZING));
}
/**
* Mark all initializing shards on the given node as started, then perform a reroute (which may start some other shards initializing).
*
* @return the cluster state after completing the reroute.
*/
public static ClusterState startInitializingShardsAndReroute(AllocationService allocationService,
ClusterState clusterState,
RoutingNode routingNode) {
return startShardsAndReroute(allocationService, clusterState, routingNode.shardsWithState(INITIALIZING));
}
/**
* Mark all initializing shards for the given index as started, then perform a reroute (which may start some other shards initializing).
*
* @return the cluster state after completing the reroute.
*/
public static ClusterState startInitializingShardsAndReroute(AllocationService allocationService,
ClusterState clusterState,
String index) {
return startShardsAndReroute(allocationService, clusterState,
clusterState.routingTable().index(index).shardsWithState(INITIALIZING));
}
/**
* Mark the given shards as started, then perform a reroute (which may start some other shards initializing).
*
* @return the cluster state after completing the reroute.
*/
public static ClusterState startShardsAndReroute(AllocationService allocationService,
ClusterState clusterState,
ShardRouting... initializingShards) {
return startShardsAndReroute(allocationService, clusterState, Arrays.asList(initializingShards));
}
/**
* Mark the given shards as started, then perform a reroute (which may start some other shards initializing).
*
* @return the cluster state after completing the reroute.
*/
public static ClusterState startShardsAndReroute(AllocationService allocationService,
ClusterState clusterState,
List<ShardRouting> initializingShards) {
return allocationService.reroute(allocationService.applyStartedShards(clusterState, initializingShards), "reroute after starting");
}
public static class TestAllocateDecision extends AllocationDecider {
private final Decision decision;
public TestAllocateDecision(Decision decision) {
this.decision = decision;
}
@Override
public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) {
return decision;
}
@Override
public Decision canAllocate(ShardRouting shardRouting, RoutingAllocation allocation) {
return decision;
}
@Override
public Decision canAllocate(RoutingNode node, RoutingAllocation allocation) {
return decision;
}
}
/** A lock {@link AllocationService} allowing tests to override time */
protected static class MockAllocationService extends AllocationService {
private volatile long nanoTimeOverride = -1L;
public MockAllocationService(AllocationDeciders allocationDeciders,
GatewayAllocator gatewayAllocator,
ShardsAllocator shardsAllocator,
ClusterInfoService clusterInfoService) {
super(allocationDeciders, gatewayAllocator, shardsAllocator, clusterInfoService);
}
public void setNanoTimeOverride(long nanoTime) {
this.nanoTimeOverride = nanoTime;
}
@Override
protected long currentNanoTime() {
return nanoTimeOverride == -1L ? super.currentNanoTime() : nanoTimeOverride;
}
}
}
|
apache-2.0
|
haipn/togoparts
|
src/sg/togoparts/login/Price.java
|
5083
|
package sg.togoparts.login;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import sg.togoparts.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
public class Price extends Activity {
EditText mEdtPrice;
EditText mEdtOriginalPrice;
Spinner mSpnPriceType;
Button mBtnSave;
CheckBox mCbClearance;
int firmNeg;
double price, originalPrice;
boolean clearance;
HashMap<String, Integer> listPricetype;
public boolean mIsPostingPack;
private boolean mIsMerchant;
private ImageButton mBtnBack;
private ImageButton mBtnApply;
private ProgressBar mProgress;
private TextView mTvTitleHeader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.price);
createHeader();
Intent i = getIntent();
mIsPostingPack = i.getBooleanExtra(PostAdActivity.POSTING_PACK, false);
mIsMerchant = i.getBooleanExtra(PostAdActivity.MERCHANT_PACK, false);
DecimalFormat df = new DecimalFormat("###.##");
price = i.getDoubleExtra(PostAdActivity.PRICE, 0);
originalPrice = i.getDoubleExtra(PostAdActivity.ORIGINAL_PRICE, 0);
firmNeg = i.getIntExtra(PostAdActivity.PRICETYPE, 0);
clearance = i.getBooleanExtra(PostAdActivity.CLEARANCE, false);
mEdtOriginalPrice = (EditText) findViewById(R.id.edtOriginalPrice);
mEdtPrice = (EditText) findViewById(R.id.edtPrice);
mSpnPriceType = (Spinner) findViewById(R.id.spnFirmNeg);
mBtnSave = (Button) findViewById(R.id.btnSave);
mCbClearance = (CheckBox) findViewById(R.id.cbClearance);
if (originalPrice != 0)
mEdtOriginalPrice.setText(df.format(originalPrice));
if (price != 0)
mEdtPrice.setText(df.format(price));
mCbClearance.setChecked(clearance);
if (mIsMerchant || mIsPostingPack) {
findViewById(R.id.tvLabelOriginal).setVisibility(View.VISIBLE);
findViewById(R.id.llOriginalPrice).setVisibility(View.VISIBLE);
} else {
findViewById(R.id.tvLabelOriginal).setVisibility(View.GONE);
findViewById(R.id.llOriginalPrice).setVisibility(View.GONE);
}
if (mIsPostingPack)
findViewById(R.id.llClearance).setVisibility(View.VISIBLE);
else
findViewById(R.id.llClearance).setVisibility(View.GONE);
setListValues();
initSpinner();
mBtnSave.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
saveButton();
}
});
}
private void createHeader() {
mBtnBack = (ImageButton) findViewById(R.id.btnBack);
mBtnApply = (ImageButton) findViewById(R.id.btnSearch);
mBtnApply.setBackgroundResource(R.drawable.btn_apply_icon);
mBtnApply.setVisibility(View.VISIBLE);
findViewById(R.id.logo).setVisibility(View.INVISIBLE);
mBtnApply.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
saveButton();
}
});
mProgress = (ProgressBar) findViewById(R.id.progress);
mTvTitleHeader = (TextView) findViewById(R.id.title);
mTvTitleHeader.setVisibility(View.VISIBLE);
mTvTitleHeader.setText(R.string.title_price);
mBtnBack.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
setResult(RESULT_CANCELED);
onBackPressed();
}
});
}
private void initSpinner() {
int i = 0, d = 0;
ArrayAdapter<String> adtPricetype = new ArrayAdapter<String>(this,
R.layout.spinner_text);
Iterator itTranstype = listPricetype.entrySet().iterator();
while (itTranstype.hasNext()) {
Map.Entry pairs = (Map.Entry) itTranstype.next();
adtPricetype.add((String) pairs.getKey());
if (firmNeg == (Integer) pairs.getValue()) {
d = i;
}
i++;
}
adtPricetype
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpnPriceType.setAdapter(adtPricetype);
mSpnPriceType.setSelection(d);
}
private void setListValues() {
listPricetype = new LinkedHashMap<String, Integer>();
listPricetype.put("Do not specify", 3);
listPricetype.put("Firm", 1);
listPricetype.put("Negotiable", 2);
}
private void saveButton() {
Intent i = getIntent();
double price;
if (mEdtPrice.getText().toString().length() > 0)
price = Double.valueOf(mEdtPrice.getText().toString());
else
price = 0;
i.putExtra(PostAdActivity.PRICE, price);
double original;
if (mEdtOriginalPrice.getText().toString().length() > 0)
original = Double.valueOf(mEdtOriginalPrice.getText().toString());
else
original = 0;
i.putExtra(PostAdActivity.ORIGINAL_PRICE, original);
i.putExtra(PostAdActivity.PRICETYPE,
listPricetype.get(mSpnPriceType.getSelectedItem()));
i.putExtra(PostAdActivity.CLEARANCE, mCbClearance.isChecked());
setResult(RESULT_OK, i);
finish();
}
}
|
apache-2.0
|
k82/kubernetes
|
pkg/scheduler/framework/plugins/nodevolumelimits/csi_test.go
|
20039
|
/*
Copyright 2019 The Kubernetes Authors.
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 nodevolumelimits
import (
"context"
"fmt"
"reflect"
"strings"
"testing"
v1 "k8s.io/api/core/v1"
storagev1 "k8s.io/api/storage/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/rand"
"k8s.io/apimachinery/pkg/util/sets"
utilfeature "k8s.io/apiserver/pkg/util/feature"
featuregatetesting "k8s.io/component-base/featuregate/testing"
csitrans "k8s.io/csi-translation-lib"
csilibplugins "k8s.io/csi-translation-lib/plugins"
"k8s.io/kubernetes/pkg/features"
framework "k8s.io/kubernetes/pkg/scheduler/framework/v1alpha1"
fakelisters "k8s.io/kubernetes/pkg/scheduler/listers/fake"
schedulertypes "k8s.io/kubernetes/pkg/scheduler/types"
volumeutil "k8s.io/kubernetes/pkg/volume/util"
utilpointer "k8s.io/utils/pointer"
)
const (
ebsCSIDriverName = csilibplugins.AWSEBSDriverName
gceCSIDriverName = csilibplugins.GCEPDDriverName
hostpathInTreePluginName = "kubernetes.io/hostpath"
)
// getVolumeLimitKey returns a ResourceName by filter type
func getVolumeLimitKey(filterType string) v1.ResourceName {
switch filterType {
case ebsVolumeFilterType:
return v1.ResourceName(volumeutil.EBSVolumeLimitKey)
case gcePDVolumeFilterType:
return v1.ResourceName(volumeutil.GCEVolumeLimitKey)
case azureDiskVolumeFilterType:
return v1.ResourceName(volumeutil.AzureVolumeLimitKey)
case cinderVolumeFilterType:
return v1.ResourceName(volumeutil.CinderVolumeLimitKey)
default:
return v1.ResourceName(volumeutil.GetCSIAttachLimitKey(filterType))
}
}
func TestCSILimits(t *testing.T) {
runningPod := &v1.Pod{
Spec: v1.PodSpec{
Volumes: []v1.Volume{
{
VolumeSource: v1.VolumeSource{
PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
ClaimName: "csi-ebs.csi.aws.com-3",
},
},
},
},
},
}
pendingVolumePod := &v1.Pod{
Spec: v1.PodSpec{
Volumes: []v1.Volume{
{
VolumeSource: v1.VolumeSource{
PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
ClaimName: "csi-4",
},
},
},
},
},
}
// Different pod than pendingVolumePod, but using the same unbound PVC
unboundPVCPod2 := &v1.Pod{
Spec: v1.PodSpec{
Volumes: []v1.Volume{
{
VolumeSource: v1.VolumeSource{
PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
ClaimName: "csi-4",
},
},
},
},
},
}
missingPVPod := &v1.Pod{
Spec: v1.PodSpec{
Volumes: []v1.Volume{
{
VolumeSource: v1.VolumeSource{
PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
ClaimName: "csi-6",
},
},
},
},
},
}
noSCPVCPod := &v1.Pod{
Spec: v1.PodSpec{
Volumes: []v1.Volume{
{
VolumeSource: v1.VolumeSource{
PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
ClaimName: "csi-5",
},
},
},
},
},
}
gceTwoVolPod := &v1.Pod{
Spec: v1.PodSpec{
Volumes: []v1.Volume{
{
VolumeSource: v1.VolumeSource{
PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
ClaimName: "csi-pd.csi.storage.gke.io-1",
},
},
},
{
VolumeSource: v1.VolumeSource{
PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
ClaimName: "csi-pd.csi.storage.gke.io-2",
},
},
},
},
},
}
// In-tree volumes
inTreeOneVolPod := &v1.Pod{
Spec: v1.PodSpec{
Volumes: []v1.Volume{
{
VolumeSource: v1.VolumeSource{
PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
ClaimName: "csi-kubernetes.io/aws-ebs-0",
},
},
},
},
},
}
inTreeTwoVolPod := &v1.Pod{
Spec: v1.PodSpec{
Volumes: []v1.Volume{
{
VolumeSource: v1.VolumeSource{
PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
ClaimName: "csi-kubernetes.io/aws-ebs-1",
},
},
},
{
VolumeSource: v1.VolumeSource{
PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
ClaimName: "csi-kubernetes.io/aws-ebs-2",
},
},
},
},
},
}
// pods with matching csi driver names
csiEBSOneVolPod := &v1.Pod{
Spec: v1.PodSpec{
Volumes: []v1.Volume{
{
VolumeSource: v1.VolumeSource{
PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
ClaimName: "csi-ebs.csi.aws.com-0",
},
},
},
},
},
}
csiEBSTwoVolPod := &v1.Pod{
Spec: v1.PodSpec{
Volumes: []v1.Volume{
{
VolumeSource: v1.VolumeSource{
PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
ClaimName: "csi-ebs.csi.aws.com-1",
},
},
},
{
VolumeSource: v1.VolumeSource{
PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
ClaimName: "csi-ebs.csi.aws.com-2",
},
},
},
},
},
}
inTreeNonMigratableOneVolPod := &v1.Pod{
Spec: v1.PodSpec{
Volumes: []v1.Volume{
{
VolumeSource: v1.VolumeSource{
PersistentVolumeClaim: &v1.PersistentVolumeClaimVolumeSource{
ClaimName: "csi-kubernetes.io/hostpath-0",
},
},
},
},
},
}
tests := []struct {
newPod *v1.Pod
existingPods []*v1.Pod
filterName string
maxVols int
driverNames []string
test string
migrationEnabled bool
limitSource string
wantStatus *framework.Status
}{
{
newPod: csiEBSOneVolPod,
existingPods: []*v1.Pod{runningPod, csiEBSTwoVolPod},
filterName: "csi",
maxVols: 4,
driverNames: []string{ebsCSIDriverName},
test: "fits when node volume limit >= new pods CSI volume",
limitSource: "node",
},
{
newPod: csiEBSOneVolPod,
existingPods: []*v1.Pod{runningPod, csiEBSTwoVolPod},
filterName: "csi",
maxVols: 2,
driverNames: []string{ebsCSIDriverName},
test: "doesn't when node volume limit <= pods CSI volume",
limitSource: "node",
wantStatus: framework.NewStatus(framework.Unschedulable, ErrReasonMaxVolumeCountExceeded),
},
{
newPod: csiEBSOneVolPod,
existingPods: []*v1.Pod{runningPod, csiEBSTwoVolPod},
filterName: "csi",
maxVols: 2,
driverNames: []string{ebsCSIDriverName},
test: "should when driver does not support volume limits",
limitSource: "csinode-with-no-limit",
},
// should count pending PVCs
{
newPod: csiEBSOneVolPod,
existingPods: []*v1.Pod{pendingVolumePod, csiEBSTwoVolPod},
filterName: "csi",
maxVols: 2,
driverNames: []string{ebsCSIDriverName},
test: "count pending PVCs towards volume limit <= pods CSI volume",
limitSource: "node",
wantStatus: framework.NewStatus(framework.Unschedulable, ErrReasonMaxVolumeCountExceeded),
},
// two same pending PVCs should be counted as 1
{
newPod: csiEBSOneVolPod,
existingPods: []*v1.Pod{pendingVolumePod, unboundPVCPod2, csiEBSTwoVolPod},
filterName: "csi",
maxVols: 4,
driverNames: []string{ebsCSIDriverName},
test: "count multiple pending pvcs towards volume limit >= pods CSI volume",
limitSource: "node",
},
// should count PVCs with invalid PV name but valid SC
{
newPod: csiEBSOneVolPod,
existingPods: []*v1.Pod{missingPVPod, csiEBSTwoVolPod},
filterName: "csi",
maxVols: 2,
driverNames: []string{ebsCSIDriverName},
test: "should count PVCs with invalid PV name but valid SC",
limitSource: "node",
wantStatus: framework.NewStatus(framework.Unschedulable, ErrReasonMaxVolumeCountExceeded),
},
// don't count a volume which has storageclass missing
{
newPod: csiEBSOneVolPod,
existingPods: []*v1.Pod{runningPod, noSCPVCPod},
filterName: "csi",
maxVols: 2,
driverNames: []string{ebsCSIDriverName},
test: "don't count pvcs with missing SC towards volume limit",
limitSource: "node",
},
// don't count multiple volume types
{
newPod: csiEBSOneVolPod,
existingPods: []*v1.Pod{gceTwoVolPod, csiEBSTwoVolPod},
filterName: "csi",
maxVols: 2,
driverNames: []string{ebsCSIDriverName, gceCSIDriverName},
test: "count pvcs with the same type towards volume limit",
limitSource: "node",
wantStatus: framework.NewStatus(framework.Unschedulable, ErrReasonMaxVolumeCountExceeded),
},
{
newPod: gceTwoVolPod,
existingPods: []*v1.Pod{csiEBSTwoVolPod, runningPod},
filterName: "csi",
maxVols: 2,
driverNames: []string{ebsCSIDriverName, gceCSIDriverName},
test: "don't count pvcs with different type towards volume limit",
limitSource: "node",
},
// Tests for in-tree volume migration
{
newPod: inTreeOneVolPod,
existingPods: []*v1.Pod{inTreeTwoVolPod},
filterName: "csi",
maxVols: 2,
driverNames: []string{csilibplugins.AWSEBSInTreePluginName, ebsCSIDriverName},
migrationEnabled: true,
limitSource: "csinode",
test: "should count in-tree volumes if migration is enabled",
wantStatus: framework.NewStatus(framework.Unschedulable, ErrReasonMaxVolumeCountExceeded),
},
{
newPod: pendingVolumePod,
existingPods: []*v1.Pod{inTreeTwoVolPod},
filterName: "csi",
maxVols: 2,
driverNames: []string{csilibplugins.AWSEBSInTreePluginName, ebsCSIDriverName},
migrationEnabled: true,
limitSource: "csinode",
test: "should count unbound in-tree volumes if migration is enabled",
wantStatus: framework.NewStatus(framework.Unschedulable, ErrReasonMaxVolumeCountExceeded),
},
{
newPod: inTreeOneVolPod,
existingPods: []*v1.Pod{inTreeTwoVolPod},
filterName: "csi",
maxVols: 2,
driverNames: []string{csilibplugins.AWSEBSInTreePluginName, ebsCSIDriverName},
migrationEnabled: false,
limitSource: "csinode",
test: "should not count in-tree volume if migration is disabled",
},
{
newPod: inTreeOneVolPod,
existingPods: []*v1.Pod{inTreeTwoVolPod},
filterName: "csi",
maxVols: 2,
driverNames: []string{csilibplugins.AWSEBSInTreePluginName, ebsCSIDriverName},
migrationEnabled: true,
limitSource: "csinode-with-no-limit",
test: "should not limit pod if volume used does not report limits",
},
{
newPod: inTreeOneVolPod,
existingPods: []*v1.Pod{inTreeTwoVolPod},
filterName: "csi",
maxVols: 2,
driverNames: []string{csilibplugins.AWSEBSInTreePluginName, ebsCSIDriverName},
migrationEnabled: false,
limitSource: "csinode-with-no-limit",
test: "should not limit in-tree pod if migration is disabled",
},
{
newPod: inTreeNonMigratableOneVolPod,
existingPods: []*v1.Pod{csiEBSTwoVolPod},
filterName: "csi",
maxVols: 2,
driverNames: []string{hostpathInTreePluginName, ebsCSIDriverName},
migrationEnabled: true,
limitSource: "csinode",
test: "should not count non-migratable in-tree volumes",
},
// mixed volumes
{
newPod: inTreeOneVolPod,
existingPods: []*v1.Pod{csiEBSTwoVolPod},
filterName: "csi",
maxVols: 2,
driverNames: []string{csilibplugins.AWSEBSInTreePluginName, ebsCSIDriverName},
migrationEnabled: true,
limitSource: "csinode",
test: "should count in-tree and csi volumes if migration is enabled (when scheduling in-tree volumes)",
wantStatus: framework.NewStatus(framework.Unschedulable, ErrReasonMaxVolumeCountExceeded),
},
{
newPod: csiEBSOneVolPod,
existingPods: []*v1.Pod{inTreeTwoVolPod},
filterName: "csi",
maxVols: 2,
driverNames: []string{csilibplugins.AWSEBSInTreePluginName, ebsCSIDriverName},
migrationEnabled: true,
limitSource: "csinode",
test: "should count in-tree and csi volumes if migration is enabled (when scheduling csi volumes)",
wantStatus: framework.NewStatus(framework.Unschedulable, ErrReasonMaxVolumeCountExceeded),
},
{
newPod: csiEBSOneVolPod,
existingPods: []*v1.Pod{csiEBSTwoVolPod, inTreeTwoVolPod},
filterName: "csi",
maxVols: 3,
driverNames: []string{csilibplugins.AWSEBSInTreePluginName, ebsCSIDriverName},
migrationEnabled: false,
limitSource: "csinode",
test: "should not count in-tree and count csi volumes if migration is disabled (when scheduling csi volumes)",
},
{
newPod: inTreeOneVolPod,
existingPods: []*v1.Pod{csiEBSTwoVolPod},
filterName: "csi",
maxVols: 2,
driverNames: []string{csilibplugins.AWSEBSInTreePluginName, ebsCSIDriverName},
migrationEnabled: false,
limitSource: "csinode",
test: "should not count in-tree and count csi volumes if migration is disabled (when scheduling in-tree volumes)",
},
}
// running attachable predicate tests with feature gate and limit present on nodes
for _, test := range tests {
t.Run(test.test, func(t *testing.T) {
node, csiNode := getNodeWithPodAndVolumeLimits(test.limitSource, test.existingPods, int64(test.maxVols), test.driverNames...)
if test.migrationEnabled {
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.CSIMigration, true)()
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.CSIMigrationAWS, true)()
enableMigrationOnNode(csiNode, csilibplugins.AWSEBSInTreePluginName)
} else {
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.CSIMigration, false)()
defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.CSIMigrationAWS, false)()
}
p := &CSILimits{
csiNodeLister: getFakeCSINodeLister(csiNode),
pvLister: getFakeCSIPVLister(test.filterName, test.driverNames...),
pvcLister: getFakeCSIPVCLister(test.filterName, "csi-sc", test.driverNames...),
scLister: getFakeCSIStorageClassLister("csi-sc", test.driverNames[0]),
randomVolumeIDPrefix: rand.String(32),
translator: csitrans.New(),
}
gotStatus := p.Filter(context.Background(), nil, test.newPod, node)
if !reflect.DeepEqual(gotStatus, test.wantStatus) {
t.Errorf("status does not match: %v, want: %v", gotStatus, test.wantStatus)
}
})
}
}
func getFakeCSIPVLister(volumeName string, driverNames ...string) fakelisters.PersistentVolumeLister {
pvLister := fakelisters.PersistentVolumeLister{}
for _, driver := range driverNames {
for j := 0; j < 4; j++ {
volumeHandle := fmt.Sprintf("%s-%s-%d", volumeName, driver, j)
pv := v1.PersistentVolume{
ObjectMeta: metav1.ObjectMeta{Name: volumeHandle},
Spec: v1.PersistentVolumeSpec{
PersistentVolumeSource: v1.PersistentVolumeSource{
CSI: &v1.CSIPersistentVolumeSource{
Driver: driver,
VolumeHandle: volumeHandle,
},
},
},
}
switch driver {
case csilibplugins.AWSEBSInTreePluginName:
pv.Spec.PersistentVolumeSource = v1.PersistentVolumeSource{
AWSElasticBlockStore: &v1.AWSElasticBlockStoreVolumeSource{
VolumeID: volumeHandle,
},
}
case hostpathInTreePluginName:
pv.Spec.PersistentVolumeSource = v1.PersistentVolumeSource{
HostPath: &v1.HostPathVolumeSource{
Path: "/tmp",
},
}
default:
pv.Spec.PersistentVolumeSource = v1.PersistentVolumeSource{
CSI: &v1.CSIPersistentVolumeSource{
Driver: driver,
VolumeHandle: volumeHandle,
},
}
}
pvLister = append(pvLister, pv)
}
}
return pvLister
}
func getFakeCSIPVCLister(volumeName, scName string, driverNames ...string) fakelisters.PersistentVolumeClaimLister {
pvcLister := fakelisters.PersistentVolumeClaimLister{}
for _, driver := range driverNames {
for j := 0; j < 4; j++ {
v := fmt.Sprintf("%s-%s-%d", volumeName, driver, j)
pvc := v1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{Name: v},
Spec: v1.PersistentVolumeClaimSpec{VolumeName: v},
}
pvcLister = append(pvcLister, pvc)
}
}
pvcLister = append(pvcLister, v1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{Name: volumeName + "-4"},
Spec: v1.PersistentVolumeClaimSpec{StorageClassName: &scName},
})
pvcLister = append(pvcLister, v1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{Name: volumeName + "-5"},
Spec: v1.PersistentVolumeClaimSpec{},
})
// a pvc with missing PV but available storageclass.
pvcLister = append(pvcLister, v1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{Name: volumeName + "-6"},
Spec: v1.PersistentVolumeClaimSpec{StorageClassName: &scName, VolumeName: "missing-in-action"},
})
return pvcLister
}
func enableMigrationOnNode(csiNode *storagev1.CSINode, pluginName string) {
nodeInfoAnnotations := csiNode.GetAnnotations()
if nodeInfoAnnotations == nil {
nodeInfoAnnotations = map[string]string{}
}
newAnnotationSet := sets.NewString()
newAnnotationSet.Insert(pluginName)
nas := strings.Join(newAnnotationSet.List(), ",")
nodeInfoAnnotations[v1.MigratedPluginsAnnotationKey] = nas
csiNode.Annotations = nodeInfoAnnotations
}
func getFakeCSIStorageClassLister(scName, provisionerName string) fakelisters.StorageClassLister {
return fakelisters.StorageClassLister{
{
ObjectMeta: metav1.ObjectMeta{Name: scName},
Provisioner: provisionerName,
},
}
}
func getFakeCSINodeLister(csiNode *storagev1.CSINode) fakelisters.CSINodeLister {
if csiNode != nil {
return fakelisters.CSINodeLister(*csiNode)
}
return fakelisters.CSINodeLister{}
}
func getNodeWithPodAndVolumeLimits(limitSource string, pods []*v1.Pod, limit int64, driverNames ...string) (*schedulertypes.NodeInfo, *storagev1.CSINode) {
nodeInfo := schedulertypes.NewNodeInfo(pods...)
node := &v1.Node{
ObjectMeta: metav1.ObjectMeta{Name: "node-for-max-pd-test-1"},
Status: v1.NodeStatus{
Allocatable: v1.ResourceList{},
},
}
var csiNode *storagev1.CSINode
addLimitToNode := func() {
for _, driver := range driverNames {
node.Status.Allocatable[getVolumeLimitKey(driver)] = *resource.NewQuantity(limit, resource.DecimalSI)
}
}
initCSINode := func() {
csiNode = &storagev1.CSINode{
ObjectMeta: metav1.ObjectMeta{Name: "csi-node-for-max-pd-test-1"},
Spec: storagev1.CSINodeSpec{
Drivers: []storagev1.CSINodeDriver{},
},
}
}
addDriversCSINode := func(addLimits bool) {
initCSINode()
for _, driver := range driverNames {
driver := storagev1.CSINodeDriver{
Name: driver,
NodeID: "node-for-max-pd-test-1",
}
if addLimits {
driver.Allocatable = &storagev1.VolumeNodeResources{
Count: utilpointer.Int32Ptr(int32(limit)),
}
}
csiNode.Spec.Drivers = append(csiNode.Spec.Drivers, driver)
}
}
switch limitSource {
case "node":
addLimitToNode()
case "csinode":
addDriversCSINode(true)
case "both":
addLimitToNode()
addDriversCSINode(true)
case "csinode-with-no-limit":
addDriversCSINode(false)
case "no-csi-driver":
initCSINode()
default:
// Do nothing.
}
nodeInfo.SetNode(node)
return nodeInfo, csiNode
}
|
apache-2.0
|
esteve/r2d2-nxt
|
cmake/Modules/CheckCXX11Features/cxx11-test-auto.cpp
|
228
|
int main() {
auto i = 5;
auto f = 3.14159f;
auto d = 3.14159;
bool ret = (
(sizeof(f) < sizeof(d)) &&
(sizeof(i) == sizeof(int))
);
return ret ? 0 : 1;
}
|
apache-2.0
|
Ramagonibharath/Coffee
|
Assignment5/Obstack.java
|
653
|
import java.util.ArrayList;
class ObStack<T> extends ArrayList<T> {
private static final long serialVersionUID = 1L;
final T pop() {
final int last = this.size() - 1;
return this.remove(last);
}
final void push(final T O) {
add(O);
}
final T peek() {
return get(this.size() - 1);
}
}
public class GeneriClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
ObStack<String> ob=new ObStack<String>();
ob.push(" 1");
ob.push(" 2");
ob.push(" 3");
ob.push("4");
System.out.println("Top "+ob.peek());
ob.pop();
System.out.println("Top After Pop "+ob.peek());
}
}
|
apache-2.0
|
QualiMaster/QM-IConf
|
QualiMasterApplication/src/de/uni_hildesheim/sse/qmApp/dialogs/AbstractDialog.java
|
2666
|
/*
* Copyright 2009-2015 University of Hildesheim, Software Systems Engineering
*
* 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 de.uni_hildesheim.sse.qmApp.dialogs;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Shell;
import net.ssehub.easy.basics.logger.EASyLoggerFactory;
import net.ssehub.easy.basics.logger.EASyLoggerFactory.EASyLogger;
import qualimasterapplication.Activator;
/**
* An abstract dialog.
*
* @author Holger Eichelberger
* @author Niko Nowatzki
*/
public abstract class AbstractDialog extends Dialog {
/**
* Creates the dialog.
*
* @param parentShell the parent shell
*/
protected AbstractDialog(Shell parentShell) {
super(parentShell);
}
/**
* Method used to set the dialog in the centre of the monitor.
*
* @param newShell The machine configurator.
*/
protected void setDialogLocation(Shell newShell) {
//parent
Rectangle monitorArea = newShell.getParent().getBounds();
int x = monitorArea.x + (monitorArea.width - newShell.getBounds().width) / 2;
int y = monitorArea.y + (monitorArea.height - newShell.getBounds().height) / 2;
newShell.setLocation(x, y);
}
@Override
protected void configureShell(Shell newShell) {
newShell.pack();
newShell.setSize(getIntendedSize());
super.configureShell(newShell);
newShell.setText(getTitle());
setDialogLocation(newShell);
}
/**
* Returns the (initial) title.
*
* @return the initial title
*/
protected abstract String getTitle();
/**
* Returns the intended (initial) size.
*
* @return the intended initial size
*/
protected abstract Point getIntendedSize();
/**
* Returns the (class-dependent) logger.
*
* @return the logger instance
*/
protected EASyLogger getLogger() {
return EASyLoggerFactory.INSTANCE.getLogger(getClass(), Activator.PLUGIN_ID);
}
}
|
apache-2.0
|
kenmccracken/here-aaa-java-sdk
|
here-oauth-client/src/main/java/com/here/account/oauth2/AccessTokenRequest.java
|
4922
|
/*
* Copyright (c) 2016 HERE Europe B.V.
*
* 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.here.account.oauth2;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* One of the OAuth2.0
* <a href="https://tools.ietf.org/html/rfc6749#section-1.3">Authorization Grant</a> Request
* types supported by HERE.
*
* @author kmccrack
*
*/
public abstract class AccessTokenRequest {
/**
* expiresIn; the parameter name for "expires in" when conveyed in a JSON body.
*/
private static final String EXPIRES_IN_JSON = "expiresIn";
/**
* expires_in; the parameter name for "expires in" when conveyed in a form body.
*/
private static final String EXPIRES_IN_FORM = "expires_in";
protected static final String GRANT_TYPE_JSON = "grantType";
protected static final String GRANT_TYPE_FORM = "grant_type";
private final String grantType;
/**
* The optional lifetime in seconds of the access token returned by
* this request.
*
* <p>
* This property is a HERE extension to RFC6749 providing additional data.
*/
private Long expiresIn;
protected AccessTokenRequest(String grantType) {
this.grantType = grantType;
}
public String getGrantType() {
return grantType;
}
/**
* Optionally set the lifetime in seconds of the access token returned by
* this request.
* Must be a positive number. Ignored if greater than the maximum expiration
* for the client application.
* Typically you can set this from 1 to 86400, the latter representing 24
* hours.
*
* <p>
* While the OAuth2.0 RFC doesn't list this as a request parameter,
* we add this so the client can request Access Token expirations within the
* allowable range. See also the response parameter
* <a href="https://tools.ietf.org/html/rfc6749#section-5.1">expires_in</a>.
*
* <p>
* This property is a HERE extension to RFC6749 providing additional data.
*
* @param expiresIn desired lifetime in seconds of the access token
* @return this
* @see AccessTokenResponse#getExpiresIn()
* @see #getExpiresIn()
*/
public AccessTokenRequest setExpiresIn(Long expiresIn) {
this.expiresIn = expiresIn;
return this;
}
/**
* Gets the expiresIn value, the desired lifetime in seconds of the access token
* returned by this request.
*
* <p>
* This property is a HERE extension to RFC6749 providing additional data.
*
* @return the expiresIn value, the desired lifetime in seconds of the access token
* returned by this request.
*/
public Long getExpiresIn() {
return this.expiresIn;
}
/**
* Converts this request, into its JSON body representation.
*
* @return the JSON body, for use with application/json bodies
*/
public String toJson() {
return "{\"" + GRANT_TYPE_JSON + "\":\"" + getGrantType() + "\""
+ (null != expiresIn ? ",\"" + EXPIRES_IN_JSON + "\":" + expiresIn : "")
+ "}";
}
/**
* Converts this request, to its formParams Map representation.
*
* @return the formParams, for use with application/x-www-form-urlencoded bodies.
*/
public Map<String, List<String>> toFormParams() {
Map<String, List<String>> formParams = new HashMap<String, List<String>>();
addFormParam(formParams, GRANT_TYPE_FORM, getGrantType());
addFormParam(formParams, EXPIRES_IN_FORM, getExpiresIn());
return formParams;
}
/**
* Adds the specified name and value to the form parameters.
* If the value is non-null, the name and singleton-List of the value.toString() is
* added to the formParams Map.
*
* @param formParams the formParams Map, for use with application/x-www-form-urlencoded bodies
* @param name the name of the form parameter
* @param value the value of the form parameter
*/
protected final static void addFormParam(Map<String, List<String>> formParams, String name, Object value) {
if (null != formParams && null != name && null != value) {
formParams.put(name, Collections.singletonList(value.toString()));
}
}
}
|
apache-2.0
|
googleapis/python-spanner-sqlalchemy
|
create_test_database.py
|
3339
|
# -*- coding: utf-8 -*-
#
# Copyright 2021 Google LLC
#
# 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
#
# https://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 configparser
import os
import time
from create_test_config import set_test_config
from google.api_core.exceptions import AlreadyExists, ResourceExhausted
from google.cloud.spanner_v1 import Client
from google.cloud.spanner_v1.instance import Instance
USE_EMULATOR = os.getenv("SPANNER_EMULATOR_HOST") is not None
PROJECT = os.getenv(
"GOOGLE_CLOUD_PROJECT",
os.getenv("PROJECT_ID", "emulator-test-project"),
)
CLIENT = None
if USE_EMULATOR:
from google.auth.credentials import AnonymousCredentials
CLIENT = Client(project=PROJECT, credentials=AnonymousCredentials())
else:
CLIENT = Client(project=PROJECT)
def delete_stale_test_instances():
"""Delete test instances that are older than four hours."""
cutoff = int(time.time()) - 4 * 60 * 60
instances_pbs = CLIENT.list_instances(
"labels.python-spanner-sqlalchemy-systest:true"
)
for instance_pb in instances_pbs:
instance = Instance.from_pb(instance_pb, CLIENT)
if "created" not in instance.labels:
continue
create_time = int(instance.labels["created"])
if create_time > cutoff:
continue
# Backups are not used in sqlalchemy dialect test,
# therefore instance can just be deleted.
try:
instance.delete()
time.sleep(5) # Sleep for 5 seconds to give time for cooldown.
except ResourceExhausted:
print(
"Unable to drop stale instance '{}'. May need manual delete.".format(
instance.instance_id
)
)
def create_test_instance():
configs = list(CLIENT.list_instance_configs())
if not USE_EMULATOR:
# Filter out non "us" locations
configs = [config for config in configs if "-us-" in config.name]
instance_config = configs[0].name
create_time = str(int(time.time()))
unique_resource_id = "%s%d" % ("-", 1000 * time.time())
instance_id = (
"sqlalchemy-dialect-test"
if USE_EMULATOR
else "sqlalchemy-test" + unique_resource_id
)
labels = {"python-spanner-sqlalchemy-systest": "true", "created": create_time}
instance = CLIENT.instance(instance_id, instance_config, labels=labels)
try:
created_op = instance.create()
created_op.result(1800) # block until completion
except AlreadyExists:
pass # instance was already created
try:
database = instance.database("compliance-test")
created_op = database.create()
created_op.result(1800)
except AlreadyExists:
pass # instance was already created
set_test_config(PROJECT, instance_id)
delete_stale_test_instances()
create_test_instance()
|
apache-2.0
|
Sp2000/colplus-backend
|
colplus-dao/src/main/java/life/catalogue/db/type2/AbstractSetTypeHandler.java
|
2131
|
/*
* Copyright 2013 Global Biodiversity Information Facility (GBIF)
* 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 copyTaxon 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 life.catalogue.db.type2;
import java.sql.*;
import java.util.Collections;
import java.util.Set;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
/**
* Stores sets as non null arrays in postgres, avoiding nulls and uses empty sets instead.
*/
public abstract class AbstractSetTypeHandler<T> extends BaseTypeHandler<Set<T>> {
private final String arrayType;
public AbstractSetTypeHandler(String arrayType) {
this.arrayType = arrayType;
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Set<T> parameter, JdbcType jdbcType) throws SQLException {
Array array = ps.getConnection().createArrayOf(arrayType, parameter.toArray());
ps.setArray(i, array);
}
@Override
public void setParameter(PreparedStatement ps, int i, Set<T> parameter, JdbcType jdbcType) throws SQLException {
setNonNullParameter(ps, i, parameter == null ? Collections.emptySet() : parameter, jdbcType);
}
@Override
public Set<T> getNullableResult(ResultSet rs, String columnName) throws SQLException {
return toSet(rs.getArray(columnName));
}
@Override
public Set<T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return toSet(rs.getArray(columnIndex));
}
@Override
public Set<T> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return toSet(cs.getArray(columnIndex));
}
abstract Set<T> toSet(Array pgArray) throws SQLException;
}
|
apache-2.0
|
houdunwang/hdphp
|
vendor/houdunwang/aliyun/aliyun-openapi-php-sdk-master/aliyun-php-sdk-ecs/Ecs/Request/V20140526/DescribeImageSupportInstanceTypesRequest.php
|
2103
|
<?php
/*
* 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.
*/
namespace Ecs\Request\V20140526;
class DescribeImageSupportInstanceTypesRequest extends \RpcAcsRequest
{
function __construct()
{
parent::__construct("Ecs", "2014-05-26", "DescribeImageSupportInstanceTypes");
$this->setMethod("POST");
}
private $resourceOwnerId;
private $imageId;
private $resourceOwnerAccount;
private $ownerId;
public function getResourceOwnerId() {
return $this->resourceOwnerId;
}
public function setResourceOwnerId($resourceOwnerId) {
$this->resourceOwnerId = $resourceOwnerId;
$this->queryParameters["ResourceOwnerId"]=$resourceOwnerId;
}
public function getImageId() {
return $this->imageId;
}
public function setImageId($imageId) {
$this->imageId = $imageId;
$this->queryParameters["ImageId"]=$imageId;
}
public function getResourceOwnerAccount() {
return $this->resourceOwnerAccount;
}
public function setResourceOwnerAccount($resourceOwnerAccount) {
$this->resourceOwnerAccount = $resourceOwnerAccount;
$this->queryParameters["ResourceOwnerAccount"]=$resourceOwnerAccount;
}
public function getOwnerId() {
return $this->ownerId;
}
public function setOwnerId($ownerId) {
$this->ownerId = $ownerId;
$this->queryParameters["OwnerId"]=$ownerId;
}
}
|
apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.