code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9
values | license stringclasses 15
values | size int32 3 1.05M |
|---|---|---|---|---|---|
# -*- encoding: utf-8 -*-
class Bounscale::Collector::Throughput < Bounscale::Collector::Busyness
def pre
end
def post
end
def name
"throughput"
end
def value
#2つ以上のアクセスがないと測定不能なので0を返す
return 0 if history.length < 2
#リクエスト数 / 全体の時間 がスループット(分あたり換算なので60をかける)
(history.length.to_f / whole_sec) * 60
end
end | bounscale/bounscale | lib/bounscale/collector/throughput.rb | Ruby | mit | 478 |
using System;
using System.Collections.Generic;
namespace Example_TableParts
{
/// <summary>
/// A group that contains table items
/// </summary>
public class TableItemGroup
{
public string Name { get; set; }
public string Footer { get; set; }
public List<string> Items
{
get { return items; }
set { items = value; }
}
protected List<string> items = new List<string> ();
}
}
| bratsche/monotouch-samples | TableParts/TableParts/Code/TableItemGroup.cs | C# | mit | 405 |
const should = require('should');
var Regex = require('../');
var conStr = 'dHello World';
describe( 'replace test', function () {
it( 'left area', function () {
var regex = new Regex('H');
regex.replace(conStr,'h').should.equal('dhello World');
} );
it( 'middle area', function () {
var regex = new Regex('o\\sW');
regex.replace(conStr,'T').should.equal('dHellTorld');
} );
it( 'right area', function () {
var regex = new Regex('d$');
regex.replace(conStr,'P').should.equal('dHello WorlP');
} );
it( 'more match', function () {
var regex = new Regex('o','ig');
regex.replace(conStr,'').should.equal('dHell Wrld');
} );
} ); | kelvv/regexper.js | test/test.replace.js | JavaScript | mit | 726 |
module Maths
class Brain
# Public: Assigns data
def self.assign(variable, value)
data = read
data[variable] = value
write(data)
value
end
# Public: Looks up data
def self.lookup(variable)
value = read[variable]
if value.nil?
nil
else
BigDecimal.new(read[variable])
end
end
# Public: The file we're using to store our memories
def self.brain_file
File.join(ENV['HOME'], ".maths_brain")
end
# Public: Reads the data out of the brain
def self.read
if File.exist?(brain_file)
JSON.parse(File.read(brain_file))
else
{}
end
end
# Public: Reads the
def self.write(data)
File.open(brain_file, "wb") do |file|
file << JSON.generate(data)
end
end
end
end | commondream/maths | lib/maths/brain.rb | Ruby | mit | 870 |
package com.myapp2.mihir.quiz;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity
{
TextView dispques;
RadioGroup rgroup;
RadioButton radio[]=new RadioButton[4];
Button next,quit,tryAgain;
QuizLogic q;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
try
{
displayQuestion();
setRadioOptions();
q.getCorrectAns();
}
catch (Exception e)
{
e.printStackTrace();
}
}
@Override
protected void onStart()
{
super.onStart();
}
public void init()
{
try {
InputStream is= this.getResources().openRawResource(R.raw.question);
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
q=new QuizLogic(br);
} catch (Exception e) {
e.printStackTrace();
}
dispques=(TextView)findViewById(R.id.display_question);
rgroup=(RadioGroup)findViewById(R.id.answer_group);
next=(Button)findViewById(R.id.next_btn);
quit=(Button)findViewById(R.id.quit_btn);
tryAgain=(Button)findViewById(R.id.try_btn);
radio[0]=(RadioButton)findViewById(R.id.option1);
radio[1]=(RadioButton)findViewById(R.id.option2);
radio[2]=(RadioButton)findViewById(R.id.option3);
radio[3]=(RadioButton)findViewById(R.id.option4);
ButtonAction b=new ButtonAction(this);
next.setOnClickListener(b);
quit.setOnClickListener(b);
tryAgain.setOnClickListener(b);
}
private void displayQuestion()throws Exception
{
String s=q.getQuestion();
s=q.quesno+"."+s;
dispques.setText(s);
}
private void setRadioOptions()throws Exception
{
String s[]=new String[4];
for(int i=0;i<4;i++)
s[i] = q.getAns();
for(int i=0;i<4;i++)
radio[i].setText(s[i]);
}
private void makeInvisible()
{
next.setVisibility(View.GONE);
quit.setVisibility(View.GONE);
for(int i=0;i<4;i++)
radio[i].setVisibility(View.GONE);
}
private class ButtonAction implements View.OnClickListener
{
MainActivity m;
ButtonAction(MainActivity m)
{
this.m=m;
}
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.next_btn: nextAction();
break;
case R.id.quit_btn:
String s="You have given correction ans of "+(--q.quesno)+"/10 questions";
dispques.setText(s);
makeInvisible();
tryAgain.setVisibility(View.VISIBLE);
try
{
q.br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
break;
case R.id.try_btn:
clearAllToStartAgain();
try
{
displayQuestion();
setRadioOptions();
q.getCorrectAns();
}
catch (Exception e)
{
e.printStackTrace();
}
break;
}
}
public void nextAction()
{
boolean b[]=checkAns();
rgroup.clearCheck();
if(b[0])
{
if(b[1])
{
q.prize+=1000000;
try
{
if(q.quesno==10)
{
makeInvisible();
dispques.setText("You won the game");
q.br.close();
return;
}
displayQuestion();
setRadioOptions();
q.getCorrectAns();
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
makeInvisible();
if(q.prize!=0)
q.prize-=1000000;
dispques.setText("You have given correction ans of "+(--q.quesno)+"/10 questions");
try
{
q.br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
tryAgain.setVisibility(View.VISIBLE);
}
}
}
private boolean[] checkAns()
{
boolean b[]=new boolean[2];
b[0]=false;
b[1]=false;
int a=3;
switch (rgroup.getCheckedRadioButtonId())
{
case R.id.option1: a--;
case R.id.option2: a--;
case R.id.option3: a--;
case R.id.option4: b[0]=true;
break;
default:return b;
}
if(Integer.parseInt(q.ans)==a)
{
b[1]=true;
}
return b;
}
void clearAllToStartAgain()
{
try
{
InputStream is= m.getResources().openRawResource(R.raw.question);
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
q=new QuizLogic(br);
} catch (Exception e) {
e.printStackTrace();
}
next.setVisibility(View.VISIBLE);
quit.setVisibility(View.VISIBLE);
for(int i=0;i<4;i++)
radio[i].setVisibility(View.VISIBLE);
rgroup.clearCheck();
tryAgain.setVisibility(View.GONE);
}
}
}
| MihirJayavant/Quiz | src/main/java/com/myapp2/mihir/quiz/MainActivity.java | Java | mit | 7,020 |
// This file is part of graze/golang-service
//
// Copyright (c) 2016 Nature Delivered Ltd. <https://www.graze.com>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//
// license: https://github.com/graze/golang-service/blob/master/LICENSE
// link: https://github.com/graze/golang-service
package handlers
import (
"net/http"
"github.com/graze/golang-service/log"
uuid "github.com/satori/go.uuid"
)
// logContextHandler contains a local logger context and the handler
type logContextHandler struct {
logger log.FieldLogger
handler http.Handler
}
// ServeHTTP modifies the context of the request by adding a local logger context
func (h logContextHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
url := *req.URL
ip := ""
if userIP, err := getUserIP(req); err == nil {
ip = userIP.String()
}
ctx := h.logger.Ctx(req.Context()).With(log.KV{
"transaction": uuid.NewV4().String(),
"http.method": req.Method,
"http.protocol": req.Proto,
"http.uri": parseURI(req, url),
"http.path": uriPath(req, url),
"http.host": req.Host,
"http.user": ip,
"http.ref": req.Referer(),
"http.user-agent": req.Header.Get("User-Agent"),
}).NewContext(req.Context())
h.handler.ServeHTTP(w, req.WithContext(ctx))
}
// LoggingContextHandler returns a handler that adds `http` and `transaction` items into the provided logging context
//
// It adds the following fields to the `LoggingResponseWriter` log context:
// http.method - GET/POST/...
// http.protocol - HTTP/1.1
// http.uri - /path?with=query
// http.path - /path
// http.host - localhost:80
// http.user - 192.168.0.1 - ip address of the user
// http.ref - http://google.com - referrer
// http.user-agent - The user agent of the user
// transaction - unique uuid4 for this request
func LoggingContextHandler(logger log.FieldLogger, h http.Handler) http.Handler {
return logContextHandler{logger.With(log.KV{}), h}
}
| graze/golang-service | handlers/context.go | GO | mit | 2,064 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Survey Results</title>
<link href="/api/css/styles.css" rel="stylesheet" type="text/css" />
<style>
.ieDiv{
display:none;
}
</style>
<!--[if lte IE 6]>
<style>
.ieDiv{
background-color:#808080;
color:#000000;
display:block;
text-align:center;
width:100%;
height:100%;
padding-top:10px;
}
.content_div{
display:none;
}
</style>
<![endif]-->
<script type="text/javascript">
function $id(id){
return document.getElementById(id);
}
function radio_group_val(id){
for(var i=0;i<document.getElementsByName(id).length;i++){
var chked = 0;
if(document.getElementsByName(id)[i].checked){
chked=1;
break;
}
}
if(!chked)
return false;
else
return true;
}
</script>
</head>
<body>
<div class="ieDiv"><h1><strong>You are using older version of Internet Explorer. <br/><br/>Please upgrade your browser <br/><br/>or use mozilla, chrome or any other browser</strong></h1></div>
<div id="workArea"> <table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr><td valign="top" height="10px">
<div class="alert" style="text-align: center">
<p>This figure shows what direction the you may be leaning in their decision about treatment goals for their loved one.</p>
<p>On the far left side of the line below is comfort care. The far right represents doing everything possible for survival.</p>
<p>The BLUE TRIANGLE on the line shows where you might be leaning based on your answers to the survey questions.</p>
</div>
</td></tr>
<tr><td valign="middle" style="text-align:center;" id="temp_div">
<div id="slider-div">
<div id="slider"> </div>
<img src="http://test.teamkollab.com/pmv/themes/default/images/arrow.png" id="slider_arrow" />
<div id="sliderArrow"></div>
</div>
<div id="sliderSteps">
<table width="100%" border="0" cellspacing="0" cellpadding="0" align="center">
<tr>
<td valign="top" align="left" colspan="3"></td>
</tr>
<tr>
<td valign="top" align="left" width="25%">Comfort</td>
<td valign="top" align="center">Survival but no <br/>
prolonged life support</td>
<td valign="top" align="right" width="25%">Survival at All Cost</td>
</tr>
</table>
</div>
</td></tr>
<tr><td>
</td></tr></table>
<script type="text/javascript">
var points = parseInt("<?php echo $_GET['points']; ?>");
var incr =0;
if(points >= 8 && points <= 9)
incr+=191.25;
else if(points >=3 && points<=5)
incr+=573.75;
else if(points <= 2)
incr+=765;
else if(points >= 6 && points <= 7)
incr+=382.5;
$id("slider_arrow").style.left = incr+"px";
document.getElementById("temp_div").style.height = (document.height-350)+"px";
</script>
<h2 style='text-align: center'>Thank you for completing this survey.<br /><br />Please return this device to the nurse.</h2>
</div>
</body>
</html>
| deanchen/CPS196-Ventilator-Client | result.php | PHP | mit | 3,061 |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'', include('frontpage.urls')),
url(r'^auth/', include('social.apps.django_app.urls', namespace='social')),
url(r'^admin/', include(admin.site.urls)),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'next_page': '/'}, name='logout'),
)
| cncdnua/cncdnua | cncdnua/cncdnua/urls.py | Python | mit | 405 |
import fetchopenfmri.fetch
| wiheto/fetchopenfmri | fetchopenfmri/__init__.py | Python | mit | 28 |
/**
* generated by Xtext
*/
package uk.ac.kcl.inf.robotics.ui.quickfix;
import org.eclipse.xtext.ui.editor.quickfix.DefaultQuickfixProvider;
/**
* Custom quickfixes.
*
* See https://www.eclipse.org/Xtext/documentation/304_ide_concepts.html#quick-fixes
*/
@SuppressWarnings("all")
public class RigidBodiesQuickfixProvider extends DefaultQuickfixProvider {
}
| szschaler/RigidBodies | uk.ac.kcl.inf.robotics.rigid_bodies.ui/xtend-gen/uk/ac/kcl/inf/robotics/ui/quickfix/RigidBodiesQuickfixProvider.java | Java | mit | 366 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 Jerry Lee
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
namespace CSharpExtensions.Net.Sockets
{
/// <summary>
/// The interface definition for a socket packet.
/// </summary>
public interface ISocketPacket
{
/// <summary>
/// Gets the specified byte array of the packet.
/// </summary>
/// <value>The specified byte array of the packet.</value>
byte[] Bytes
{
get;
}
}
} | cosmos53076/CSharpExtensions | CSharpExtensions.Net/src/CSharpExtensions/Net/Sockets/ISocketPacket.cs | C# | mit | 1,610 |
@extends('layouts.master')
@section('content')
<div id="first">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-default">
<div class="panel-heading">
LAB PERFORMANCE STATS ON EID <div class="display_date"></div>
</div>
<div class="panel-body">
<div id="lab_perfomance_stats"><center><div class="loader"></div></center></div>
<div class="col-md-12" style="margin-top: 1em;margin-bottom: 1em;">
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="panel panel-default">
<div class="panel-heading">
Tests with valid outcomes (Trends) <div class="display_date"></div>
</div>
<div class="panel-body">
<div id="test_trends"><center><div class="loader"></div></center></div>
<div class="col-md-12" style="margin-top: 1em;margin-bottom: 1em;">
</div>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="panel panel-default">
<div class="panel-heading">
Tests with valid outcomes <div class="display_date"></div>
</div>
<div class="panel-body">
<div id="test_outcomes"><center><div class="loader"></div></center></div>
<div class="col-md-12" style="margin-top: 1em;margin-bottom: 1em;">
</div>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="panel panel-default">
<div class="panel-heading">
Positivity Trends (Initial PCR) <div class="display_date"></div>
</div>
<div class="panel-body">
<div id="positivity_trends"><center><div class="loader"></div></center></div>
<div class="col-md-12" style="margin-top: 1em;margin-bottom: 1em;">
</div>
</div>
</div>
</div>
<div class="col-md-6 col-sm-6 col-xs-6">
<div class="panel panel-default">
<div class="panel-heading">
Rejected Trends <div class="display_date"></div>
</div>
<div class="panel-body">
<div id="rejected_trends"><center><div class="loader"></div></center></div>
<div class="col-md-12" style="margin-top: 1em;margin-bottom: 1em;">
</div>
</div>
</div>
</div>
<div id="graphs"></div>
<div id="stacked_graph" class="col-md-6"></div>
</div>
<div id="lineargauge"></div>
</div>
<div id="second">
<div id="lab_summary_two_years"></div>
<div id="trends_lab"></div>
</div>
<div id="third">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-default">
<div class="panel-heading">
Samples Rejections <div class="display_date"></div>
</div>
<div class="panel-body" id="lab_rejections">
<center><div class="loader"></div></center>
</div>
</div>
</div>
</div>
</div>
<div id="fourth">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-default">
<div class="panel-heading">
Mapping <div class="display_date"></div>
</div>
<div class="panel-body" id="mapping" style="height: 700px">
<center><div class="loader"></div></center>
</div>
</div>
</div>
</div>
</div>
<div id="fifth">
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-default">
<div class="panel-heading">
POC Hub-Spoke Stats <div class="display_date"></div>
</div>
<div class="panel-body" id="poc">
<center><div class="loader"></div></center>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-default">
<div class="panel-heading">
POC Outcomes <div class="display_date"></div>
</div>
<div class="panel-body" id="poc_outcomes">
<center><div class="loader"></div></center>
</div>
</div>
</div>
</div>
</div>
<div id="my_empty_div"></div>
@endsection
@section('scripts')
<script type="text/javascript">
function reload_page(labFilter = null)
{
var filter_value = $("#{{ $filter_name }}").val();
if (filter_value && filter_value != 'null') {
$("#first").hide();
$("#second").show();
$("#fourth").show();
$("#fifth").hide();
$("#breadcrum").show();
if(filter_value==11 || filter_value =='11'){
$("#fourth").hide();
$("#fifth").show();
$("#poc").load("{{ url('lab/poc_performance_stat') }}");
$("#poc_outcomes").load("{{ url('lab/poc_outcomes') }}");
}
else{
$("#mapping").html("<center><div class='loader'></div></center>");
$("#mapping").load("{{ url('lab/mapping') }}");
}
} else {
$("#first").show();
$("#second").hide();
$("#fourth").hide();
$("#fifth").hide();
$("#lab_perfomance_stats").html("<center><div class='loader'></div></center>");
$("#test_trends").html("<center><div class='loader'></div></center>");
$("#test_outcomes").html("<center><div class='loader'></div></center>");
$("#positivity_trends").html("<center><div class='loader'></div></center>");
$("#rejected_trends").html("<center><div class='loader'></div></center>");
$("#lineargauge").html("<center><div class='loader'></div></center>");
$("#lab_perfomance_stats").load("{{ url('lab/lab_performance_stat') }}");
$("#test_trends").load("{{ url('lab/lab_testing_trends/testing') }}");
$("#test_outcomes").load("{{ url('county/county_outcomes/5') }}");
$("#positivity_trends").load("{{ url('lab/lab_testing_trends/positivity') }}");
$("#rejected_trends").load("{{ url('lab/lab_testing_trends/rejection') }}");
$("#lineargauge").load("{{ url('lab/labs_turnaround') }}");
}
$("#lab_rejections").html("<center><div class='loader'></div></center>");
$("#lab_rejections").load("{{ url('lab/rejections') }}");
}
function expand_poc(facility_id)
{
$("#my_empty_div").load("{{ url('lab/poc_performance_details') }}/"+facility_id);
}
$().ready(function(){
// reload_page();
date_filter('yearly', "{{ date('Y') }}");
});
</script>
@endsection | bakasajoshua/eid_dashboard | resources/views/base/lab.blade.php | PHP | mit | 7,467 |
package com.team254.frc2015;
import com.team254.frc2015.behavior.Commands;
import com.team254.lib.util.Latch;
import edu.wpi.first.wpilibj.Joystick;
import java.util.Optional;
public class OperatorInterface {
private Commands m_commands = new Commands();
Joystick leftStick = HardwareAdaptor.kLeftStick;
Joystick rightStick = HardwareAdaptor.kRightStick;
Joystick buttonBoard = HardwareAdaptor.kButtonBoard;
Latch horizontalCanLatch = new Latch();
Latch coopLatch = new Latch();
Latch verticalCanLatch = new Latch();
public void reset() {
m_commands = new Commands();
}
public Commands getCommands() {
// Left stick
if (leftStick.getRawButton(1)) {
m_commands.roller_request = Commands.RollerRequest.INTAKE;
} else if (leftStick.getRawButton(2)) {
m_commands.roller_request = Commands.RollerRequest.EXHAUST;
} else {
m_commands.roller_request = Commands.RollerRequest.NONE;
}
// Right stick
if (rightStick.getRawButton(2)) {
m_commands.intake_request = Commands.IntakeRequest.OPEN;
} else {
m_commands.intake_request = Commands.IntakeRequest.CLOSE;
}
// Button board
if (buttonBoard.getRawAxis(3) > 0.1) {
m_commands.elevator_mode = Commands.ElevatorMode.BOTTOM_CARRIAGE_MODE;
} else {
m_commands.elevator_mode = Commands.ElevatorMode.TOP_CARRIAGE_MODE;
}
if (buttonBoard.getRawButton(3)) {
m_commands.bottom_carriage_flapper_request = Commands.BottomCarriageFlapperRequest.OPEN;
} else {
m_commands.bottom_carriage_flapper_request = Commands.BottomCarriageFlapperRequest.CLOSE;
}
if (buttonBoard.getRawButton(8)) { // Bottom carriage jog up
if (buttonBoard.getRawButton(11)) { // Slow
m_commands.bottom_jog = Optional.of(Constants.kElevatorJogSlowPwm);
} else if (buttonBoard.getRawButton(12)) { // Fast
m_commands.bottom_jog = Optional.of(Constants.kElevatorJogFastPwm);
} else { // Medium
m_commands.bottom_jog = Optional.of(Constants.kElevatorJogFastPwm); // disable old man mode
}
} else if (buttonBoard.getRawButton(10)) { // Bottom carriage jog down
if (buttonBoard.getRawButton(11)) { // Slow
m_commands.bottom_jog = Optional.of(-Constants.kElevatorJogSlowPwm);
} else if (buttonBoard.getRawButton(12)) { // Fast
m_commands.bottom_jog = Optional.of(-Constants.kElevatorJogFastPwm);
} else { // Medium
m_commands.bottom_jog = Optional.of(-Constants.kElevatorJogMediumPwm);
}
} else {
m_commands.bottom_jog = Optional.empty();
}
if (buttonBoard.getRawButton(7)) { // top up
if (buttonBoard.getRawButton(11)) { // Slow
m_commands.top_jog = Optional.of(Constants.kElevatorJogSlowPwm);
} else if (buttonBoard.getRawButton(12)) { // Fast
m_commands.top_jog = Optional.of(Constants.kElevatorJogFastPwm);
} else { // Medium
m_commands.top_jog = Optional.of(Constants.kElevatorJogFastPwm); // disable old man mode
}
} else if (buttonBoard.getRawButton(9)) { // top down
if (buttonBoard.getRawButton(11)) { // Slow
m_commands.top_jog = Optional.of(-Constants.kElevatorJogSlowPwm);
} else if (buttonBoard.getRawButton(12)) { // Fast
m_commands.top_jog = Optional.of(-Constants.kElevatorJogFastPwm);
} else { // Medium
m_commands.top_jog = Optional.of(-Constants.kElevatorJogMediumPwm);
}
} else {
m_commands.top_jog = Optional.empty();
}
m_commands.cancel_current_routine = buttonBoard.getX() < 0; // Button 6
if (coopLatch.update(buttonBoard.getY() < 0)) { // Button 5
m_commands.preset_request = Commands.PresetRequest.COOP;
} else if (buttonBoard.getRawButton(5)) { // Button 2
m_commands.preset_request = Commands.PresetRequest.SCORE;
} else if (buttonBoard.getRawButton(4)) { // Button 1
//m_commands.preset_request = Commands.PresetRequest.CARRY_SQUEZE;
} else {
m_commands.preset_request = Commands.PresetRequest.NONE;
}
if (verticalCanLatch.update(buttonBoard.getRawButton(6))) { // Button 3
m_commands.vertical_can_grab_request = Commands.VerticalCanGrabberRequests.ACTIVATE;
} else {
m_commands.vertical_can_grab_request = Commands.VerticalCanGrabberRequests.NONE;
}
m_commands.top_carriage_claw_request = Commands.TopCarriageClawRequest.CLOSE;
if (buttonBoard.getRawButton(1)) {
m_commands.top_carriage_claw_request = Commands.TopCarriageClawRequest.OPEN;
}
if (horizontalCanLatch.update(buttonBoard.getRawButton(2))) {
m_commands.horizontal_can_grabber_request = Commands.HorizontalCanGrabberRequests.ACTIVATE;
} else {
m_commands.horizontal_can_grabber_request = Commands.HorizontalCanGrabberRequests.NONE;
}
m_commands.floor_load_mode = buttonBoard.getRawAxis(3) > 0.1;
m_commands.deploy_peacock = buttonBoard.getRawButton(11) && buttonBoard.getZ() < 0; // button 4;
if (buttonBoard.getZ() < 0) { // left motor peacock
if (buttonBoard.getRawButton(11)) {
m_commands.left_motor_peacock_requests = Commands.MotorPeacockRequests.MOVE_DOWN;
} else {
m_commands.left_motor_peacock_requests = Commands.MotorPeacockRequests.MOVE_UP;
}
} else {
m_commands.left_motor_peacock_requests = Commands.MotorPeacockRequests.NONE;
}
if (buttonBoard.getRawButton(4)) { // right motor peacock
if (buttonBoard.getRawButton(11)) {
m_commands.right_motor_peacock_requests = Commands.MotorPeacockRequests.MOVE_DOWN;
} else {
m_commands.right_motor_peacock_requests = Commands.MotorPeacockRequests.MOVE_UP;
}
} else {
m_commands.right_motor_peacock_requests = Commands.MotorPeacockRequests.NONE;
}
return m_commands;
}
}
| Team254/FRC-2015 | src/com/team254/frc2015/OperatorInterface.java | Java | mit | 6,448 |
using System;
using System.IO;
namespace Songhay
{
/// <summary>
/// A few static helper members
/// for <see cref="System.IO"/>.
/// </summary>
public static partial class ProgramFileUtility
{
/// <summary>
/// Returns the file name
/// based on the specified path
/// and <see cref="Path.DirectorySeparatorChar"/>.
/// </summary>
/// <param name="pathWithFile">
/// The specified path.
/// </param>
[Obsolete("Since .NET 1.1 use System.IO.Path.GetFileName().")]
public static string GetFileName(string pathWithFile)
{
return GetFileName(pathWithFile, null);
}
/// <summary>
/// Returns the file name
/// based on the specified path.
/// </summary>
/// <param name="pathWithFile">
/// The specified path.
/// </param>
/// <param name="pathDelimiter">
/// Path delimiter (e.g. \ or /).
/// </param>
[Obsolete("Since .NET 1.1 use System.IO.Path.GetFileName().")]
public static string GetFileName(string pathWithFile, char? pathDelimiter)
{
if(string.IsNullOrWhiteSpace(pathWithFile)) return null;
char delim = (pathDelimiter.HasValue) ? pathDelimiter.Value : Path.DirectorySeparatorChar;
int pos = pathWithFile.LastIndexOf(delim);
pos++;
if (pos > pathWithFile.Length)
return null;
else
return pathWithFile.Substring(pos);
}
/// <summary>
/// Returns the directory root
/// based on the specified path.
/// </summary>
/// <param name="pathWithFile">
/// The specified path.
/// </param>
[Obsolete("Since .NET 1.1 use System.IO.Path.GetDirectoryName().")]
public static string GetPathRoot(string pathWithFile)
{
return GetPathRoot(pathWithFile, null);
}
/// <summary>
/// Returns the directory root
/// based on the specified path.
/// </summary>
/// <param name="pathWithFile">
/// The specified path.
/// </param>
/// <param name="pathDelimiter">
/// Path delimiter (e.g. \ or /).
/// </param>
[Obsolete("Since .NET 1.1 use System.IO.Path.GetDirectoryName().")]
public static string GetPathRoot(string pathWithFile, char? pathDelimiter)
{
if(string.IsNullOrWhiteSpace(pathWithFile)) return null;
string ret = GetFileName(pathWithFile, pathDelimiter);
return pathWithFile.Replace(ret, string.Empty);
}
/// <summary>
/// Joins the path and root.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="root">The root.</param>
[Obsolete("Since .NET 4.0 use System.IO.Path.Combine().")]
public static string JoinPathAndRoot(string path, string root)
{
return JoinPathAndRoot(path, root, null);
}
/// <summary>
/// Joins the path and root.
/// </summary>
/// <param name="path">The path.</param>
/// <param name="root">The root.</param>
/// <param name="pathDelimiter">
/// Path delimiter (e.g. \ or /).
/// </param>
[Obsolete("Since .NET 4.0 use System.IO.Path.Combine().")]
public static string JoinPathAndRoot(string path, string root, char? pathDelimiter)
{
if(string.IsNullOrWhiteSpace(path) || string.IsNullOrWhiteSpace(root)) return root;
char delim = (pathDelimiter.HasValue) ? pathDelimiter.Value : Path.DirectorySeparatorChar;
path = path.Replace("./", string.Empty);
string s = string.Concat(root, delim.ToString(), path);
s = s.Replace(string.Concat(delim.ToString(), delim.ToString()), delim.ToString());
return s;
}
/// <summary>
/// Writes the specified content to a file.
/// </summary>
/// <param name="content">The content to write or overwrite.</param>
/// <param name="pathWithFile">The path to the file.</param>
[Obsolete("Since .NET 2.0 use System.IO.File.WriteAllText().")]
public static void Write(string content, string pathWithFile)
{
using(StreamWriter writer = File.CreateText(pathWithFile))
{
writer.Write(content);
}
}
}
}
| BryanWilhite/SonghayCore | SonghayCore/ProgramFileUtility.Obsolete.cs | C# | mit | 4,553 |
import Icon from '../components/Icon.vue'
Icon.register({
'mars-stroke-h': {
width: 480,
height: 512,
paths: [
{
d: 'M476.2 247.5c4.7 4.7 4.7 12.3 0.1 17l-55.9 55.9c-7.6 7.5-20.5 2.2-20.5-8.5v-23.9h-23.9v20c0 6.6-5.4 12-12 12h-40c-6.6 0-12-5.4-12-12v-20h-27.6c-5.8 25.6-18.7 49.9-38.6 69.8-56.2 56.2-147.4 56.2-203.6 0s-56.2-147.4 0-203.6 147.4-56.2 203.6 0c19.9 19.9 32.8 44.2 38.6 69.8h27.6v-20c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v20h23.8v-23.9c0-10.7 12.9-16.1 20.5-8.5zM200.6 312.6c31.2-31.2 31.2-82 0-113.1-31.2-31.2-81.9-31.2-113.1 0s-31.2 81.9 0 113.1c31.2 31.2 81.9 31.2 113.1 0z'
}
]
}
})
| Justineo/vue-awesome | src/icons/mars-stroke-h.js | JavaScript | mit | 644 |
'use strict';
exports.port = process.env.PORT || 3000;
exports.mongodb = {
uri: process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'localhost/lulucrawler'
};
exports.getThisUrl = '';
exports.companyName = '';
exports.projectName = 'luluCrawler';
exports.systemEmail = 'your@email.addy';
exports.cryptoKey = 'k3yb0ardc4t';
exports.loginAttempts = {
forIp: 50,
forIpAndUser: 7,
logExpiration: '20m'
};
exports.smtp = {
from: {
name: process.env.SMTP_FROM_NAME || exports.projectName +' Website',
address: process.env.SMTP_FROM_ADDRESS || 'your@email.addy'
},
credentials: {
user: process.env.SMTP_USERNAME || 'your@email.addy',
password: process.env.SMTP_PASSWORD || 'bl4rg!',
host: process.env.SMTP_HOST || 'smtp.gmail.com',
ssl: true
}
};
| s890506/LuLuCrawler | config.example.js | JavaScript | mit | 784 |
import { IBot, IBotCommand, IBotCommandHelp, IBotMessage } from '../api'
import { getRandomInt } from '../utils'
interface IMountain {
name: string
height: number
img?: string
}
export default class GrowlCommand implements IBotCommand {
private readonly CMD_REGEXP = /^(or|ор)(?: |$)/im
private _mountains: IMountain[]
public getHelp(): IBotCommandHelp {
return { caption: 'ор / or', description: 'Показывает уровень ора.' }
}
public init(bot: IBot, dataPath: string): void {
this._mountains = (require(`${dataPath}`) as IMountain[]).sort((a, b) => a.height - b.height)
}
public isValid(msg: string): boolean {
return this.CMD_REGEXP.test(msg)
}
public async process(msg: string, answer: IBotMessage): Promise<void> {
const id = getRandomInt(0, this._mountains.length)
const low = id > 0 ? this._mountains[id - 1] : undefined
const hi = id < this._mountains.length - 1 ? this._mountains[id + 1] : undefined
if (!hi) {
if (low && low.img) {
answer.setImage(low.img)
}
answer.setDescription('Ваш ор выше всех гор!')
return
}
if (hi && hi.img) {
answer.setImage(hi.img)
}
if (!low) {
answer.setDescription('Ваш ор ниже всех гор!')
} else {
answer.setDescription(`Ваш ор выше "${low.name}" (${low.height}м) и ниже "${hi.name}" (${hi.height}м)!`)
}
}
} | Leopotam/discord-bot | src/commands/growl.ts | TypeScript | mit | 1,580 |
package com.bsuir.wtlab3.source;
import java.util.ArrayList;
import com.bsuir.wtlab3.entity.Note;
public class Notepad {
private ArrayList<Note> notes = new ArrayList<Note>();
private static Notepad instance;
public static Notepad getInstance(){
if(instance == null){
instance = new Notepad();
}
return instance;
}
private Notepad(){};
public ArrayList<Note> getNotes() {
return notes;
}
public boolean addNote(Note note){
return this.notes.add(note);
}
}
| VerkhovtsovPavel/BSUIR_Labs | Labs/WT/WT-3/src/com/bsuir/wtlab3/source/Notepad.java | Java | mit | 490 |
#region License
// The MIT License
//
// Copyright (c) 2011 Julien Blin, julien.blin@gmail.com
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Linq;
using System.ServiceModel;
using System.Threading.Tasks;
using System.Timers;
using Castle.Core.Logging;
using Colombo.Alerts;
using Colombo.Messages;
namespace Colombo.Wcf
{
/// <summary>
/// <see cref="IRequestProcessor"/> implementation that uses WCF to transfer requests. See <see cref="IColomboService"/>.
/// </summary>
public class WcfClientRequestProcessor : IRequestProcessor
{
private ILogger logger = NullLogger.Instance;
/// <summary>
/// Logger
/// </summary>
public ILogger Logger
{
get { return logger; }
set { logger = value; }
}
private IColomboAlerter[] alerters = new IColomboAlerter[0];
/// <summary>
/// Alerters to use. All will be notified.
/// </summary>
public IColomboAlerter[] Alerters
{
get { return alerters; }
set
{
if (value == null) throw new ArgumentNullException("Alerters");
Contract.EndContractBlock();
alerters = value;
if (!Logger.IsInfoEnabled) return;
if (alerters.Length == 0)
Logger.Info("No alerters has been registered for the WcfClientRequestProcessor.");
else
Logger.InfoFormat("WcfClientRequestProcessor monitoring with the following alerters: {0}", string.Join(", ", alerters.Select(x => x.GetType().Name)));
}
}
private readonly IColomboServiceFactory serviceFactory;
/// <summary>
/// Constructor
/// </summary>
/// <param name="serviceFactory"></param>
public WcfClientRequestProcessor(IColomboServiceFactory serviceFactory)
{
if (serviceFactory == null) throw new ArgumentNullException("serviceFactory");
Contract.EndContractBlock();
this.serviceFactory = serviceFactory;
}
/// <summary>
/// <c>true</c> if the processor can process the request, <c>false</c> otherwise.
/// </summary>
public bool CanProcess(BaseRequest request)
{
if (request == null) throw new ArgumentNullException("request");
Contract.EndContractBlock();
var groupName = request.GetGroupName();
if (string.IsNullOrEmpty(groupName))
throw new ColomboException(string.Format("Groupname cannot be null or empty for {0}", request));
return serviceFactory.CanCreateChannelForRequestGroup(groupName);
}
/// <summary>
/// Process the requests.
/// </summary>
public ResponsesGroup Process(IList<BaseRequest> requests)
{
if (requests == null) throw new ArgumentNullException("requests");
Contract.EndContractBlock();
var requestsGroups = requests.GroupBy(x => x.GetGroupName());
foreach (var requestsGroup in requestsGroups)
{
Contract.Assume(requestsGroup.Key != null);
if (!serviceFactory.CanCreateChannelForRequestGroup(requestsGroup.Key))
throw new ColomboException(string.Format("Internal error: Unable to send to {0}.", requestsGroup.Key));
}
if (Logger.IsDebugEnabled)
{
Logger.Debug("Mapping for requests/uri is the following:");
foreach (var requestsGroup in requestsGroups)
{
Contract.Assume(requestsGroup.Key != null);
Logger.DebugFormat("{0} => {{", serviceFactory.GetAddressForRequestGroup(requestsGroup.Key));
foreach (var request in requestsGroup)
{
Logger.DebugFormat(" {0}", request);
}
Logger.Debug("}");
}
}
var tasks = new List<Task<Response[]>>();
var tasksGroupAssociation = new Dictionary<string, Task<Response[]>>();
foreach (var requestGroup in requestsGroups)
{
var task = Task.Factory.StartNew(g =>
{
var group = (IGrouping<string, BaseRequest>)g;
IColomboService service = null;
try
{
service = serviceFactory.CreateChannel(group.Key);
Logger.DebugFormat("Sending {0} request(s) to {1}...", group.Count(), ((IClientChannel)service).RemoteAddress.Uri);
var asyncResult = service.BeginProcessAsync(group.ToArray(), null, null);
asyncResult.AsyncWaitHandle.WaitOne();
return service.EndProcessAsync(asyncResult);
}
finally
{
if (service != null)
{
try
{
((IClientChannel)service).Close();
}
catch (Exception)
{
((IClientChannel)service).Abort();
}
}
}
},
requestGroup
);
tasks.Add(task);
tasksGroupAssociation[requestGroup.Key] = task;
}
try
{
Task.WaitAll(tasks.ToArray());
}
catch (AggregateException ex)
{
const string message = "An exception occured inside one or several WCF endpoint";
Logger.Error(message, ex);
foreach (var innerEx in ex.InnerExceptions)
Logger.Error(innerEx.ToString());
throw new ColomboException(message, ex);
}
Logger.Debug("All the WCF clients have executed successfully.");
Logger.Debug("Reconstituing responses...");
var responses = new ResponsesGroup();
foreach (var requestsGroup in requestsGroups)
{
var task = tasksGroupAssociation[requestsGroup.Key];
var requestsArray = requestsGroup.ToArray();
for (var i = 0; i < requestsArray.Length; i++)
{
var request = requestsArray[i];
responses[request] = task.Result[i];
}
}
Logger.DebugFormat("{0} responses are returned.", responses.Count);
Contract.Assume(responses.Count == requests.Count);
return responses;
}
private Timer healthCheckTimer;
private int healthCheckHeartBeatInSeconds;
/// <summary>
/// Interval in seconds between health check for endpoints.
/// Set to 0 or a negative number to disable the check.
/// </summary>
public int HealthCheckHeartBeatInSeconds
{
get { return healthCheckHeartBeatInSeconds; }
set
{
healthCheckHeartBeatInSeconds = value;
if (healthCheckTimer != null)
{
healthCheckTimer.Stop();
healthCheckTimer = null;
}
if (healthCheckHeartBeatInSeconds <= 0) return;
healthCheckTimer = new Timer(healthCheckHeartBeatInSeconds * 1000) {AutoReset = true};
healthCheckTimer.Elapsed += HealthCheckTimerElapsed;
healthCheckTimer.Start();
}
}
internal void HealthCheckTimerElapsed(object sender, ElapsedEventArgs e)
{
IColomboService currentService = null;
try
{
foreach (var wcfService in serviceFactory.CreateChannelsForAllEndPoints())
{
if(wcfService == null) throw new ColomboException("Internal error: channel should not be null.");
currentService = wcfService;
try
{
var hcRequest = new HealthCheckRequest();
Logger.DebugFormat("Sending healthcheck request to {0}...", ((IClientChannel)currentService).RemoteAddress.Uri);
var asyncResult = currentService.BeginProcessAsync(new BaseRequest[] { hcRequest }, null, null);
asyncResult.AsyncWaitHandle.WaitOne();
currentService.EndProcessAsync(asyncResult);
Logger.DebugFormat("Healthcheck OK for {0}...", ((IClientChannel)currentService).RemoteAddress.Uri);
}
catch (Exception ex)
{
var alert = new HealthCheckFailedAlert(Environment.MachineName, ((IClientChannel)currentService).RemoteAddress.Uri.ToString(), ex);
Logger.Warn(alert.ToString());
foreach (var alerter in Alerters)
{
alerter.Alert(alert);
}
}
}
}
catch (Exception ex)
{
Logger.Error("An error occured while executing a health check.", ex);
}
finally
{
if (currentService != null)
{
try
{
((IClientChannel)currentService).Close();
}
catch (Exception)
{
((IClientChannel)currentService).Abort();
}
}
}
}
}
}
| julienblin/Colombo | src/Colombo/Wcf/WcfClientRequestProcessor.cs | C# | mit | 11,301 |
<?php
session_start();
error_reporting(E_ALL ^ E_DEPRECATED);
$host="localhost";
$nm=$_POST['nm'];
$username="root";
$password="";
$db_name="Vazhai";
$tbl_name="Student";
$link=mysql_connect("$host","$username","$password");
mysql_select_db("$db_name",$link);
$sql="select * from Student where name like'%$nm%'";
$result=mysql_query($sql);
?>
<html>
<head>
<title>STUDENT FORM</title>
<h2>STUDENT FORM</h2>
</head>
<body background="b1.jpg"><font face="calibri">
<p align="right"><font size="5"><?php echo($_SESSION['un']);?></font></p>
<p align="right"><a href="home.php">Home</a></p>
<?php
while($row=mysql_fetch_assoc($result))
{
?>
<table>
<tr><td><b>Year of Admission</b></td><td><?php echo($row['yoj']);?></td></tr>
<tr><td><b>Registration ID</b></td><td><?php echo($row['regid']);?></td></tr>
<tr><td><b>Name</b></td><td><?php echo($row['name']);?></td><td></td><td>
<tr><td><b>Gender</b></td><td><?php echo($row['sex']);?></td></tr>
<tr><td><b>Date of Birth</b></td><td><?php echo($row['dob']);?></td></tr>
<tr><td><b>Father Status</b></td><td><?php echo($row['fs']);?></td></tr>
<tr><td><b>Father Name</b></td><td><?php echo($row['fname']);?></td></tr>
<tr><td><b>Father Occupation</b></td><td><?php echo($row['foccu']);?></td></tr>
<tr><td><b>Mother Status</b></td><td><?php echo($row['ms']);?></td></tr>
<tr><td><b>Mother Name</b></td><td><?php echo($row['mname']);?></td></tr>
<tr><td><b>Mother Occupation</b></td><td><?php echo($row['moccu']);?></td></tr>
<tr><td><b>Gaurdian Name</b></td><td><?php echo($row['gname']);?></td></tr>
<tr><td><b>Guardian Occupation</b></td><td><?php echo($row['goccu']);?></td></tr>
<tr><td><b>Contact Numbers:</b></td><td><b>Mobile</b></td><td><?php echo($row['cnumm']);?></td></tr>
<tr><td></td><td><b>Home</b></td><td><?php echo($row['cnumh']);?></td>
<tr><td></td><td><b>Gaurdian</b></td><td><?php echo($row['cnumg']);?></td>
<tr><td><b>Address</b></td><td><?php echo($row['addr']);?></td></tr>
<tr><td><b>Standard</b></td><td><?php echo($row['std1']);?></td></tr>
<tr><td><b>School</b></td><td><?php echo($row['schl']);?></td></tr>
<tr><td><b>Interests</b></td><td><?php echo($row['intrs']);?></td></tr>
<tr><td><b>Physically Challenged</b></td><td><?php echo($row['pc']);?></td></tr>
<tr><td><b>If yes details</b></td><td><?php echo($row['pcdt']);?></td></tr>
<tr><td><b>Reason for Selection</b></td><td><?php echo($row['resec']);?></td></tr>
<tr><td><b>Blood group</b></td><td><?php echo($row['bldgp']);?></td></tr>
<tr><td><b>Mentor name</b></td><td><?php echo($row['mename']);?></td></tr>
<tr><td><b>Mentor contact</b></td><td><?php echo($row['menct']);?></td></tr>
<!-- <tr><td><b>Student Selection Form</td><td></td><td><input type="file" name="ss"></td></tr>
// <tr><td><b>Ward Profile Details</b></td><td><b>Year 1</b><td><input type="file" name="f1"></td></tr>
// <tr><td></td><td><b>Year 2</b></td><td><input type="file" name="f2"></td></tr>
//<tr><td></td><td><b>Year 3</b></td><td><input type="file" name="f3"></td></tr>
//<tr><td></td><td><b>Year 4</b></td><td><input type="file" name="f4"></td></tr>
//<tr><td></td><td><b>Year 5</b></td><td><input type="file" name="f5"></td></tr>
//<tr><td></td><td><b>Year 6</b></td><td><input type="file" name="f6"></td></tr> --!>
<tr><td><b>TIG Team</b></td><td><?php echo($row['tigt']);?></td></tr>
----------------------------------------------------------------------------------------------------------------------------------------------------<br>
----------------------------------------------------------------------------------------------------------------------------------------------------
<?php }
?>
<tr><td><a href="home.php">Home</a></td></tr>
</body>
</html> | ebayohblr2014/eBay-Opportunity-Hack-Blr-2014 | vazhai/studentviewa.php | PHP | mit | 3,866 |
<?php
//------------------------------------------------------------------------------
//*** Netherlands / "Vlaams" (Flemish) (nl)
//------------------------------------------------------------------------------
function setLanguageNl(){
$lang['='] = "="; // "equal";
$lang['>'] = ">"; // "bigger";
$lang['<'] = "<"; // "smaller";
$lang['add'] = "Toevoegen";
$lang['add_new'] = "+ nieuw";
$lang['add_new_record'] = "Voeg nieuwe record toe";
$lang['add_new_record_blocked'] = "Security check: poging van het toevoegen van een nieuw record! Controleer uw instellingen, wordt de operatie niet toegestaan!";
$lang['adding_operation_completed'] = "Toevoegen is geslaagd!";
$lang['adding_operation_uncompleted'] = "Toevoegen is niet voltooid!";
$lang['alert_perform_operation'] = "Weet u zeker dat u de uitvoering van deze operatie?";
$lang['alert_select_row'] = "U moet Selecteer een of meer rijen voor het uitvoeren van deze operatie!";
$lang['and'] = "en";
$lang['any'] = "eender";
$lang['ascending'] = "Oplopend";
$lang['back'] = "Terug";
$lang['cancel'] = "Annuleer";
$lang['cancel_creating_new_record'] = "Aanmaken van nieuwe record annuleren: bent u zeker?";
$lang['check_all'] = "Markeer alles";
$lang['clear'] = "Duidelijk";
$lang['click_to_download'] = "Klik om te downloaden";
$lang['clone_selected'] = "Kloon geselecteerd";
$lang['cloning_record_blocked'] = "Security check: poging van het klonen van een record! Controleer uw instellingen, wordt de operatie niet toegestaan!";
$lang['cloning_operation_completed'] = "Het klonen bewerking is voltooid!";
$lang['cloning_operation_uncompleted'] = "Het klonen onvoltooide!";
$lang['create'] = "Maak nieuw";
$lang['create_new_record'] = "Maak nieuwe record";
$lang['current'] = "huidige";
$lang['delete'] = "Verwijder";
$lang['delete_record'] = "Verwijder record";
$lang['delete_record_blocked'] = "Security check: poging van het verwijderen van een record! Controleer uw instellingen, is de operatie niet toegestaan!";
$lang['delete_selected'] = "Geselecteerde";
$lang['delete_selected_records'] = "Geselecteerde records verwijderen: bent u zeker?";
$lang['delete_this_record'] = "Deze record verwijderen: bent u zeker?";
$lang['deleting_operation_completed'] = "Verwijderen is geslaagd!";
$lang['deleting_operation_uncompleted'] = "Verwijderen is niet voltooid!";
$lang['descending'] = "Aflopend";
$lang['details'] = "Details";
$lang['details_selected'] = "Bekijk selectie";
$lang['download'] = "Downloaden";
$lang['edit'] = "Wijzig";
$lang['edit_selected'] = "Wijzig selectie";
$lang['edit_record'] = "Wijzig record";
$lang['edit_selected_records'] = "Bent u zeker dat u de geselecteerde records wilt wijzigen?";
$lang['errors'] = "Fouten";
$lang['export_to_excel'] = "Exporteer naar Excel";
$lang['export_to_pdf'] = "Exporteer naar PDF";
$lang['export_to_xml'] = "Exporteer naar XML";
$lang['export_message'] = "<label class=\"default_dg_label\">Het bestand _FILE_ is klaar. Wanneer u klaar bent met downloaden,</label> <a class=\"default_dg_error_message\" href=\"javascript: window.close();\">sluit dit venster</a>.";
$lang['field'] = "Veld";
$lang['field_value'] = "Waarde";
$lang['file_find_error'] = "Kan bestand niet vinden: <b>_FILE_</b>. <br>Controleer of dit bestand bestaat!";
$lang['file_opening_error'] = "Kan bestand niet openen. Kijk toegangsrechten na.";
$lang['file_extension_error'] = "File upload error: file extension not allowed for upload. Please select another file.";
$lang['file_writing_error'] = "Kan niet naar bestand schrijven. Kijk schrijfrechten na!";
$lang['file_invalid_file_size'] = "Ongeldige bestandsgrootte!";
$lang['file_uploading_error'] = "Fout bij uploaden bestand: probeer opnieuw!";
$lang['file_deleting_error'] = "Bestand kon niet verwijderd worden!";
$lang['first'] = "eerste";
$lang['format'] = "Formaat";
$lang['generate'] = "Het genereren van";
$lang['handle_selected_records'] = "Bent u zeker dat u de geselecteerde records wilt gebruiken?";
$lang['hide_search'] = "Verberg zoeken";
$lang['item'] = "item";
$lang['items'] = "artikelen";
$lang['last'] = "laatste";
$lang['like'] = "zoals";
$lang['like%'] = "zoals%"; // "begins with";
$lang['%like'] = "%zoals"; // "ends with";
$lang['%like%'] = "%zoals%";
$lang['loading_data'] = "bezig met laden...";
$lang['max'] = "max";
$lang['max_number_of_records'] = "Je hebt het maximale aantal toegestane records!";
$lang['move_down'] = "Omlaag";
$lang['move_up'] = "Omhoog";
$lang['move_operation_completed'] = "De bewegende rij-operatie is voltooid!";
$lang['move_operation_uncompleted'] = "De bewegende rij-operatie onvoltooide!";
$lang['next'] = "volgende";
$lang['no'] = "Nee";
$lang['no_data_found'] = "Geen gegevens gevonden";
$lang['no_data_found_error'] = "Geen gegevens gevonden! Kijk de syntax van uw code goed na!<br>Er kunnen problemen zijn met hoofdlettergevoeligheid of met onverwachte symbolen.";
$lang['no_image'] = "Geen afbeelding";
$lang['not_like'] = "niet zoals";
$lang['of'] = "van";
$lang['operation_was_already_done'] = "De operatie was reeds voltooid! Je kunt niet weer opnieuw proberen het.";
$lang['or'] = "van";
$lang['pages'] = "Pagina's";
$lang['page_size'] = "Paginalengte";
$lang['previous'] = "vorige";
$lang['printable_view'] = "Afdrukvoorbeeld";
$lang['print_now'] = "Nu afdrukken";
$lang['print_now_title'] = "Klik hier om deze pagina af te drukken";
$lang['record_n'] = "Record #";
$lang['refresh_page'] = "Pagina vernieuwen";
$lang['remove'] = "Verwijder";
$lang['reset'] = "Reset";
$lang['results'] = "Resultaten";
$lang['required_fields_msg'] = "Velden gemarkeerd met <font color='#cd0000'>*</font> zijn vereist";
$lang['search'] = "Zoek";
$lang['search_d'] = "Zoek"; // (description)
$lang['search_type'] = "Zoeken met";
$lang['select'] = "Selecteer";
$lang['set_date'] = "Stel datum in";
$lang['sort'] = "Sorteren";
$lang['test'] = "Test";
$lang['total'] = "Totaal";
$lang['turn_on_debug_mode'] = "Schakel debug modus in voor meer informatie.";
$lang['uncheck_all'] = "Niets gemarkeerd";
$lang['unhide_search'] = "Toon zoeken";
$lang['unique_field_error'] = "Het veld _FIELD_ laat enkel unieke waarden toe - opnieuw invoegen aub!";
$lang['update'] = "Bijwerken";
$lang['update_record'] = "Record bijwerken";
$lang['update_record_blocked'] = "Security check: poging van het bijwerken van een record! Controleer uw instellingen, is de operatie niet toegestaan!";
$lang['updating_operation_completed'] = "Bijwerken is geslaagd!";
$lang['updating_operation_uncompleted'] = "Bijwerken is niet voltooid!";
$lang['upload'] = "Uploaden";
$lang['uploaded_file_not_image'] = "Het geüploade bestand lijkt niet te zijn een afbeelding.";
$lang['view'] = "Details";
$lang['view_details'] = "Bekijk details";
$lang['warnings'] = "Waarschuwingen";
$lang['with_selected'] = "Met geselecteerde";
$lang['wrong_field_name'] = "Verkeerde veldnaam";
$lang['wrong_parameter_error'] = "Verkeerde parameter in [<b>_FIELD_</b>]: _VALUE_";
$lang['yes'] = "Ja";
// date-time
$lang['day'] = "dag";
$lang['month'] = "maanden";
$lang['year'] = "jaar";
$lang['hour'] = "uur";
$lang['min'] = "min";
$lang['sec'] = "sec";
$lang['months'][1] = "Januari";
$lang['months'][2] = "Februari";
$lang['months'][3] = "Maart";
$lang['months'][4] = "April";
$lang['months'][5] = "Kan";
$lang['months'][6] = "Juni";
$lang['months'][7] = "Juli";
$lang['months'][8] = "Augustus";
$lang['months'][9] = "September";
$lang['months'][10] = "Oktober";
$lang['months'][11] = "November";
$lang['months'][12] = "December";
return $lang;
}
?> | jessadayim/findtheroom | web/datagrid-backend/datagrid/languages/nl.php | PHP | mit | 8,191 |
<?php
/**
* Application.php
*
*/
namespace Pails\Listeners;
use Pails\Injectable;
class Application extends Injectable
{
public function boot($event, $application)
{
}
public function beforeStartModule($event, $application, $moduleName)
{
}
public function afterStartModule($event, $application, $module)
{
}
public function beforeHandleRequest($event, $application, $dispatcher)
{
}
public function afterHandleRequest($event, $application, $controller)
{
}
public function viewRender($event, $application, $view)
{
}
public function beforeSendResponse($event, $application, $response)
{
}
}
| xueron/pails | src/Pails/Listeners/Application.php | PHP | mit | 688 |
require 'rails_helper'
describe DwpMonitor do
subject(:service) { described_class.new }
it { is_expected.to be_a described_class }
describe 'methods' do
describe '.state' do
subject { service.state }
context 'when more than 50% of the last dwp_results are "400 Bad Request"' do
before { build_dwp_checks_with_bad_requests }
it { is_expected.to eql 'offline' }
end
context 'when more than 50% of the last dwp_results are validation "Bad Request"' do
before do
create_list :benefit_check, 10, dwp_result: 'BadRequest', error_message: 'entitlement_check_date is invalid'
end
it { is_expected.to eql 'online' }
end
context 'when more than 25% of the last dwp_results are "400 Bad Request"' do
before { build_dwp_checks_with_bad_requests(6, 4) }
it { is_expected.to eql 'warning' }
end
context 'checks for all error messages' do
before { build_dwp_checks_with_all_errors }
it { is_expected.to eql 'warning' }
end
context 'when less than 25% of the last dwp_results are "400 Bad Request"' do
before { build_dwp_checks_with_bad_requests(8, 2) }
it { is_expected.to eql 'online' }
end
end
end
end
| ministryofjustice/fr-staffapp | spec/services/dwp_monitor_spec.rb | Ruby | mit | 1,282 |
import { Assertions, Mouse, UiFinder } from '@ephox/agar';
import { Obj, Type } from '@ephox/katamari';
import { Attribute, Checked, Class, Focus, SugarBody, SugarElement, Traverse, Value } from '@ephox/sugar';
import { assert } from 'chai';
import Editor from 'tinymce/core/api/Editor';
export interface ImageDialogData {
src: {
value: string;
};
alt: string;
title: string;
decorative: boolean;
dimensions: {
width: string;
height: string;
};
caption: boolean;
class: string;
border: string;
hspace: string;
vspace: string;
borderstyle: string;
}
export const generalTabSelectors = {
src: 'label.tox-label:contains("Source") + div.tox-form__controls-h-stack div.tox-control-wrap input.tox-textfield',
title: 'label.tox-label:contains("Image title") + input.tox-textfield',
alt: 'label.tox-label:contains("Alternative description") + input.tox-textfield',
width: 'div.tox-form__controls-h-stack div label:contains("Width") + input.tox-textfield',
height: 'div.tox-form__controls-h-stack div label:contains("Height") + input.tox-textfield',
caption: 'label.tox-label:contains("Caption") + label input.tox-checkbox__input',
class: 'label.tox-label:contains("Class") + div.tox-listboxfield > .tox-listbox',
images: 'label.tox-label:contains("Image list") + div.tox-listboxfield > .tox-listbox',
decorative: 'label.tox-label:contains("Accessibility") + label.tox-checkbox>input'
};
export const advancedTabSelectors = {
border: 'label.tox-label:contains("Border width") + input.tox-textfield',
hspace: 'label.tox-label:contains("Horizontal space") + input.tox-textfield',
vspace: 'label.tox-label:contains("Vertical space") + input.tox-textfield',
borderstyle: 'label.tox-label:contains("Border style") + div.tox-listboxfield > .tox-listbox'
};
const isObjWithValue = (value: ImageDialogData[keyof ImageDialogData]): value is { value: string } =>
Type.isObject(value) && Obj.has(value as Record<string, any>, 'value');
const gotoAdvancedTab = (): void => {
const tab = UiFinder.findIn(SugarBody.body(), 'div.tox-tab:contains(Advanced)').getOrDie();
Mouse.click(tab);
};
const setFieldValue = (selector: string, value: string | boolean): SugarElement<HTMLElement> => {
const element = UiFinder.findIn<HTMLInputElement>(SugarBody.body(), selector).getOrDie();
Focus.focus(element);
if (element.dom.type === 'checkbox' && Type.isBoolean(value)) {
Checked.set(element, value);
} else if (Class.has(element, 'tox-listbox')) {
Attribute.set(element, 'data-value', value);
} else {
Value.set(element, String(value));
}
return element;
};
const setTabFieldValues = (data: Partial<ImageDialogData>, tabSelectors: Record<string, string>): void => {
Obj.each(tabSelectors, (value, key: keyof Omit<ImageDialogData, 'dimensions'>) => {
if (Obj.has(data, key)) {
const obj = data[key];
const newValue = isObjWithValue(obj) ? obj.value : obj;
setFieldValue(tabSelectors[key], newValue);
} else if (Obj.has(data, 'dimensions') && Obj.has(data.dimensions as Record<string, string>, key)) {
setFieldValue(tabSelectors[key], data.dimensions[key]);
}
});
};
const fillActiveDialog = (data: Partial<ImageDialogData>, hasAdvanced = false): void => {
setTabFieldValues(data, generalTabSelectors);
if (hasAdvanced) {
gotoAdvancedTab();
setTabFieldValues(data, advancedTabSelectors);
}
};
const fakeEvent = (elm: SugarElement<Node>, name: string): void => {
const evt = document.createEvent('HTMLEvents');
evt.initEvent(name, true, true);
elm.dom.dispatchEvent(evt);
};
const setInputValue = (selector: string, value: string): SugarElement<HTMLElement> => {
const field = setFieldValue(selector, value);
fakeEvent(field, 'input');
return field;
};
const setSelectValue = (selector: string, value: string): SugarElement<HTMLElement> => {
const field = setFieldValue(selector, value);
fakeEvent(field, 'change');
return field;
};
const cleanHtml = (html: string): string =>
html.replace(/<p>( |<br[^>]+>)<\/p>$/, '');
const assertCleanHtml = (label: string, editor: Editor, expected: string): void =>
Assertions.assertHtml(label, expected, cleanHtml(editor.getContent()));
const assertInputValue = (selector: string, expected: string): void => {
const element = UiFinder.findIn<HTMLInputElement>(SugarBody.body(), selector).getOrDie();
const value = Value.get(element);
assert.equal(value, expected, `input value should be ${expected}`);
};
const assertInputCheckbox = (selector: string, expectedState: boolean): void => {
const element = UiFinder.findIn<HTMLInputElement>(SugarBody.body(), selector).getOrDie();
const value = Checked.get(element);
assert.equal(value, expectedState, `input value should be ${expectedState}`);
};
const pSetListBoxItem = async (selector: string, itemText: string): Promise<void> => {
const listBox = UiFinder.findIn(SugarBody.body(), selector).getOrDie();
Mouse.click(listBox);
await UiFinder.pWaitForVisible('Wait for list to open', SugarBody.body(), '.tox-menu.tox-collection--list');
const item = UiFinder.findIn(SugarBody.body(), '.tox-collection__item-label:contains(' + itemText + ')').getOrDie();
const itemParent = Traverse.parent(item).getOrDie('Failed to find list box item parent');
Mouse.click(itemParent);
};
export {
fillActiveDialog,
fakeEvent,
setInputValue,
setSelectValue,
assertCleanHtml,
assertInputValue,
assertInputCheckbox,
pSetListBoxItem
};
| tinymce/tinymce | modules/tinymce/src/plugins/image/test/ts/module/Helpers.ts | TypeScript | mit | 5,504 |
package appeng.api.parts.layers;
import ic2.api.energy.tile.IEnergySink;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.common.ForgeDirection;
import appeng.api.parts.IBusPart;
import appeng.api.parts.LayerBase;
public class LayerIEnergySink extends LayerBase implements IEnergySink
{
@Override
public boolean acceptsEnergyFrom(TileEntity emitter, ForgeDirection direction)
{
IBusPart part = getPart( direction );
if ( part instanceof IEnergySink )
return ((IEnergySink) part).acceptsEnergyFrom( emitter, direction );
return false;
}
@Override
public double demandedEnergyUnits()
{
// this is a flawed implementation, that requires a change to the IC2 API.
double maxRequired = 0;
for (ForgeDirection dir : ForgeDirection.VALID_DIRECTIONS)
{
IBusPart part = getPart( dir );
if ( part instanceof IEnergySink )
{
// use lower number cause ic2 deletes power it sends that isn't recieved.
maxRequired = Math.min( maxRequired, ((IEnergySink) part).demandedEnergyUnits() );
}
}
return maxRequired;
}
@Override
public double injectEnergyUnits(ForgeDirection directionFrom, double amount)
{
IBusPart part = getPart( directionFrom );
if ( part instanceof IEnergySink )
return ((IEnergySink) part).injectEnergyUnits( directionFrom, amount );
return amount;
}
@Override
public int getMaxSafeInput()
{
return Integer.MAX_VALUE; // no real options here...
}
}
| Gamoholic/Applied-Energistics-2-API | parts/layers/LayerIEnergySink.java | Java | mit | 1,448 |
// main.go
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
var router *gin.Engine
func main() {
// Set Gin to production mode
gin.SetMode(gin.ReleaseMode)
// Set the router as the default one provided by Gin
router = gin.Default()
// Process the templates at the start so that they don't have to be loaded
// from the disk again. This makes serving HTML pages very fast.
router.LoadHTMLGlob("templates/*")
// Initialize the routes
initializeRoutes()
// Start serving the application
router.Run()
}
// Render one of HTML, JSON or CSV based on the 'Accept' header of the request
// If the header doesn't specify this, HTML is rendered, provided that
// the template name is present
func render(c *gin.Context, data gin.H, templateName string) {
loggedInInterface, _ := c.Get("is_logged_in")
data["is_logged_in"] = loggedInInterface.(bool)
switch c.Request.Header.Get("Accept") {
case "application/json":
// Respond with JSON
c.JSON(http.StatusOK, data["payload"])
case "application/xml":
// Respond with XML
c.XML(http.StatusOK, data["payload"])
default:
// Respond with HTML
c.HTML(http.StatusOK, templateName, data)
}
}
| demo-apps/go-gin-app | main.go | GO | mit | 1,177 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BillPrint
{
public class Print
{
}
}
| mkmpvtltd1/mkm-BookStore | BillPrint/Print.cs | C# | mit | 149 |
// Description: Entity Framework Bulk Operations & Utilities (EF Bulk SaveChanges, Insert, Update, Delete, Merge | LINQ Query Cache, Deferred, Filter, IncludeFilter, IncludeOptimize | Audit)
// Website & Documentation: https://github.com/zzzprojects/Entity-Framework-Plus
// Forum & Issues: https://github.com/zzzprojects/EntityFramework-Plus/issues
// License: https://github.com/zzzprojects/EntityFramework-Plus/blob/master/LICENSE
// More projects: http://www.zzzprojects.com/
// Copyright © ZZZ Projects Inc. 2014 - 2016. All rights reserved.
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Z.EntityFramework.Plus;
namespace Z.Test.EntityFramework.Plus
{
public partial class BatchDelete_Executing
{
[TestMethod]
public void WhileDelayTemplate()
{
TestContext.DeleteAll(x => x.Entity_Basics);
TestContext.Insert(x => x.Entity_Basics, 50);
using (var ctx = new TestContext())
{
var sql = "";
// BEFORE
Assert.AreEqual(1225, ctx.Entity_Basics.Sum(x => x.ColumnInt));
// ACTION
var rowsAffected = ctx.Entity_Basics.Where(x => x.ColumnInt > 10 && x.ColumnInt <= 40).Delete(delete =>
{
delete.BatchDelayInterval = 50;
delete.Executing = command => sql = command.CommandText;
});
// AFTER
Assert.AreEqual(460, ctx.Entity_Basics.Sum(x => x.ColumnInt));
Assert.AreEqual(30, rowsAffected);
#if EF5
Assert.AreEqual(@"
DECLARE @stop int
DECLARE @rowAffected INT
DECLARE @totalRowAffected INT
SET @stop = 0
SET @totalRowAffected = 0
WHILE @stop=0
BEGIN
IF @rowAffected IS NOT NULL
BEGIN
WAITFOR DELAY '00:00:00:050'
END
DELETE TOP (4000)
FROM A
FROM [dbo].[Entity_Basic] AS A
INNER JOIN ( SELECT
[Extent1].[ID] AS [ID]
FROM [dbo].[Entity_Basic] AS [Extent1]
WHERE ([Extent1].[ColumnInt] > 10) AND ([Extent1].[ColumnInt] <= 40)
) AS B ON A.[ID] = B.[ID]
SET @rowAffected = @@ROWCOUNT
SET @totalRowAffected = @totalRowAffected + @rowAffected
IF @rowAffected < 4000
SET @stop = 1
END
SELECT @totalRowAffected
", sql);
#elif EF6
Assert.AreEqual(@"
DECLARE @stop int
DECLARE @rowAffected INT
DECLARE @totalRowAffected INT
SET @stop = 0
SET @totalRowAffected = 0
WHILE @stop=0
BEGIN
IF @rowAffected IS NOT NULL
BEGIN
WAITFOR DELAY '00:00:00:050'
END
DELETE TOP (4000)
FROM A
FROM [dbo].[Entity_Basic] AS A
INNER JOIN ( SELECT
[Extent1].[ID] AS [ID]
FROM [dbo].[Entity_Basic] AS [Extent1]
WHERE ([Extent1].[ColumnInt] > 10) AND ([Extent1].[ColumnInt] <= 40)
) AS B ON A.[ID] = B.[ID]
SET @rowAffected = @@ROWCOUNT
SET @totalRowAffected = @totalRowAffected + @rowAffected
IF @rowAffected < 4000
SET @stop = 1
END
SELECT @totalRowAffected
", sql);
#elif EFCORE_2X
Assert.AreEqual(@"
DECLARE @stop int
DECLARE @rowAffected INT
DECLARE @totalRowAffected INT
SET @stop = 0
SET @totalRowAffected = 0
WHILE @stop=0
BEGIN
IF @rowAffected IS NOT NULL
BEGIN
WAITFOR DELAY '00:00:00:050'
END
DELETE TOP (4000)
FROM A
FROM [Entity_Basic] AS A
INNER JOIN ( SELECT [x].[ID]
FROM [Entity_Basic] AS [x]
WHERE ([x].[ColumnInt] > 10) AND ([x].[ColumnInt] <= 40)
) AS B ON A.[ID] = B.[ID]
SET @rowAffected = @@ROWCOUNT
SET @totalRowAffected = @totalRowAffected + @rowAffected
IF @rowAffected < 4000
SET @stop = 1
END
SELECT @totalRowAffected
", sql);
#elif EFCORE_3X
Assert.AreEqual(@"
DECLARE @stop int
DECLARE @rowAffected INT
DECLARE @totalRowAffected INT
SET @stop = 0
SET @totalRowAffected = 0
WHILE @stop=0
BEGIN
IF @rowAffected IS NOT NULL
BEGIN
WAITFOR DELAY '00:00:00:050'
END
DELETE TOP (4000)
FROM A
FROM [Entity_Basic] AS A
INNER JOIN ( SELECT [e].[ID]
FROM [Entity_Basic] AS [e]
WHERE ([e].[ColumnInt] > 10) AND ([e].[ColumnInt] <= 40)
) AS B ON A.[ID] = B.[ID]
SET @rowAffected = @@ROWCOUNT
SET @totalRowAffected = @totalRowAffected + @rowAffected
IF @rowAffected < 4000
SET @stop = 1
END
SELECT @totalRowAffected
", sql);
#endif
}
}
}
} | zzzprojects/EntityFramework-Plus | src/Z.Test.EntityFramework.Plus.EFCore.Shared/BatchDelete/Executing/WhileDelayTemplate.cs | C# | mit | 4,820 |
=begin
Write a method max_duffel_bag_value() that takes an array of cake type arrays and a weight capacity, and returns the maximum monetary value the duffel bag can hold.
=end
cake_arrays = [[7, 160], [3, 90], [2, 15]]
capacity = 20
def max_duffel_bag_value(cake_arrays, capacity)
cake_arrays.sort { |a, b| b[1] / b[0] <=> a[1] / a[0] }
current_max = 0
current_value = 0
end
puts "#{cake_arrays.sort { |a, b| b[1] / b[0] <=> a[1] / a[0] }}"
| KEN-chan/til | algorithm/max_duffel_bag_value.rb | Ruby | mit | 457 |
(function($){
$(document).ready(function(){
$('.rainbowcake').rainbowcake();
});
}(jQuery)); | jgett/rainbowcake | client/js/client.js | JavaScript | mit | 100 |
import os
import re
import subprocess
from utils import whereis_exe
class osx_voice():
def __init__(self, voice_line):
mess = voice_line.split(' ')
cleaned = [ part for part in mess if len(part)>0 ]
self.name = cleaned[0]
self.locality = cleaned[1]
self.desc = cleaned[2].replace('# ', '')
def __str__(self):
return self.name + ' ' + self.locality + ' ' + self.desc
def fetch_voices():
osx_voices = []
if whereis_exe("say"):
voices_raw = os.popen("say -v ?").read()
voice_lines = voices_raw.split('\n')
for line in voice_lines:
try:
osx_voices.append(osx_voice(line))
except IndexError:
pass
return osx_voices
def speak(text, voice, rate):
if whereis_exe("say"):
subprocess.call(["say", text, "-v", voice, "-r", rate])
| brousch/saythis2 | tts_engines/osx_say.py | Python | mit | 888 |
import { Pkcs10CertificateRequest } from "@peculiar/x509";
import * as graphene from "graphene-pk11";
import { Convert } from "pvtsutils";
import * as core from "webcrypto-core";
import { CryptoKey } from "../key";
import { Pkcs11Object } from "../p11_object";
import { CryptoCertificate, Pkcs11ImportAlgorithms } from "./cert";
export class X509CertificateRequest extends CryptoCertificate implements core.CryptoX509CertificateRequest {
public get subjectName() {
return this.getData()?.subject;
}
public type: "request" = "request";
public p11Object?: graphene.Data;
public csr?: Pkcs10CertificateRequest;
public get value(): ArrayBuffer {
Pkcs11Object.assertStorage(this.p11Object);
return new Uint8Array(this.p11Object.value).buffer as ArrayBuffer;
}
/**
* Creates new CertificateRequest in PKCS11 session
* @param data
* @param algorithm
* @param keyUsages
*/
public async importCert(data: Buffer, algorithm: Pkcs11ImportAlgorithms, keyUsages: KeyUsage[]) {
const array = new Uint8Array(data).buffer as ArrayBuffer;
this.parse(array);
const { token, label, sensitive, ...keyAlg } = algorithm; // remove custom attrs for key
this.publicKey = await this.getData().publicKey.export(keyAlg, keyUsages, this.crypto as globalThis.Crypto) as CryptoKey;
const hashSPKI = this.publicKey.p11Object.id;
const template = this.crypto.templateBuilder.build({
action: "import",
type: "request",
attributes: {
id: hashSPKI,
label: algorithm.label || "X509 Request",
token: !!(algorithm.token),
},
})
// set data attributes
template.value = Buffer.from(data);
this.p11Object = this.crypto.session.create(template).toType<graphene.Data>();
}
public async exportCert() {
return this.value;
}
public toJSON() {
return {
publicKey: this.publicKey.toJSON(),
subjectName: this.subjectName,
type: this.type,
value: Convert.ToBase64Url(this.value),
};
}
public async exportKey(): Promise<CryptoKey>;
public async exportKey(algorithm: Algorithm, usages: KeyUsage[]): Promise<CryptoKey>;
public async exportKey(algorithm?: Algorithm, usages?: KeyUsage[]) {
if (!this.publicKey) {
const publicKeyID = this.id.replace(/\w+-\w+-/i, "");
const keyIndexes = await this.crypto.keyStorage.keys();
for (const keyIndex of keyIndexes) {
const parts = keyIndex.split("-");
if (parts[0] === "public" && parts[2] === publicKeyID) {
if (algorithm && usages) {
this.publicKey = await this.crypto.keyStorage.getItem(keyIndex, algorithm, true, usages);
} else {
this.publicKey = await this.crypto.keyStorage.getItem(keyIndex);
}
break;
}
}
if (!this.publicKey) {
if (algorithm && usages) {
this.publicKey = await this.getData().publicKey.export(algorithm, usages, this.crypto as globalThis.Crypto) as CryptoKey;
} else {
this.publicKey = await this.getData().publicKey.export(this.crypto as globalThis.Crypto) as CryptoKey;
}
}
}
return this.publicKey;
}
protected parse(data: ArrayBuffer) {
this.csr = new Pkcs10CertificateRequest(data);
}
/**
* returns parsed ASN1 value
*/
protected getData() {
if (!this.csr) {
this.parse(this.value);
}
return this.csr!;
}
}
| PeculiarVentures/node-webcrypto-p11 | src/certs/csr.ts | TypeScript | mit | 3,449 |
#ifndef __BD_SO_BROADCASTCENTER__
#define __BD_SO_BROADCASTCENTER__
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string>
#include <cstring>
#include <strings.h>
const int MAXDATASIZE = 256;
namespace bd_so {
class BroadcastCenter {
private:
bool is_sender; /// is a caster;
bool is_casting; /// is sending broadcast
bool is_receiving; /// is waiting broadcast
void init_addr(); /// init sockets
int socket_fd;
struct sockaddr_in my_addr,user_addr;
char buf[MAXDATASIZE];
int so_broadcast = 1;
char my_ip[20];
public:
BroadcastCenter(bool is_s):is_sender(is_s) {
init_addr();
}
void startSend(std::string msg,std::string &server_ip);
static void start_listen_thread(void);
friend void startReceiving(void *);
};
void startReceiving(void *);
};
#endif
| ZQYA/broadcasthome | broadcast/broadcast.hpp | C++ | mit | 805 |
<?php
/* FOSUserBundle:Registration:register_content.html.twig */
class __TwigTemplate_95d43d3d47f0cebed743a080cf5ec4515b09f53f648044d0e4ad5b16ddbd90ab extends Twig_Template
{
public function __construct(Twig_Environment $env)
{
parent::__construct($env);
$this->parent = false;
$this->blocks = array(
);
}
protected function doDisplay(array $context, array $blocks = array())
{
// line 2
echo "
";
// line 3
echo $this->env->getExtension('form')->renderer->renderBlock((isset($context["form"]) ? $context["form"] : null), 'form_start', array("method" => "post", "action" => $this->env->getExtension('routing')->getPath("fos_user_registration_register"), "attr" => array("class" => "fos_user_registration_register")));
echo "
";
// line 4
echo $this->env->getExtension('form')->renderer->searchAndRenderBlock((isset($context["form"]) ? $context["form"] : null), 'widget');
echo "
<div>
<input type=\"submit\" value=\"";
// line 6
echo twig_escape_filter($this->env, $this->env->getExtension('translator')->trans("registration.submit", array(), "FOSUserBundle"), "html", null, true);
echo "\" />
</div>
";
// line 8
echo $this->env->getExtension('form')->renderer->renderBlock((isset($context["form"]) ? $context["form"] : null), 'form_end');
echo "
";
}
public function getTemplateName()
{
return "FOSUserBundle:Registration:register_content.html.twig";
}
public function isTraitable()
{
return false;
}
public function getDebugInfo()
{
return array ( 36 => 8, 31 => 6, 26 => 4, 22 => 3, 19 => 2,);
}
}
/* {% trans_default_domain 'FOSUserBundle' %}*/
/* */
/* {{ form_start(form, {'method': 'post', 'action': path('fos_user_registration_register'), 'attr': {'class': 'fos_user_registration_register'}}) }}*/
/* {{ form_widget(form) }}*/
/* <div>*/
/* <input type="submit" value="{{ 'registration.submit'|trans }}" />*/
/* </div>*/
/* {{ form_end(form) }}*/
/* */
| DevKhater/YallaWebSite | app/cache/prod/twig/5e/5e3292f12bc65076b5a0da4b70a00b8df21396b14e3dfce7dc509c5ef4167279.php | PHP | mit | 2,159 |
// function add(a, b){
// return a+b;
// }
//
// console.log(add(3,1));
//
// var toAdd = [9, 5];
// console.log(add(...toAdd));
// var groupA = ['Jen', 'Cory'];
// var groupB = ['Vikram'];
// var final = [...groupB, 3, ...groupA];
// console.log(...final);
var person = ['Andew', 25];
var personTwo = ['Jen', 29];
function greetingAge(a, b){
return 'Hi '+a+', you are '+ b;
}
console.log(greetingAge(...person));
console.log(greetingAge(...personTwo));
var names = ['Mike', 'Ben'];
var final = ['Quentin', ...names];
for(i in final){
console.log('Hi '+ final[i]);
}
| kana7/react-todo | playground/spread.js | JavaScript | mit | 577 |
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {DateAdapter} from '@angular/material/core';
/**
* Function that attempts to coerce a value to a date using a DateAdapter. Date instances, null,
* and undefined will be passed through. Empty strings will be coerced to null. Valid ISO 8601
* strings (https://www.ietf.org/rfc/rfc3339.txt) will be coerced to dates. All other values will
* result in an error being thrown.
* @param adapter The date adapter to use for coercion
* @param value The value to coerce.
* @return A date object coerced from the value.
* @throws Throws when the value cannot be coerced.
*/
export function coerceDateProperty<D>(adapter: DateAdapter<D>, value: any): D | null {
if (typeof value === 'string') {
if (value == '') {
value = null;
} else {
value = adapter.fromIso8601(value) || value;
}
}
if (value == null || adapter.isDateInstance(value)) {
return value;
}
throw Error(`Datepicker: Value must be either a date object recognized by the DateAdapter or ` +
`an ISO 8601 string. Instead got: ${value}`);
}
| jasnoponjatno/material2 | src/lib/datepicker/coerce-date-property.ts | TypeScript | mit | 1,262 |
<?php
/**
* Framey Framework
*
* @copyright Copyright Framey
*/
namespace app\framework\Component\Storage\Driver;
/**
* Interface DirectoryAwareInterface
*
* @package app\framework\Component\Storage\Driver
*/
interface DirectoryAwareInterface
{
/**
* Check if key is directory
*
* @param string $key
*
* @return boolean
*/
public function isDirectory($key);
} | MrFibunacci/Framy | app/framework/Component/Storage/Driver/DirectoryAwareInterface.php | PHP | mit | 475 |
<?php
/* SVN FILE: $Id$ */
/**
* Short description for file.
*
* In this file, you set up routes to your controllers and their actions.
* Routes are very important mechanism that allows you to freely connect
* different urls to chosen controllers and their actions (functions).
*
* PHP versions 4 and 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright 2005-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @package cake
* @subpackage cake.app.config
* @since CakePHP(tm) v 0.2.9
* @version $Revision$
* @modifiedby $LastChangedBy$
* @lastmodified $Date$
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
/**
* Here, we are connecting '/' (base path) to controller called 'Pages',
* its action called 'display', and we pass a param to select the view file
* to use (in this case, /app/views/pages/home.ctp)...
*
*/
require_once CORE_PATH.'app'.DS.'plugins'.DS.'PluginManager'.DS.'bootstrap.php';
Router::connect('/', array('plugin' => 'olog', 'controller' => 'logs', 'action' => 'index', 'home'));
/**
* ...and connect the rest of 'Pages' controller's urls.
*/
Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));
?> | Olog/olog-logbook | logbook/app/config/routes.php | PHP | mit | 1,561 |
import urllib2
import os
baseurl = "http://ceoaperms.ap.gov.in/TS_Rolls/PDFGeneration.aspx?urlPath=D:\SSR2016_Final\Telangana\AC_001\English\S29A"
constituencyCount = 0
constituencyTotal = 229
while constituencyCount <= constituencyTotal:
pdfCount = 1
notDone = True
constituencyCount = constituencyCount + 1
while notDone:
http://ceoaperms.ap.gov.in/TS_Rolls/PDFGeneration.aspx?urlPath=D:\SSR2016_Final\Telangana\AC_001\English\S29A001P001.PDF
url = baseurl+str(constituencyCount).zfill(2)+'P'+str(pdfCount).zfill(3)+".pdf"
pdfCount = pdfCount + 1
try:
u = urllib2.urlopen(url)
response_headers = u.info()
if response_headers.type == 'application/pdf':
directory = "Path to dir" + str(constituencyCount).zfill(3) + "/"
try:
os.makedirs(directory)
except OSError:
pass # already exists
file_name = directory + url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,
f.close()
else:
notDone = False
except urllib2.URLError, e:
if e.code == 404:
notDone = False
| abhishek-malani/python-basic-coding | python-basic-coding/python-basic-coding/voter_data_download.py | Python | mit | 1,936 |
package asciifier;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import javax.imageio.ImageIO;
/**
* A program that "ASCIIfies" a given input image using a given character/symbol.
* It takes an input image and creates a new image where all the pixels from the input
* image are drawn as the given character/symbol.
*
* @author Joel Abrahamsson
* @version %G%
*/
public class ASCIIfier
{
private BufferedImage input;
private BufferedImage output;
private Font font = new Font(Font.SANS_SERIF, Font.PLAIN, 8);
private FontMetrics metrics;
private HashMap<Integer, Color> colors;
private char lastChar;
/**
* Creates a new ASCIIfier which uses the given image as input image when ASCIIfying.
*
* @param image the image to ASCIIfy.
*/
public ASCIIfier(BufferedImage image)
{
input = image;
metrics = input.createGraphics().getFontMetrics(font);
createColorMap();
}
/**
* Creates a HashMap of all colors in the input image.
*/
private void createColorMap()
{
colors = new HashMap<Integer, Color>();
if (input != null)
{
int height = input.getHeight(),
width = input.getWidth();
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int color = input.getRGB(x, y);
if (!colors.containsKey(color))
colors.put(color, new Color(color));
}
}
}
}
/**
* Creates a new BufferedImage with the right dimensions.
*
* @param c the character to use as reference for image width and height
*/
private void createOutputImage(char c)
{
if (input != null)
{
int charWidth = metrics.charWidth(c),
charHeight = metrics.getAscent() + metrics.getDescent(),
charSize = Math.max(charWidth, charHeight),
width = charSize * input.getWidth(),
height = charSize * input.getHeight();
output = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
System.out.printf("Input (%d, %d); Output (%d, %d)\n", input.getWidth(), input.getHeight(),
output.getWidth(), output.getHeight());
}
}
/**
* Returns the processed image.
*
* @return the processed image
* @see BufferedImage
*/
public BufferedImage getProcessedImage()
{
return output;
}
/**
* ASCIIfies the input image using the given character.
*
* @param c the character to use to ASCIIfy the input image
*/
public void process(char c)
{
if (output == null || lastChar != c)
{
createOutputImage(c);
lastChar = c;
}
Graphics2D g = output.createGraphics();
int height = input.getHeight(),
width = input.getWidth(),
ascent = metrics.getAscent(),
charWidth = metrics.charWidth(c),
charHeight = ascent + metrics.getDescent(),
charSize = Math.max(charWidth, charHeight);
String s = Character.toString(c);
g.setFont(font);
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
g.setColor(colors.get(input.getRGB(x, y)));
g.drawString(s, x * charSize, y * charSize + ascent);
}
}
g.dispose();
}
/**
* Changes the font to use to create the image.
*
* @param font the font to use
* @see Font
*/
public void setFont(Font font)
{
if (font != null && input != null)
{
this.font = font;
metrics = input.createGraphics().getFontMetrics(font);
if (lastChar != '\u0000')
createOutputImage(lastChar);
}
}
/**
* Changes the size of the current font.
*
* @param size the new font size
*/
public void setFontSize(float size)
{
setFont(font.deriveFont(size));
}
/**
* Usage:
* java ASCIIfier IMAGE CHARACTER [FONT SIZE]
*
* IMAGE - The input image.
* CHARACTER - The character to use when ASCIIfying.
* [FONT SIZE] - Optional, change the font size
*/
public static void main(String[] args)
{
if (args.length > 1)
{
try
{
BufferedImage image = ImageIO.read(new File(args[0]));
if (image != null)
{
ASCIIfier asciifier = new ASCIIfier(image);
if (args.length > 2)
{
float fontSize = Float.parseFloat(args[2]);
asciifier.setFontSize(fontSize);
}
asciifier.process(args[1].charAt(0));
ImageIO.write(asciifier.getProcessedImage(), "png", new File(args[0] + "_asciified.png"));
}
}
catch (Exception e)
{
System.err.println(e.getMessage());
e.printStackTrace();
}
}
else
{
System.out.println("Usage:");
System.out.println("java ASCIIfier IMAGE CHARACTER [FONT SIZE]");
}
}
}
| joelabr/Laborationer-Programmering-1 | asciifier/ASCIIfier.java | Java | mit | 5,077 |
#!/usr/bin/env python3
# Advent of Code 2016 - Day 7, Part One
import sys
import re
from itertools import islice
def window(seq, n=2):
"Returns a sliding window (of width n) over data from the iterable"
" s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ... "
it = iter(seq)
result = tuple(islice(it, n))
if len(result) == n:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result
def has_abba(string):
for s in window(string, 4):
if s[:2] == s[:1:-1] and s[0] != s[1]:
return True
return False
def main(argv):
if len(argv) < 2:
print("Usage: day07-pt1.py puzzle.txt")
return 1
valid = 0
with open(argv[1]) as f:
for line in f:
nets = re.split('[\[\]]', line.strip())
if any(has_abba(s) for s in nets[::2]) \
and not any(has_abba(h) for h in nets[1::2]):
valid += 1
print(valid)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
| mcbor/adventofcode | 2016/day07/day07-pt1.py | Python | mit | 1,067 |
Brick.util.Language.add('en',{'mod': {'{C#MODNAME}':{
'accounteditor': {
'widget': {
'1': 'Add account'
},
'editor': {
'1': 'Edit account',
'2': 'Create account',
'3': 'Save',
'4': 'Cancel',
'5': 'Close'
},
'row': {
'1': 'Remove this account',
'2': 'Remove',
'3': 'Account type',
'4': 'Title',
'5': 'Remark',
'6': 'Opening balance',
'7': 'Currency',
'8': 'Member account'
}
}
}}}); | abricos/abricos-mod-money | src/js/langs/accountEditor_en.js | JavaScript | mit | 437 |
function solve(params) {
var number = +params[0]
switch (number) {
case 0:
return 'zero';
break;
case 1:
return 'one';
break;
case 2:
return 'two';
break;
case 3:
return 'three';
break;
case 4:
return 'four';
break;
case 5:
return 'five';
break;
case 6:
return 'six';
break;
case 7:
return 'seven';
break;
case 8:
return 'eight';
break;
case 9:
return 'nine';
break;
default:
return 'not a digit'
break;
}
} | SHAMMY1/Telerik-Academy-2016 | JSFundamentals/Homeworks/05.conditional-statements/05.digit-as-word/app.js | JavaScript | mit | 772 |
export default [
{
'English short name': 'Afghanistan',
'French short name': "Afghanistan (l')",
'Alpha-2 code': 'AF',
'Alpha-3 code': 'AFG',
Numeric: 4,
Capital: 'Kaboul',
Continent: 5,
},
{
'English short name': 'Åland Islands',
'French short name': 'Åland(les Îles)',
'Alpha-2 code': 'AX',
'Alpha-3 code': 'ALA',
Numeric: 248,
Capital: 'Mariehamn',
Continent: 4,
},
{
'English short name': 'Albania',
'French short name': "Albanie (l')",
'Alpha-2 code': 'AL',
'Alpha-3 code': 'ALB',
Numeric: 8,
Capital: 'Tirana',
Continent: 4,
},
{
'English short name': 'Algeria',
'French short name': "Algérie (l')",
'Alpha-2 code': 'DZ',
'Alpha-3 code': 'DZA',
Numeric: 12,
Capital: 'Alger',
Continent: 3,
},
{
'English short name': 'American Samoa',
'French short name': 'Samoa américaines (les)',
'Alpha-2 code': 'AS',
'Alpha-3 code': 'ASM',
Numeric: 16,
Capital: 'Pago Pago',
Continent: 6,
},
{
'English short name': 'Andorra',
'French short name': "Andorre (l')",
'Alpha-2 code': 'AD',
'Alpha-3 code': 'AND',
Numeric: 20,
Capital: 'Andorre-la-Vieille',
Continent: 4,
},
{
'English short name': 'Angola',
'French short name': "Angola (l')",
'Alpha-2 code': 'AO',
'Alpha-3 code': 'AGO',
Numeric: 24,
Capital: 'Luanda',
Continent: 3,
},
{
'English short name': 'Anguilla',
'French short name': 'Anguilla',
'Alpha-2 code': 'AI',
'Alpha-3 code': 'AIA',
Numeric: 660,
Capital: 'The Valley',
Continent: 1,
},
{
'English short name': 'Antarctica',
'French short name': "Antarctique (l')",
'Alpha-2 code': 'AQ',
'Alpha-3 code': 'ATA',
Numeric: 10,
Capital: '',
Continent: 7,
},
{
'English short name': 'Antigua and Barbuda',
'French short name': 'Antigua-et-Barbuda',
'Alpha-2 code': 'AG',
'Alpha-3 code': 'ATG',
Numeric: 28,
Capital: "Saint John's",
Continent: 1,
},
{
'English short name': 'Argentina',
'French short name': "Argentine (l')",
'Alpha-2 code': 'AR',
'Alpha-3 code': 'ARG',
Numeric: 32,
Capital: 'Buenos Aires',
Continent: 2,
},
{
'English short name': 'Armenia',
'French short name': "Arménie (l')",
'Alpha-2 code': 'AM',
'Alpha-3 code': 'ARM',
Numeric: 51,
Capital: 'Erevan',
Continent: 4,
},
{
'English short name': 'Aruba',
'French short name': 'Aruba',
'Alpha-2 code': 'AW',
'Alpha-3 code': 'ABW',
Numeric: 533,
Capital: 'Oranjestad',
Continent: 1,
},
{
'English short name': 'Australia',
'French short name': "Australie (l')",
'Alpha-2 code': 'AU',
'Alpha-3 code': 'AUS',
Numeric: 36,
Capital: 'Canberra',
Continent: 6,
},
{
'English short name': 'Austria',
'French short name': "Autriche (l')",
'Alpha-2 code': 'AT',
'Alpha-3 code': 'AUT',
Numeric: 40,
Capital: 'Vienne',
Continent: 4,
},
{
'English short name': 'Azerbaijan',
'French short name': "Azerbaïdjan (l')",
'Alpha-2 code': 'AZ',
'Alpha-3 code': 'AZE',
Numeric: 31,
Capital: 'Bakou',
Continent: 5,
},
{
'English short name': 'Bahamas (the)',
'French short name': 'Bahamas (les)',
'Alpha-2 code': 'BS',
'Alpha-3 code': 'BHS',
Numeric: 44,
Capital: 'Nassau',
Continent: 1,
},
{
'English short name': 'Bahrain',
'French short name': 'Bahreïn',
'Alpha-2 code': 'BH',
'Alpha-3 code': 'BHR',
Numeric: 48,
Capital: 'Manama',
Continent: 5,
},
{
'English short name': 'Bangladesh',
'French short name': 'Bangladesh (le)',
'Alpha-2 code': 'BD',
'Alpha-3 code': 'BGD',
Numeric: 50,
Capital: 'Dacca',
Continent: 5,
},
{
'English short name': 'Barbados',
'French short name': 'Barbade (la)',
'Alpha-2 code': 'BB',
'Alpha-3 code': 'BRB',
Numeric: 52,
Capital: 'Bridgetown',
Continent: 1,
},
{
'English short name': 'Belarus',
'French short name': 'Bélarus (le)',
'Alpha-2 code': 'BY',
'Alpha-3 code': 'BLR',
Numeric: 112,
Capital: 'Minsk',
Continent: 5,
},
{
'English short name': 'Belgium',
'French short name': 'Belgique (la)',
'Alpha-2 code': 'BE',
'Alpha-3 code': 'BEL',
Numeric: 56,
Capital: 'Bruxelles',
Continent: 4,
},
{
'English short name': 'Belize',
'French short name': 'Belize (le)',
'Alpha-2 code': 'BZ',
'Alpha-3 code': 'BLZ',
Numeric: 84,
Capital: 'Belmopan',
Continent: 1,
},
{
'English short name': 'Benin',
'French short name': 'Bénin (le)',
'Alpha-2 code': 'BJ',
'Alpha-3 code': 'BEN',
Numeric: 204,
Capital: 'Porto-Novo',
Continent: 3,
},
{
'English short name': 'Bermuda',
'French short name': 'Bermudes (les)',
'Alpha-2 code': 'BM',
'Alpha-3 code': 'BMU',
Numeric: 60,
Capital: 'Hamilton',
Continent: 1,
},
{
'English short name': 'Bhutan',
'French short name': 'Bhoutan (le)',
'Alpha-2 code': 'BT',
'Alpha-3 code': 'BTN',
Numeric: 64,
Capital: 'Thimphou',
Continent: 5,
},
{
'English short name': 'Bolivia (Plurinational State of)',
'French short name': 'Bolivie (État plurinational de)',
'Alpha-2 code': 'BO',
'Alpha-3 code': 'BOL',
Numeric: 68,
Capital: 'La Paz',
Continent: 2,
},
{
'English short name': 'Bonaire, Sint Eustatius and Saba',
'French short name': 'Bonaire, Saint-Eustache et Saba',
'Alpha-2 code': 'BQ',
'Alpha-3 code': 'BES',
Numeric: 535,
Capital: '',
Continent: 1,
},
{
'English short name': 'Bosnia and Herzegovina',
'French short name': 'Bosnie-Herzégovine (la)',
'Alpha-2 code': 'BA',
'Alpha-3 code': 'BIH',
Numeric: 70,
Capital: 'Sarajevo',
Continent: 4,
},
{
'English short name': 'Botswana',
'French short name': 'Botswana (le)',
'Alpha-2 code': 'BW',
'Alpha-3 code': 'BWA',
Numeric: 72,
Capital: 'Gaborone',
Continent: 3,
},
{
'English short name': 'Bouvet Island',
'French short name': "Bouvet (l'Île)",
'Alpha-2 code': 'BV',
'Alpha-3 code': 'BVT',
Numeric: 74,
Capital: '',
Continent: 7,
},
{
'English short name': 'Brazil',
'French short name': 'Brésil (le)',
'Alpha-2 code': 'BR',
'Alpha-3 code': 'BRA',
Numeric: 76,
Capital: 'Brasilia',
Continent: 3,
},
{
'English short name': 'British Indian Ocean Territory (the)',
'French short name': "Indien (le Territoire britannique de l'océan)",
'Alpha-2 code': 'IO',
'Alpha-3 code': 'IOT',
Numeric: 86,
Capital: '',
Continent: 6,
},
{
'English short name': 'Brunei Darussalam',
'French short name': 'Brunéi Darussalam (le)',
'Alpha-2 code': 'BN',
'Alpha-3 code': 'BRN',
Numeric: 96,
Capital: 'Bandar Seri Begawan',
Continent: 6,
},
{
'English short name': 'Bulgaria',
'French short name': 'Bulgarie (la)',
'Alpha-2 code': 'BG',
'Alpha-3 code': 'BGR',
Numeric: 100,
Capital: 'Sofia',
Continent: 4,
},
{
'English short name': 'Burkina Faso',
'French short name': 'Burkina Faso (le)',
'Alpha-2 code': 'BF',
'Alpha-3 code': 'BFA',
Numeric: 854,
Capital: 'Ouagadougou',
Continent: 3,
},
{
'English short name': 'Burundi',
'French short name': 'Burundi (le)',
'Alpha-2 code': 'BI',
'Alpha-3 code': 'BDI',
Numeric: 108,
Capital: 'Bujumbura',
Continent: 3,
},
{
'English short name': 'Cabo Verde',
'French short name': 'Cabo Verde',
'Alpha-2 code': 'CV',
'Alpha-3 code': 'CPV',
Numeric: 132,
Capital: 'Praia',
Continent: 3,
},
{
'English short name': 'Cambodia',
'French short name': 'Cambodge (le)',
'Alpha-2 code': 'KH',
'Alpha-3 code': 'KHM',
Numeric: 116,
Capital: 'Phnom Penh',
Continent: 5,
},
{
'English short name': 'Cameroon',
'French short name': 'Cameroun (le)',
'Alpha-2 code': 'CM',
'Alpha-3 code': 'CMR',
Numeric: 120,
Capital: 'Yaoundé',
Continent: 3,
},
{
'English short name': 'Canada',
'French short name': 'Canada (le)',
'Alpha-2 code': 'CA',
'Alpha-3 code': 'CAN',
Numeric: 124,
Capital: 'Ottawa',
Continent: 0,
},
{
'English short name': 'Cayman Islands (the)',
'French short name': 'Caïmans (les Îles)',
'Alpha-2 code': 'KY',
'Alpha-3 code': 'CYM',
Numeric: 136,
Capital: '',
Continent: 1,
},
{
'English short name': 'Central African Republic (the)',
'French short name': 'République centrafricaine (la)',
'Alpha-2 code': 'CF',
'Alpha-3 code': 'CAF',
Numeric: 140,
Capital: 'Bangui',
Continent: 3,
},
{
'English short name': 'Chad',
'French short name': 'Tchad (le)',
'Alpha-2 code': 'TD',
'Alpha-3 code': 'TCD',
Numeric: 148,
Capital: "N'Djaména",
Continent: 3,
},
{
'English short name': 'Chile',
'French short name': 'Chili (le)',
'Alpha-2 code': 'CL',
'Alpha-3 code': 'CHL',
Numeric: 152,
Capital: 'Santiago',
Continent: 2,
},
{
'English short name': 'China',
'French short name': 'Chine (la)',
'Alpha-2 code': 'CN',
'Alpha-3 code': 'CHN',
Numeric: 156,
Capital: 'Pékin',
Continent: 5,
},
{
'English short name': 'Christmas Island',
'French short name': "Christmas (l'Île)",
'Alpha-2 code': 'CX',
'Alpha-3 code': 'CXR',
Numeric: 162,
Capital: 'Flying Fish Cove',
Continent: 6,
},
{
'English short name': 'Cocos (Keeling) Islands (the)',
'French short name': 'Cocos (les Îles)/ Keeling (les Îles)',
'Alpha-2 code': 'CC',
'Alpha-3 code': 'CCK',
Numeric: 166,
Capital: '',
Continent: 6,
},
{
'English short name': 'Colombia',
'French short name': 'Colombie (la)',
'Alpha-2 code': 'CO',
'Alpha-3 code': 'COL',
Numeric: 170,
Capital: 'Bogota',
Continent: 2,
},
{
'English short name': 'Comoros (the)',
'French short name': 'Comores (les)',
'Alpha-2 code': 'KM',
'Alpha-3 code': 'COM',
Numeric: 174,
Capital: 'Moroni',
Continent: 3,
},
{
'English short name': 'Congo (the Democratic Republic of the)',
'French short name': 'Congo (la République démocratique du)',
'Alpha-2 code': 'CD',
'Alpha-3 code': 'COD',
Numeric: 180,
Capital: 'Kinshasa',
Continent: 3,
},
{
'English short name': 'Congo (the)',
'French short name': 'Congo (le)',
'Alpha-2 code': 'CG',
'Alpha-3 code': 'COG',
Numeric: 178,
Capital: 'Brazzaville',
Continent: 3,
},
{
'English short name': 'Cook Islands (the)',
'French short name': 'Cook (les Îles)',
'Alpha-2 code': 'CK',
'Alpha-3 code': 'COK',
Numeric: 184,
Capital: 'Avarua',
Continent: 6,
},
{
'English short name': 'Costa Rica',
'French short name': 'Costa Rica (le)',
'Alpha-2 code': 'CR',
'Alpha-3 code': 'CRI',
Numeric: 188,
Capital: 'San José',
Continent: 1,
},
{
'English short name': "Côte d'Ivoire",
'French short name': "Côte d'Ivoire (la)",
'Alpha-2 code': 'CI',
'Alpha-3 code': 'CIV',
Numeric: 384,
Capital: 'Yamoussoukro',
Continent: 3,
},
{
'English short name': 'Croatia',
'French short name': 'Croatie (la)',
'Alpha-2 code': 'HR',
'Alpha-3 code': 'HRV',
Numeric: 191,
Capital: 'Zagreb',
Continent: 4,
},
{
'English short name': 'Cuba',
'French short name': 'Cuba',
'Alpha-2 code': 'CU',
'Alpha-3 code': 'CUB',
Numeric: 192,
Capital: 'La Havane',
Continent: 1,
},
{
'English short name': 'Curaçao',
'French short name': 'Curaçao',
'Alpha-2 code': 'CW',
'Alpha-3 code': 'CUW',
Numeric: 531,
Capital: 'Willemstad',
Continent: 2,
},
{
'English short name': 'Cyprus',
'French short name': 'Chypre',
'Alpha-2 code': 'CY',
'Alpha-3 code': 'CYP',
Numeric: 196,
Capital: 'Nicosie',
Continent: 4,
},
{
'English short name': 'Czechia',
'French short name': 'Tchéquie (la)',
'Alpha-2 code': 'CZ',
'Alpha-3 code': 'CZE',
Numeric: 203,
Capital: 'Prague',
Continent: 4,
},
{
'English short name': 'Denmark',
'French short name': 'Danemark (le)',
'Alpha-2 code': 'DK',
'Alpha-3 code': 'DNK',
Numeric: 208,
Capital: 'Copenhague',
Continent: 4,
},
{
'English short name': 'Djibouti',
'French short name': 'Djibouti',
'Alpha-2 code': 'DJ',
'Alpha-3 code': 'DJI',
Numeric: 262,
Capital: 'Djibouti',
Continent: 3,
},
{
'English short name': 'Dominica',
'French short name': 'Dominique (la)',
'Alpha-2 code': 'DM',
'Alpha-3 code': 'DMA',
Numeric: 212,
Capital: 'Roseau',
Continent: 1,
},
{
'English short name': 'Dominican Republic (the)',
'French short name': 'dominicaine (la République)',
'Alpha-2 code': 'DO',
'Alpha-3 code': 'DOM',
Numeric: 214,
Capital: 'Saint-Domingue',
Continent: 1,
},
{
'English short name': 'Ecuador',
'French short name': "Équateur (l')",
'Alpha-2 code': 'EC',
'Alpha-3 code': 'ECU',
Numeric: 218,
Capital: 'Quito',
Continent: 2,
},
{
'English short name': 'Egypt',
'French short name': "Égypte (l')",
'Alpha-2 code': 'EG',
'Alpha-3 code': 'EGY',
Numeric: 818,
Capital: 'Le Caire',
Continent: 3,
},
{
'English short name': 'El Salvador',
'French short name': 'El Salvador',
'Alpha-2 code': 'SV',
'Alpha-3 code': 'SLV',
Numeric: 222,
Capital: 'San Salvador',
Continent: 1,
},
{
'English short name': 'Equatorial Guinea',
'French short name': 'Guinée équatoriale (la)',
'Alpha-2 code': 'GQ',
'Alpha-3 code': 'GNQ',
Numeric: 226,
Capital: 'Malabo',
Continent: 3,
},
{
'English short name': 'Eritrea',
'French short name': "Érythrée (l')",
'Alpha-2 code': 'ER',
'Alpha-3 code': 'ERI',
Numeric: 232,
Capital: 'Asmara',
Continent: 3,
},
{
'English short name': 'Estonia',
'French short name': "Estonie (l')",
'Alpha-2 code': 'EE',
'Alpha-3 code': 'EST',
Numeric: 233,
Capital: 'Tallinn',
Continent: 5,
},
{
'English short name': 'Ethiopia',
'French short name': "Éthiopie (l')",
'Alpha-2 code': 'ET',
'Alpha-3 code': 'ETH',
Numeric: 231,
Capital: 'Addis-Abeba',
Continent: 3,
},
{
'English short name': 'Falkland Islands (the) [Malvinas]',
'French short name': 'Falkland (les Îles)/Malouines (les Îles)',
'Alpha-2 code': 'FK',
'Alpha-3 code': 'FLK',
Numeric: 238,
Capital: 'Stanley',
Continent: 2,
},
{
'English short name': 'Faroe Islands (the)',
'French short name': 'Féroé (les Îles)',
'Alpha-2 code': 'FO',
'Alpha-3 code': 'FRO',
Numeric: 234,
Capital: 'Tórshavn',
Continent: 4,
},
{
'English short name': 'Fiji',
'French short name': 'Fidji (les)',
'Alpha-2 code': 'FJ',
'Alpha-3 code': 'FJI',
Numeric: 242,
Capital: 'Suva',
Continent: 6,
},
{
'English short name': 'Finland',
'French short name': 'Finlande (la)',
'Alpha-2 code': 'FI',
'Alpha-3 code': 'FIN',
Numeric: 246,
Capital: 'Helsinki',
Continent: 4,
},
{
'English short name': 'France',
'French short name': 'France (la)',
'Alpha-2 code': 'FR',
'Alpha-3 code': 'FRA',
Numeric: 250,
Capital: 'Paris',
Continent: 4,
},
{
'English short name': 'French Guiana',
'French short name': 'Guyane française (la )',
'Alpha-2 code': 'GF',
'Alpha-3 code': 'GUF',
Numeric: 254,
Capital: 'Cayenne',
Continent: 2,
},
{
'English short name': 'French Polynesia',
'French short name': 'Polynésie française (la)',
'Alpha-2 code': 'PF',
'Alpha-3 code': 'PYF',
Numeric: 258,
Capital: 'Papeete',
Continent: 6,
},
{
'English short name': 'French Southern Territories (the)',
'French short name': 'Terres australes françaises (les)',
'Alpha-2 code': 'TF',
'Alpha-3 code': 'ATF',
Numeric: 260,
Capital: 'Saint-Pierre',
Continent: 7,
},
{
'English short name': 'Gabon',
'French short name': 'Gabon (le)',
'Alpha-2 code': 'GA',
'Alpha-3 code': 'GAB',
Numeric: 266,
Capital: 'Libreville',
Continent: 3,
},
{
'English short name': 'Gambia (the)',
'French short name': 'Gambie (la)',
'Alpha-2 code': 'GM',
'Alpha-3 code': 'GMB',
Numeric: 270,
Capital: 'Banjul',
Continent: 3,
},
{
'English short name': 'Georgia',
'French short name': 'Géorgie (la)',
'Alpha-2 code': 'GE',
'Alpha-3 code': 'GEO',
Numeric: 268,
Capital: 'Tbilissi',
Continent: 5,
},
{
'English short name': 'Germany',
'French short name': "Allemagne (l')",
'Alpha-2 code': 'DE',
'Alpha-3 code': 'DEU',
Numeric: 276,
Capital: 'Berlin',
Continent: 4,
},
{
'English short name': 'Ghana',
'French short name': 'Ghana (le)',
'Alpha-2 code': 'GH',
'Alpha-3 code': 'GHA',
Numeric: 288,
Capital: 'Accra',
Continent: 3,
},
{
'English short name': 'Gibraltar',
'French short name': 'Gibraltar',
'Alpha-2 code': 'GI',
'Alpha-3 code': 'GIB',
Numeric: 292,
Capital: '',
Continent: 4,
},
{
'English short name': 'Greece',
'French short name': 'Grèce (la)',
'Alpha-2 code': 'GR',
'Alpha-3 code': 'GRC',
Numeric: 300,
Capital: 'Athènes',
Continent: 4,
},
{
'English short name': 'Greenland',
'French short name': 'Groenland (le)',
'Alpha-2 code': 'GL',
'Alpha-3 code': 'GRL',
Numeric: 304,
Capital: 'Nuuk',
Continent: 0,
},
{
'English short name': 'Grenada',
'French short name': 'Grenade (la)',
'Alpha-2 code': 'GD',
'Alpha-3 code': 'GRD',
Numeric: 308,
Capital: 'Saint-Georges',
Continent: 1,
},
{
'English short name': 'Guadeloupe',
'French short name': 'Guadeloupe (la)',
'Alpha-2 code': 'GP',
'Alpha-3 code': 'GLP',
Numeric: 312,
Capital: 'Basse-Terre',
Continent: 1,
},
{
'English short name': 'Guam',
'French short name': 'Guam',
'Alpha-2 code': 'GU',
'Alpha-3 code': 'GUM',
Numeric: 316,
Capital: 'Hagåtña',
Continent: 6,
},
{
'English short name': 'Guatemala',
'French short name': 'Guatemala (le)',
'Alpha-2 code': 'GT',
'Alpha-3 code': 'GTM',
Numeric: 320,
Capital: 'Guatemala',
Continent: 1,
},
{
'English short name': 'Guernsey',
'French short name': 'Guernesey',
'Alpha-2 code': 'GG',
'Alpha-3 code': 'GGY',
Numeric: 831,
Capital: 'Saint-Pierre-Port',
Continent: 4,
},
{
'English short name': 'Guinea',
'French short name': 'Guinée (la)',
'Alpha-2 code': 'GN',
'Alpha-3 code': 'GIN',
Numeric: 324,
Capital: 'Conakry',
Continent: 3,
},
{
'English short name': 'Guinea-Bissau',
'French short name': 'Guinée-Bissau (la)',
'Alpha-2 code': 'GW',
'Alpha-3 code': 'GNB',
Numeric: 624,
Capital: 'Bissau',
Continent: 3,
},
{
'English short name': 'Guyana',
'French short name': 'Guyane (la)',
'Alpha-2 code': 'GY',
'Alpha-3 code': 'GUY',
Numeric: 328,
Capital: 'Georgetown',
Continent: 2,
},
{
'English short name': 'Haiti',
'French short name': 'Haïti',
'Alpha-2 code': 'HT',
'Alpha-3 code': 'HTI',
Numeric: 332,
Capital: 'Port-au-Prince',
Continent: 1,
},
{
'English short name': 'Heard Island and McDonald Islands',
'French short name': "Heard-et-Îles MacDonald (l'Île)",
'Alpha-2 code': 'HM',
'Alpha-3 code': 'HMD',
Numeric: 334,
Capital: '',
Continent: 7,
},
{
'English short name': 'Holy See (the)',
'French short name': 'Saint-Siège (le)',
'Alpha-2 code': 'VA',
'Alpha-3 code': 'VAT',
Numeric: 336,
Capital: 'Vatican',
Continent: 4,
},
{
'English short name': 'Honduras',
'French short name': 'Honduras (le)',
'Alpha-2 code': 'HN',
'Alpha-3 code': 'HND',
Numeric: 340,
Capital: 'Tegucigalpa',
Continent: 1,
},
{
'English short name': 'Hong Kong',
'French short name': 'Hong Kong',
'Alpha-2 code': 'HK',
'Alpha-3 code': 'HKG',
Numeric: 344,
Capital: 'Hong Kong',
Continent: 5,
},
{
'English short name': 'Hungary',
'French short name': 'Hongrie (la)',
'Alpha-2 code': 'HU',
'Alpha-3 code': 'HUN',
Numeric: 348,
Capital: 'Budapest',
Continent: 4,
},
{
'English short name': 'Iceland',
'French short name': "Islande (l')",
'Alpha-2 code': 'IS',
'Alpha-3 code': 'ISL',
Numeric: 352,
Capital: 'Reykjavik',
Continent: 4,
},
{
'English short name': 'India',
'French short name': "Inde (l')",
'Alpha-2 code': 'IN',
'Alpha-3 code': 'IND',
Numeric: 356,
Capital: 'New Delhi',
Continent: 5,
},
{
'English short name': 'Indonesia',
'French short name': "Indonésie (l')",
'Alpha-2 code': 'ID',
'Alpha-3 code': 'IDN',
Numeric: 360,
Capital: 'Jakarta',
Continent: 6,
},
{
'English short name': 'Iran (Islamic Republic of)',
'French short name': "Iran (République Islamique d')",
'Alpha-2 code': 'IR',
'Alpha-3 code': 'IRN',
Numeric: 364,
Capital: 'Téhéran',
Continent: 5,
},
{
'English short name': 'Iraq',
'French short name': "Iraq (l')",
'Alpha-2 code': 'IQ',
'Alpha-3 code': 'IRQ',
Numeric: 368,
Capital: 'Bagdad',
Continent: 5,
},
{
'English short name': 'Ireland',
'French short name': "Irlande (l')",
'Alpha-2 code': 'IE',
'Alpha-3 code': 'IRL',
Numeric: 372,
Capital: 'Dublin',
Continent: 4,
},
{
'English short name': 'Isle of Man',
'French short name': 'Île de Man',
'Alpha-2 code': 'IM',
'Alpha-3 code': 'IMN',
Numeric: 833,
Capital: '',
Continent: 4,
},
{
'English short name': 'Israel',
'French short name': 'Israël',
'Alpha-2 code': 'IL',
'Alpha-3 code': 'ISR',
Numeric: 376,
Capital: 'Tel Aviv',
Continent: 5,
},
{
'English short name': 'Italy',
'French short name': "Italie (l')",
'Alpha-2 code': 'IT',
'Alpha-3 code': 'ITA',
Numeric: 380,
Capital: 'Rome',
Continent: 4,
},
{
'English short name': 'Jamaica',
'French short name': 'Jamaïque (la)',
'Alpha-2 code': 'JM',
'Alpha-3 code': 'JAM',
Numeric: 388,
Capital: 'Kingston',
Continent: 1,
},
{
'English short name': 'Japan',
'French short name': 'Japon (le)',
'Alpha-2 code': 'JP',
'Alpha-3 code': 'JPN',
Numeric: 392,
Capital: 'Tokyo',
Continent: 5,
},
{
'English short name': 'Jersey',
'French short name': 'Jersey',
'Alpha-2 code': 'JE',
'Alpha-3 code': 'JEY',
Numeric: 832,
Capital: '',
Continent: 4,
},
{
'English short name': 'Jordan',
'French short name': 'Jordanie (la)',
'Alpha-2 code': 'JO',
'Alpha-3 code': 'JOR',
Numeric: 400,
Capital: 'Amman',
Continent: 5,
},
{
'English short name': 'Kazakhstan',
'French short name': 'Kazakhstan (le)',
'Alpha-2 code': 'KZ',
'Alpha-3 code': 'KAZ',
Numeric: 398,
Capital: 'Astana',
Continent: 5,
},
{
'English short name': 'Kenya',
'French short name': 'Kenya (le)',
'Alpha-2 code': 'KE',
'Alpha-3 code': 'KEN',
Numeric: 404,
Capital: 'Nairobi',
Continent: 3,
},
{
'English short name': 'Kiribati',
'French short name': 'Kiribati',
'Alpha-2 code': 'KI',
'Alpha-3 code': 'KIR',
Numeric: 296,
Capital: 'Tarawa-Sud',
Continent: 3,
},
{
'English short name': "North Korea (the Democratic People's Republic of)",
'French short name': 'Corée du Nord (la République populaire démocratique de)',
'Alpha-2 code': 'KP',
'Alpha-3 code': 'PRK',
Numeric: 408,
Capital: 'Pyongyang',
Continent: 5,
},
{
'English short name': 'South Korea (the Republic of)',
'French short name': 'Corée du Sud (la République de)',
'Alpha-2 code': 'KR',
'Alpha-3 code': 'KOR',
Numeric: 410,
Capital: 'Séoul',
Continent: 5,
},
{
'English short name': 'Kuwait',
'French short name': 'Koweït (le)',
'Alpha-2 code': 'KW',
'Alpha-3 code': 'KWT',
Numeric: 414,
Capital: 'Koweït',
Continent: 5,
},
{
'English short name': 'Kyrgyzstan',
'French short name': 'Kirghizistan (le)',
'Alpha-2 code': 'KG',
'Alpha-3 code': 'KGZ',
Numeric: 417,
Capital: 'Bichkek',
Continent: 5,
},
{
'English short name': "Lao People's Democratic Republic (the)",
'French short name': 'Laos, République démocratique populaire',
'Alpha-2 code': 'LA',
'Alpha-3 code': 'LAO',
Numeric: 418,
Capital: 'Vientiane',
Continent: 5,
},
{
'English short name': 'Latvia',
'French short name': 'Lettonie (la)',
'Alpha-2 code': 'LV',
'Alpha-3 code': 'LVA',
Numeric: 428,
Capital: 'Riga',
Continent: 5,
},
{
'English short name': 'Lebanon',
'French short name': 'Liban (le)',
'Alpha-2 code': 'LB',
'Alpha-3 code': 'LBN',
Numeric: 422,
Capital: 'Beyrouth',
Continent: 5,
},
{
'English short name': 'Lesotho',
'French short name': 'Lesotho (le)',
'Alpha-2 code': 'LS',
'Alpha-3 code': 'LSO',
Numeric: 426,
Capital: 'Maseru',
Continent: 3,
},
{
'English short name': 'Liberia',
'French short name': 'Libéria (le)',
'Alpha-2 code': 'LR',
'Alpha-3 code': 'LBR',
Numeric: 430,
Capital: 'Monrovia',
Continent: 3,
},
{
'English short name': 'Libya',
'French short name': 'Libye (la)',
'Alpha-2 code': 'LY',
'Alpha-3 code': 'LBY',
Numeric: 434,
Capital: 'Tripoli',
Continent: 3,
},
{
'English short name': 'Liechtenstein',
'French short name': 'Liechtenstein (le)',
'Alpha-2 code': 'LI',
'Alpha-3 code': 'LIE',
Numeric: 438,
Capital: 'Vaduz',
Continent: 4,
},
{
'English short name': 'Lithuania',
'French short name': 'Lituanie (la)',
'Alpha-2 code': 'LT',
'Alpha-3 code': 'LTU',
Numeric: 440,
Capital: 'Vilnius',
Continent: 5,
},
{
'English short name': 'Luxembourg',
'French short name': 'Luxembourg (le)',
'Alpha-2 code': 'LU',
'Alpha-3 code': 'LUX',
Numeric: 442,
Capital: 'Luxembourg',
Continent: 4,
},
{
'English short name': 'Macao',
'French short name': 'Macao',
'Alpha-2 code': 'MO',
'Alpha-3 code': 'MAC',
Numeric: 446,
Capital: '',
Continent: 5,
},
{
'English short name': 'Macedonia (the former Yugoslav Republic of)',
'French short name': "Macédoine (l'ex?République yougoslave de)",
'Alpha-2 code': 'MK',
'Alpha-3 code': 'MKD',
Numeric: 807,
Capital: 'Skopje',
Continent: 4,
},
{
'English short name': 'Madagascar',
'French short name': 'Madagascar',
'Alpha-2 code': 'MG',
'Alpha-3 code': 'MDG',
Numeric: 450,
Capital: 'Antananarivo',
Continent: 3,
},
{
'English short name': 'Malawi',
'French short name': 'Malawi (le)',
'Alpha-2 code': 'MW',
'Alpha-3 code': 'MWI',
Numeric: 454,
Capital: 'Lilongwe',
Continent: 3,
},
{
'English short name': 'Malaysia',
'French short name': 'Malaisie (la)',
'Alpha-2 code': 'MY',
'Alpha-3 code': 'MYS',
Numeric: 458,
Capital: 'Kuala Lumpur',
Continent: 6,
},
{
'English short name': 'Maldives',
'French short name': 'Maldives (les)',
'Alpha-2 code': 'MV',
'Alpha-3 code': 'MDV',
Numeric: 462,
Capital: 'Malé',
Continent: 3,
},
{
'English short name': 'Mali',
'French short name': 'Mali (le)',
'Alpha-2 code': 'ML',
'Alpha-3 code': 'MLI',
Numeric: 466,
Capital: 'Bamako',
Continent: 3,
},
{
'English short name': 'Malta',
'French short name': 'Malte',
'Alpha-2 code': 'MT',
'Alpha-3 code': 'MLT',
Numeric: 470,
Capital: 'La Valette',
Continent: 4,
},
{
'English short name': 'Marshall Islands (the)',
'French short name': 'Marshall (Îles)',
'Alpha-2 code': 'MH',
'Alpha-3 code': 'MHL',
Numeric: 584,
Capital: 'Majuro',
Continent: 6,
},
{
'English short name': 'Martinique',
'French short name': 'Martinique (la)',
'Alpha-2 code': 'MQ',
'Alpha-3 code': 'MTQ',
Numeric: 474,
Capital: 'Fort-de-France',
Continent: 1,
},
{
'English short name': 'Mauritania',
'French short name': 'Mauritanie (la)',
'Alpha-2 code': 'MR',
'Alpha-3 code': 'MRT',
Numeric: 478,
Capital: 'Nouakchott',
Continent: 3,
},
{
'English short name': 'Mauritius',
'French short name': 'Maurice',
'Alpha-2 code': 'MU',
'Alpha-3 code': 'MUS',
Numeric: 480,
Capital: 'Port-Louis',
Continent: 3,
},
{
'English short name': 'Mayotte',
'French short name': 'Mayotte',
'Alpha-2 code': 'YT',
'Alpha-3 code': 'MYT',
Numeric: 175,
Capital: 'Mamoudzou',
Continent: 3,
},
{
'English short name': 'Mexico',
'French short name': 'Mexique (le)',
'Alpha-2 code': 'MX',
'Alpha-3 code': 'MEX',
Numeric: 484,
Capital: 'Mexico',
Continent: 1,
},
{
'English short name': 'Micronesia (Federated States of)',
'French short name': 'Micronésie (États fédérés de)',
'Alpha-2 code': 'FM',
'Alpha-3 code': 'FSM',
Numeric: 583,
Capital: 'Palikir',
Continent: 6,
},
{
'English short name': 'Moldova (the Republic of)',
'French short name': 'Moldavie , République de',
'Alpha-2 code': 'MD',
'Alpha-3 code': 'MDA',
Numeric: 498,
Capital: 'Chișinău',
Continent: 4,
},
{
'English short name': 'Monaco',
'French short name': 'Monaco',
'Alpha-2 code': 'MC',
'Alpha-3 code': 'MCO',
Numeric: 492,
Capital: 'Monaco',
Continent: 4,
},
{
'English short name': 'Mongolia',
'French short name': 'Mongolie (la)',
'Alpha-2 code': 'MN',
'Alpha-3 code': 'MNG',
Numeric: 496,
Capital: 'Oulan-Bator',
Continent: 5,
},
{
'English short name': 'Montenegro',
'French short name': 'Monténégro (le)',
'Alpha-2 code': 'ME',
'Alpha-3 code': 'MNE',
Numeric: 499,
Capital: 'Podgorica',
Continent: 4,
},
{
'English short name': 'Montserrat',
'French short name': 'Montserrat',
'Alpha-2 code': 'MS',
'Alpha-3 code': 'MSR',
Numeric: 500,
Capital: 'Montserrat',
Continent: 1,
},
{
'English short name': 'Morocco',
'French short name': 'Maroc (le)',
'Alpha-2 code': 'MA',
'Alpha-3 code': 'MAR',
Numeric: 504,
Capital: 'Rabat',
Continent: 3,
},
{
'English short name': 'Mozambique',
'French short name': 'Mozambique (le)',
'Alpha-2 code': 'MZ',
'Alpha-3 code': 'MOZ',
Numeric: 508,
Capital: 'Maputo',
Continent: 3,
},
{
'English short name': 'Myanmar',
'French short name': 'Myanmar (le)',
'Alpha-2 code': 'MM',
'Alpha-3 code': 'MMR',
Numeric: 104,
Capital: 'Naypyidaw',
Continent: 5,
},
{
'English short name': 'Namibia',
'French short name': 'Namibie (la)',
'Alpha-2 code': 'NA',
'Alpha-3 code': 'NAM',
Numeric: 516,
Capital: 'Windhoek',
Continent: 3,
},
{
'English short name': 'Nauru',
'French short name': 'Nauru',
'Alpha-2 code': 'NR',
'Alpha-3 code': 'NRU',
Numeric: 520,
Capital: 'Yaren',
Continent: 6,
},
{
'English short name': 'Nepal',
'French short name': 'Népal (le)',
'Alpha-2 code': 'NP',
'Alpha-3 code': 'NPL',
Numeric: 524,
Capital: 'Katmandou',
Continent: 5,
},
{
'English short name': 'Netherlands (the)',
'French short name': 'Pays-Bas (les)',
'Alpha-2 code': 'NL',
'Alpha-3 code': 'NLD',
Numeric: 528,
Capital: 'Amsterdam',
Continent: 4,
},
{
'English short name': 'New Caledonia',
'French short name': 'Nouvelle-Calédonie (la)',
'Alpha-2 code': 'NC',
'Alpha-3 code': 'NCL',
Numeric: 540,
Capital: 'Nouméa',
Continent: 6,
},
{
'English short name': 'New Zealand',
'French short name': 'Nouvelle-Zélande (la)',
'Alpha-2 code': 'NZ',
'Alpha-3 code': 'NZL',
Numeric: 554,
Capital: 'Wellington',
Continent: 6,
},
{
'English short name': 'Nicaragua',
'French short name': 'Nicaragua (le)',
'Alpha-2 code': 'NI',
'Alpha-3 code': 'NIC',
Numeric: 558,
Capital: 'Managua',
Continent: 1,
},
{
'English short name': 'Niger (the)',
'French short name': 'Niger (le)',
'Alpha-2 code': 'NE',
'Alpha-3 code': 'NER',
Numeric: 562,
Capital: 'Niamey',
Continent: 3,
},
{
'English short name': 'Nigeria',
'French short name': 'Nigéria (le)',
'Alpha-2 code': 'NG',
'Alpha-3 code': 'NGA',
Numeric: 566,
Capital: 'Abuja',
Continent: 3,
},
{
'English short name': 'Niue',
'French short name': 'Niué',
'Alpha-2 code': 'NU',
'Alpha-3 code': 'NIU',
Numeric: 570,
Capital: 'Alofi',
Continent: 6,
},
{
'English short name': 'Norfolk Island',
'French short name': "Norfolk (l'Île)",
'Alpha-2 code': 'NF',
'Alpha-3 code': 'NFK',
Numeric: 574,
Capital: '',
Continent: 6,
},
{
'English short name': 'Northern Mariana Islands (the)',
'French short name': 'Mariannes du Nord (les Îles)',
'Alpha-2 code': 'MP',
'Alpha-3 code': 'MNP',
Numeric: 580,
Capital: 'Saipan',
Continent: 6,
},
{
'English short name': 'Norway',
'French short name': 'Norvège (la)',
'Alpha-2 code': 'NO',
'Alpha-3 code': 'NOR',
Numeric: 578,
Capital: 'Oslo',
Continent: 4,
},
{
'English short name': 'Oman',
'French short name': 'Oman',
'Alpha-2 code': 'OM',
'Alpha-3 code': 'OMN',
Numeric: 512,
Capital: 'Mascate',
Continent: 5,
},
{
'English short name': 'Pakistan',
'French short name': 'Pakistan (le)',
'Alpha-2 code': 'PK',
'Alpha-3 code': 'PAK',
Numeric: 586,
Capital: 'Islamabad',
Continent: 5,
},
{
'English short name': 'Palau',
'French short name': 'Palaos (les)',
'Alpha-2 code': 'PW',
'Alpha-3 code': 'PLW',
Numeric: 585,
Capital: 'Ngerulmud',
Continent: 6,
},
{
'English short name': 'Palestine, State of',
'French short name': 'Palestine, État de',
'Alpha-2 code': 'PS',
'Alpha-3 code': 'PSE',
Numeric: 275,
Capital: 'Jérusalem',
Continent: 5,
},
{
'English short name': 'Panama',
'French short name': 'Panama (le)',
'Alpha-2 code': 'PA',
'Alpha-3 code': 'PAN',
Numeric: 591,
Capital: 'Panama',
Continent: 1,
},
{
'English short name': 'Papua New Guinea',
'French short name': 'Papouasie-Nouvelle-Guinée (la)',
'Alpha-2 code': 'PG',
'Alpha-3 code': 'PNG',
Numeric: 598,
Capital: 'Port Moresby',
Continent: 6,
},
{
'English short name': 'Paraguay',
'French short name': 'Paraguay (le)',
'Alpha-2 code': 'PY',
'Alpha-3 code': 'PRY',
Numeric: 600,
Capital: 'Asuncion',
Continent: 2,
},
{
'English short name': 'Peru',
'French short name': 'Pérou (le)',
'Alpha-2 code': 'PE',
'Alpha-3 code': 'PER',
Numeric: 604,
Capital: 'Lima',
Continent: 2,
},
{
'English short name': 'Philippines (the)',
'French short name': 'Philippines (les)',
'Alpha-2 code': 'PH',
'Alpha-3 code': 'PHL',
Numeric: 608,
Capital: 'Manille',
Continent: 6,
},
{
'English short name': 'Pitcairn',
'French short name': 'Pitcairn',
'Alpha-2 code': 'PN',
'Alpha-3 code': 'PCN',
Numeric: 612,
Capital: 'Adamstown',
Continent: 6,
},
{
'English short name': 'Poland',
'French short name': 'Pologne (la)',
'Alpha-2 code': 'PL',
'Alpha-3 code': 'POL',
Numeric: 616,
Capital: 'Varsovie',
Continent: 4,
},
{
'English short name': 'Portugal',
'French short name': 'Portugal (le)',
'Alpha-2 code': 'PT',
'Alpha-3 code': 'PRT',
Numeric: 620,
Capital: 'Lisbonne',
Continent: 4,
},
{
'English short name': 'Puerto Rico',
'French short name': 'Porto Rico',
'Alpha-2 code': 'PR',
'Alpha-3 code': 'PRI',
Numeric: 630,
Capital: 'San Juan',
Continent: 1,
},
{
'English short name': 'Qatar',
'French short name': 'Qatar (le)',
'Alpha-2 code': 'QA',
'Alpha-3 code': 'QAT',
Numeric: 634,
Capital: 'Doha',
Continent: 5,
},
{
'English short name': 'Réunion',
'French short name': 'Réunion (La)',
'Alpha-2 code': 'RE',
'Alpha-3 code': 'REU',
Numeric: 638,
Capital: 'Saint-Denis',
Continent: 3,
},
{
'English short name': 'Romania',
'French short name': 'Roumanie (la)',
'Alpha-2 code': 'RO',
'Alpha-3 code': 'ROU',
Numeric: 642,
Capital: 'Bucarest',
Continent: 4,
},
{
'English short name': 'Russian Federation (the)',
'French short name': 'Russie (la Fédération de)',
'Alpha-2 code': 'RU',
'Alpha-3 code': 'RUS',
Numeric: 643,
Capital: 'Moscou',
Continent: 5,
},
{
'English short name': 'Rwanda',
'French short name': 'Rwanda (le)',
'Alpha-2 code': 'RW',
'Alpha-3 code': 'RWA',
Numeric: 646,
Capital: 'Kigali',
Continent: 3,
},
{
'English short name': 'Saint Barthélemy',
'French short name': 'Saint-Barthélemy',
'Alpha-2 code': 'BL',
'Alpha-3 code': 'BLM',
Numeric: 652,
Capital: 'Gustavia',
Continent: 1,
},
{
'English short name': 'Saint Helena, Ascension and Tristan da Cunha',
'French short name': 'Sainte-Hélène, Ascension et Tristan da Cunha',
'Alpha-2 code': 'SH',
'Alpha-3 code': 'SHN',
Numeric: 654,
Capital: 'Jamestown',
Continent: 3,
},
{
'English short name': 'Saint Kitts and Nevis',
'French short name': 'Saint-Kitts-et-Nevis',
'Alpha-2 code': 'KN',
'Alpha-3 code': 'KNA',
Numeric: 659,
Capital: 'Basseterre',
Continent: 1,
},
{
'English short name': 'Saint Lucia',
'French short name': 'Sainte-Lucie',
'Alpha-2 code': 'LC',
'Alpha-3 code': 'LCA',
Numeric: 662,
Capital: 'Castries',
Continent: 1,
},
{
'English short name': 'Saint Martin (French part)',
'French short name': 'Saint-Martin (partie française)',
'Alpha-2 code': 'MF',
'Alpha-3 code': 'MAF',
Numeric: 663,
Capital: '',
Continent: 1,
},
{
'English short name': 'Sint Maarten (Dutch part)',
'French short name': 'Saint-Martin (partie néerlandaise)',
'Alpha-2 code': 'SX',
'Alpha-3 code': 'SXM',
Numeric: 534,
Capital: '',
Continent: 1,
},
{
'English short name': 'Saint Pierre and Miquelon',
'French short name': 'Saint-Pierre-et-Miquelon',
'Alpha-2 code': 'PM',
'Alpha-3 code': 'SPM',
Numeric: 666,
Capital: 'Saint-Pierre',
Continent: 0,
},
{
'English short name': 'Saint Vincent and the Grenadines',
'French short name': 'Saint-Vincent-et-les Grenadines',
'Alpha-2 code': 'VC',
'Alpha-3 code': 'VCT',
Numeric: 670,
Capital: 'Kingstown',
Continent: 1,
},
{
'English short name': 'Samoa',
'French short name': 'Samoa (le)',
'Alpha-2 code': 'WS',
'Alpha-3 code': 'WSM',
Numeric: 882,
Capital: 'Apia',
Continent: 6,
},
{
'English short name': 'San Marino',
'French short name': 'Saint-Marin',
'Alpha-2 code': 'SM',
'Alpha-3 code': 'SMR',
Numeric: 674,
Capital: 'Saint-Marin',
Continent: 4,
},
{
'English short name': 'Sao Tome and Principe',
'French short name': 'Sao Tomé-et-Principe',
'Alpha-2 code': 'ST',
'Alpha-3 code': 'STP',
Numeric: 678,
Capital: 'São Tomé',
Continent: 3,
},
{
'English short name': 'Saudi Arabia',
'French short name': "Arabie saoudite (l')",
'Alpha-2 code': 'SA',
'Alpha-3 code': 'SAU',
Numeric: 682,
Capital: 'Riyad',
Continent: 5,
},
{
'English short name': 'Senegal',
'French short name': 'Sénégal (le)',
'Alpha-2 code': 'SN',
'Alpha-3 code': 'SEN',
Numeric: 686,
Capital: 'Dakar',
Continent: 3,
},
{
'English short name': 'Serbia',
'French short name': 'Serbie (la)',
'Alpha-2 code': 'RS',
'Alpha-3 code': 'SRB',
Numeric: 688,
Capital: 'Belgrade',
Continent: 4,
},
{
'English short name': 'Seychelles',
'French short name': 'Seychelles (les)',
'Alpha-2 code': 'SC',
'Alpha-3 code': 'SYC',
Numeric: 690,
Capital: 'Vicotria',
Continent: 3,
},
{
'English short name': 'Sierra Leone',
'French short name': 'Sierra Leone (la)',
'Alpha-2 code': 'SL',
'Alpha-3 code': 'SLE',
Numeric: 694,
Capital: 'Freetown',
Continent: 3,
},
{
'English short name': 'Singapore',
'French short name': 'Singapour',
'Alpha-2 code': 'SG',
'Alpha-3 code': 'SGP',
Numeric: 702,
Capital: 'Singapour',
Continent: 6,
},
{
'English short name': 'Slovakia',
'French short name': 'Slovaquie (la)',
'Alpha-2 code': 'SK',
'Alpha-3 code': 'SVK',
Numeric: 703,
Capital: 'Bratislava',
Continent: 4,
},
{
'English short name': 'Slovenia',
'French short name': 'Slovénie (la)',
'Alpha-2 code': 'SI',
'Alpha-3 code': 'SVN',
Numeric: 705,
Capital: 'Ljubljana',
Continent: 5,
},
{
'English short name': 'Solomon Islands',
'French short name': 'Salomon (Îles)',
'Alpha-2 code': 'SB',
'Alpha-3 code': 'SLB',
Numeric: 90,
Capital: 'Honiara',
Continent: 6,
},
{
'English short name': 'Somalia',
'French short name': 'Somalie (la)',
'Alpha-2 code': 'SO',
'Alpha-3 code': 'SOM',
Numeric: 706,
Capital: 'Mogadiscio',
Continent: 3,
},
{
'English short name': 'South Africa',
'French short name': "Afrique du Sud (l')",
'Alpha-2 code': 'ZA',
'Alpha-3 code': 'ZAF',
Numeric: 710,
Capital: 'Pretoria/Le Cap',
Continent: 3,
},
{
'English short name': 'South Georgia and the South Sandwich Islands',
'French short name': 'Géorgie du Sud-et-les Îles Sandwich du Sud (la)',
'Alpha-2 code': 'GS',
'Alpha-3 code': 'SGS',
Numeric: 239,
Capital: '',
Continent: 6,
},
{
'English short name': 'Sudan (the)',
'French short name': 'Soudan (le)',
'Alpha-2 code': 'SD',
'Alpha-3 code': 'SDN',
Numeric: 729,
Capital: 'Khartoum',
Continent: 3,
},
{
'English short name': 'South Sudan',
'French short name': 'Soudan du Sud (le)',
'Alpha-2 code': 'SS',
'Alpha-3 code': 'SSD',
Numeric: 728,
Capital: 'Djouba',
Continent: 3,
},
{
'English short name': 'Spain',
'French short name': "Espagne (l')",
'Alpha-2 code': 'ES',
'Alpha-3 code': 'ESP',
Numeric: 724,
Capital: 'Madrid',
Continent: 4,
},
{
'English short name': 'Sri Lanka',
'French short name': 'Sri Lanka',
'Alpha-2 code': 'LK',
'Alpha-3 code': 'LKA',
Numeric: 144,
Capital: 'Sri Jayawardenapura',
Continent: 5,
},
{
'English short name': 'Suriname',
'French short name': 'Suriname (le)',
'Alpha-2 code': 'SR',
'Alpha-3 code': 'SUR',
Numeric: 740,
Capital: 'Paramaribo',
Continent: 2,
},
{
'English short name': 'Svalbard and Jan Mayen',
'French short name': "Svalbard et l'Île Jan Mayen (le)",
'Alpha-2 code': 'SJ',
'Alpha-3 code': 'SJM',
Numeric: 744,
Capital: '',
Continent: 0,
},
{
'English short name': 'Swaziland',
'French short name': 'Swaziland (le)',
'Alpha-2 code': 'SZ',
'Alpha-3 code': 'SWZ',
Numeric: 748,
Capital: 'Mbabane',
Continent: 3,
},
{
'English short name': 'Sweden',
'French short name': 'Suède (la)',
'Alpha-2 code': 'SE',
'Alpha-3 code': 'SWE',
Numeric: 752,
Capital: 'Stockholm',
Continent: 4,
},
{
'English short name': 'Switzerland',
'French short name': 'Suisse (la)',
'Alpha-2 code': 'CH',
'Alpha-3 code': 'CHE',
Numeric: 756,
Capital: 'Berne',
Continent: 4,
},
{
'English short name': 'Syrian Arab Republic',
'French short name': 'République arabe syrienne (la)',
'Alpha-2 code': 'SY',
'Alpha-3 code': 'SYR',
Numeric: 760,
Capital: 'Damas',
Continent: 5,
},
{
'English short name': 'Taiwan (Province of China)',
'French short name': 'Taïwan (Province de Chine)',
'Alpha-2 code': 'TW',
'Alpha-3 code': 'TWN',
Numeric: 158,
Capital: 'Nankin',
Continent: 5,
},
{
'English short name': 'Tajikistan',
'French short name': 'Tadjikistan (le)',
'Alpha-2 code': 'TJ',
'Alpha-3 code': 'TJK',
Numeric: 762,
Capital: 'Douchambé',
Continent: 5,
},
{
'English short name': 'Tanzania, United Republic of',
'French short name': 'Tanzanie, République-Unie de',
'Alpha-2 code': 'TZ',
'Alpha-3 code': 'TZA',
Numeric: 834,
Capital: 'Dodoma',
Continent: 3,
},
{
'English short name': 'Thailand',
'French short name': 'Thaïlande (la)',
'Alpha-2 code': 'TH',
'Alpha-3 code': 'THA',
Numeric: 764,
Capital: 'Bangkok',
Continent: 5,
},
{
'English short name': 'Timor-Leste',
'French short name': 'Timor-Leste (le)',
'Alpha-2 code': 'TL',
'Alpha-3 code': 'TLS',
Numeric: 626,
Capital: 'Dili',
Continent: 6,
},
{
'English short name': 'Togo',
'French short name': 'Togo (le)',
'Alpha-2 code': 'TG',
'Alpha-3 code': 'TGO',
Numeric: 768,
Capital: 'Lomé',
Continent: 3,
},
{
'English short name': 'Tokelau',
'French short name': 'Tokelau (les)',
'Alpha-2 code': 'TK',
'Alpha-3 code': 'TKL',
Numeric: 772,
Capital: 'Atafu',
Continent: 6,
},
{
'English short name': 'Tonga',
'French short name': 'Tonga (les)',
'Alpha-2 code': 'TO',
'Alpha-3 code': 'TON',
Numeric: 776,
Capital: "Nuku'alofa",
Continent: 6,
},
{
'English short name': 'Trinidad and Tobago',
'French short name': 'Trinité-et-Tobago (la)',
'Alpha-2 code': 'TT',
'Alpha-3 code': 'TTO',
Numeric: 780,
Capital: "Port-d'Espagne",
Continent: 2,
},
{
'English short name': 'Tunisia',
'French short name': 'Tunisie (la)',
'Alpha-2 code': 'TN',
'Alpha-3 code': 'TUN',
Numeric: 788,
Capital: 'Tunis',
Continent: 3,
},
{
'English short name': 'Turkey',
'French short name': 'Turquie (la)',
'Alpha-2 code': 'TR',
'Alpha-3 code': 'TUR',
Numeric: 792,
Capital: 'Ankara',
Continent: 5,
},
{
'English short name': 'Turkmenistan',
'French short name': 'Turkménistan (le)',
'Alpha-2 code': 'TM',
'Alpha-3 code': 'TKM',
Numeric: 795,
Capital: 'Achgabat',
Continent: 5,
},
{
'English short name': 'Turks and Caicos Islands (the)',
'French short name': 'Turks-et-Caïcos (les Îles)',
'Alpha-2 code': 'TC',
'Alpha-3 code': 'TCA',
Numeric: 796,
Capital: 'Cockburn Town',
Continent: 1,
},
{
'English short name': 'Tuvalu',
'French short name': 'Tuvalu (les)',
'Alpha-2 code': 'TV',
'Alpha-3 code': 'TUV',
Numeric: 798,
Capital: 'Funafuti',
Continent: 6,
},
{
'English short name': 'Uganda',
'French short name': "Ouganda (l')",
'Alpha-2 code': 'UG',
'Alpha-3 code': 'UGA',
Numeric: 800,
Capital: 'Kampala',
Continent: 3,
},
{
'English short name': 'Ukraine',
'French short name': "Ukraine (l')",
'Alpha-2 code': 'UA',
'Alpha-3 code': 'UKR',
Numeric: 804,
Capital: 'Kiev',
Continent: 5,
},
{
'English short name': 'United Arab Emirates (the)',
'French short name': 'Émirats arabes unis (les)',
'Alpha-2 code': 'AE',
'Alpha-3 code': 'ARE',
Numeric: 784,
Capital: 'Abou Dabi',
Continent: 5,
},
{
'English short name': 'England',
'French short name': 'Angleterre',
'Alpha-2 code': 'GB',
'Alpha-3 code': 'GBR',
Numeric: 826,
Capital: 'Londres',
Continent: 4,
},
{
'English short name': 'United States Minor Outlying Islands (the)',
'French short name': 'Îles mineures éloignées des États-Unis (les)',
'Alpha-2 code': 'UM',
'Alpha-3 code': 'UMI',
Numeric: 581,
Capital: '',
Continent: 6,
},
{
'English short name': 'United States of America (the)',
'French short name': "États-Unis d'Amérique (les)",
'Alpha-2 code': 'US',
'Alpha-3 code': 'USA',
Numeric: 840,
Capital: 'Washington D.C.',
Continent: 0,
},
{
'English short name': 'Uruguay',
'French short name': "Uruguay (l')",
'Alpha-2 code': 'UY',
'Alpha-3 code': 'URY',
Numeric: 858,
Capital: 'Montevideo',
Continent: 2,
},
{
'English short name': 'Uzbekistan',
'French short name': "Ouzbékistan (l')",
'Alpha-2 code': 'UZ',
'Alpha-3 code': 'UZB',
Numeric: 860,
Capital: 'Tachkent',
Continent: 5,
},
{
'English short name': 'Vanuatu',
'French short name': 'Vanuatu (le)',
'Alpha-2 code': 'VU',
'Alpha-3 code': 'VUT',
Numeric: 548,
Capital: 'Port-Vila',
Continent: 6,
},
{
'English short name': 'Venezuela (Bolivarian Republic of)',
'French short name': 'Venezuela (République bolivarienne du)',
'Alpha-2 code': 'VE',
'Alpha-3 code': 'VEN',
Numeric: 862,
Capital: 'Caracas',
Continent: 2,
},
{
'English short name': 'Viet Nam',
'French short name': 'Viet Nam (le)',
'Alpha-2 code': 'VN',
'Alpha-3 code': 'VNM',
Numeric: 704,
Capital: 'Hanoï',
Continent: 5,
},
{
'English short name': 'Virgin Islands (British)',
'French short name': 'Vierges britanniques (les Îles)',
'Alpha-2 code': 'VG',
'Alpha-3 code': 'VGB',
Numeric: 92,
Capital: 'Road Town',
Continent: 1,
},
{
'English short name': 'Virgin Islands (U.S.)',
'French short name': 'Vierges des États-Unis (les Îles)',
'Alpha-2 code': 'VI',
'Alpha-3 code': 'VIR',
Numeric: 850,
Capital: 'Charlotte Amalie',
Continent: 1,
},
{
'English short name': 'Wallis and Futuna',
'French short name': 'Wallis-et-Futuna',
'Alpha-2 code': 'WF',
'Alpha-3 code': 'WLF',
Numeric: 876,
Capital: 'Mata-Utu',
Continent: 6,
},
{
'English short name': 'Western Sahara',
'French short name': 'Sahara occidental (le)',
'Alpha-2 code': 'EH',
'Alpha-3 code': 'ESH',
Numeric: 732,
Capital: 'Laâyoune',
Continent: 3,
},
{
'English short name': 'Yemen',
'French short name': 'Yémen (le)',
'Alpha-2 code': 'YE',
'Alpha-3 code': 'YEM',
Numeric: 887,
Capital: 'Sanaa',
Continent: 5,
},
{
'English short name': 'Zambia',
'French short name': 'Zambie (la)',
'Alpha-2 code': 'ZM',
'Alpha-3 code': 'ZMB',
Numeric: 894,
Capital: 'Lusaka',
Continent: 3,
},
{
'English short name': 'Zimbabwe',
'French short name': 'Zimbabwe (le)',
'Alpha-2 code': 'ZW',
'Alpha-3 code': 'ZWE',
Numeric: 716,
Capital: 'Harare',
Continent: 3,
},
];
| Sharlaan/material-ui-superselectfield | demo/src/assets/countries.js | JavaScript | mit | 52,219 |
import java.util.HashMap;
/**
* Enum type med dage.
*/
public enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY;
/**
* Oversæt streng til enum type.
* Går ud fra at teksten er på dansk.
* @param streng med dag
*/
public static Day fromString(String day) {
if (day != null) {
/*for (Day d : Day.values()) {
if (d.name().equalsIgnoreCase(day)) {
return d;
}
}*/
switch(day.toLowerCase()) {
case "mandag": return Day.MONDAY;
case "tirsdag": return Day.TUESDAY;
case "onsdag": return Day.WEDNESDAY;
case "torsdag": return Day.THURSDAY;
case "fredag": return Day.FRIDAY;
case "lørdag": return Day.SATURDAY;
case "søndag": return Day.SUNDAY;
}
}
return null;
}
}
| Herover/IP-VVH-LALN-MH-OCC | OOPD/uge5/Day.java | Java | mit | 867 |
re.on = function(name, callback) {
return function(el) {
return el.addEventListener(name, callback);
};
};
(function() {
[ 'click', 'dblclick', 'wheel',
'keydown', 'keyup',
'input', 'focus', 'blur',
'drag', 'dragstart', 'dragover', 'dragstop', 'drop',
'mousedown', 'mouseup', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout'
].forEach(function(eventName) {
re.on[eventName] = function(callback) {
return re.on(eventName, callback);
};
});
re.on.wheel.down = function wheelDown(callback) {
return re.on.wheel(function(ev) {
ev.preventDefault();
if (ev.wheelDelta < 0)
callback(ev);
});
};
re.on.wheel.up = function wheelUp(callback) {
return re.on.wheel(function(ev) {
ev.preventDefault();
if (ev.wheelDelta > 0)
callback(ev);
});
};
// keystroke sugar:
// re.on.keydown.g(ev => console.log('you pressed g!'));
// re.on.keydown.ctrl.s(functionThatSavesMyStuff)(document.body);
var chars;
var otherKeys;
function loadKeyNames(evName) {
if (!chars) {
chars = [];
for (var i=0 ; i<230 ; i++) {
var char = String.fromCharCode(i);
if (char.length != "")
chars.push(char);
}
}
if (!otherKeys)
otherKeys = {
shift:16, ctrl:17, alt:18,
backspace:8, tab:9, enter:13, pause:19, capsLock:20, escape:27,
pageUp:33, pageDown:34, end:35, home:36, left:37, up:38, right:39, down:40,
insert:45, delete:46,
leftWindow:91, rightWindow:92, select:93,
f1:112, f2:113, f3:114, f4:115, f5:116, f6:117, f7:118, f8:119, f9:120, f10:121, f11:122, f12:123,
numLock:144, scrollLock:145
};
var evSetup = re.on[evName];
Object.keys(otherKeys).forEach(function(keyName) {
evSetup[keyName] = function(callback) {
return evSetup(function(ev) {
if (otherKeys[keyName] === ev.which) {
ev.preventDefault();
callback(ev);
}
});
};
});
chars.forEach(function(char) {
evSetup[char] = function(callback) {
return evSetup(function(ev) {
if (String.fromCharCode(ev.which).toLowerCase() === char) {
ev.preventDefault();
callback(ev);
}
});
};
evSetup.ctrl[char] = function(callback) {
return evSetup(function(ev) {
if ((ev.ctrlKey || ev.metaKey) && String.fromCharCode(ev.which).toLowerCase() === char) {
ev.preventDefault();
callback(ev);
}
});
};
evSetup.shift[char] = function(callback) {
return evSetup(function(ev) {
if (ev.shiftKey && String.fromCharCode(ev.which).toLowerCase() === char) {
ev.preventDefault();
callback(ev);
}
});
};
evSetup.alt[char] = function(callback) {
return evSetup(function(ev) {
if (ev.altKey && String.fromCharCode(ev.which).toLowerCase() === char) {
ev.preventDefault();
callback(ev);
}
});
};
});
};
// performs an action once when a property is first used via a getter and then removes function based property
function setupProperty(obj, prop, loader) {
//if (!Object.defineProperty)
loader(prop);
/*else {
var holder = obj[prop];
Object.defineProperty(obj, prop, {
get: function() {
loader(prop);
var out = obj[prop];
Object.defineProperty(obj, prop, {
value: obj[prop],
enumerable: true
});
return out;
},
enumerable: true,
configurable: true
});
}*/
}
['keydown', 'keyup'].forEach(function(evName) {
setupProperty(re.on, evName, loadKeyNames);
});
})();
(function() {
var hashRouter;
re.getHashRouter = function getHashRouter() {
if (!hashRouter) {
hashRouter = {};
var gsLoc = re(hashRouter, 'location', function() {
return window.location;
});
['hash', 'search', 'pathname'].map(function(prop) {
return re(hashRouter, prop, function get() {
return hashRouter.location[prop];
}, function set(value) {
hashRouter.location[prop] = value;
});
});
var ops = window.onpopstate;
window.onpopstate = function(ev) {
re.invalidate(gsLoc);
if (ops)
ops(ev);
};
var priorLoc;
setInterval(function() {
var loc = window.location.toString();
if (priorLoc !== loc)
re.invalidate(gsLoc);
priorLoc = loc;
}, 200);
}
return hashRouter;
};
})();
(function() {
function eventTrigger(thiz) {
var counter = 1;
var out = function(callback) {
var id = counter++;
out.dependents[id] = callback;
out.remove = function() {
delete out.dependents[id];
};
};
out.trigger = function() {
var args = arguments;
Object.keys(out.dependents).forEach(function(key) {
var callback = out.dependents[key];
callback.apply(thiz, args);
});
};
out.dependents = {};
return out;
}
re.alertArray = function(arr) {
if (!arr.onRemove) {
arr.onRemove = eventTrigger(arr);
arr.onInsert = eventTrigger(arr);
var push = arr.push;
arr.push = function(val) {
var out = push.call(arr, val);
arr.onInsert.trigger(val, arr.length);
return out;
};
var pop = arr.pop;
arr.pop = function() {
var out = pop.apply(arr);
arr.onRemove.trigger(arr.length - 1);
return out;
};
var shift = arr.shift;
arr.shift = function() {
var out = shift.apply(arr);
arr.onRemove.trigger(0);
return out;
};
var unshift = arr.unshift;
arr.unshift = function(val) {
var out = unshift.call(arr, val);
arr.onRemove.trigger(val, 0);
return out;
};
var splice = arr.splice;
arr.splice = function(pos, deleteCount) {
pos = pos.valueOf();
var out = splice.apply(arr, arguments);
while (deleteCount > 0) {
arr.onRemove.trigger(pos + deleteCount - 1);
deleteCount--;
}
for (var i=2; i<arguments.length; i++) {
var item = arguments[i];
arr.onInsert.trigger(item, pos + i - 2);
}
return out;
};
}
};
re.bindMap = function(arr, transform) {
function posGetter(val) {
var out = function getPos() {
for (var i=0; i<arr.length; i++)
if (val === arr[i])
return i;
};
out.valueOf = out;
return out;
};
// map via for loop to prevent undesired change detection
var out = [];
for (var i=0; i<arr.length; i++) {
var item = arr[i];
var tItem = transform(item, posGetter(item), arr);
out.push(tItem);
}
re.alertArray(arr);
arr.onRemove(function(pos) {
return out.splice(pos, 1);
});
arr.onInsert(function(item, pos) {
var tItem = transform(item, posGetter(item), arr);
return out.splice(pos, 0, tItem);
});
return out;
};
re.arrInstall = function(arr) {
re.alertArray(arr);
var initialized = false;
var installations = [];
return function(el, loc) {
if (!initialized) {
initialized = true;
arr.onRemove(function(pos) {
arr;
var inst = installations[pos];
inst.remove();
installations.splice(pos, 1);
});
arr.onInsert(function(item, pos) {
arr;
var instPos = installations[pos];
var inst;
if (instPos)
inst = instPos.insertContent(item);
else
inst = loc.installChild(item, el);
installations.splice(pos, 0, inst);
});
arr.forEach(function(item) {
var inst = loc.installChild(item, el);
installations.push(inst);
});
}
};
};
re.mapInstall = function(arr, transform) {
return re.arrInstall(re.bindMap(arr, transform));
};
re.for = re.mapInstall;
})();
| eascherman/relativity | toolkit.js | JavaScript | mit | 10,391 |
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M12 2C8.14 2 5 5.14 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.86-3.14-7-7-7zm4 8h-3v3h-2v-3H8V8h3V5h2v3h3v2z"
}), 'AddLocation'); | AlloyTeam/Nuclear | components/icon/esm/add-location.js | JavaScript | mit | 247 |
var a = function() {
return 'b';
};
b = function doB(q, wer, ty) {
var c = function(n) {
return function() {
return q +
wer - ty;
}
}
return c
}
this.foo = {
bar: function() {
var r = function() {
re(); draw();
return log('foo') + 'bar';
};
},
ipsum: function(amet) {
return function() {
amet()
}
}
};
var noop = function() {};
var add = function(a, b) {
return a + b;
}
call(function(a) {
b();
});
// issue #36
var obj = {
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
}
};
// issue #134
var foo = new MyConstructor(function otherFunction() {});
// issue #143
if (!this._pollReceive) {
this._pollReceive = nn.PollReceiveSocket(this.binding, function(events) {
if (events) this._receive();
}.bind(this));
}
// issue #283
var foo = function foo() {
bar()
}
var foo = function() {
bar()
}
// default params (#285)
var defaultParams = function defaults(z, x = 1, y = 2) {
return z + x + y;
}
// issue #350
var foo = function*() {
yield '123';
yield '456';
};
var foo = function*() {
yield '123';
yield '456';
};
| TommyM/esformatter | test/compare/default/function_expression-out.js | JavaScript | mit | 1,161 |
'use strict';
define([
'jquery', 'underscore', 'angular',
'angular-resource'
],
function ($, _, angular) {
var resourceApp = angular.module('resourceApp', [ 'ngResource' ]);
resourceApp.factory('NodeFactory', function ($resource) {
// $resource(url[, paramDefaults][, actions]);
return $resource('/document/node/:nid', {}, {
// save: { method: 'PUT', params: { nid: '@nid'}, transformResponse: function () {
// console.log('transformResponse', arguments);
// }, transformRequest: function () {
// console.log('transformRequest', arguments);
// } },
// get: { ... }
create: { method: 'POST' },
read: { method: 'GET', isArray: true },
update: { method: 'PUT', params: { nid: '@nid'} },
delete: { method: 'DELETE', params: { nid: '@nid'}, query: {} }
});
});
resourceApp.controller('ResourceDemoCtrl', function ($scope, NodeFactory) {
// We can retrieve a collection from the server
$scope.nodelist = NodeFactory.read(function readSuccess (value, responseHeaders) {
// console.log(nodelist);
// GET: /document/node
// server returns: [ {...}, {...}, ... ];
var node = value[0];
node.ipAddr = '211.114.0.250';
node.alive = false;
delete node.os;
node.$update();
// PUT: /document/node/160
// server returns: { ... };
});
$scope.setCurr = function (node) {
// clone
$scope.nodeData = {
nid: node.nid,
ipAddr: node.ipAddr,
port: node.port,
alive: node.alive
};
// ref
// $scope.nodeData = node;
};
$scope.requestByFactory = function (method, node) {
switch (method) {
case 'create':
var newNode = NodeFactory.create(node, function (value, responseHeaders) {
$scope.nodelist.push(newNode);
}, function (httpResponse) {
alert(httpResponse.data);
});
// POST: /document/node
// server returns: { ... };
break;
case 'update':
var updated = NodeFactory.update(node, function (value, responseHeaders) {
var selected = _.findWhere($scope.nodelist, { nid: node.nid });
if (selected) {
updated = _.extend(selected, updated);
}
}, function (httpResponse) {
alert(httpResponse.data);
});
// PUT: /document/node/:nid
// server returns: { ... };
break;
case 'getOne':
$scope.nodeData = NodeFactory.get(node);
break;
case 'delete':
var nid = NodeFactory.delete(node, function (value, responseHeaders) {
var selected = _.findWhere($scope.nodelist, { nid: node.nid });
if (selected) {
$scope.nodelist.splice(_.indexOf($scope.nodelist, selected), 1);
}
}, function (httpResponse) {
alert(httpResponse.data);
});
// DELETE: /document/node/:nid
// server returns: nid
break;
}
};
$scope.requestByInstence = function (method, node) {
switch (method) {
case 'update':
node.$update(function (value, responseHeaders) {
node = value;
}, function (httpResponse) {
alert(httpResponse.data);
});
// PUT: /document/node/:nid
// server returns: { ... };
break;
// case 'getOne':
// node = node.$get(node);
// break;
case 'delete':
node.$delete(function (value, responseHeaders) {
$scope.nodelist.splice(_.indexOf($scope.nodelist, node), 1);
}, function (httpResponse) {
alert(httpResponse.data);
});
// DELETE: /document/node/:nid
// server returns: nid
break;
}
};
});
});
| veldise/js-examples | angular/public/apps/resource.js | JavaScript | mit | 4,785 |
(function($, f) {
// If there's no jQuery, Unslider can't work, so kill the operation.
if(!$) return f;
var Unslider = function() {
// Set up our elements
this.el = f;
this.items = f;
// Dimensions
this.sizes = [];
this.max = [0,0];
// Current inded
this.current = 0;
// Start/stop timer
this.interval = f;
// Set some options
this.opts = {
speed: 500,
delay: 3000, // f for no autoplay
complete: f, // when a slide's finished
keys: !f, // keyboard shortcuts - disable if it breaks things
dots: f, // display �T�T�T�▊�� pagination
fluid: f // is it a percentage width?,
};
// Create a deep clone for methods where context changes
var _ = this;
this.init = function(el, opts) {
this.el = el;
this.ul = el.children('ul');
this.max = [el.outerWidth(), el.outerHeight()];
this.items = this.ul.children('li').each(this.calculate);
// Check whether we're passing any options in to Unslider
this.opts = $.extend(this.opts, opts);
// Set up the Unslider
this.setup();
return this;
};
// Get the width for an element
// Pass a jQuery element as the context with .call(), and the index as a parameter: Unslider.calculate.call($('li:first'), 0)
this.calculate = function(index) {
var me = $(this),
width = me.outerWidth(), height = me.outerHeight();
// Add it to the sizes list
_.sizes[index] = [width, height];
// Set the max values
if(width > _.max[0]) _.max[0] = width;
if(height > _.max[1]) _.max[1] = height;
};
// Work out what methods need calling
this.setup = function() {
// Set the main element
this.el.css({
overflow: 'hidden',
width: _.max[0],
height: this.items.first().outerHeight()
});
// Set the relative widths
this.ul.css({width: (this.items.length * 100) + '%', position: 'relative'});
this.items.css('width', (100 / this.items.length) + '%');
if(this.opts.delay !== f) {
this.start();
this.el.hover(this.stop, this.start);
}
// Custom keyboard support
this.opts.keys && $(document).keydown(this.keys);
// Dot pagination
this.opts.dots && this.dots();
// Little patch for fluid-width sliders. Screw those guys.
if(this.opts.fluid) {
var resize = function() {
_.el.css('width', Math.min(Math.round((_.el.outerWidth() / _.el.parent().outerWidth()) * 100), 100) + '%');
};
resize();
$(window).resize(resize);
}
if(this.opts.arrows) {
this.el.parent().append('<p class="arrows"><span class="prev">��</span><span class="next">��</span></p>')
.find('.arrows span').click(function() {
$.isFunction(_[this.className]) && _[this.className]();
});
};
// Swipe support
if($.event.swipe) {
this.el.on('swipeleft', _.prev).on('swiperight', _.next);
}
};
// Move Unslider to a slide index
this.move = function(index, cb) {
// If it's out of bounds, go to the first slide
if(!this.items.eq(index).length) index = 0;
if(index < 0) index = (this.items.length - 1);
var target = this.items.eq(index);
var obj = {height: target.outerHeight()};
var speed = cb ? 5 : this.opts.speed;
if(!this.ul.is(':animated')) {
// Handle those pesky dots
_.el.find('.dot:eq(' + index + ')').addClass('active').siblings().removeClass('active');
this.el.animate(obj, speed) && this.ul.animate($.extend({left: '-' + index + '00%'}, obj), speed, function(data) {
_.current = index;
$.isFunction(_.opts.complete) && !cb && _.opts.complete(_.el);
});
}
};
// Autoplay functionality
this.start = function() {
_.interval = setInterval(function() {
_.move(_.current + 1);
}, _.opts.delay);
};
// Stop autoplay
this.stop = function() {
_.interval = clearInterval(_.interval);
return _;
};
// Keypresses
this.keys = function(e) {
var key = e.which;
var map = {
// Prev/next
37: _.prev,
39: _.next,
// Esc
27: _.stop
};
if($.isFunction(map[key])) {
map[key]();
}
};
// Arrow navigation
this.next = function() { return _.stop().move(_.current + 1) };
this.prev = function() { return _.stop().move(_.current - 1) };
this.dots = function() {
// Create the HTML
var html = '<ol class="dots">';
$.each(this.items, function(index) { html += '<li class="dot' + (index < 1 ? ' active' : '') + '">' + (index + 1) + '</li>'; });
html += '</ol>';
// Add it to the Unslider
this.el.addClass('has-dots').append(html).find('.dot').click(function() {
_.move($(this).index());
});
};
};
// Create a jQuery plugin
$.fn.unslider = function(o) {
var len = this.length;
// Enable multiple-slider support
return this.each(function(index) {
// Cache a copy of $(this), so it
var me = $(this);
var instance = (new Unslider).init(me, o);
// Invoke an Unslider instance
me.data('unslider' + (len > 1 ? '-' + (index + 1) : ''), instance);
});
};
})(window.jQuery, false);
jQuery(document).ready(function($){
// browser window scroll (in pixels) after which the "back to top" link is shown
var offset = 300,
//browser window scroll (in pixels) after which the "back to top" link opacity is reduced
offset_opacity = 1200,
//duration of the top scrolling animation (in ms)
scroll_top_duration = 700,
//grab the "back to top" link
$back_to_top = $('.back-top');
//hide or show the "back to top" link
$(window).scroll(function(){
( $(this).scrollTop() > offset ) ? $back_to_top.addClass('cd-is-visible') : $back_to_top.removeClass('cd-is-visible cd-fade-out');
if( $(this).scrollTop() > offset_opacity ) {
$back_to_top.addClass('cd-fade-out');
}
});
//smooth scroll to top
$back_to_top.on('click', function(event){
event.preventDefault();
$('body,html').animate({
scrollTop: 0 ,
}, scroll_top_duration
);
});
//設定footer置底
var winheight = $( window ).height();
var bodyheight = $("body").height();
if (winheight >= bodyheight){
$(".outer-footer").css("position" , "fixed");
$(".outer-footer").css("bottom" , "0");
}
});
/**
* Unslider by @idiot
*/
| Betty-Hsieh/makemoney888 | resource/js/backtop.js | JavaScript | mit | 6,349 |
//$Id: Timer_Queue_Iterator.cpp 2622 2015-08-13 18:30:00Z mitza $
#ifndef ACE_TIMER_QUEUE_ITERATOR_CPP
#define ACE_TIMER_QUEUE_ITERATOR_CPP
#include "ace/config-all.h"
#if defined (ACE_HAS_ALLOC_HOOKS)
# include "ace/Malloc_Base.h"
#endif /* ACE_HAS_ALLOC_HOOKS */
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
#if !defined (__ACE_INLINE__)
#include "ace/Timer_Queue_Iterator.inl"
#endif /* __ACE_INLINE__ */
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
ACE_ALLOC_HOOK_DEFINE_Tc(ACE_Timer_Node_T)
template <class TYPE> void
ACE_Timer_Node_T<TYPE>::dump (void) const
{
#if defined (ACE_HAS_DUMP)
ACE_TRACE ("ACE_Timer_Node_T::dump");
ACELIB_DEBUG ((LM_DEBUG, ACE_BEGIN_DUMP, this));
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("\nact_ = %x"), this->act_));
this->timer_value_.dump ();
this->interval_.dump ();
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("\nprev_ = %x"), this->prev_));
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("\nnext_ = %x"), this->next_));
ACELIB_DEBUG ((LM_DEBUG, ACE_TEXT ("\ntimer_id_ = %d\n"), this->timer_id_));
ACELIB_DEBUG ((LM_DEBUG, ACE_END_DUMP));
#endif /* ACE_HAS_DUMP */
}
template <class TYPE>
ACE_Timer_Node_T<TYPE>::ACE_Timer_Node_T (void)
: act_ (0),
prev_ (0),
next_ (0),
timer_id_ (-1)
{
ACE_TRACE ("ACE_Timer_Node_T::ACE_Timer_Node_T");
}
template <class TYPE>
ACE_Timer_Node_T<TYPE>::~ACE_Timer_Node_T (void)
{
ACE_TRACE ("ACE_Timer_Node_T::~ACE_Timer_Node_T");
}
template <class TYPE>
ACE_Timer_Queue_Iterator_T<TYPE>::ACE_Timer_Queue_Iterator_T (void)
{
}
template <class TYPE>
ACE_Timer_Queue_Iterator_T<TYPE>::~ACE_Timer_Queue_Iterator_T (void)
{
}
ACE_END_VERSIONED_NAMESPACE_DECL
#endif /* ACE_TIMER_QUEUE_ITERATOR_CPP */
| binary42/OCI | ace/Timer_Queue_Iterator.cpp | C++ | mit | 1,722 |
#include "bitcoinunits.h"
#include <QStringList>
BitcoinUnits::BitcoinUnits(QObject *parent):
QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
unitlist.append(BTC);
unitlist.append(mBTC);
unitlist.append(uBTC);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch(unit)
{
case BTC:
case mBTC:
case uBTC:
return true;
default:
return false;
}
}
QString BitcoinUnits::name(int unit)
{
switch(unit)
{
case BTC: return QString("BDOG");
case mBTC: return QString("mBDOG");
case uBTC: return QString::fromUtf8("μBDOG");
default: return QString("???");
}
}
QString BitcoinUnits::description(int unit)
{
switch(unit)
{
case BTC: return QString("blackdogcoins");
case mBTC: return QString("Milli-blackdogcoins (1 / 1,000)");
case uBTC: return QString("Micro-blackdogcoins (1 / 1,000,000)");
default: return QString("???");
}
}
qint64 BitcoinUnits::factor(int unit)
{
switch(unit)
{
case BTC: return 100000000;
case mBTC: return 100000;
case uBTC: return 100;
default: return 100000000;
}
}
int BitcoinUnits::amountDigits(int unit)
{
switch(unit)
{
case BTC: return 8; // 21,000,000 (# digits, without commas)
case mBTC: return 11; // 21,000,000,000
case uBTC: return 14; // 21,000,000,000,000
default: return 0;
}
}
int BitcoinUnits::decimals(int unit)
{
switch(unit)
{
case BTC: return 8;
case mBTC: return 5;
case uBTC: return 2;
default: return 0;
}
}
QString BitcoinUnits::format(int unit, qint64 n, bool fPlus)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if(!valid(unit))
return QString(); // Refuse to format invalid unit
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Right-trim excess zeros after the decimal point
int nTrim = 0;
for (int i = remainder_str.size()-1; i>=2 && (remainder_str.at(i) == '0'); --i)
++nTrim;
remainder_str.chop(nTrim);
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
return quotient_str + QString(".") + remainder_str;
}
QString BitcoinUnits::formatWithUnit(int unit, qint64 amount, bool plussign)
{
return format(unit, amount, plussign) + QString(" ") + name(unit);
}
bool BitcoinUnits::parse(int unit, const QString &value, qint64 *val_out)
{
if(!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
QStringList parts = value.split(".");
if(parts.size() > 2)
{
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if(parts.size() > 1)
{
decimals = parts[1];
}
if(decimals.size() > num_decimals)
{
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if(str.size() > 18)
{
return false; // Longer numbers will exceed 63 bits
}
qint64 retvalue = str.toLongLong(&ok);
if(val_out)
{
*val_out = retvalue;
}
return ok;
}
int BitcoinUnits::rowCount(const QModelIndex &parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex &index, int role) const
{
int row = index.row();
if(row >= 0 && row < unitlist.size())
{
Unit unit = unitlist.at(row);
switch(role)
{
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case UnitRole:
return QVariant(static_cast<int>(unit));
}
}
return QVariant();
}
| blackdogcoin/blackdogcoin | src/qt/bitcoinunits.cpp | C++ | mit | 4,299 |
<?php
/**
*
* * This is an iumio Framework component
* *
* * (c) RAFINA DANY <dany.rafina@iumio.com>
* *
* * iumio Framework, an iumio component [https://iumio.com]
* *
* * To get more information about licence, please check the licence file
*
*/
namespace iumioFramework\Core\Additional\Manager\Module\App;
use iumioFramework\Core\Additional\Manager\Module\ModuleManager;
use iumioFramework\Core\Server\Server as Server;
use iumioFramework\Core\Base\Json\JsonListener;
use iumioFramework\Core\Additional\Manager\CoreManager;
use iumioFramework\Core\Additional\Manager\Module\Assets\AssetsManager;
use iumioFramework\Core\Exception\Server\Server500;
use iumioFramework\Core\Additional\Manager\FEnvFcm;
use iumioFramework\Core\Additional\Manager\Module\ModuleManagerInterface;
use iumioFramework\Core\Additional\Manager\Module\App\OutputManagerOverride as Output;
/**
* Class AppManager
* @package iumioFramework\Core\Additional\Manager\Module\App
* @category Framework
* @licence MIT License
* @link https://framework.iumio.com
* @author RAFINA Dany <dany.rafina@iumio.com>
*/
class AppManager extends ModuleManager implements ModuleManagerInterface
{
protected $options;
protected $stage = array(
"Application name (like DefaultApp --> end with App): ",
"You can install a default template with your app. Would you like to have one ? (yes/no) - Tap Enter for yes: ",
"Yeah! Would you like to enabled your app ? (yes/no) - Tap Enter for yes:",
"Informations are correct ? (yes/no) - Tap Enter for yes:",
"Deleting your app means all files and directories in your app will be deleted.
Are you sure to confirm this action ? (yes/no) - Tap Enter for yes:",
"Ok. I process to deleting your app ...",
"Deleting action is aborted ",
"Your app list. To select one, please enter the number matching with app",
"Enter your app prefix? (App prefix must be a string without special character except [ _ & numbers])
- Tap Enter for no app prefix:"
);
protected $params = array("appname" => "", "template" => "", "isdefault" => "", "correct" => "",
"applist" => array(), "capp" => "");
/**
* @return mixed|void
* @param $options
* @throws \Exception
*/
public function __render(array $options)
{
$this->options = $options;
if (!isset($options["commands"])) {
Output::outputAsError("App Manager Error \n You must to specify an option\n");
}
$opt = $options["commands"][0] ?? null;
if ($opt == "app:create") {
$this->stepNewProject();
} elseif ($opt == "app:remove") {
$this->stepRemoveProject();
} elseif ($opt == "app:enabled") {
$this->stepEnabledProject();
} elseif ($opt == "app:disabled") {
$this->stepDisabledProject();
} else {
Output::outputAsError("App Manager Error \n
This command doesn't exist. Referer to help comannd\n");
}
}
/** Check app name format
* @param string $appname App name
* @return int Is valid app name
*/
final protected function checkAppName(string $appname):int
{
if ($appname == "App" || strpos($appname, "App") == false ||
preg_match('/[\'^£$%&*()}{@#~?><>,|=+¬-]/', $appname)) {
return (-1);
}
return (1);
}
/** Check boolean response
* @param string $res response
* @return int Is valid boolean response
*/
final protected function checkBooleanResponse(string $res):int
{
if (trim($res) == "yes" || trim($res) == "no" || trim($res) == "") {
return (1);
}
return (-1);
}
/** Check prefix response
* @param string $res response
* @return int Is valid prefix response
*/
final protected function checkPrefix(string $res):int
{
if (!preg_match('/[\/\'^£$%&*()}{@#~?><>,|=+¬-]/', $res) &&
strpos($res, "\\") == false) {
return (1);
}
return (-1);
}
/** Check if app name exist
* @param string $appname App name
* @return bool If app exist
* @throws Server500
*/
final protected function checkAppExist(string $appname):bool
{
if (file_exists(FEnvFcm::get("framework.apps").$appname)) {
return (true);
}
return (false);
}
/** Listen the STDIN
* @return string STDIN value
*/
final protected function listener():string
{
while ($resp = rtrim(fgets(STDIN))) {
return $resp;
}
return ('');
}
/** Create an app
* @throws Server500
* @throws \Exception
*/
final protected function stepNewProject()
{
Output::clear();
Output::displayAsGreen("Welcome on App Manager.\n".
"I'm assist you to create your new app. Many question will ask you.", "none");
Output::outputAsReadLine($this->stage[0], "none");
$this->params['appname'] = ucfirst($this->listener());
$elem = false;
while ($elem == false) {
if ($this->checkAppName($this->params['appname']) != 1) {
Output::displayAsRed("Your app name is invalid. Please Retry.", "none", false);
} elseif ($this->checkAppExist($this->params['appname']) == true) {
$elem = false;
Output::displayAsRed(
"This app name is already exist, Please enter an other app name.",
"none",
false
);
} else {
$elem = true;
continue;
}
Output::outputAsReadLine($this->stage[0], "none");
$this->params['appname'] = ucfirst($this->listener());
}
Output::displayAsGreen(
"Great! Your app name is ".$this->params['appname'],
"none",
false
);
Output::outputAsReadLine($this->stage[1], "none");
$this->params['template'] = $this->listener();
while ($this->checkBooleanResponse($this->params['template']) != 1) {
Output::displayAsRed("Invalid response. Please Retry (yes/no)", "none", false);
Output::outputAsReadLine($this->stage[1], "none");
$this->params['template'] = $this->listener();
}
Output::outputAsReadLine($this->stage[2], "none");
$this->params['enabled'] = $this->listener();
while ($this->checkBooleanResponse($this->params['enabled']) != 1) {
Output::displayAsRed("Invalid response. Please Retry (yes/no)", "none", false);
Output::outputAsReadLine($this->stage[2], "none");
$this->params['enabled'] = $this->listener();
}
Output::outputAsReadLine($this->stage[8], "none");
$this->params['prefix'] = strtolower($this->listener());
while ($this->checkPrefix($this->params['prefix']) != 1) {
Output::displayAsRed("Invalid response. Please Retry (yes/no)", "none", false);
Output::outputAsReadLine($this->stage[8], "none");
$this->params['prefix'] = strtolower($this->listener());
}
$this->params['template'] = (($this->params['template'] != "")? $this->params['template'] : "yes");
$this->params['enabled'] = (($this->params['enabled'] != "")? $this->params['enabled'] : "yes");
$this->showRecap();
Output::outputAsReadLine($this->stage[3], "none");
$this->params['correct'] = $this->listener();
while ($this->checkBooleanResponse($this->params['correct']) != 1) {
Output::displayAsRed("Invalid response. Please Retry", "none", false);
Output::outputAsReadLine($this->stage[3], "none");
$this->params['correct'] = $this->listener();
}
if ($this->params['correct'] == "no") {
Output::displayAsRed("Creation Aborted. Please re-run app and enter the correct informations");
}
$this->createAppProcess();
}
/**
* Remove an app
* @throws
*/
final protected function stepRemoveProject()
{
Output::clear();
Output::displayAsGreen("Welcome on App Manager.\n".
"I'm assist you to remove your app. Many question will ask you.", "none");
Output::outputAsReadLine($this->stage[0], "none");
$this->params['appname'] = ucfirst($this->listener());
$elem = false;
while ($elem == false) {
if ($this->checkAppName($this->params['appname']) != 1) {
Output::displayAsRed("Your app name is invalid. Please Retry.", "none", false);
} elseif ($this->checkAppExist($this->params['appname']) == false &&
$this->checkAppRegister($this->params['appname']) == false) {
$elem = false;
Output::displayAsRed(
"This app not exist, Please enter an existed app name",
"none",
false
);
} else {
$elem = true;
continue;
}
Output::outputAsReadLine($this->stage[0], "none");
$this->params['appname'] = ucfirst($this->listener());
}
if ($this->checkAppExist($this->params['appname']) == true &&
$this->checkAppRegister($this->params['appname']) == false) {
Output::displayAsGreen("Ok ! Your app is ".$this->params['appname'].
". It exist on apps directory but it's not declared in app declarator", "none", false);
} elseif ($this->checkAppExist($this->params['appname']) == false &&
$this->checkAppRegister($this->params['appname']) == true) {
Output::displayAsGreen("Ok ! Your app is ".$this->params['appname'].
". It's declared in app declarator but not exist in apps directory", "none", false);
} else {
Output::displayAsGreen("Ok ! Your app is ".$this->params['appname'].
". It's declared in app declarator and exist in apps directory", "none", false);
}
Output::outputAsReadLine($this->stage[4], "none");
$conf = ((!empty($this->listener()))? $this->listener() : "yes");
while ($this->checkBooleanResponse($conf) != 1) {
Output::displayAsRed("Invalid response. Please Retry (yes/no)", "none", false);
Output::outputAsReadLine($this->stage[4], "none");
$conf = ((!empty($this->listener()))? $this->listener() : "yes");
}
if ($conf == "no") {
Output::outputAsError($this->stage[6]);
}
$this->removeAppProcess();
}
/**
* @throws Server500
*/
final protected function stepEnabledProject()
{
Output::clear();
Output::displayAsGreen("Welcome on App Manager.\n".
"I'm assist you to enabled your app. Many question will ask you.\n".$this->stage[7], "none");
if ($this->showDisabledAppsRegister() == false) {
return ;
}
Output::outputAsReadLine("Which number ? : ", "none");
$this->params['capp'] = $this->listener();
while (!@isset($this->params['applist'][$this->params['capp'] - 1])) {
Output::displayAsRed("Your choose is incorrect. Please Retry", "none", false);
$this->showDisabledAppsRegister();
Output::outputAsReadLine("Which number ? : ", "none");
$this->params['capp'] = $this->listener();
}
$this->params['capp'] = $this->params['applist'][$this->params['capp'] - 1];
Output::displayAsGreen(
"Ok ! You choose ".$this->params['capp']." to be enabled",
"none",
false
);
$this->enabledAppProcess();
}
/**
* Disable an app
* @throws Server500
*/
final protected function stepDisabledProject()
{
Output::clear();
Output::displayAsGreen("Welcome on App Manager.\n".
"I'm assist you to disabled your app. Many question will ask you.\n".$this->stage[7], "none");
if ($this->showEnabledAppsRegister() == false) {
return ;
}
Output::outputAsReadLine("Which number ? : ", "none");
$this->params['capp'] = $this->listener();
while (!is_numeric($this->params['capp']) || !isset($this->params['applist'][$this->params['capp'] - 1])) {
Output::displayAsRed("Your choose is incorrect. Please retry", "none", false);
$this->showEnabledAppsRegister();
Output::outputAsReadLine("Which number ? : ", "none");
$this->params['capp'] = $this->listener();
}
$this->params['capp'] = $this->params['applist'][$this->params['capp'] - 1];
Output::displayAsGreen(
"Ok ! You choose ".$this->params['capp']." to be disabled",
"none",
false
);
$this->disabledAppProcess();
}
/**
* Show recap
*/
final protected function showRecap()
{
$strOutput = "Summary of actions : \n";
$strOutput .= "----------------------------\n";
$strOutput .= " - Name : ".$this->params['appname']." \n";
$strOutput .= " - Template : ".$this->params['template']." \n";
$strOutput .= " - Enabled : ".$this->params['enabled']. "\n";
$strOutput .= " - Prefix : ".(($this->params['prefix'] == "")?
"no prefix" : "/".trim(stripslashes($this->params['prefix'])));
Output::displayAsGreen($strOutput, "none", false);
}
/** Check if app is registered to apps.json
* @param string $appname App name
* @return bool If exist or not
* @throws Server500
*/
final protected function checkAppRegister(string $appname):bool
{
$file = json_decode(file_get_contents(FEnvFcm::get("framework.config.core.apps.file")));
if (empty($file)) {
return (false);
}
foreach ($file as $val) {
if ($val->name == $appname) {
return (true);
}
}
return (false);
}
/** Show all app in apps.json
* @return bool
* @throws Server500
*/
final protected function showAppsRegister()
{
$file = json_decode(file_get_contents(FEnvFcm::get("framework.config.core.apps.file")));
$i = 1;
if (count($file) == 0) {
Output::outputAsError("Ops! You have no app registered. Please create an app with app");
}
$str = "";
foreach ($file as $val) {
$str .= $i.") ".$val->name.(($val->enabled == "yes")? " : Enabled" : "Disabled")."\n";
array_push($this->params['applist'], $val->name);
$i++;
}
Output::outputAsNormal("Your apps \n------------\n".$str, "none");
return (false);
}
/** Show enabled app in apps.json
* @return int
* @throws Server500
*/
final protected function showEnabledAppsRegister():int
{
$this->params['applist'] = array();
$file = json_decode(file_get_contents(FEnvFcm::get("framework.config.core.apps.file")));
$i = 1;
if ((is_string($file) && strlen($file) < 3) || (count((array) $file) == 0)) {
Output::outputAsError("Ops! You do not have an enabled application.");
return (false);
}
$str = "";
foreach ($file as $val) {
if ($val->enabled == "yes") {
$str .= $i . ") " . $val->name . " : Enabled" . "\n";
array_push($this->params['applist'], $val->name);
$i++;
}
}
if (count($this->params['applist']) == 0) {
Output::displayAsRed("Ops! You do not have an enabled app.");
return (false);
} else {
Output::displayAsGreen("Your apps \n------------\n".$str, "none", false);
}
return (true);
}
/** Show disabled app in apps.json
* @return int
* @throws Server500
*/
final protected function showDisabledAppsRegister():int
{
$this->params['applist'] = array();
$file = json_decode(file_get_contents(FEnvFcm::get("framework.config.core.apps.file")));
$i = 1;
if ((is_string($file) && strlen($file) < 3) || (count((array) $file) == 0)) {
Output::displayAsRed("Ops! You do not have a disabled app.");
return (false);
}
$str = "";
foreach ($file as $val) {
if ($val->enabled == "no") {
$str .= $i . ") " . $val->name . " : Disabled" . "\n";
array_push($this->params['applist'], $val->name);
$i++;
}
}
if (count($this->params['applist']) == 0) {
Output::displayAsRed("Ops! You do not have a disabled app.");
return (false);
} else {
Output::displayAsGreen("Your apps \n------------\n".$str, "none", false);
}
return (true);
}
/**
* Processing to create app
* @throws \Exception
*/
final protected function createAppProcess()
{
$appname = $this->params['appname'];
Output::outputAsReadLine("Processing to create app : $appname", "none");
sleep(1);
$temp = $this->params['template'];
$temdirbase = __DIR__."/AppTemplate";
$tempdir = ($temp == "no")? $temdirbase.'/notemplate/{appname}/' : $temdirbase.'/template/{appname}/';
Server::copy($tempdir, FEnvFcm::get("framework.apps").$appname, 'directory');
$napp = FEnvFcm::get("framework.apps").$appname;
// APP
$file = file_get_contents($napp."/{appname}.php.local");
$str = str_replace("{appname}", $appname, $file);
file_put_contents($napp."/{appname}.php.local", $str);
rename($napp."/{appname}.php.local", $napp."/$appname.php");
// Mercure
$file = file_get_contents($napp."/Routing/default.merc");
$str = str_replace("{appname}", $appname, $file);
file_put_contents($napp."/Routing/default.merc", $str);
// MASTER
$file = file_get_contents($napp."/Masters/DefaultMaster.php.local");
$str = str_replace("{appname}", $appname, $file);
file_put_contents($napp."/Masters/DefaultMaster.php.local", $str);
rename($napp."/Masters/DefaultMaster.php.local", $napp."/Masters/DefaultMaster.php");
// REGISTER TO APP CORE
$file = JsonListener::open(FEnvFcm::get("framework.config.core.apps.file"));
if (empty($file)) {
$file = new \stdClass();
}
$lastapp = count((array) $file);
$file->$lastapp = new \stdClass();
$file->$lastapp->name = $this->params['appname'];
$file->$lastapp->enabled = (($this->params['enabled'] != "")? $this->params['enabled'] : "yes");
$file->$lastapp->prefix = trim(stripslashes($this->params['prefix']));
$file->$lastapp->class = "\\".$this->params['appname']."\\".$this->params['appname'];
$ndate = new \DateTime('UTC');
$file->$lastapp->creation = $ndate;
$file->$lastapp->update = $ndate;
$file = json_encode($file, JSON_PRETTY_PRINT);
file_put_contents(FEnvFcm::get("framework.config.core.apps.file"), $file);
$this->initialJSON();
if ($this->params['template'] == "yes") {
$asm = new AssetsManager();
$asm->__render(["commands" => ["assets:copy"], "options" => ["--symlink", "--noexit", "--appname=".
$this->params['appname']]]);
}
// $this->addComposerApp($this->params['appname']);
Output::displayAsGreen("Your app is ready to use. To test your app,
go to project location on your browser with parameter ".(($this->params['prefix'] != "")?
"/".trim(stripslashes($this->params['prefix'])) : "")."/index. Enjoy !", "none", false);
}
/**
* Build framework.config.json
* @throws Server500
*/
final protected function initialJSON()
{
$file = json_decode(file_get_contents(FEnvFcm::get("framework.config.core.config.file")));
if (isset($file->installation) && $file->installation == null) {
$file->installation = new \DateTime();
$file->default_env = "dev";
$file->location = realpath(__DIR__."../../../../../../../../").DIRECTORY_SEPARATOR;
$result = json_encode($file, JSON_PRETTY_PRINT);
file_put_contents(FEnvFcm::get("framework.config.core.config.file"), $result);
}
}
/**
* Processing to enabled an app
* @throws Server500
*/
final protected function enabledAppProcess()
{
$appname = $this->params['capp'];
Output::displayAsGreen(
"Processing to enabled app : $appname will be enabled \n",
"none",
false
);
sleep(1);
$file = json_decode(file_get_contents(FEnvFcm::get("framework.config.core.apps.file")));
foreach ($file as $val) {
if ($val->name == $this->params['capp']) {
$val->update = new \DateTime();
$val->enabled = "yes";
}
}
$file = json_encode($file, JSON_PRETTY_PRINT);
file_put_contents(FEnvFcm::get("framework.config.core.apps.file"), $file);
Output::displayAsGreen("Now, the ".$this->params['capp']." is enabled", "none", false);
}
/**
* Processing to disabled an app
* @throws Server500
*/
final protected function disabledAppProcess()
{
$appname = $this->params['capp'];
Output::displayAsGreen(
"Processing to enabled app : $appname will be enabled \n",
"none",
false
);
sleep(1);
$file = json_decode(file_get_contents(FEnvFcm::get("framework.config.core.apps.file")));
foreach ($file as $val) {
if ($val->name == $this->params['capp']) {
$val->update = new \DateTime();
$val->enabled = "no";
}
}
$file = json_encode($file, JSON_PRETTY_PRINT);
file_put_contents(FEnvFcm::get("framework.config.core.apps.file"), $file);
Output::displayAsGreen("Now, the ".$this->params['capp']." is disabled.", "none", false);
}
/**
* Processing to remove app
* @throws Server500
* @throws \Exception
*/
final protected function removeAppProcess()
{
$appname = $this->params['appname'];
Output::displayAsGreen("Processing to delete app : $appname \n", "none", false);
sleep(1);
// DELETE TO APP CORE
$file = json_decode(file_get_contents(FEnvFcm::get("framework.config.core.apps.file")));
if (!empty($file)) {
foreach ($file as $one => $val) {
if ($val->name == $appname) {
unset($file->$one);
break;
}
}
$file = array_values((array)$file);
$filetemp = $file;
$file = json_encode((object) $file, JSON_PRETTY_PRINT);
file_put_contents(FEnvFcm::get("framework.config.core.apps.file"), $file);
if (strlen($file) < 3) {
file_put_contents(FEnvFcm::get("framework.config.core.apps.file"), "");
}
}
$asm = new AssetsManager();
$asm->__render(["commands" => ["assets:clear"],
"options" => ["--quiet", "--noexit", "--appname=". $this->params['appname']]]);
// $this->removeComposerApp($appname);
Server::delete(FEnvFcm::get("framework.apps")."$appname", "directory");
if (empty($filetemp)) {
$base = __DIR__."/../../../../../../";
$elem = json_decode(file_get_contents($base."elements/config_files/core/framework.config.json"));
$elem->installation = null;
$elem->deployment = null;
file_put_contents($base."elements/config_files/core/framework.config.json", json_encode($elem));
}
Output::displayAsGreen("The application has been deleted. To create a new application,
use [app create] .", "none", false);
}
public function __alter()
{
// TODO: Implement __alter() method.
}
/**
* AppManager constructor.
*/
public function __construct()
{
CoreManager::setCurrentModule("App Manager");
}
}
| iumio-team/iumio-framework | Core/Additional/Manager/Module/App/AppManager.php | PHP | mit | 24,756 |
var _curry2 = require('./internal/_curry2');
/**
* Tests if two items are equal. Equality is strict here, meaning reference equality for objects and
* non-coercing equality for primitives.
*
* @func
* @memberOf R
* @category Relation
* @sig a -> b -> Boolean
* @param {*} a
* @param {*} b
* @return {Boolean}
* @example
*
* var o = {};
* R.eq(o, o); //=> true
* R.eq(o, {}); //=> false
* R.eq(1, 1); //=> true
* R.eq(1, '1'); //=> false
*/
module.exports = _curry2(function eq(a, b) { return a === b; });
| stoeffel/ramda | src/eq.js | JavaScript | mit | 551 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
[assembly: AssemblyTitle("vbacGUI")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("vbacGUI")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
// その型の ComVisible 属性を true に設定してください。
[assembly: ComVisible(false)]
// 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です
[assembly: Guid("75c23f68-7470-405c-9422-0bcee6c3c41a")]
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
// 既定値にすることができます:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| dck-jp/vbacGUI | vbacGUI/Properties/AssemblyInfo.cs | C# | mit | 1,646 |
import { valid } from 'semver';
import { logger } from '../../../logger';
import type { PackageFile } from '../../types';
import { getNpmLock } from './npm';
import type { LockFile } from './types';
import { getYarnLock } from './yarn';
export async function getLockedVersions(
packageFiles: PackageFile[]
): Promise<void> {
const lockFileCache: Record<string, LockFile> = {};
logger.debug('Finding locked versions');
for (const packageFile of packageFiles) {
const { yarnLock, npmLock, pnpmShrinkwrap } = packageFile;
const lockFiles = [];
if (yarnLock) {
logger.trace('Found yarnLock');
lockFiles.push(yarnLock);
if (!lockFileCache[yarnLock]) {
logger.trace('Retrieving/parsing ' + yarnLock);
lockFileCache[yarnLock] = await getYarnLock(yarnLock);
}
const { lockfileVersion, isYarn1 } = lockFileCache[yarnLock];
if (!isYarn1) {
if (lockfileVersion >= 6) {
// https://github.com/yarnpkg/berry/commit/f753790380cbda5b55d028ea84b199445129f9ba
packageFile.constraints.yarn = '^2.2.0';
} else {
packageFile.constraints.yarn = '^2.0.0';
}
}
for (const dep of packageFile.deps) {
dep.lockedVersion =
lockFileCache[yarnLock].lockedVersions[
`${dep.depName}@${dep.currentValue}`
];
if (dep.depType === 'engines' && dep.depName === 'yarn' && !isYarn1) {
dep.lookupName = '@yarnpkg/cli';
}
}
} else if (npmLock) {
logger.debug('Found ' + npmLock + ' for ' + packageFile.packageFile);
lockFiles.push(npmLock);
if (!lockFileCache[npmLock]) {
logger.trace('Retrieving/parsing ' + npmLock);
lockFileCache[npmLock] = await getNpmLock(npmLock);
}
const { lockfileVersion } = lockFileCache[npmLock];
if (lockfileVersion === 1) {
if (packageFile.constraints.npm) {
packageFile.constraints.npm += ' <7';
} else {
packageFile.constraints.npm = '<7';
}
}
for (const dep of packageFile.deps) {
dep.lockedVersion = valid(
lockFileCache[npmLock].lockedVersions[dep.depName]
);
}
} else if (pnpmShrinkwrap) {
logger.debug('TODO: implement pnpm-lock.yaml parsing of lockVersion');
lockFiles.push(pnpmShrinkwrap);
}
if (lockFiles.length) {
packageFile.lockFiles = lockFiles;
}
}
}
| singapore/renovate | lib/manager/npm/extract/locked-versions.ts | TypeScript | mit | 2,446 |
module ObserverPattern
module Weather
class ForecastDisplay
include DisplayElement
include Observer
attr_accessor :current_pressure, :last_pressure, :weather_data
def initialize(weather_data)
self.weather_data = weather_data
self.weather_data.register_observer(self)
self.current_pressure = 29.92
end
def display
if current_pressure > last_pressure
puts_and_return "Forecast: Improving weather on the way!"
elsif current_pressure == last_pressure
puts_and_return "Forecast: More of the same"
elsif current_pressure < last_pressure
puts_and_return "Forecast: Watch out for cooler, rainy weather"
end
end
def update(temperature, humidity, pressure)
self.last_pressure = current_pressure
self.current_pressure = pressure
end
end
end
end
| billywatson/head_first_design_patterns_rb | lib/head_first_design_patterns_rb/observer_pattern/weather/forecast_display.rb | Ruby | mit | 907 |
package cc.openframeworks.androidSwipeExample;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import cc.openframeworks.OFAndroid;
public class OFActivity extends cc.openframeworks.OFActivity{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
String packageName = getPackageName();
ofApp = new OFAndroid(packageName,this);
}
@Override
public void onDetachedFromWindow() {
}
@Override
protected void onPause() {
super.onPause();
ofApp.pause();
}
@Override
protected void onResume() {
super.onResume();
ofApp.resume();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (OFAndroid.keyDown(keyCode, event)) {
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (OFAndroid.keyUp(keyCode, event)) {
return true;
} else {
return super.onKeyUp(keyCode, event);
}
}
OFAndroid ofApp;
// Menus
// http://developer.android.com/guide/topics/ui/menus.html
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Create settings menu options from here, one by one or infalting an xml
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// This passes the menu option string to OF
// you can add additional behavior from java modifying this method
// but keep the call to OFAndroid so OF is notified of menu events
if(OFAndroid.menuItemSelected(item.getItemId())){
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onPrepareOptionsMenu (Menu menu){
// This method is called every time the menu is opened
// you can add or remove menu options from here
return super.onPrepareOptionsMenu(menu);
}
}
| SpecularStudio/ofQt | of_v0.9.0/examples/android/androidSwipeExample/srcJava/cc/openframeworks/androidSwipeExample/OFActivity.java | Java | mit | 2,098 |
var searchData=
[
['wait_5ffor_5fcal_132',['wait_for_cal',['../class_a_d_c___module.html#a4fb69b5b2d07c3fc8f5f0bbbf05dfa2a',1,'ADC_Module']]],
['waituntilstable_133',['waitUntilStable',['../namespace_v_r_e_f.html#a108f7c1b5a2073bc092eafcae58575b0',1,'VREF']]],
['wrong_5fadc_134',['WRONG_ADC',['../namespace_a_d_c___error.html#ad050c44d1f3422d02e5f9726edeee8f0a52df2c8ae830ed21e0c2fc269087b3ec',1,'ADC_Error']]],
['wrong_5fpin_135',['WRONG_PIN',['../namespace_a_d_c___error.html#ad050c44d1f3422d02e5f9726edeee8f0ab578c19f4fab8e2bfeddc85fa17b5acf',1,'ADC_Error']]]
];
| pedvide/ADC | docs/Teensy_3_2_html/search/all_11.js | JavaScript | mit | 575 |
from pydatastream import Datastream
import json
import datetime
import sys
import os.path
#hardcoded directories
dir_input = "input/"
dir_output = "output/"
#check that the login credentials and input file location are being passed in
numOfArgs = len(sys.argv) - 1
if numOfArgs != 3:
print "Please run this python script with username,password and input file location in that order respectively."
exit()
#Setup login credentials and input file location
username = str(sys.argv[1])
pw = str(sys.argv[2])
input_file_loc = dir_input + str(sys.argv[3])
#Ensure that the input file location exists
if ( not os.path.isfile(str(input_file_loc)) ):
print "The file " + str(input_file_loc) + " does not exist."
exit()
#login credentials to datastream
DWE = Datastream(username=username,password=pw)
#other info from datastream
info = DWE.system_info()
subscribed_sources = DWE.sources()
#replace missing data with NaNs
DWE.raise_on_error = False
#get all codes, groups, start dates from input file
with open(input_file_loc,'r') as input_file:
symbol_ref = json.load(input_file)
#download timestamp
download_date = {'Custom_Download_Date' : datetime.datetime.now().isoformat()}
#calculate time taken for entire process
time_taken = datetime.datetime.now()
time_taken = time_taken - time_taken
for desc,desc_value in symbol_ref.iteritems():
for group,group_value in desc_value.iteritems():
#create list for custom fields
custom_fields = list()
for code_key,code_value in group_value.iteritems():
for key,value in code_value.iteritems():
if(key == 'code'):
search_code = value
search_symbol = {'Custom_Ticker' : value}
if(key == 'start_date'):
start_date = value
if(key == 'custom_field'):
custom_fields[:] = []
custom_fields.append(value)
startTime = datetime.datetime.now()
#send request to retrieve the data from Datastream
req = DWE.fetch(str(search_code),custom_fields,date_from=str(start_date),only_data=False)
time_taken = time_taken + datetime.datetime.now() - startTime
#format date and convert to json
raw_json = req[0].to_json(date_format='iso')
raw_metadata = req[1].to_json()
#Data cleaning and processing
#remove the time component including the '.' char from the key values of datetime in the data
raw_json = raw_json.replace("T00:00:00.000Z","")
#replace the metadata's keys from "0" to "default_ws_key"
raw_metadata = raw_metadata.replace("\"0\"","\"Custom_WS_Key\"")
#combine the data and the metadata about the code
allData_str = json.loads(raw_json)
metadata_str = json.loads(raw_metadata)
datastream_combined = {key : value for (key,value) in (allData_str.items() + metadata_str.items())}
#create symbol json string and append to data
data_with_symbol = {key : value for (key,value) in (search_symbol.items() + datastream_combined.items())}
#append group
group_code = {'Custom_Group' : group}
data_with_group = {key : value for (key,value) in (group_code.items() + data_with_symbol.items())}
#append category
category = {'Custom_Description' : desc}
data_with_category = {key : value for (key,value) in (category.items() + data_with_group.items())}
#append download timestamp
final_data = {key : value for (key,value) in (download_date.items() + data_with_category.items())}
final_data_json = json.dumps(final_data)
#decode to the right format for saving to disk
json_file = json.JSONDecoder().decode((final_data_json))
#save to json file on server
if(len(group_value) > 1):
filename = dir_output + desc + '_' + group + '_' + code_key + '.json'
else:
filename = dir_output + desc + '_' + group + '.json'
with open(filename,'w') as outfile:
json.dump(json_file,outfile,sort_keys=True)
print "time taken for " + str(sys.argv[3]) + " to be retrieved: " + str(time_taken)
| jinser/automate_pydatastream | getcustom.py | Python | mit | 3,917 |
class Goblin extends Entity {
constructor(x, y, team) {
super(x, y, team);
this.totalHealth = 100;
this.attackStrength = 60;
this.attackSpeed = 1100;
this.speed = 0.15; // 10 px/ms
this.deploySpeed = 1000;
this.size = 10;
this.color = 'green';
super.setup();
}
}
class Skeleton extends Entity {
constructor(x, y, team) {
super(x, y, team);
this.totalHealth = 38;
this.attackStrength = 38;
this.attackSpeed = 1000;
this.speed = 0.1; // 10 px/ms
this.deploySpeed = 1000;
this.size = 7;
this.color = 'white';
super.setup();
}
}
class Archer extends Entity {
constructor(x, y, team) {
super(x, y, team);
this.totalHealth = 175;
this.attackStrength = 59;
this.attackSpeed = 1200;
this.attackAir = true;
this.speed = 0.05; // 10 px/ms
this.range = 100;
this.deploySpeed = 1000;
this.size = 10;
this.color = 'pink';
super.setup();
}
}
class BabyDragon extends Entity {
constructor(x, y, team) {
super(x, y, team);
this.totalHealth = 800;
this.attackStrength = 100;
this.attackSpeed = 1600;
this.attackSplash = true;
this.attackAir = true;
this.speed = 0.05; // 10 px/ms
this.range = 70;
this.targetRadius = 20;
this.deploySpeed = 1000;
this.flyingTroop = true;
this.size = 15;
this.color = 'darkgreen';
super.setup();
}
}
class Giant extends Entity {
constructor(x, y, team) {
super(x, y, team);
this.totalHealth = 2000;
this.attackStrength = 145;
this.attackSpeed = 1500;
this.speed = 0.01; // 10 px/ms
this.deploySpeed = 1000;
this.attackBuilding = true;
this.size = 20;
this.color = 'brown';
super.setup();
}
} | richyliu/clash-royale | Troop.js | JavaScript | mit | 2,072 |
import db from './db';
const authenticatedOnly = (req, res, next) => {
if (req.isAuthenticated()) { return next(); }
return res.status(401).send('Authentication required');
};
const dbRoutes = (app) => {
app.post('/users', authenticatedOnly, (req, res) => {
db.update(req.body, (doc) => {
if (process.env.NODE_ENV !== 'production') {
console.log('Saved:', doc);
}
res.send(doc.data);
});
});
};
export default dbRoutes;
| Chingu-cohorts/devgaido | src/server/dbRoutes.js | JavaScript | mit | 465 |
//%2005////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2000, 2001, 2002 BMC Software; Hewlett-Packard Development
// Company, L.P.; IBM Corp.; The Open Group; Tivoli Systems.
// Copyright (c) 2003 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation, The Open Group.
// Copyright (c) 2004 BMC Software; Hewlett-Packard Development Company, L.P.;
// IBM Corp.; EMC Corporation; VERITAS Software Corporation; The Open Group.
// Copyright (c) 2005 Hewlett-Packard Development Company, L.P.; IBM Corp.;
// EMC Corporation; VERITAS Software Corporation; The Open Group.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// THE ABOVE COPYRIGHT NOTICE AND THIS PERMISSION NOTICE SHALL BE INCLUDED IN
// ALL COPIES OR SUBSTANTIAL PORTIONS OF THE SOFTWARE. THE SOFTWARE IS PROVIDED
// "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//==============================================================================
//
// Author: Christopher Neufeld <neufeld@linuxcare.com>
// David Kennedy <dkennedy@linuxcare.com>
//
// Modified By: David Kennedy <dkennedy@linuxcare.com>
// Christopher Neufeld <neufeld@linuxcare.com>
// Al Stone <ahs3@fc.hp.com>
//
//%////////////////////////////////////////////////////////////////////////////
#include <Pegasus/Common/System.h>
#include <Pegasus/Common/Logger.h>
#include "DebianPackageManagerData.h"
#include <strings.h>
PEGASUS_NAMESPACE_BEGIN
#define DEBUG(X) Logger::put(Logger::DEBUG_LOG, "DebianPackageManagerData", Logger::INFORMATION, "$0", X)
DebianPackageManagerData::DebianPackageManagerData(void)
{
statusFile=NULL;
databaseDirectory=DEFAULT_DEBIAN_DIRECTORY;
}
DebianPackageManagerData::DebianPackageManagerData(const String &inDatabaseDirectory)
{
statusFile=NULL;
databaseDirectory=inDatabaseDirectory;
}
DebianPackageManagerData::~DebianPackageManagerData(void)
{
if(statusFile)
CloseStatusFile(statusFile);
statusFile=NULL;
}
int DebianPackageManagerData::initialize(void)
{
return 0;
}
void DebianPackageManagerData::terminate(void)
{
}
/* Get all the packages and put them in an array */
Array <PackageInformation *> DebianPackageManagerData::GetAllPackages(void)
{
DebianPackageInformation *package;
Array <PackageInformation *> packages;
package = (DebianPackageInformation *) GetFirstPackage();
while(package&&package->isValid()){
packages.append((PackageInformation *)package);
/* Need to keep packages lingering because we are using an
array of pointers to objects */
package=(DebianPackageInformation *)GetNextPackage();
}
EndGetPackage();
return packages;
}
/* Get the first package in the database */
PackageInformation * DebianPackageManagerData::GetFirstPackage(void)
{
String statusFilename(databaseDirectory);
if(statusFile!=NULL){
CloseStatusFile(statusFile);
statusFile=NULL;
}
statusFilename.append('/');
statusFilename.append(DEBIAN_STATUS_FILENAME);
statusFile=OpenStatusFile(statusFilename);
if(statusFile==NULL){
return NULL;
}
return(GetNextPackage());
}
/* Get the next package in the database */
PackageInformation * DebianPackageManagerData::GetNextPackage(void)
{
/*
The select file is in the form of:
Package: syslinux
Status: install ok installed
Priority: optional
Section: base
Installed-Size: 206
Maintainer: Juan Cespedes <cespedes@debian.org>
Version: 1.63-1
Depends: libc6 (>= 2.2.3-7)
Suggests: lilo (>= 20)
Description: Bootloader for Linux/i386 using MS-DOS floppies
SYSLINUX is a boot loader for the Linux/i386 operating system which
operates off an MS-DOS/Windows FAT filesystem. It is intended to
simplify first-time installation of Linux, and for creation of rescue
and other special-purpose boot disks.
.
SYSLINUX is probably not suitable as a general purpose boot loader.
However, SYSLINUX has shown itself to be quite useful in a number of
special-purpose applications.
.
You will need support for `msdos' filesystem in order to use this program
To get packages: search for any line that starts with 'Package'
*/
/* Parse the file looking for the keys (delimited by ':') */
return(ReadStatusPackage(statusFile));
}
void DebianPackageManagerData::EndGetPackage(void)
{
if(statusFile)
CloseStatusFile(statusFile);
statusFile=NULL;
}
PackageInformation * DebianPackageManagerData::GetPackage(const String &inName, const String &inVersion)
{
DebianPackageInformation * curPackage;
String junk;
junk = "dpmd-> look for package " + inName + ", version " + inVersion;
DEBUG(junk);
curPackage=(DebianPackageInformation *)GetFirstPackage();
while(curPackage&&curPackage->isValid()){
if (String::equal(curPackage->GetName(), inName) &&
String::equal(curPackage->GetVersion(), inVersion))
{
EndGetPackage();
DEBUG("dpmd-> FOUND package " + curPackage->GetName());
return curPackage;
}
junk = "dpmd-> not package " + curPackage->GetName();
junk.append(", version " + curPackage->GetVersion());
DEBUG(junk);
delete curPackage;
curPackage=(DebianPackageInformation *)GetNextPackage();
}
if (curPackage) {
delete curPackage;
curPackage = NULL;
}
EndGetPackage();
return NULL;
}
FILE * DebianPackageManagerData::OpenStatusFile(const String &filename){
FILE * retval;
retval= fopen(filename.getCString(),"r");
return retval;
}
int DebianPackageManagerData::CloseStatusFile(FILE * handle){
int retval=0;
if(handle)
retval=fclose(handle);
handle=NULL;
return retval;
}
String DebianPackageManagerData::ReadStatusLine(FILE * handle){
char *result;
char *returnLoc;
static char buffer[BUFSIZ];
String resultString;
/* Assume that no line is longer than BUFSIZ */
result=fgets(buffer,BUFSIZ,handle);
if(result==NULL){
return String::EMPTY;
}
/* Remove the trailing whitespace */
returnLoc=rindex(buffer,'\n');
if(returnLoc){
*returnLoc='\0';
}
resultString.assign(buffer);
return resultString;
}
/* Read in an entire package and return it */
DebianPackageInformation * DebianPackageManagerData::ReadStatusPackage(FILE * handle){
String nextLine;
enum parseStatus {NONE, LINE, DESCRIPTION } parser = LINE;
unsigned int colonLocation;
DebianPackageInformation *curPackage;
String curKey;
/* Assume that we are at the beginning of a package */
nextLine=ReadStatusLine(handle);
curPackage=new DebianPackageInformation;
while((nextLine!=String::EMPTY)&&(nextLine!="")&&(nextLine!="\n")){
/* Parse up the line */
switch(parser){
case LINE:
/* We are doing line by line reading */
if(nextLine[0]!=' '){ /* If this is a description, let if fall through */
colonLocation=nextLine.find(':');
if(colonLocation==PEG_NOT_FOUND){
/* parse error */
delete curPackage;
return NULL;
}
curKey=nextLine.subString(0,colonLocation);
curPackage->add(curKey,nextLine.subString(colonLocation+2));
break;
}
/* No break because the if falls through */
case DESCRIPTION:
/* We are reading in the description (multi line) */
parser=DESCRIPTION;
if(nextLine!="\n"){
curPackage->add(curKey,nextLine);
}
else {
parser=LINE;
return curPackage;
}
break;
default:
/* A parsing error occurred */
delete curPackage;
return NULL;
}
nextLine=ReadStatusLine(handle);
}
return curPackage;
}
PEGASUS_NAMESPACE_END
| ncultra/Pegasus-2.5 | src/Providers/linux/ProviderData/PackageManager/DebianPackageManagerData.cpp | C++ | mit | 8,200 |
import Tipp from 'src/models/TippModel';
/**
* Save a new tipp
* @param {Object} req Request object
* @param {Object} res Response object
* @param {Function} next Callback for next middleware in route
*/
export const postTipp = (req, res, next) => new Tipp(req.body).save()
.then(data => res.json(data))
.catch(err => next(err));
/**
* Delete a tipp, needs authentication
* @param {Object} req Request object
* @param {Object} res Response object
* @param {Function} next Callback for next middleware in route
*/
export const deleteTipp = (req, res, next) => Tipp.remove({
_id: req.params.id,
})
.then(data => res.json(data))
.catch(err => next(err));
/**
* Update a tipp
* @param {Objec} req
* @param {Object} res
* @param {Function} next Callback for next middleware in route
*/
export const putTipp = (req, res, next) => Tipp.findByIdAndUpdate(req.params.id, {
$set: req.body,
}, {
new: true,
})
.then(data => res.json(data))
.catch(err => next(err));
/**
* Get a list of all tipps
* @param {Object} req
* @param {Object} res
* @param {Function} next Callback for next middleware in route
*/
export const listTipps = (req, res, next) => Tipp
.find({}, '-email')
.sort('-created')
.then(data => res.json(data))
.catch(err => next(err));
/**
* Get one tipp
* @param {Object} req
* @param {Object} res
* @param {Function} next Callback for next middleware in route
*/
export const getTipp = (req, res, next) => Tipp.findOne({
_id: req.params.id,
})
.then(data => res.json(data))
.catch(err => next(err));
| tuelsch/bolg | src/server/api/tipp-api.js | JavaScript | mit | 1,567 |
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using NJsonApi.Exceptions;
using NJsonApi.Serialization.Converters;
using NJsonApi.Utils;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace NJsonApi
{
public class Configuration : IConfiguration
{
private readonly Dictionary<string, IResourceMapping> resourcesMappingsByResourceType = new Dictionary<string, IResourceMapping>();
private readonly Dictionary<Type, IResourceMapping> resourcesMappingsByType = new Dictionary<Type, IResourceMapping>();
private readonly JsonSerializerSettings jsonSerializerSettings;
public Configuration()
{
jsonSerializerSettings = new JsonSerializerSettings();
jsonSerializerSettings.Converters.Add(new IsoDateTimeConverter());
jsonSerializerSettings.Converters.Add(new RelationshipDataConverter());
jsonSerializerSettings.Converters.Add(new StringEnumConverter() { CamelCaseText = true });
#if DEBUG
jsonSerializerSettings.Formatting = Formatting.Indented;
#endif
}
public string DefaultJsonApiMediaType => "application/vnd.api+json";
public void AddMapping(IResourceMapping resourceMapping)
{
resourcesMappingsByResourceType[resourceMapping.ResourceType] = resourceMapping;
resourcesMappingsByType[resourceMapping.ResourceRepresentationType] = resourceMapping;
}
public bool IsMappingRegistered(Type type)
{
if (typeof(IEnumerable).IsAssignableFrom(type) && type.GetTypeInfo().IsGenericType)
{
return resourcesMappingsByType.ContainsKey(type.GetGenericArguments()[0]);
}
return resourcesMappingsByType.ContainsKey(type);
}
public IResourceMapping GetMapping(Type type)
{
IResourceMapping mapping;
resourcesMappingsByType.TryGetValue(type, out mapping);
return mapping;
}
public IResourceMapping GetMapping(object objectGraph)
{
return GetMapping(Reflection.GetObjectType(objectGraph));
}
public bool ValidateIncludedRelationshipPaths(string[] includedPaths, object objectGraph)
{
var mapping = GetMapping(objectGraph);
if (mapping == null)
{
throw new MissingMappingException(Reflection.GetObjectType(objectGraph));
}
return mapping.ValidateIncludedRelationshipPaths(includedPaths);
}
public JsonSerializerSettings GetJsonSerializerSettings()
{
return jsonSerializerSettings;
}
public JsonSerializer GetJsonSerializer()
{
var jsonSerializer = JsonSerializer.Create(GetJsonSerializerSettings());
return jsonSerializer;
}
public bool ValidateAcceptHeader(string acceptsHeaders)
{
if (string.IsNullOrEmpty(acceptsHeaders))
{
return true;
}
return acceptsHeaders
.Split(',')
.Select(x => x.Trim())
.Any(x =>
x == "*/*" ||
x == DefaultJsonApiMediaType);
}
public string[] FindRelationshipPathsToInclude(string includeQueryParameter)
{
return string.IsNullOrEmpty(includeQueryParameter) ? new string[0] : includeQueryParameter.Split(',');
}
}
} | miclip/NJsonApiCore | src/NJsonApiCore/Configuration.cs | C# | mit | 3,581 |
# Marshmallow, the campfire chatbot
#
# You need to know one the following:
# (a) the secret public URL, or
# (b) an account/password for your room and the room number.
#
# Usage:
# to login with a password:
#
# bot = Marshmallow.new( :domain => 'mydomain', :ssl => true )
# bot.login :method => :login,
# :username => "yourbot@email.com",
# :password => "passw0rd",
# :room => "11234"
# bot.say("So many ponies in here! I want one!")
#
# to use the public url:
#
# Marshmallow.domain = 'mydomain'
# bot = Marshmallow.new
# bot.login( :url => 'aDxf3' )
# bot.say "Ponies!!"
# bot.paste "<script type='text/javascript'>\nalert('Ponies!')\n</script>"
#
class Marshmallow
require 'net/https'
require 'open-uri'
require 'cgi'
require 'yaml'
def self.version
"0.2"
end
attr_accessor :domain
def initialize(options={})
@debug = options[:debug]
@domain = options[:domain] || @@domain
@ssl = options[:ssl]
end
def login(options)
options = { :method => :url, :username => 'Marshmallow' }.merge(options)
@req = Net::HTTP::new("#{@domain}.campfirenow.com", @ssl ? 443 : 80)
@req.use_ssl = @ssl
# Gonna need a better cert to verify the Campfire cert with.
# if File.exist?('/usr/share/curl/curl-ca-bundle.crt')
# @req.verify_mode = OpenSSL::SSL::VERIFY_PEER
# @req.ca_file = '/usr/share/curl/curl-ca-bundle.crt'
# end
headers = { 'Content-Type' => 'application/x-www-form-urlencoded' }
case options[:method]
when :url
res = @req.post("/#{options[:url]}", "name=#{options[:username]}", headers)
# parse our response headers for the room number.. magic!
@room_id = res['location'].scan(/room\/(\d+)/).to_s
puts res.body if @debug
when :login
params = "email_address=#{CGI.escape(options[:username])}&password=#{CGI.escape(options[:password])}"
puts params if @debug
res = @req.post("/login/", params, headers)
@room_id = options[:room]
puts "Logging into room #{@room_id}" if @debug
puts res.body if @debug
end
@headers = { 'Cookie' => res.response['set-cookie'] }
res2 = @req.get(res['location'], @headers)
puts res2.body if @debug
# refresh our headers
@headers = { 'Cookie' => res.response['set-cookie'] }
@req.get("/room/#{@room_id}/") # join the room if necessary
return @headers
end
def paste(message)
say(message, true)
end
def say(message, paste=false)
puts "Posting #{message}" if @debug
res = @req.post("/room/#{@room_id}/speak", "#{'paste=true&' if paste}message=#{CGI.escape(message.to_s)}", @headers)
puts res.body if @debug
end
end | crowdvine/highrise_to_campfire | lib/marshmallow.rb | Ruby | mit | 2,759 |
/**
* Copyright (c) Acroquest Technology Co, Ltd. All Rights Reserved.
* Please read the associated COPYRIGHTS file for more details.
*
* THE SOFTWARE IS PROVIDED BY Acroquest Technolog Co., Ltd.,
* WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDER BE LIABLE FOR ANY
* CLAIM, DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING
* OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
*/
package acromusashi.stream.ml.clustering.kmeans.entity;
import java.io.Serializable;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
/**
* KMeansクラスタリングの学習モデルを保持するエンティティクラス
*
* @author kimura
*/
public class KmeansDataSet implements Serializable
{
/** シリアル */
private static final long serialVersionUID = 338231277453149972L;
/** 各クラスタの中心座標の行列を格納した配列 */
private double[][] centroids;
/** 各クラスタに分類された要素数 */
private long[] clusteredNum;
/**
* パラメータを指定せずにインスタンスを生成する。
*/
public KmeansDataSet()
{}
/**
* @return the centroids
*/
public double[][] getCentroids()
{
return this.centroids;
}
/**
* @param centroids the centroids to set
*/
public void setCentroids(double[][] centroids)
{
this.centroids = centroids;
}
/**
* @return the clusteredNum
*/
public long[] getClusteredNum()
{
return this.clusteredNum;
}
/**
* @param clusteredNum the clusteredNum to set
*/
public void setClusteredNum(long[] clusteredNum)
{
this.clusteredNum = clusteredNum;
}
/**
* {@inheritDoc}
*/
@Override
public String toString()
{
String result = ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
return result;
}
}
| acromusashi/acromusashi-stream-ml | src/main/java/acromusashi/stream/ml/clustering/kmeans/entity/KmeansDataSet.java | Java | mit | 2,184 |
package com.algolia.search.integration.async;
import com.algolia.search.AlgoliaObject;
import com.algolia.search.AsyncAlgoliaIntegrationTest;
import com.algolia.search.AsyncIndex;
import com.algolia.search.inputs.BatchOperation;
import com.algolia.search.inputs.batch.BatchDeleteIndexOperation;
import com.algolia.search.objects.Query;
import com.algolia.search.responses.SearchResult;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
abstract public class AsyncIndicesTest extends AsyncAlgoliaIntegrationTest {
private static List<String> indicesNames = Arrays.asList(
"index1",
"index2",
"index3",
"index4",
"index5",
"index6",
"index7"
);
@Before
@After
public void cleanUp() throws Exception {
List<BatchOperation> clean = indicesNames.stream().map(BatchDeleteIndexOperation::new).collect(Collectors.toList());
waitForCompletion(client.batch(clean));
}
@Test
public void getAllIndices() throws Exception {
assertThat(client.listIndices()).isNotNull();
AsyncIndex<AlgoliaObject> index = client.initIndex("index1", AlgoliaObject.class);
waitForCompletion(index.addObject(new AlgoliaObject("algolia", 4)));
futureAssertThat(client.listIndices()).extracting("name").contains("index1");
}
@Test
public void deleteIndex() throws Exception {
AsyncIndex<AlgoliaObject> index = client.initIndex("index2", AlgoliaObject.class);
waitForCompletion(index.addObject(new AlgoliaObject("algolia", 4)));
futureAssertThat(client.listIndices()).extracting("name").contains("index2");
waitForCompletion(index.delete());
futureAssertThat(client.listIndices()).extracting("name").doesNotContain("index2");
}
@Test
public void moveIndex() throws Exception {
AsyncIndex<AlgoliaObject> index = client.initIndex("index3", AlgoliaObject.class);
waitForCompletion(index.addObject(new AlgoliaObject("algolia", 4)));
futureAssertThat(client.listIndices()).extracting("name").contains("index3");
waitForCompletion(index.moveTo("index4"));
futureAssertThat(client.listIndices()).extracting("name").doesNotContain("index3").contains("index4");
}
@Test
public void copyIndex() throws Exception {
AsyncIndex<AlgoliaObject> index = client.initIndex("index5", AlgoliaObject.class);
waitForCompletion(index.addObject(new AlgoliaObject("algolia", 4)));
futureAssertThat(client.listIndices()).extracting("name").contains("index5");
waitForCompletion(index.copyTo("index6"));
futureAssertThat(client.listIndices()).extracting("name").contains("index5", "index6");
}
@Test
public void clearIndex() throws Exception {
AsyncIndex<AlgoliaObject> index = client.initIndex("index7", AlgoliaObject.class);
waitForCompletion(index.addObject(new AlgoliaObject("algolia", 4)));
waitForCompletion(index.clear());
SearchResult<AlgoliaObject> results = index.search(new Query("")).get();
assertThat(results.getHits()).isEmpty();
}
}
| algoliareadmebot/algoliasearch-client-java-2 | algoliasearch-common/src/test/java/com/algolia/search/integration/async/AsyncIndicesTest.java | Java | mit | 3,145 |
/**
* Django admin inlines
*
* Based on jQuery Formset 1.1
* @author Stanislaus Madueke (stan DOT madueke AT gmail DOT com)
* @requires jQuery 1.2.6 or later
*
* Copyright (c) 2009, Stanislaus Madueke
* All rights reserved.
*
* Spiced up with Code from Zain Memon's GSoC project 2009
* and modified for Django by Jannis Leidel, Travis Swicegood and Julien Phalip.
*
* Licensed under the New BSD License
* See: http://www.opensource.org/licenses/bsd-license.php
*/
(function($) {
$.fn.formset = function(opts) {
var options = $.extend({}, $.fn.formset.defaults, opts);
var $this = $(this);
var $parent = $this.parent();
var nextIndex = get_no_forms(options.prefix);
//store the options. This is needed for nested inlines, to recreate the same form
var group = $this.closest('.inline-group');
group.data('django_formset', options);
// Add form classes for dynamic behaviour
$this.each(function(i) {
$(this).not("." + options.emptyCssClass).addClass(options.formCssClass);
});
if (isAddButtonVisible(options)) {
var addButton;
if ($this.attr("tagName") == "TR") {
// If forms are laid out as table rows, insert the
// "add" button in a new table row:
var numCols = this.eq(-1).children().length;
$parent.append('<tr class="' + options.addCssClass + '"><td colspan="' + numCols + '"><a href="javascript:void(0)">' + options.addText + "</a></tr>");
addButton = $parent.find("tr:last a");
} else {
// Otherwise, insert it immediately after the last form:
$this.filter(":last").after('<div class="' + options.addCssClass + '"><a href="javascript:void(0)">' + options.addText + "</a></div>");
addButton = $this.filter(":last").next().find("a");
}
addButton.click(function(e) {
e.preventDefault();
addRow(options);
});
}
return this;
};
/* Setup plugin defaults */
$.fn.formset.defaults = {
prefix : "form", // The form prefix for your django formset
addText : "add another", // Text for the add link
deleteText : "remove", // Text for the delete link
addCssClass : "add-row", // CSS class applied to the add link
deleteCssClass : "delete-row", // CSS class applied to the delete link
emptyCssClass : "empty-row", // CSS class applied to the empty row
formCssClass : "dynamic-form", // CSS class applied to each form in a formset
added : null, // Function called each time a new form is added
removed : null // Function called each time a form is deleted
};
// Tabular inlines ---------------------------------------------------------
$.fn.tabularFormset = function(options) {
var $rows = $(this);
var alternatingRows = function(row) {
row_number = 0;
$($rows.selector).not(".add-row").removeClass("row1 row2").each(function() {
$(this).addClass('row' + ((row_number%2)+1));
next = $(this).next();
while (next.hasClass('nested-inline-row')) {
next.addClass('row' + ((row_number%2)+1));
next = next.next();
}
row_number = row_number + 1;
});
};
var reinitDateTimeShortCuts = function() {
// Reinitialize the calendar and clock widgets by force
if ( typeof DateTimeShortcuts != "undefined") {
$(".datetimeshortcuts").remove();
DateTimeShortcuts.init();
}
};
var updateSelectFilter = function() {
// If any SelectFilter widgets are a part of the new form,
// instantiate a new SelectFilter instance for it.
if ( typeof SelectFilter != 'undefined') {
$('.selectfilter').each(function(index, value) {
var namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length - 1], false, options.adminStaticPrefix);
});
$('.selectfilterstacked').each(function(index, value) {
var namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length - 1], true, options.adminStaticPrefix);
});
}
};
var initPrepopulatedFields = function(row) {
row.find('.prepopulated_field').each(function() {
var field = $(this), input = field.find('input, select, textarea'), dependency_list = input.data('dependency_list') || [], dependencies = [];
$.each(dependency_list, function(i, field_name) {
dependencies.push('#' + row.find('.field-' + field_name).find('input, select, textarea').attr('id'));
});
if (dependencies.length) {
input.prepopulate(dependencies, input.attr('maxlength'));
}
});
};
$rows.formset({
prefix : options.prefix,
addText : options.addText,
formCssClass : "dynamic-" + options.prefix,
deleteCssClass : "inline-deletelink",
deleteText : options.deleteText,
emptyCssClass : "empty-form",
removed : function(row) {
alternatingRows(row);
if(options.removed) options.removed(row);
},
added : function(row) {
initPrepopulatedFields(row);
reinitDateTimeShortCuts();
updateSelectFilter();
alternatingRows(row);
if(options.added) options.added(row);
}
});
return $rows;
};
// Stacked inlines ---------------------------------------------------------
$.fn.stackedFormset = function(options) {
var $rows = $(this);
var update_inline_labels = function(formset_to_update) {
formset_to_update.children('.inline-related').not('.empty-form').children('h3').find('.inline_label').each(function(i) {
var count = i + 1;
$(this).html($(this).html().replace(/(#\d+)/g, "#" + count));
});
};
var reinitDateTimeShortCuts = function() {
// Reinitialize the calendar and clock widgets by force, yuck.
if ( typeof DateTimeShortcuts != "undefined") {
$(".datetimeshortcuts").remove();
DateTimeShortcuts.init();
}
};
var updateSelectFilter = function() {
// If any SelectFilter widgets were added, instantiate a new instance.
if ( typeof SelectFilter != "undefined") {
$(".selectfilter").each(function(index, value) {
var namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length - 1], false, options.adminStaticPrefix);
});
$(".selectfilterstacked").each(function(index, value) {
var namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length - 1], true, options.adminStaticPrefix);
});
}
};
var initPrepopulatedFields = function(row) {
row.find('.prepopulated_field').each(function() {
var field = $(this), input = field.find('input, select, textarea'), dependency_list = input.data('dependency_list') || [], dependencies = [];
$.each(dependency_list, function(i, field_name) {
dependencies.push('#' + row.find('.form-row .field-' + field_name).find('input, select, textarea').attr('id'));
});
if (dependencies.length) {
input.prepopulate(dependencies, input.attr('maxlength'));
}
});
};
$rows.formset({
prefix : options.prefix,
addText : options.addText,
formCssClass : "dynamic-" + options.prefix,
deleteCssClass : "inline-deletelink",
deleteText : options.deleteText,
emptyCssClass : "empty-form",
removed : function(row) {
update_inline_labels(row);
if(options.removed) options.removed(row);
},
added : (function(row) {
initPrepopulatedFields(row);
reinitDateTimeShortCuts();
updateSelectFilter();
update_inline_labels(row.parent());
if(options.added) options.added(row);
})
});
return $rows;
};
function create_nested_formsets(parentPrefix, rowId) {
// we use the first formset as template. so replace every index by 0
var sourceParentPrefix = parentPrefix.replace(/[-][0-9][-]/g, "-0-");
var row_prefix = parentPrefix+'-'+rowId;
var row = $('#'+row_prefix);
// Check if the form should have nested formsets
// This is horribly hackish. It tries to collect one set of nested inlines from already existing rows and clone these
var search_space = $("#"+sourceParentPrefix+'-0').nextUntil("."+sourceParentPrefix + "-not-nested");
//all nested inlines
var nested_inlines = search_space.find("." + sourceParentPrefix + "-nested-inline");
nested_inlines.each(function(index) {
// prefixes for the nested formset
var normalized_formset_prefix = $(this).attr('id').split('-group')[0];
// = "parent_formset_prefix"-0-"nested_inline_name"_set
var formset_prefix = normalized_formset_prefix.replace(sourceParentPrefix + "-0", row_prefix);
// = "parent_formset_prefix"-"next_form_id"-"nested_inline_name"_set
// Find the normalized formset and clone it
var template = $(this).clone();
//get the options that were used to create the source formset
var options = $(this).data('django_formset');
//clone, so that we don't modify the old one
options = $.extend({}, options);
options.prefix = formset_prefix;
var isTabular = template.find('#'+normalized_formset_prefix+'-empty').is('tr');
//remove all existing rows from the clone
if (isTabular) {
//tabular
template.find(".form-row").not(".empty-form").remove();
template.find(".nested-inline-row").remove();
} else {
//stacked cleanup
template.find(".inline-related").not(".empty-form").remove();
}
//remove other unnecessary things
template.find('.'+options.addCssClass).remove();
//replace the cloned prefix with the new one
update_props(template, normalized_formset_prefix, formset_prefix);
//reset update formset management variables
template.find('#id_' + formset_prefix + '-INITIAL_FORMS').val(0);
template.find('#id_' + formset_prefix + '-TOTAL_FORMS').val(0);
//remove the fk and id values, because these don't exist yet
template.find('.original').empty();
//postprocess stacked/tabular
if (isTabular) {
var formset = template.find('.tabular.inline-related tbody tr.' + formset_prefix + '-not-nested').tabularFormset(options);
var border_class = (index+1 < nested_inlines.length) ? ' no-bottom-border' : '';
var wrapped = $('<tr class="nested-inline-row' + border_class + '"/>').html($('<td colspan="100%"/>').html(template));
//insert the formset after the row
row.after(wrapped);
} else {
var formset = template.find(".inline-related").stackedFormset(options);
row.after(template);
}
//add a empty row. This will in turn create the nested formsets
addRow(options);
});
return nested_inlines.length;
};
function update_props(template, normalized_formset_prefix, formset_prefix) {
// Fix template id
template.attr('id', template.attr('id').replace(normalized_formset_prefix, formset_prefix));
template.find('*').each(function() {
if ($(this).attr("for")) {
$(this).attr("for", $(this).attr("for").replace(normalized_formset_prefix, formset_prefix));
}
if ($(this).attr("class")) {
$(this).attr("class", $(this).attr("class").replace(normalized_formset_prefix, formset_prefix));
}
if (this.id) {
this.id = this.id.replace(normalized_formset_prefix, formset_prefix);
}
if (this.name) {
this.name = this.name.replace(normalized_formset_prefix, formset_prefix);
}
});
};
// This returns the amount of forms in the given formset
function get_no_forms(formset_prefix) {
formset_prop = $("#id_" + formset_prefix + "-TOTAL_FORMS")
if (!formset_prop.length) {
return 0;
}
return parseInt(formset_prop.attr("autocomplete", "off").val());
}
function change_no_forms(formset_prefix, increase) {
var no_forms = get_no_forms(formset_prefix);
if (increase) {
$("#id_" + formset_prefix + "-TOTAL_FORMS").attr("autocomplete", "off").val(parseInt(no_forms) + 1);
} else {
$("#id_" + formset_prefix + "-TOTAL_FORMS").attr("autocomplete", "off").val(parseInt(no_forms) - 1);
}
};
// This return the maximum amount of forms in the given formset
function get_max_forms(formset_prefix) {
var max_forms = $("#id_" + formset_prefix + "-MAX_NUM_FORMS").attr("autocomplete", "off").val();
if ( typeof max_forms == 'undefined' || max_forms == '') {
return '';
}
return parseInt(max_forms);
};
function addRow(options) {
var nextIndex = get_no_forms(options.prefix);
var row = insertNewRow(options.prefix, options);
updateAddButton(options.prefix);
// Add delete button handler
row.find("a." + options.deleteCssClass).click(function(e) {
e.preventDefault();
// Find the row that will be deleted by this button
var row = $(this).parents("." + options.formCssClass);
// Remove the parent form containing this button:
var formset_to_update = row.parent();
//remove nested inlines
while (row.next().hasClass('nested-inline-row')) {
row.next().remove();
}
row.remove();
change_no_forms(options.prefix, false);
// If a post-delete callback was provided, call it with the deleted form:
if (options.removed) {
options.removed(formset_to_update);
}
});
var num_formsets = create_nested_formsets(options.prefix, nextIndex);
if(row.is("tr") && num_formsets > 0) {
row.addClass("no-bottom-border");
}
// If a post-add callback was supplied, call it with the added form:
if (options.added) {
options.added(row);
}
nextIndex = nextIndex + 1;
};
function insertNewRow(prefix, options) {
var template = $("#" + prefix + "-empty");
var nextIndex = get_no_forms(prefix);
var row = prepareRowTemplate(template, prefix, nextIndex, options);
// when adding something from a cloned formset the id is the same
// Insert the new form when it has been fully edited
row.insertBefore($(template));
// Update number of total forms
change_no_forms(prefix, true);
return row;
};
function prepareRowTemplate(template, prefix, index, options) {
var row = template.clone(true);
row.removeClass(options.emptyCssClass).addClass(options.formCssClass).attr("id", prefix + "-" + index);
if (row.is("tr")) {
// If the forms are laid out in table rows, insert
// the remove button into the last table cell:
row.children(":last").append('<div><a class="' + options.deleteCssClass + '" href="javascript:void(0)">' + options.deleteText + "</a></div>");
} else if (row.is("ul") || row.is("ol")) {
// If they're laid out as an ordered/unordered list,
// insert an <li> after the last list item:
row.append('<li><a class="' + options.deleteCssClass + '" href="javascript:void(0)">' + options.deleteText + "</a></li>");
} else {
// Otherwise, just insert the remove button as the
// last child element of the form's container:
row.children(":first").append('<span><a class="' + options.deleteCssClass + '" href="javascript:void(0)">' + options.deleteText + "</a></span>");
}
row.find("*").each(function() {
updateElementIndex(this, prefix, index);
});
return row;
};
function updateElementIndex(el, prefix, ndx) {
var id_regex = new RegExp("(" + prefix + "-(\\d+|__prefix__))");
var replacement = prefix + "-" + ndx;
if ($(el).attr("for")) {
$(el).attr("for", $(el).attr("for").replace(id_regex, replacement));
}
if (el.id) {
el.id = el.id.replace(id_regex, replacement);
}
if (el.name) {
el.name = el.name.replace(id_regex, replacement);
}
};
/** show or hide the addButton **/
function updateAddButton(options) {
// Hide add button in case we've hit the max, except we want to add infinitely
var btn = $("#" + options.prefix + "-empty").parent().children('.'+options.addCssClass);
if (isAddButtonVisible(options)) {
btn.hide();
} else {
btn.show();
}
}
function isAddButtonVisible(options) {
return !(get_max_forms(options.prefix) !== '' && (get_max_forms(options.prefix) - get_no_forms(options.prefix)) <= 0);
}
})(django.jQuery);
// TODO:
// Remove border between tabular fieldset and nested inline
// Fix alternating rows
| pitcons/django-nested-inlines | nested_inlines/static/admin/js/inlines.js | JavaScript | mit | 15,670 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using Frameshop.Data;
namespace Frameshop
{
internal class Option : PList
{
public static readonly string PLUGIN_FOLDER = Path.GetDirectoryName(Application.ExecutablePath) + "\\plugin";
public static readonly string COMMAND_EXT = ".fsc";
public static readonly string CMD_ESC_FULL = "$FULL$";
public static readonly string CMD_ESC_PARENT = "$PARENT$";
public static readonly string CMD_ESC_FILE = "$FILE$";
public static readonly string CMD_ESC_EXT = "$EXT$";
public static string GetCommandFilePath(string name)
{
return PLUGIN_FOLDER + "\\" + name + COMMAND_EXT;
}
private string SettingsFilePath
{
get
{
return Path.GetDirectoryName(Application.ExecutablePath) + "\\options.plist";
}
}
private Option()
{
}
private static Option self = null;
public static Option GetInstance()
{
if (self == null)
self = new Option();
return self;
}
public void Init()
{
PList winProp = new PList();
this["win_prop"] = winProp;
winProp["max"] = true;
winProp["x"] = 20;
winProp["y"] = 10;
winProp["w"] = 800;
winProp["h"] = 600;
PList winAnim = new PList();
this["win_anim"] = winAnim;
winAnim["max"] = false;
winAnim["x"] = 50;
winAnim["y"] = 30;
winAnim["w"] = 640;
winAnim["h"] = 480;
PList fsc = new PList();
this["commands"] = fsc;
fsc["folder"] = string.Empty;
fsc["tex"] = string.Empty;
fsc["data"] = string.Empty;
fsc["anim"] = string.Empty;
fsc["call_anim_at_pub"] = true;
PList misc = new PList();
this["misc"] = misc;
misc["first_run"] = true;
misc["last_dir"] = Environment.CurrentDirectory;
misc["ask_before_rem_frame"] = true;
misc["add_folder_recursively"] = true;
}
public void Load()
{
if (File.Exists(SettingsFilePath))
Load(SettingsFilePath);
else
Init();
}
public void Save()
{
Save(SettingsFilePath);
}
}
}
| paladin-t/frameshop | Option.cs | C# | mit | 2,687 |
module Patterns
# Monster -> Object
#
# The monster class. It delegates its calls to the monster type class.
# This is an example of the Type Object pattern.
# This is also an example of the concept of Object Composition over inheritance. The monster HAS a type attribute instead of inheriting one.
# This allows us to decouple the monster from its type and stops inheritance from getting out of control in a system with many similar objects.
class Monster
# The MonsterType object of the Monster
attr_accessor :monster_type
# Initializes the monster class
#
# * +monster_type+ - The type of the monster that has a corresponding json file
#
# Examples
#
# => orc = Monster.new('orc')
def initialize(monster_type)
@monster_type = MonsterType.new(monster_type)
end
# Performs a deep clone of the Monster Object by utilizing the MonsterType object
#
# Examples
#
# => orc2 = orc.clone
def deep_clone
Monster.new(@monster_type)
end
# Delegates getting monster health to the monster_type
#
# Examples
#
# => orc.health
def health
@monster_type.health
end
# Delegates getting monster attack to the monster_type
#
# Examples
#
# => orc.attack
def attack
@monster_type.attack
end
# Delegates getting monster range to the monster_type
#
# Examples
#
# => orc.range
def range
@monster_type.range
end
# Delegates getting monster resistances to the monster_type
#
# Examples
#
# => orc.resistances
def resistances
@monster_type.resistances
end
# Delegates getting monster weaknesses to the monster_type
#
# Examples
#
# => orc.weaknesses
def weaknesses
@monster_type.weaknesses
end
# Gets this monster's prototype name if it has one and the string 'none' if it does not
#
# Examples
#
# => orc_wizard.prototype_name
def prototype_name
@monster_type.prototype_name
end
end
end | Alistanis/DesignPatterns | app/models/type_object/monster.rb | Ruby | mit | 2,094 |
/// <reference path="./interface.ts" />
/// <reference path="../canvas.ts" />
/// <reference path="../../../controller/controller.ts" />
module Prisc {
export class TrimTool implements Tool {
private start: ICoordinates;
private end: ICoordinates;
private lineWidth: number = 0.5;
private strokeStyle: string = '#AAA';
constructor(private canvas: Canvas) {}
onStart(ev) {
this.start = {
x: ev.offsetX,
y: ev.offsetY
};
}
onMove(ev) {
this.rollback();
this.end = {
x: ev.offsetX,
y: ev.offsetY
};
this.draw();
}
onFinish(ev) {
this.end = {
x: ev.offsetX,
y: ev.offsetY
};
this.rollback();
var imageURI = this.getTrimmedImageURI();
Controller.openCaptureViewByMessagingUrl(imageURI);
}
private rollback() {
this.canvas.__context.putImageData(
this.canvas.stashedImageData,0,0
);
}
private draw() {
// 切り取り描画のときだけ
this.canvas.__context.lineWidth = this.lineWidth;
this.canvas.__context.strokeStyle = this.strokeStyle;
this.canvas.__context.strokeRect(
this.start.x,
this.start.y,
this.end.x - this.start.x,
this.end.y - this.start.y
);
}
private getTrimmedImageURI(): string {
var partialData = this.canvas.__context.getImageData(
this.start.x,
this.start.y,
this.end.x - this.start.x,
this.end.y - this.start.y
);
// 一時的にキャンバスを作る
var _tmpCanvas = document.createElement('canvas');
_tmpCanvas.width = partialData.width;
_tmpCanvas.height = partialData.height;
var _tmpContext = _tmpCanvas.getContext('2d');
_tmpContext.putImageData(partialData, 0, 0);
// FIXME: とりあえずハード
var format = 'image/png';
var imageURI = _tmpCanvas.toDataURL(format);
return imageURI;
}
}
} | otiai10/prisc | src/model/canvas/tools/trim.ts | TypeScript | mit | 2,372 |
import React from 'react';
import { combineReducers } from 'redux';
import { connect } from 'react-redux';
// Count reducer
const count = (state = 10, action) => {
switch (action.type) {
case 'increment':
return state + 1;
case 'decrement':
return state -1;
default:
return state;
}
}
// The store reducer for our Counter component.
export const reducer = combineReducers({
count,
});
// A simple React component
class Counter extends React.Component {
render() {
return React.createElement(
'div',
null,
this.props.count,
React.createElement(
'button',
{ onClick: () => this.props.dispatch({ type: 'increment' }) },
'inc'
),
React.createElement(
'button',
{ onClick: () => this.props.dispatch({ type: 'decrement' }) },
'dec'
)
);
}
}
export default connect(state => ({...state}))(Counter);
| musawirali/preact-rpc | src/example/component.js | JavaScript | mit | 933 |
/*
* =============================================================
* elaostrap
*
* (c) 2015 Jeremy FAGIS <jeremy@fagis.fr>
* =============================================================
*/
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({"/Volumes/Elao/workspace/JeremyFagis/ElaoStrap/assets/js/vendors/html5shiv.js":[function(require,module,exports){
/**
* @preserve HTML5 Shiv 3.7.2 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
*/
;(function(window, document) {
/*jshint evil:true */
/** version */
var version = '3.7.2';
/** Preset options */
var options = window.html5 || {};
/** Used to skip problem elements */
var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i;
/** Not all elements can be cloned in IE **/
var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i;
/** Detect whether the browser supports default html5 styles */
var supportsHtml5Styles;
/** Name of the expando, to work with multiple documents or to re-shiv one document */
var expando = '_html5shiv';
/** The id for the the documents expando */
var expanID = 0;
/** Cached data for each document */
var expandoData = {};
/** Detect whether the browser supports unknown elements */
var supportsUnknownElements;
(function() {
try {
var a = document.createElement('a');
a.innerHTML = '<xyz></xyz>';
//if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles
supportsHtml5Styles = ('hidden' in a);
supportsUnknownElements = a.childNodes.length == 1 || (function() {
// assign a false positive if unable to shiv
(document.createElement)('a');
var frag = document.createDocumentFragment();
return (
typeof frag.cloneNode == 'undefined' ||
typeof frag.createDocumentFragment == 'undefined' ||
typeof frag.createElement == 'undefined'
);
}());
} catch(e) {
// assign a false positive if detection fails => unable to shiv
supportsHtml5Styles = true;
supportsUnknownElements = true;
}
}());
/*--------------------------------------------------------------------------*/
/**
* Creates a style sheet with the given CSS text and adds it to the document.
* @private
* @param {Document} ownerDocument The document.
* @param {String} cssText The CSS text.
* @returns {StyleSheet} The style element.
*/
function addStyleSheet(ownerDocument, cssText) {
var p = ownerDocument.createElement('p'),
parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement;
p.innerHTML = 'x<style>' + cssText + '</style>';
return parent.insertBefore(p.lastChild, parent.firstChild);
}
/**
* Returns the value of `html5.elements` as an array.
* @private
* @returns {Array} An array of shived element node names.
*/
function getElements() {
var elements = html5.elements;
return typeof elements == 'string' ? elements.split(' ') : elements;
}
/**
* Extends the built-in list of html5 elements
* @memberOf html5
* @param {String|Array} newElements whitespace separated list or array of new element names to shiv
* @param {Document} ownerDocument The context document.
*/
function addElements(newElements, ownerDocument) {
var elements = html5.elements;
if(typeof elements != 'string'){
elements = elements.join(' ');
}
if(typeof newElements != 'string'){
newElements = newElements.join(' ');
}
html5.elements = elements +' '+ newElements;
shivDocument(ownerDocument);
}
/**
* Returns the data associated to the given document
* @private
* @param {Document} ownerDocument The document.
* @returns {Object} An object of data.
*/
function getExpandoData(ownerDocument) {
var data = expandoData[ownerDocument[expando]];
if (!data) {
data = {};
expanID++;
ownerDocument[expando] = expanID;
expandoData[expanID] = data;
}
return data;
}
/**
* returns a shived element for the given nodeName and document
* @memberOf html5
* @param {String} nodeName name of the element
* @param {Document} ownerDocument The context document.
* @returns {Object} The shived element.
*/
function createElement(nodeName, ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createElement(nodeName);
}
if (!data) {
data = getExpandoData(ownerDocument);
}
var node;
if (data.cache[nodeName]) {
node = data.cache[nodeName].cloneNode();
} else if (saveClones.test(nodeName)) {
node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode();
} else {
node = data.createElem(nodeName);
}
// Avoid adding some elements to fragments in IE < 9 because
// * Attributes like `name` or `type` cannot be set/changed once an element
// is inserted into a document/fragment
// * Link elements with `src` attributes that are inaccessible, as with
// a 403 response, will cause the tab/window to crash
// * Script elements appended to fragments will execute when their `src`
// or `text` property is set
return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node;
}
/**
* returns a shived DocumentFragment for the given document
* @memberOf html5
* @param {Document} ownerDocument The context document.
* @returns {Object} The shived DocumentFragment.
*/
function createDocumentFragment(ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createDocumentFragment();
}
data = data || getExpandoData(ownerDocument);
var clone = data.frag.cloneNode(),
i = 0,
elems = getElements(),
l = elems.length;
for(;i<l;i++){
clone.createElement(elems[i]);
}
return clone;
}
/**
* Shivs the `createElement` and `createDocumentFragment` methods of the document.
* @private
* @param {Document|DocumentFragment} ownerDocument The document.
* @param {Object} data of the document.
*/
function shivMethods(ownerDocument, data) {
if (!data.cache) {
data.cache = {};
data.createElem = ownerDocument.createElement;
data.createFrag = ownerDocument.createDocumentFragment;
data.frag = data.createFrag();
}
ownerDocument.createElement = function(nodeName) {
//abort shiv
if (!html5.shivMethods) {
return data.createElem(nodeName);
}
return createElement(nodeName, ownerDocument, data);
};
ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' +
'var n=f.cloneNode(),c=n.createElement;' +
'h.shivMethods&&(' +
// unroll the `createElement` calls
getElements().join().replace(/[\w\-:]+/g, function(nodeName) {
data.createElem(nodeName);
data.frag.createElement(nodeName);
return 'c("' + nodeName + '")';
}) +
');return n}'
)(html5, data.frag);
}
/*--------------------------------------------------------------------------*/
/**
* Shivs the given document.
* @memberOf html5
* @param {Document} ownerDocument The document to shiv.
* @returns {Document} The shived document.
*/
function shivDocument(ownerDocument) {
if (!ownerDocument) {
ownerDocument = document;
}
var data = getExpandoData(ownerDocument);
if (html5.shivCSS && !supportsHtml5Styles && !data.hasCSS) {
data.hasCSS = !!addStyleSheet(ownerDocument,
// corrects block display not defined in IE6/7/8/9
'article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}' +
// adds styling not present in IE6/7/8/9
'mark{background:#FF0;color:#000}' +
// hides non-rendered elements
'template{display:none}'
);
}
if (!supportsUnknownElements) {
shivMethods(ownerDocument, data);
}
return ownerDocument;
}
/*--------------------------------------------------------------------------*/
/**
* The `html5` object is exposed so that more elements can be shived and
* existing shiving can be detected on iframes.
* @type Object
* @example
*
* // options can be changed before the script is included
* html5 = { 'elements': 'mark section', 'shivCSS': false, 'shivMethods': false };
*/
var html5 = {
/**
* An array or space separated string of node names of the elements to shiv.
* @memberOf html5
* @type Array|String
*/
'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video',
/**
* current version of html5shiv
*/
'version': version,
/**
* A flag to indicate that the HTML5 style sheet should be inserted.
* @memberOf html5
* @type Boolean
*/
'shivCSS': (options.shivCSS !== false),
/**
* Is equal to true if a browser supports creating unknown/HTML5 elements
* @memberOf html5
* @type boolean
*/
'supportsUnknownElements': supportsUnknownElements,
/**
* A flag to indicate that the document's `createElement` and `createDocumentFragment`
* methods should be overwritten.
* @memberOf html5
* @type Boolean
*/
'shivMethods': (options.shivMethods !== false),
/**
* A string to describe the type of `html5` object ("default" or "default print").
* @memberOf html5
* @type String
*/
'type': 'default',
// shivs the document according to the specified `html5` object options
'shivDocument': shivDocument,
//creates a shived element
createElement: createElement,
//creates a shived documentFragment
createDocumentFragment: createDocumentFragment,
//extends list of elements
addElements: addElements
};
/*--------------------------------------------------------------------------*/
// expose html5
window.html5 = html5;
// shiv the document
shivDocument(document);
}(this, document));
},{}]},{},["/Volumes/Elao/workspace/JeremyFagis/ElaoStrap/assets/js/vendors/html5shiv.js"]) | JeremyFagis/ElaoStrap | dist/js/vendors/html5shiv.js | JavaScript | mit | 11,002 |
'use strict';
/**
* Module dependencies.
*/
var debug = require('debug')('swara:config'),
path = require('path'),
_ = require('lodash'),
glob = require('glob');
/**
* Load app configurations
*/
module.exports = _.extend(
require('./env/all'),
require('./env/' + process.env.NODE_ENV) || {}
);
/**
* Get files by glob patterns
*/
module.exports.getGlobbedFiles = function (globPatterns, removeRoot) {
// For context switching
var _this = this;
// URL paths regex
var urlRegex = new RegExp('^(?:[a-z]+:)?\/\/', 'i');
// The output array
var output = [];
// If glob pattern is array so we use each pattern in a recursive way, otherwise we use glob
if (_.isArray(globPatterns)) {
globPatterns.forEach(function (globPattern) {
output = _.union(output, _this.getGlobbedFiles(globPattern, removeRoot));
});
} else if (_.isString(globPatterns)) {
if (urlRegex.test(globPatterns)) {
output.push(globPatterns);
} else {
var publicRE = /^public\//;
if (publicRE.test(globPatterns)) {
globPatterns = __dirname + '/../' + globPatterns;
var newRoot = __dirname + '/../' + removeRoot;
removeRoot = path.normalize(newRoot);
}
var files = glob.sync(globPatterns);
if (removeRoot) {
files = files.map(function (file) {
return file.replace(removeRoot, '');
});
}
output = _.union(output, files);
}
}
debug('Returning with output: %j', output);
return output;
};
/**
* Get the modules JavaScript files
*/
module.exports.getJavaScriptAssets = function (includeTests) {
var output = this.getGlobbedFiles(this.assets.lib.js.concat(this.assets.js), 'public/');
// To include tests
if (includeTests) {
output = _.union(output, this.getGlobbedFiles(this.assets.tests));
}
debug('getJavaScriptAssets returning with: %j', output);
return output;
};
/**
* Get the modules CSS files
*/
module.exports.getCSSAssets = function () {
var output = this.getGlobbedFiles(this.assets.lib.css.concat(this.assets.css), 'public/');
debug('getCSSAssets returning with: %j', output);
return output;
};
| swara-app/swara-server | mean-app/config/config.js | JavaScript | mit | 2,168 |
using System;
using System.Collections.Generic;
namespace ServiceBelt
{
public class ListResponse<T>
{
public int Count { get; set; }
public int Offset { get; set; }
public int Limit { get; set; }
public string DbQuery { get; set; }
public List<T> Items { get; set; }
}
}
| jlyonsmith/ToolBelt | ServiceBelt/Models/Service/ListResponse.cs | C# | mit | 329 |
export { default } from "./Paragraph";
| ceramic-ui/ceramic-ui | packages/web/src/Paragraph/index.js | JavaScript | mit | 39 |
/**
* The MIT License (MIT)
*
* adapted from musicdsp.org-post by mistert@inwind.it
*
* Copyright (c) 2013-2017 Igor Zinken - http://www.igorski.nl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "lpfhpfilter.h"
#include "../global.h"
#include <math.h>
namespace MWEngine {
// constructor
LPFHPFilter::LPFHPFilter( float aLPCutoff, float aHPCutoff, int amountOfChannels )
{
setLPF( aLPCutoff, AudioEngineProps::SAMPLE_RATE );
setHPF( aHPCutoff, AudioEngineProps::SAMPLE_RATE );
outSamples = new SAMPLE_TYPE[ amountOfChannels ];
inSamples = new SAMPLE_TYPE[ amountOfChannels ];
for ( int i = 0; i < amountOfChannels; ++i )
{
outSamples[ i ] = 0.0;
inSamples[ i ] = 0.0;
}
}
LPFHPFilter::~LPFHPFilter()
{
delete[] outSamples;
delete[] inSamples;
}
/* public methods */
void LPFHPFilter::setLPF( float aCutOffFrequency, int aSampleRate )
{
SAMPLE_TYPE w = 2.0 * aSampleRate;
SAMPLE_TYPE Norm;
aCutOffFrequency *= TWO_PI;
Norm = 1.0 / ( aCutOffFrequency + w );
b1 = ( w - aCutOffFrequency ) * Norm;
a0 = a1 = aCutOffFrequency * Norm;
}
void LPFHPFilter::setHPF( float aCutOffFrequency, int aSampleRate )
{
SAMPLE_TYPE w = 2.0 * aSampleRate;
SAMPLE_TYPE Norm;
aCutOffFrequency *= TWO_PI;
Norm = 1.0 / ( aCutOffFrequency + w );
a0 = w * Norm;
a1 = -a0;
b1 = ( w - aCutOffFrequency ) * Norm;
}
void LPFHPFilter::process( AudioBuffer* sampleBuffer, bool isMonoSource )
{
int bufferSize = sampleBuffer->bufferSize;
for ( int c = 0, ca = sampleBuffer->amountOfChannels; c < ca; ++c )
{
SAMPLE_TYPE* channelBuffer = sampleBuffer->getBufferForChannel( c );
for ( int i = 0; i < bufferSize; ++i )
{
SAMPLE_TYPE sample = channelBuffer[ i ];
channelBuffer[ i ] = sample * a0 + inSamples[ c ] * a1 + outSamples[ c ] * b1;
inSamples[ c ] = sample; // store this unprocessed sample for next iteration
outSamples[ c ] = channelBuffer[ i ]; // and the processed sample too
}
// save CPU cycles when source is mono
if ( isMonoSource )
{
sampleBuffer->applyMonoSource();
break;
}
}
}
} // E.O namespace MWEngine
| igorski/MWEngine | mwengine/src/main/cpp/processors/lpfhpfilter.cpp | C++ | mit | 3,415 |
import { List, Set, fromJS, OrderedMap } from 'immutable';
import { get, escapeRegExp } from 'lodash';
import { stringTemplate } from 'netlify-cms-lib-widgets';
import consoleError from '../lib/consoleError';
import { CONFIG_SUCCESS } from '../actions/config';
import { FILES, FOLDER } from '../constants/collectionTypes';
import { COMMIT_DATE, COMMIT_AUTHOR } from '../constants/commitProps';
import { INFERABLE_FIELDS, IDENTIFIER_FIELDS, SORTABLE_FIELDS } from '../constants/fieldInference';
import { formatExtensions } from '../formats/formats';
import { selectMediaFolder } from './entries';
import { summaryFormatter } from '../lib/formatters';
import type {
Collection,
Collections,
CollectionFiles,
EntryField,
EntryMap,
ViewFilter,
ViewGroup,
CmsConfig,
} from '../types/redux';
import type { ConfigAction } from '../actions/config';
import type { Backend } from '../backend';
const { keyToPathArray } = stringTemplate;
const defaultState: Collections = fromJS({});
function collections(state = defaultState, action: ConfigAction) {
switch (action.type) {
case CONFIG_SUCCESS: {
const collections = action.payload.collections;
let newState = OrderedMap({});
collections.forEach(collection => {
newState = newState.set(collection.name, fromJS(collection));
});
return newState;
}
default:
return state;
}
}
const selectors = {
[FOLDER]: {
entryExtension(collection: Collection) {
return (
collection.get('extension') ||
get(formatExtensions, collection.get('format') || 'frontmatter')
).replace(/^\./, '');
},
fields(collection: Collection) {
return collection.get('fields');
},
entryPath(collection: Collection, slug: string) {
const folder = (collection.get('folder') as string).replace(/\/$/, '');
return `${folder}/${slug}.${this.entryExtension(collection)}`;
},
entrySlug(collection: Collection, path: string) {
const folder = (collection.get('folder') as string).replace(/\/$/, '');
const slug = path
.split(folder + '/')
.pop()
?.replace(new RegExp(`\\.${escapeRegExp(this.entryExtension(collection))}$`), '');
return slug;
},
allowNewEntries(collection: Collection) {
return collection.get('create');
},
allowDeletion(collection: Collection) {
return collection.get('delete', true);
},
templateName(collection: Collection) {
return collection.get('name');
},
},
[FILES]: {
fileForEntry(collection: Collection, slug: string) {
const files = collection.get('files');
return files && files.filter(f => f?.get('name') === slug).get(0);
},
fields(collection: Collection, slug: string) {
const file = this.fileForEntry(collection, slug);
return file && file.get('fields');
},
entryPath(collection: Collection, slug: string) {
const file = this.fileForEntry(collection, slug);
return file && file.get('file');
},
entrySlug(collection: Collection, path: string) {
const file = (collection.get('files') as CollectionFiles)
.filter(f => f?.get('file') === path)
.get(0);
return file && file.get('name');
},
entryLabel(collection: Collection, slug: string) {
const file = this.fileForEntry(collection, slug);
return file && file.get('label');
},
allowNewEntries() {
return false;
},
allowDeletion(collection: Collection) {
return collection.get('delete', false);
},
templateName(_collection: Collection, slug: string) {
return slug;
},
},
};
function getFieldsWithMediaFolders(fields: EntryField[]) {
const fieldsWithMediaFolders = fields.reduce((acc, f) => {
if (f.has('media_folder')) {
acc = [...acc, f];
}
if (f.has('fields')) {
const fields = f.get('fields')?.toArray() as EntryField[];
acc = [...acc, ...getFieldsWithMediaFolders(fields)];
} else if (f.has('field')) {
const field = f.get('field') as EntryField;
acc = [...acc, ...getFieldsWithMediaFolders([field])];
} else if (f.has('types')) {
const types = f.get('types')?.toArray() as EntryField[];
acc = [...acc, ...getFieldsWithMediaFolders(types)];
}
return acc;
}, [] as EntryField[]);
return fieldsWithMediaFolders;
}
export function getFileFromSlug(collection: Collection, slug: string) {
return collection
.get('files')
?.toArray()
.find(f => f.get('name') === slug);
}
export function selectFieldsWithMediaFolders(collection: Collection, slug: string) {
if (collection.has('folder')) {
const fields = collection.get('fields').toArray();
return getFieldsWithMediaFolders(fields);
} else if (collection.has('files')) {
const fields = getFileFromSlug(collection, slug)?.get('fields').toArray() || [];
return getFieldsWithMediaFolders(fields);
}
return [];
}
export function selectMediaFolders(config: CmsConfig, collection: Collection, entry: EntryMap) {
const fields = selectFieldsWithMediaFolders(collection, entry.get('slug'));
const folders = fields.map(f => selectMediaFolder(config, collection, entry, f));
if (collection.has('files')) {
const file = getFileFromSlug(collection, entry.get('slug'));
if (file) {
folders.unshift(selectMediaFolder(config, collection, entry, undefined));
}
}
if (collection.has('media_folder')) {
// stop evaluating media folders at collection level
collection = collection.delete('files');
folders.unshift(selectMediaFolder(config, collection, entry, undefined));
}
return Set(folders).toArray();
}
export function selectFields(collection: Collection, slug: string) {
return selectors[collection.get('type')].fields(collection, slug);
}
export function selectFolderEntryExtension(collection: Collection) {
return selectors[FOLDER].entryExtension(collection);
}
export function selectFileEntryLabel(collection: Collection, slug: string) {
return selectors[FILES].entryLabel(collection, slug);
}
export function selectEntryPath(collection: Collection, slug: string) {
return selectors[collection.get('type')].entryPath(collection, slug);
}
export function selectEntrySlug(collection: Collection, path: string) {
return selectors[collection.get('type')].entrySlug(collection, path);
}
export function selectAllowNewEntries(collection: Collection) {
return selectors[collection.get('type')].allowNewEntries(collection);
}
export function selectAllowDeletion(collection: Collection) {
return selectors[collection.get('type')].allowDeletion(collection);
}
export function selectTemplateName(collection: Collection, slug: string) {
return selectors[collection.get('type')].templateName(collection, slug);
}
export function getFieldsNames(fields: EntryField[], prefix = '') {
let names = fields.map(f => `${prefix}${f.get('name')}`);
fields.forEach((f, index) => {
if (f.has('fields')) {
const fields = f.get('fields')?.toArray() as EntryField[];
names = [...names, ...getFieldsNames(fields, `${names[index]}.`)];
} else if (f.has('field')) {
const field = f.get('field') as EntryField;
names = [...names, ...getFieldsNames([field], `${names[index]}.`)];
} else if (f.has('types')) {
const types = f.get('types')?.toArray() as EntryField[];
names = [...names, ...getFieldsNames(types, `${names[index]}.`)];
}
});
return names;
}
export function selectField(collection: Collection, key: string) {
const array = keyToPathArray(key);
let name: string | undefined;
let field;
let fields = collection.get('fields', List<EntryField>()).toArray();
while ((name = array.shift()) && fields) {
field = fields.find(f => f.get('name') === name);
if (field?.has('fields')) {
fields = field?.get('fields')?.toArray() as EntryField[];
} else if (field?.has('field')) {
fields = [field?.get('field') as EntryField];
} else if (field?.has('types')) {
fields = field?.get('types')?.toArray() as EntryField[];
}
}
return field;
}
export function traverseFields(
fields: List<EntryField>,
updater: (field: EntryField) => EntryField,
done = () => false,
) {
if (done()) {
return fields;
}
fields = fields
.map(f => {
const field = updater(f as EntryField);
if (done()) {
return field;
} else if (field.has('fields')) {
return field.set('fields', traverseFields(field.get('fields')!, updater, done));
} else if (field.has('field')) {
return field.set(
'field',
traverseFields(List([field.get('field')!]), updater, done).get(0),
);
} else if (field.has('types')) {
return field.set('types', traverseFields(field.get('types')!, updater, done));
} else {
return field;
}
})
.toList() as List<EntryField>;
return fields;
}
export function updateFieldByKey(
collection: Collection,
key: string,
updater: (field: EntryField) => EntryField,
) {
const selected = selectField(collection, key);
if (!selected) {
return collection;
}
let updated = false;
function updateAndBreak(f: EntryField) {
const field = f as EntryField;
if (field === selected) {
updated = true;
return updater(field);
} else {
return field;
}
}
collection = collection.set(
'fields',
traverseFields(collection.get('fields', List<EntryField>()), updateAndBreak, () => updated),
);
return collection;
}
export function selectIdentifier(collection: Collection) {
const identifier = collection.get('identifier_field');
const identifierFields = identifier ? [identifier, ...IDENTIFIER_FIELDS] : [...IDENTIFIER_FIELDS];
const fieldNames = getFieldsNames(collection.get('fields', List()).toArray());
return identifierFields.find(id =>
fieldNames.find(name => name.toLowerCase().trim() === id.toLowerCase().trim()),
);
}
export function selectInferedField(collection: Collection, fieldName: string) {
if (fieldName === 'title' && collection.get('identifier_field')) {
return selectIdentifier(collection);
}
const inferableField = (
INFERABLE_FIELDS as Record<
string,
{
type: string;
synonyms: string[];
secondaryTypes: string[];
fallbackToFirstField: boolean;
showError: boolean;
}
>
)[fieldName];
const fields = collection.get('fields');
let field;
// If collection has no fields or fieldName is not defined within inferables list, return null
if (!fields || !inferableField) return null;
// Try to return a field of the specified type with one of the synonyms
const mainTypeFields = fields
.filter(f => f?.get('widget', 'string') === inferableField.type)
.map(f => f?.get('name'));
field = mainTypeFields.filter(f => inferableField.synonyms.indexOf(f as string) !== -1);
if (field && field.size > 0) return field.first();
// Try to return a field for each of the specified secondary types
const secondaryTypeFields = fields
.filter(f => inferableField.secondaryTypes.indexOf(f?.get('widget', 'string') as string) !== -1)
.map(f => f?.get('name'));
field = secondaryTypeFields.filter(f => inferableField.synonyms.indexOf(f as string) !== -1);
if (field && field.size > 0) return field.first();
// Try to return the first field of the specified type
if (inferableField.fallbackToFirstField && mainTypeFields.size > 0) return mainTypeFields.first();
// Coundn't infer the field. Show error and return null.
if (inferableField.showError) {
consoleError(
`The Field ${fieldName} is missing for the collection “${collection.get('name')}”`,
`Netlify CMS tries to infer the entry ${fieldName} automatically, but one couldn't be found for entries of the collection “${collection.get(
'name',
)}”. Please check your site configuration.`,
);
}
return null;
}
export function selectEntryCollectionTitle(collection: Collection, entry: EntryMap) {
// prefer formatted summary over everything else
const summaryTemplate = collection.get('summary');
if (summaryTemplate) return summaryFormatter(summaryTemplate, entry, collection);
// if the collection is a file collection return the label of the entry
if (collection.get('type') == FILES) {
const label = selectFileEntryLabel(collection, entry.get('slug'));
if (label) return label;
}
// try to infer a title field from the entry data
const entryData = entry.get('data');
const titleField = selectInferedField(collection, 'title');
const result = titleField && entryData.getIn(keyToPathArray(titleField));
// if the custom field does not yield a result, fallback to 'title'
if (!result && titleField !== 'title') {
return entryData.getIn(keyToPathArray('title'));
}
return result;
}
export function selectDefaultSortableFields(
collection: Collection,
backend: Backend,
hasIntegration: boolean,
) {
let defaultSortable = SORTABLE_FIELDS.map((type: string) => {
const field = selectInferedField(collection, type);
if (backend.isGitBackend() && type === 'author' && !field && !hasIntegration) {
// default to commit author if not author field is found
return COMMIT_AUTHOR;
}
return field;
}).filter(Boolean);
if (backend.isGitBackend() && !hasIntegration) {
// always have commit date by default
defaultSortable = [COMMIT_DATE, ...defaultSortable];
}
return defaultSortable as string[];
}
export function selectSortableFields(collection: Collection, t: (key: string) => string) {
const fields = collection
.get('sortable_fields')
.toArray()
.map(key => {
if (key === COMMIT_DATE) {
return { key, field: { name: key, label: t('collection.defaultFields.updatedOn.label') } };
}
const field = selectField(collection, key);
if (key === COMMIT_AUTHOR && !field) {
return { key, field: { name: key, label: t('collection.defaultFields.author.label') } };
}
return { key, field: field?.toJS() };
})
.filter(item => !!item.field)
.map(item => ({ ...item.field, key: item.key }));
return fields;
}
export function selectSortDataPath(collection: Collection, key: string) {
if (key === COMMIT_DATE) {
return 'updatedOn';
} else if (key === COMMIT_AUTHOR && !selectField(collection, key)) {
return 'author';
} else {
return `data.${key}`;
}
}
export function selectViewFilters(collection: Collection) {
const viewFilters = collection.get('view_filters').toJS() as ViewFilter[];
return viewFilters;
}
export function selectViewGroups(collection: Collection) {
const viewGroups = collection.get('view_groups').toJS() as ViewGroup[];
return viewGroups;
}
export function selectFieldsComments(collection: Collection, entryMap: EntryMap) {
let fields: EntryField[] = [];
if (collection.has('folder')) {
fields = collection.get('fields').toArray();
} else if (collection.has('files')) {
const file = collection.get('files')!.find(f => f?.get('name') === entryMap.get('slug'));
fields = file.get('fields').toArray();
}
const comments: Record<string, string> = {};
const names = getFieldsNames(fields);
names.forEach(name => {
const field = selectField(collection, name);
if (field?.has('comment')) {
comments[name] = field.get('comment')!;
}
});
return comments;
}
export function selectHasMetaPath(collection: Collection) {
return (
collection.has('folder') &&
collection.get('type') === FOLDER &&
collection.has('meta') &&
collection.get('meta')?.has('path')
);
}
export default collections;
| netlify/netlify-cms | packages/netlify-cms-core/src/reducers/collections.ts | TypeScript | mit | 15,760 |
using System;
using BrightData;
namespace BrightWire.ExecutionGraph.Node.Gate
{
/// <summary>
/// Outputs the two input signals added together
/// </summary>
internal class AddGate : BinaryGateBase
{
public AddGate(string? name = null) : base(name) { }
protected override (IFloatMatrix Next, Func<IBackpropagate>? BackProp) Activate(IGraphSequenceContext context, IFloatMatrix primary, IFloatMatrix secondary, NodeBase primarySource, NodeBase secondarySource)
{
var output = primary.Add(secondary);
// default backpropagation behaviour is to pass the error signal to all ancestors, which is correct for addition
return (output, null);
}
}
}
| jdermody/brightwire | BrightWire/ExecutionGraph/Node/Gate/AddGate.cs | C# | mit | 739 |
'use strict';
angular.module('dashboardApp')
.controller('RentsCtrl', function ($scope, Rents, $location, $routeParams, Auth, rents) {
$scope.rents = rents;
$scope.returnBook = function(rent){
Rents.returnBook({'rentId': rent.rentId}, function(res){
console.log(res);
rent.status = res.status;
rent.rent.returnDate = res.rent.returnDate;
});
};
$scope.getStyle = function(rent){
if (rent.rent && (new Date(rent.rent.endDate) < new Date() && !rent.rent.returnDate)) {
return 'warning';
}
};
$scope.query = function(){
if (!$scope.mayQuery) {
return false;
}
var query = {page: $scope.page + 1};
query = angular.extend(query, $routeParams, {user: Auth.getUser().userId});
console.log(query);
Rents.query(query,
function(rents){
if (!rents.length) {
$scope.mayQuery = false;
}
$scope.rents = $scope.rents.concat(rents);
$scope.page += 1;
},
function(error){
});
};
$scope.page = 1;
$scope.mayQuery = true;
});
| OZ-United/united-library | dashboard/app/scripts/controllers/rents.js | JavaScript | mit | 1,066 |
<?php
if (!is_null($this->session->userdata('quiz_bg_img'))) { ?>
<style type="text/css">
body {
background-image: url("<?php echo base_url()."/public/img/".$this->session->userdata('quiz_bg_img'); ?>");
background-size: cover;
}
</style>
<img src="<?php echo base_url()."/public/img/logo.png"; ?>" class="img-responsive" id="logo">
<?php } ?>
<div class="container">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<h4 class="starter-template">
Ciena Presents
</h4>
<p class="text-center h1">
<?php echo urldecode($this->session->userdata('quiz_name')); ?>
</p>
</div>
</div>
<div class="row" style="padding-top: 5%">
<div class="col-md-12 text-center">
<?php echo anchor('/Quiz/take_quiz/'.$this->session->userdata('quiz_id'), 'Begin Quiz', array('title' => $this->session->userdata('quiz_name'), 'class' => 'btn btn-ciena-yes btn-lg ')); ?>
<h4>Do not use the back arrow button during the quiz</h4>
</div>
</div>
</div>
</div> | Jonyorker/ciena-quiz | application/views/quiz_splash_view.php | PHP | mit | 1,078 |
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
import * as Rules from './validation_rules';
import { find, partial, uniqBy } from 'lodash';
/**
* Creates a validator instance
*
* @param {array} rules
* @param {object} redux
* @param {object} validations
*
* @example
* let valid = new validator([{
* label: 'email ',
* rules: [{
* rule: 'required',
* message: 'Email address required'
* }]
* }]);
*
* @example with redux binding
* let valid = new validator([{
* label: 'email ',
* rules: [{
* rule: 'required',
* message: 'Email address required'
* }, {
* rule: action1,
* message: 'Some message'
* }]
* }], {
* store: store,
* actions: {
* action1: () => { ... },
* action2: () => { ... }
* }
* });
*
* @example with custom validations
* let valid = new validator([{
* label: 'email ',
* rules: [{
* rule: 'required',
* message: 'Email address required'
* }, {
* label: 'specialString',
* rule: [{
* rule: 'containsSomeWord',
* args: 'foo',
* message: 'This value must have the word "foo"'
* }]
* }]
* }], null, {
* containsSomeWord: (val, word) => val.indexOf(word) > -1
* });
*/
var validator = function () {
function validator(rules, redux, validations, value) {
_classCallCheck(this, validator);
this._rules = rules;
this._val = value ? value : '';
this._redux = redux;
this._validations = validations || {};
this._reduxRules = [];
this._errors = [];
}
validator.prototype.checkRules = function checkRules() {
var _this = this;
var optional = false;
this._errors = this._rules.filter(function (r) {
if (r.rule === 'optional' && _this._val === '') optional = true;
return _this.isRuleValid(r.rule);
});
// only run redux async rules if all synchronous rules have passed
// currently not logging synchronous errors for redux callbacks, use store state
this._reduxRules = uniqBy(this._reduxRules, 'rule');
if (this._reduxRules.length > 0 && this._errors.length < 1) {
this._reduxRules.forEach(function (r) {
return r.promise = _this._redux.store.dispatch(_this._redux.actions[r.rule](_this._val));
});
}
// check for optional override
if (optional) this._errors = [];
};
validator.prototype.hasArgs = function hasArgs(rule) {
return find(this._rules, function (r) {
return r.rule === rule && r.args;
});
};
validator.prototype.isRuleValid = function isRuleValid(rule) {
if (rule && (this._validations[rule] || Rules[rule])) {
var ruleToEval = Rules[rule] || this._validations[rule];
var hasArgs = this.hasArgs(rule);
var method = partial(ruleToEval, this._val);
return hasArgs ? !method(hasArgs.args) : !method();
} else if (rule && this._redux.actions[rule]) {
this._reduxRules.push({ rule: rule, promise: Promise.resolve() });
}
};
validator.prototype.reset = function reset() {
this._errors = [];
};
_createClass(validator, [{
key: 'val',
set: function set(val) {
this._val = val;
},
get: function get() {
return this._val;
}
}, {
key: 'errors',
get: function get() {
return this._errors;
}
}]);
return validator;
}();
export { validator as default }; | localvore-today/react-validator | es/validator.js | JavaScript | mit | 4,107 |
<?php
declare(strict_types=1);
/**
* PlumSearch plugin for CakePHP Rapid Development Framework
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @author Evgeny Tomenko
* @since PlumSearch 0.1
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace PlumSearch\Test\App\Model\Table;
use Cake\ORM\Query;
/**
* Articles Table
*
* @property \PlumSearch\Test\App\Model\Table\AuthorsTable|\Cake\ORM\Association\BelongsTo $Authors
* @method \PlumSearch\Model\FilterRegistry filters()
* @method \Cake\ORM\Table addFilter(string $name, array $options = [])
* @method \Cake\ORM\Table removeFilter(string $name)
*/
class ArticlesTable extends \Cake\ORM\Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config): void
{
$this->setTable('articles');
$this->setDisplayField('id');
$this->setPrimaryKey('id');
$this->addBehavior('Timestamp');
$this->addBehavior('PlumSearch.Filterable');
$this->addFilter('title', ['className' => 'Like']);
$this->addFilter('tag', ['className' => 'Tags']);
// $this->addFilter('language', ['className' => 'Value']);
$this->addFilter('author_id', ['className' => 'Value']);
$this->belongsTo('Authors', [
'foreignKey' => 'author_id',
]);
}
/**
* Authors search finder
*
* @param Query $query query object instance
* @return $this
*/
public function findWithAuthors(Query $query)
{
return $query->matching('Authors');
}
}
| skie/plum_search | tests/App/Model/Table/ArticlesTable.php | PHP | mit | 1,749 |
/* MoTo - Motion Toolkit
Copyright (c) 2006-2019 Gino van den Bergen, DTECTA
Source published under the terms of the MIT License.
For details please see COPYING file or visit
http://opensource.org/licenses/MIT
*/
#ifndef MT_DUALVECTOR3_HPP
#define MT_DUALVECTOR3_HPP
#include <moto/Dual.hpp>
#include <moto/Vector3.hpp>
#include <moto/Vector4.hpp>
namespace mt
{
template <typename Scalar> Vector3<Dual<Scalar> > makeDual(const Vector3<Scalar>& u, const Vector3<Scalar>& v);
template <typename Scalar> Vector3<Scalar> real(const Vector3<Dual<Scalar> >& v);
template <typename Scalar> Vector3<Scalar> dual(const Vector3<Dual<Scalar> >& v);
template <typename Scalar> Vector3<Dual<Scalar> > conj(const Vector3<Dual<Scalar> >& v);
// The line through p and q represented as Pluecker coordinates
template <typename Scalar> Vector3<Dual<Scalar> > makeLine(const Vector3<Scalar>& p, const Vector3<Scalar>& q);
// Again, the line through p and q but now p and q are in homogenous coordinates.
template <typename Scalar> Vector3<Dual<Scalar> > makeLine(const Vector4<Scalar>& p, const Vector4<Scalar>& q);
// The line of intersection of two planes p and q represented by homogeneous coordinates:
// ax + by + cz + dw = 0 for a plane [a, b, c, d] and a (homogenous) point on the plane [x, y, z, w]
template <typename Scalar> Vector3<Dual<Scalar> > makeIntersect(const Vector4<Scalar>& p, const Vector4<Scalar>& q);
template <typename Scalar> Vector3<Scalar> closest(const Vector3<Dual<Scalar> >& v);
template <typename Scalar> Scalar pitch(const Vector3<Dual<Scalar> >& v);
template <typename Scalar> Vector3<Scalar> moment(const Vector3<Dual<Scalar> >& v, const Vector3<Scalar>& p);
#ifdef USE_OSTREAM
template <typename CharT, typename Traits, typename Scalar>
std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const Vector3<Dual<Scalar> >& a);
#endif
template <typename Scalar>
Vector3<Dual<Scalar> > makeDual(const Vector3<Scalar>& u, const Vector3<Scalar>& v)
{
return Vector3<Dual<Scalar> >(makeDual(u.x, v.x), makeDual(u.y, v.y), makeDual(u.z, v.z));
}
template <typename Scalar>
FORCEINLINE
Vector3<Scalar> real(const Vector3<Dual<Scalar> >& v)
{
return Vector3<Scalar>(real(v.x), real(v.y), real(v.z));
}
template <typename Scalar>
FORCEINLINE
Vector3<Scalar> dual(const Vector3<Dual<Scalar> >& v)
{
return Vector3<Scalar>(dual(v.x), dual(v.y), dual(v.z));
}
template <typename Scalar>
FORCEINLINE
Vector3<Dual<Scalar> > conj(const Vector3<Dual<Scalar> >& v)
{
return Vector3<Dual<Scalar> >(conj(v.x), conj(v.y), conj(v.z));
}
template <typename Scalar>
Vector3<Dual<Scalar> > makeLine(const Vector3<Scalar>& p, const Vector3<Scalar>& q)
{
return makeDual(q - p, cross(p, q));
}
template <typename Scalar>
Vector3<Dual<Scalar> > makeLine(const Vector4<Scalar>& p, const Vector4<Scalar>& q)
{
return makeDual(xyz(q) * p.w - xyz(p) * q.w, cross(xyz(p), xyz(q)));
}
template <typename Scalar>
Vector3<Dual<Scalar> > makeIntersect(const Vector4<Scalar>& p, const Vector4<Scalar>& q)
{
return makeDual(cross(xyz(p), xyz(q)), xyz(q) * p.w - xyz(p) * q.w);
}
template <typename Scalar>
Vector3<Scalar> closest(const Vector3<Dual<Scalar> >& v)
{
return cross(real(v), dual(v)) / lengthSquared(real(v));
}
template <typename Scalar>
Scalar pitch(const Vector3<Dual<Scalar> >& v)
{
return dot(real(v), dual(v)) / lengthSquared(real(v));
}
template <typename Scalar>
Vector3<Scalar> moment(const Vector3<Dual<Scalar> >& v, const Vector3<Scalar>& p)
{
return dual(v) + cross(real(v), p);
}
#ifdef USE_OSTREAM
template <typename CharT, typename Traits, typename Scalar>
FORCEINLINE
std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const Vector3<Dual<Scalar> >& a)
{
return os << '[' << real(a) << "] + \xee [" << dual(a) << ']';
}
#endif
}
#endif
| dtecta/motion-toolkit | moto/DualVector3.hpp | C++ | mit | 4,266 |
"""Unit tests for conus_boundary.py."""
import unittest
import numpy
from gewittergefahr.gg_utils import conus_boundary
QUERY_LATITUDES_DEG = numpy.array([
33.7, 42.6, 39.7, 34.9, 40.2, 33.6, 36.4, 35.1, 30.8, 47.4, 44.2, 45.1,
49.6, 38.9, 35.0, 38.1, 40.7, 47.1, 30.2, 39.2
])
QUERY_LONGITUDES_DEG = numpy.array([
276.3, 282.7, 286.6, 287.5, 271.0, 266.4, 258.3, 257.3, 286.8, 235.0, 273.5,
262.5, 277.2, 255.3, 271.8, 254.3, 262.1, 247.8, 262.9, 251.6
])
IN_CONUS_FLAGS = numpy.array(
[1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1], dtype=bool
)
class ConusBoundaryTests(unittest.TestCase):
"""Each method is a unit test for conus_boundary.py."""
def test_find_points_in_conus_no_shortcuts(self):
"""Ensures correct output from find_points_in_conus.
In this case, does not use shortcuts.
"""
conus_latitudes_deg, conus_longitudes_deg = (
conus_boundary.read_from_netcdf()
)
these_flags = conus_boundary.find_points_in_conus(
conus_latitudes_deg=conus_latitudes_deg,
conus_longitudes_deg=conus_longitudes_deg,
query_latitudes_deg=QUERY_LATITUDES_DEG,
query_longitudes_deg=QUERY_LONGITUDES_DEG, use_shortcuts=False)
self.assertTrue(numpy.array_equal(these_flags, IN_CONUS_FLAGS))
def test_find_points_in_conus_with_shortcuts(self):
"""Ensures correct output from find_points_in_conus.
In this case, uses shortcuts.
"""
conus_latitudes_deg, conus_longitudes_deg = (
conus_boundary.read_from_netcdf()
)
these_flags = conus_boundary.find_points_in_conus(
conus_latitudes_deg=conus_latitudes_deg,
conus_longitudes_deg=conus_longitudes_deg,
query_latitudes_deg=QUERY_LATITUDES_DEG,
query_longitudes_deg=QUERY_LONGITUDES_DEG, use_shortcuts=True)
self.assertTrue(numpy.array_equal(these_flags, IN_CONUS_FLAGS))
if __name__ == '__main__':
unittest.main()
| thunderhoser/GewitterGefahr | gewittergefahr/gg_utils/conus_boundary_test.py | Python | mit | 2,046 |
<?php
namespace Iniaf\Bundle\UserBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class UserBundle extends Bundle
{
}
| crashorbo/Iniaf | src/Iniaf/Bundle/UserBundle/UserBundle.php | PHP | mit | 128 |
import path from "path";
import { assert } from "chai";
import { extract, toJson, isPseudoCode } from "../data/scripts/index";
import { Done } from "mocha";
describe("ONS Code Extraction", () => {
it("returns an error if no data directory provided", (done: Done) => {
extract({
configs: [],
done: (error: Error) => {
assert.match(error.message, /please specify a data path/i);
done();
},
});
});
describe("with valid data directory", () => {
let argv: any;
before(() => {
// Overwrite argv to point to correct data directory
argv = process.argv;
process.argv = process.argv.slice();
process.argv.push("-d");
process.argv.push(path.join(__dirname, "./seed/ons_codes"));
});
after(() => {
// Restore argv
process.argv = argv;
});
describe("extract", () => {
it("returns error if invalid file present", (done: Done) => {
extract({
configs: [
{
file: "foo",
},
{
file: "bar",
},
],
done: (error: Error) => {
assert.match(error.message, /files cannot be resolved/i);
done();
},
});
});
it("extracts data for given files", (done: Done) => {
const transform = (row: any) => {
const keyIndex = 0;
const valueIndex = 3;
if (row[keyIndex] === "CTRY12CD") return []; // Escape if header
return [row[keyIndex], row[valueIndex]];
};
extract({
configs: [
{
transform,
file: "countries.txt",
parseOptions: {
relax_column_count: true,
},
},
],
done: (error: Error, result: any) => {
assert.isNull(error);
assert.equal(result.size, 6);
assert.equal(result.get("E92000001"), "England");
done();
},
});
});
it("addends appendMissing to data file", (done: Done) => {
const transform = (row: any) => {
const keyIndex = 0;
const valueIndex = 3;
if (row[keyIndex] === "CTRY12CD") return []; // Escape if header
return [row[keyIndex], row[valueIndex]];
};
const appendMissing = {
foo: "bar",
baz: {
qux: "quux",
},
};
extract({
appendMissing,
configs: [
{
transform,
file: "countries.txt",
parseOptions: {
relax_column_count: true,
},
},
],
done: (error: Error, result: any) => {
assert.isNull(error);
assert.equal(result.size, 8);
assert.equal(result.get("foo"), "bar");
assert.deepEqual(result.get("baz"), { qux: "quux" });
done();
},
});
});
});
describe("isPseudoCode", () => {
it("returns true if pseudocode", () => {
[
"W99999999",
"S99999999",
"N99999999",
"L99999999",
"M99999999",
].forEach((code: string) => assert.isTrue(isPseudoCode(code)));
});
it("returns false if not pseudocode", () => {
["E12000001", "E12000002"].forEach((code: string) =>
assert.isFalse(isPseudoCode(code))
);
});
});
describe("toJson", () => {
let data: any;
beforeEach(() => {
data = new Map();
for (let i = 0; i < 100; i++) {
data.set(`key${i}`, "foo");
}
});
it("converts a map to an JSON object ordered by keys", () => {
const result = JSON.parse(toJson(data));
const keys = Object.keys(result);
assert.equal(keys.length, data.size);
data.forEach((value: any, key: string) =>
assert.equal(result[key], value)
);
keys.reduce((acc, key) => {
if (acc === null) return key;
assert.isTrue(key > acc);
return acc;
}, null);
});
});
});
});
| ideal-postcodes/postcodes.io | test/code-parser.unit.ts | TypeScript | mit | 4,210 |
#!/usr/bin/python3.3
import somnTCP
import somnUDP
import somnPkt
import somnRouteTable
from somnLib import *
import struct
import queue
import threading
import socket
import time
import random
PING_TIMEOUT = 5
class somnData():
def __init__(self, ID, data):
self.nodeID = ID
self.data = data
class somnMesh(threading.Thread):
TCPTxQ = queue.Queue()
TCPRxQ = queue.Queue()
UDPRxQ = queue.Queue()
UDPAlive = threading.Event()
networkAlive = threading.Event()
routeTable = somnRouteTable.somnRoutingTable()
cacheId = [0,0,0,0]
cacheRoute = [0,0,0,0]
cacheNextIndex = 0
_mainLoopRunning = 0
enrolled = False
nodeID = 0
nodeIP = "127.0.0.1"
nodePort = 0
lastEnrollReq = 0
connCache = [('',0),('',0),('',0)]
_printCallbackFunction = None
def __init__(self, TxDataQ, RxDataQ, printCallback = None):
threading.Thread.__init__(self)
self.CommTxQ = TxDataQ
self.CommRxQ = RxDataQ
random.seed()
self.nodeID = random.getrandbits(16)
self.nextConnCacheIndex = 0
self._printCallbackFunction = printCallback
TCPTxQ = queue.Queue()
TCPRxQ = queue.Queue()
UDPRxQ = queue.Queue()
self.pendingRouteID = 0
self.pendingRoute = 0
self.pendingRouteHTL = 1
self.routeLock = threading.Lock()
self.routeBlock = threading.Event()
self.pingTimer = threading.Timer(random.randrange(45,90), self._pingRouteTable)
self.pingCache = [0,0,0,0,0]
self.pingLock = threading.Lock()
def printinfo(self, outputStr):
if self._printCallbackFunction == None:
print("{0:04X}: {1}".format(self.nodeID, outputStr))
else:
self._printCallbackFunction(self.nodeID, outputStr)
def enroll(self):
#self.printinfo("enrolling")
tcpRespTimeout = False
ACK = random.getrandbits(16)
enrollPkt = somnPkt.SomnPacket()
enrollPkt.InitEmpty("NodeEnrollment")
enrollPkt.PacketFields['ReqNodeID'] = self.nodeID
enrollPkt.PacketFields['ReqNodeIP'] = IP2Int(self.nodeIP)
enrollPkt.PacketFields['ReqNodePort'] = self.nodePort
enrollPkt.PacketFields['AckSeq'] = ACK
udp = somnUDP.somnUDPThread(enrollPkt, self.UDPRxQ, self.networkAlive, self.UDPAlive)
udp.start()
while not tcpRespTimeout and self.routeTable.getNodeCount() < 3:
try:
enrollResponse = self.TCPRxQ.get(timeout = 1)
except queue.Empty:
tcpRespTimeout = True
break
respNodeID = enrollResponse.PacketFields['RespNodeID']
respNodeIP = enrollResponse.PacketFields['RespNodeIP']
respNodePort = enrollResponse.PacketFields['RespNodePort']
#self.printinfo("Got enrollment response from {0:04X}".format(respNodeID))
self.routeTable.getNodeIndexFromId(respNodeID)
if self.routeTable.getNodeIndexFromId(respNodeID) > 0:
self.TCPRxQ.task_done()
continue
elif enrollResponse.PacketType == somnPkt.SomnPacketType.NodeEnrollment and enrollResponse.PacketFields['AckSeq'] == ACK:
if self.routeTable.addNode(respNodeID, Int2IP(respNodeIP), respNodePort) < 0:
self.printinfo("Something went wrong in adding the node")
#TODO: Can we make this an exception?
packedEnrollResponse = somnPkt.SomnPacketTxWrapper(enrollResponse, Int2IP(respNodeIP),respNodePort)
self.TCPTxQ.put(packedEnrollResponse)
self.enrolled = True
self.printinfo("Enrolled to: {0:04X}".format(respNodeID))
self.TCPRxQ.task_done()
#break
return udp
def run(self):
socket.setdefaulttimeout(5)
self.networkAlive.set()
Rx = somnTCP.startSomnRx(self.nodeIP, self.nodePort, self.networkAlive, self.TCPRxQ)
Tx = somnTCP.startSomnTx(self.networkAlive, self.TCPTxQ)
while True:
if Rx.bound and Tx.bound: break
self.nodePort = Rx.port
#self.printinfo("Port: {0}".format(self.nodePort))
enrollAttempts = 0
while not self.enrolled:
self.UDPAlive.set()
UDP = self.enroll()
if self.enrolled:
break
elif enrollAttempts < 2:
self.UDPAlive.clear()
UDP.join()
enrollAttempts = enrollAttempts + 1
else:
self.enrolled = True
self.printinfo("Enrolled as Alpha Node")
break
#start main loop to handle incoming queueus
self._mainLoopRunning = 1
rxThread = threading.Thread(target = self._handleTcpRx)
rxThread.start()
self.pingTimer.start()
while self._mainLoopRunning:
self._handleUdpRx()
self._handleTx()
# Do a bunch of stuff
try:
self.pingTimer.cancel()
except:
pass
self.networkAlive.clear()
UDP.networkAlive = False
UDP.join()
Rx.join()
Tx.join()
self.TCPRxQ.join()
self.TCPTxQ.join()
self.CommTxQ.join()
self.CommRxQ.join()
def _pingRouteTable(self):
# check if previous route requests were returned
self.pingLock.acquire()
for idx, node in enumerate(self.pingCache):
if node != 0:
# remove nodes where no response was returned
self.printinfo("Dropping Node: {0:04X}".format(node))
self.routeTable.removeNodeByIndex(self.routeTable.getNodeIndexFromId(node))
# unset returned route cache
self.pingCache[idx] = 0
self.pingLock.release()
# send a RouteReqeust for node 0xFFFF to each entry in the routing table
for node in self.routeTable.getConnectedNodes():
nodeIndex = self.routeTable.getNodeIndexFromId(node)
self.pingLock.acquire()
self.pingCache[nodeIndex - 1] = node
self.pingLock.release()
pingPkt = somnPkt.SomnPacket()
pingPkt.InitEmpty(somnPkt.SomnPacketType.RouteRequest)
pingPkt.PacketFields['SourceID'] = self.nodeID
pingPkt.PacketFields['LastNodeID'] = self.nodeID
pingPkt.PacketFields['DestID'] = 0xFFFF
pingPkt.PacketFields['HTL'] = 1
TxInfo = self.routeTable.getNodeInfoByIndex(nodeIndex)
TxPkt = somnPkt.SomnPacketTxWrapper(pingPkt, TxInfo.nodeAddress, TxInfo.nodePort)
self.TCPTxQ.put(TxPkt)
self.pingTimer = threading.Timer(random.randrange(45,90), self._pingRouteTable)
self.pingTimer.start()
def _handleTx(self):
#print("Handle TX")
try:
TxData = self.CommTxQ.get(False)
except:
return
#TODO: Tx Data coming from the Comm Layer needs to packetized
route = 0
#check cache for route to dest ID
if TxData.nodeID in self.cacheId:
route = self.cacheRoute[self.cacheId.index(TxData.nodeID)]
else:
route = self._getRoute(TxData.nodeID)
#TODO Lock around this
self.pendingRouteID = 0
self.pendingRouteHTL = 1
if route == 0: # no valid rout found
self.printinfo(" *** NO ROUTE FOUND *** ")
return
# inset path into cache, for now this is a FIFO eviction policy, should upgrade to an LFU policy
self.cacheId[self.cacheNextIndex] = TxData.nodeID
self.cacheRoute[self.cacheNextIndex] = route
self.cacheNextIndex = self.cacheNextIndex + 1
if self.cacheNextIndex > 3:
self.cacheNextIndex = 0
#pop first step in route from route string
nextRoute, newRoute = self._popRoute(route)
#nextRouteStep = newRoute[0]
#set route string in packet
TxPkt = somnPkt.SomnPacket()
TxPkt.InitEmpty(somnPkt.SomnPacketType.Message)
TxPkt.PacketFields['SourceID'] = self.nodeID
TxPkt.PacketFields['DestID'] = TxData.nodeID
TxPkt.PacketFields['Message'] = TxData.data
TxPkt.PacketFields['Route'] = newRoute
#create wrapper packet to send to next step in route
TxNodeInfo = self.routeTable.getNodeInfoByIndex(nextRoute)
if TxNodeInfo is None:
self.cacheRoute[self.cacheId.index(TxData.nodeID)] = 0
self.CommTxQ.task_done()
self.CommTxQ.put(TxData)
return
txPktWrapper = somnPkt.SomnPacketTxWrapper(TxPkt, TxNodeInfo.nodeAddress, TxNodeInfo.nodePort)
#send packet to TX layer
self.TCPTxQ.put(txPktWrapper)
self.CommTxQ.task_done()
def _handleTcpRx(self):
while self._mainLoopRunning:
try:
RxPkt = self.TCPRxQ.get(False)
except:
continue
pktType = RxPkt.PacketType
#self.printinfo("Rx'd TCP packet of type: {0}".format(pktType))
if pktType == somnPkt.SomnPacketType.NodeEnrollment:
#print("Enrollment Packet Received")
self.pingTimer.cancel()
# There is a potential for stale enroll responses from enrollment phase, drop stale enroll responses
if RxPkt.PacketFields['ReqNodeID'] == self.nodeID: continue
# We need to disable a timer, enroll the node, if timer has expired, do nothing
for idx, pendingEnroll in enumerate(self.connCache):
if (RxPkt.PacketFields['ReqNodeID'], RxPkt.PacketFields['AckSeq']) == pendingEnroll[0]:
# disable timer
pendingEnroll[1].cancel()
# clear connCache entry
self.connCache[idx] = (('',0),)
# add node
self.routeTable.addNode(RxPkt.PacketFields['ReqNodeID'], Int2IP(RxPkt.PacketFields['ReqNodeIP']), RxPkt.PacketFields['ReqNodePort'])
#self.printinfo("Enrolled Node:{0:04X} ".format(RxPkt.PacketFields['ReqNodeID']))
break
self.pingTimer = threading.Timer(random.randrange(45,90), self._pingRouteTable)
self.pingTimer.start()
elif pktType == somnPkt.SomnPacketType.Message:
#print("({0:X}) Message Packet Received".format(self.nodeID))
# Check if we are the dest node
if RxPkt.PacketFields['DestID'] == self.nodeID:
self.printinfo("{0:04X} -> {1:04X}: {2}".format(RxPkt.PacketFields['SourceID'], self.nodeID, RxPkt.PacketFields['Message']))
# strip headers before pushing onto queue
commData = somnData(RxPkt.PacketFields['SourceID'], RxPkt.PacketFields['Message'])
self.CommRxQ.put(commData)
# otherwise, propagate the message along the route
elif not RxPkt.PacketFields['Route']:
# generate bad_route event
print("nothing to see here, move along folks")
else:
nextHop, RxPkt.PacketFields['Route'] = self._popRoute(RxPkt.PacketFields['Route'])
TxNodeInfo = self.routeTable.getNodeInfoByIndex(nextHop)
if TxNodeInfo is None:
# this should generate a bad route pacekt
self.printinfo("Invalid Route Event")
self.TCPRxQ.task_done()
continue
TxPkt = somnPkt.SomnPacketTxWrapper(RxPkt, TxNodeInfo.nodeAddress, TxNodeInfo.nodePort)
self.TCPTxQ.put(TxPkt)
elif pktType == somnPkt.SomnPacketType.RouteRequest:
#print("Route Req Packet Received")
if RxPkt.PacketFields['SourceID'] == self.nodeID:
# this our route request, deal with it.
if self.pendingRouteID == RxPkt.PacketFields['DestID']:
self.routeLock.acquire()
#self.printinfo("Servicing Returned Route for {0:04X}".format(self.pendingRouteID))
if RxPkt.PacketFields['Route'] != 0:
self.pendingRoute = self._pushRoute(RxPkt.PacketFields['Route'], self.routeTable.getNodeIndexFromId(RxPkt.PacketFields['LastNodeID']))
self.routeBlock.set()
self.routeLock.release()
self.TCPRxQ.task_done()
continue
elif RxPkt.PacketFields['HTL'] < 10:
self.routeLock.release()
self.pendingRouteHTL = self.pendingRouteHTL + 1
RxPkt.PacketFields['HTL'] = self.pendingRouteHTL
RxPkt.PacketFields['ReturnRoute'] = 0
TxNodeInfo = self.routeTable.getNodeInfoByIndex(self.routeTable.getNodeIndexFromId(RxPkt.PacketFields['LastNodeID']))
RxPkt.PacketFields['LastNodeID'] = self.nodeID
TxPkt = somnPkt.SomnPacketTxWrapper(RxPkt, TxNodeInfo.nodeAddress, TxNodeInfo.nodePort)
self.TCPTxQ.put(TxPkt)
self.TCPRxQ.task_done()
continue
elif RxPkt.PacketFields['DestID'] == 0xFFFF:
self.pingLock.acquire()
for idx, node in enumerate(self.pingCache):
if node == RxPkt.PacketFields['LastNodeID']:
self.pingCache[idx] = 0
self.pingLock.release()
self.TCPRxQ.task_done()
continue
else: # this route has been served
#self.routeLock.release()
#RxPkt.Reset()
self.TCPRxQ.task_done()
continue
# if route field is -0-, then it is an in-progress route request
# otherwise it is a returning route request
elif not RxPkt.PacketFields['Route']:
# check if we have the destid in our routeTable
idx = self.routeTable.getNodeIndexFromId(RxPkt.PacketFields['DestID'])
if idx < 0: # Continue route request
if RxPkt.PacketFields['HTL'] > 1:
#print("got multi Hop route request")
RxPkt.PacketFields['ReturnRoute'] = self._pushRoute(RxPkt.PacketFields['ReturnRoute'], self.routeTable.getNodeIndexFromId(RxPkt.PacketFields['LastNodeID']))
RxPkt.PacketFields['HTL'] = RxPkt.PacketFields['HTL'] - 1
lastID = RxPkt.PacketFields['LastNodeID']
RxPkt.PacketFields['LastNodeID'] = self.nodeID
#transmit to all nodes, except the transmitting node
i = 1
while i <= self.routeTable.getNodeCount():
TxNodeInfo = self.routeTable.getNodeInfoByIndex(i)
i = i + 1
if not TxNodeInfo.nodeID == lastID:
#continue
TxPkt = somnPkt.SomnPacketTxWrapper(RxPkt, TxNodeInfo.nodeAddress, TxNodeInfo.nodePort)
self.TCPTxQ.put(TxPkt)
self.TCPRxQ.task_done()
continue
elif RxPkt.PacketFields['HTL'] == 1: # Last Node in query path
RxPkt.PacketFields['HTL'] = RxPkt.PacketFields['HTL'] - 1
TxNodeInfo = self.routeTable.getNodeInfoByIndex(self.routeTable.getNodeIndexFromId(RxPkt.PacketFields['LastNodeID']))
RxPkt.PacketFields['LastNodeID'] = self.nodeID
TxPkt = somnPkt.SomnPacketTxWrapper(RxPkt, TxNodeInfo.nodeAddress, TxNodeInfo.nodePort)
self.TCPTxQ.put(TxPkt)
self.TCPRxQ.task_done()
continue
else:
#if RxPkt.PacketFields['ReturnRoute'] == 0:
# TxIndex = self.routeTable.getNodeIndexFromId(RxPkt.PacketFields['SourceID'])
#else:
TxIndex, RxPkt.PacketFields['ReturnRoute'] = self._popRoute(RxPkt.PacketFields['ReturnRoute'])
RxPkt.PacketFields['LastNodeID'] = self.nodeID
TxNodeInfo = self.routeTable.getNodeInfoByIndex(TxIndex)
TxPkt = somnPkt.SomnPacketTxWrapper(RxPkt, TxNodeInfo.nodeAddress, TxNodeInfo.nodePort)
self.TCPTxQ.put(TxPkt)
self.TCPRxQ.task_done()
continue
else: # Dest Node is contained in route table
RxPkt.PacketFields['HTL'] = 0
RxPkt.PacketFields['Route'] = self._pushRoute(RxPkt.PacketFields['Route'], self.routeTable.getNodeIndexFromId(RxPkt.PacketFields['DestID']))
#if RxPkt.PacketFields['ReturnRoute'] == 0: # Route did not go past HTL = 1
# TxIndex = self.routeTable.getNodeIndexFromId(RxPkt.PacketFields['SourceID'])
#else:
# TxIndex, RxPkt.PacketFields['ReturnRoute'] = self._popRoute(RxPkt.PacketFields['ReturnRoute'])
TxIndex = self.routeTable.getNodeIndexFromId(RxPkt.PacketFields['LastNodeID'])
RxPkt.PacketFields['LastNodeID'] = self.nodeID
TxNodeInfo = self.routeTable.getNodeInfoByIndex(TxIndex)
#print("Dest Node Found: ",RxPkt.PacketFields)
TxPkt = somnPkt.SomnPacketTxWrapper(RxPkt, TxNodeInfo.nodeAddress, TxNodeInfo.nodePort)
self.TCPTxQ.put(TxPkt)
self.TCPRxQ.task_done()
continue
else: # route path is non-empty
RxPkt.PacketFields['Route'] = self._pushRoute(RxPkt.PacketFields['Route'], self.routeTable.getNodeIndexFromId(RxPkt.PacketFields['LastNodeID']))
RxPkt.PacketFields['LastNodeID'] = self.nodeID
#print("Route Non Empty: ",RxPkt.PacketFields)
TxIndex, RxPkt.PacketFields['ReturnRoute'] = self._popRoute(RxPkt.PacketFields['ReturnRoute'])
TxNodeInfo = self.routeTable.getNodeInfoByIndex(TxIndex)
TxPkt = somnPkt.SomnPacketTxWrapper(RxPkt, TxNodeInfo.nodeAddress, TxNodeInfo.nodePort)
self.TCPTxQ.put(TxPkt)
self.TCPRxQ.task_done()
continue
elif pktType == somnPkt.SomnPacketType.BadRoute:
print("Bad Route Packet Received")
self.TCPRxQ.task_done()
continue
elif pktType == somnPkt.SomnPacketType.AddConnection:
for pendingConn in self.connCache:
if (RxPkt.PacketFields['RespNodeID'], RxPkt.PacketFields['AckSeq']) == pendingConn[1]: # This is response
# cancel timer
pendingConn[2].cancel()
# add node
routeTable.addNode(RxPkt.PacketFields['RespNodeID'], Int2IP(RxPkt.PacketFields['RespNodeIP']), RxPkt.PacketFields['RespNodePort'])
# send AddConnection ACK packet
packedTxPkt = somnPkt.SomnPacketTxWrapper(somnPkt.SomnPacket(RxPkt.ToBytes()),Int2IP(RxPkt.PacketFields['RespNodeIP']), RxPkt.PacketFields['RespNodePort'])
self.TCPTxQ.put(packedTxPkt)
continue
# This is an incoming request
# generate a TCP Tx packet, start a timer, store ReqNodeID and timer object
TxPkt = somnPkt.SomnPacket(RxPkt.ToBytes())
TxPkt.Packetfields['RespNodeID'] = self.nodeID
TxPkt.Packetfields['RespNodeIP'] = self.nodeIP
TxPkt.Packetfields['RespNodePort'] = self.nodePort
connCacheTag = (TxPkt.PacketFilds['ReqNodeID'], TxtPkt.PacketFields['AckSeq'])
TxTimer = threading.Timer(5.0, self._connTimeout, connCacheTag)
self.connCache[self.nextconnCacheEntry] = (connCacheTag, TxTimer)
self.nextConnCacheEntry = self.nextConnCacheEntry + 1
if self.nextConnCacheEntry >= len(self.connCache):
self.nextConnCacheEntry = 0
print("Add Conn Packet Received")
elif pktType == somnPkt.SomnPacketType.DropConnection:
print("Drop Conn Packet Received")
else:
#RxPkt.Reset()
self.TCPRxQ.task_done()
continue
#RxPkt.Reset()
self.TCPRxQ.task_done()
continue
def _handleUdpRx(self):
#print("handleUDP")
try:
enrollPkt = self.UDPRxQ.get(False)
except:
return
enrollRequest = somnPkt.SomnPacket(enrollPkt)
self.UDPRxQ.task_done()
#ignore incoming enrollment requests from self
if enrollRequest.PacketFields['ReqNodeID'] == self.nodeID:
return
#self.printinfo("Got enrollment request from {0:04X}".format(enrollRequest.PacketFields['ReqNodeID']))
if self.routeTable.getNodeIndexFromId(enrollRequest.PacketFields['ReqNodeID']) > 0:
#self.printinfo("Node already connected, ignoring")
#self.UDPRxQ.task_done()
return
if self.routeTable.getAvailRouteCount() > 4 or (self.lastEnrollReq == enrollRequest.PacketFields['ReqNodeID'] and self.routeTable.getAvailRouteCount() > 0):
enrollRequest.PacketFields['RespNodeID'] = self.nodeID
enrollRequest.PacketFields['RespNodeIP'] = IP2Int(self.nodeIP)
enrollRequest.PacketFields['RespNodePort'] = self.nodePort
packedEnrollResponse = somnPkt.SomnPacketTxWrapper(enrollRequest, Int2IP(enrollRequest.PacketFields['ReqNodeIP']), enrollRequest.PacketFields['ReqNodePort'])
connCacheTag = (enrollRequest.PacketFields['ReqNodeID'], enrollRequest.PacketFields['AckSeq'])
TxTimer = threading.Timer(10.0, self._enrollTimeout, connCacheTag)
self.connCache[self.nextConnCacheIndex] = (connCacheTag, TxTimer)
self.nextConnCacheIndex = self.nextConnCacheIndex + 1
if self.nextConnCacheIndex >= len(self.connCache): self.nextConnCacheIndex = 0
#print("------- START UDP LISTEN -----------")
#print(self.routeTable.getAvailRouteCount())
#print("Responded to Enroll Request")
#print("---------- END UDP LISTEN-----------")
self.TCPTxQ.put(packedEnrollResponse)
TxTimer.start()
else:
self.lastEnrollReq = enrollRequest.PacketFields['ReqNodeID']
#self.UDPRxQ.task_done()
return
#get route from this node to dest node
def _getRoute(self, destId):
#first, check if the dest is a neighboring node
routeIndex = self.routeTable.getNodeIndexFromId(destId)
if routeIndex != -1:
return routeIndex & 0x7
#unknown route (discover from mesh)
routePkt = somnPkt.SomnPacket()
routePkt.InitEmpty(somnPkt.SomnPacketType.RouteRequest)
routePkt.PacketFields['SourceID'] = self.nodeID
routePkt.PacketFields['LastNodeID'] = self.nodeID
routePkt.PacketFields['RouteRequestCode'] = 1 #random.getrandbits(16)
routePkt.PacketFields['DestID'] = destId
routePkt.PacketFields['HTL'] = 1
self.pendingRouteID = destId
self.pendingRoute = 0
t = threading.Timer(10, self._routeTimeout)
idx = 1
while idx <= self.routeTable.getNodeCount():
TxNodeInfo = self.routeTable.getNodeInfoByIndex(idx)
#print("getRoute Packet Type: ", routePkt.PacketFields)
TxPkt = somnPkt.SomnPacketTxWrapper(routePkt, TxNodeInfo.nodeAddress, TxNodeInfo.nodePort)
self.TCPTxQ.put(TxPkt)
idx = idx + 1
t.start()
#self.printinfo("Waiting for route")
self.routeBlock.wait()
self.routeBlock.clear()
#self.printinfo("Waiting Done")
try:
t.cancel()
except:
pass
return self.pendingRoute
def _routeTimeout(self):
self.routeLock.acquire()
if not self.routeBlock.isSet():
#self.printinfo("routeTimer Activate")
self.pendingRoute = 0
self.pendingRouteID = 0
self.routeBlock.set()
self.routeLock.release()
#self.printinfo("routeTimer exit")
def _popRoute(self, route):
firstStep = route & 0x7
newRoute = route >> 3
return (firstStep, newRoute)
def _pushRoute(self, route, nextStep):
newRoute = (route << 3) | (nextStep & 0x7)
return newRoute
def _enrollTimeout(self, nodeID, ACK):
for idx, pendingEnroll in enumerate(self.connCache):
if (nodeID, ACK) == pendingEnroll[0]:
self.connCache[idx] = (('',0),)
break
return
def _connTimeout(self, nodeIP, nodePort):
for idx, connAttempt in enumerate(self.connCache):
if (nodeIP, nodePort) == connAttempt[0]:
self.connCache[idx] = (('',0),)
break
return
def addConnection(self, DestNodeID):
addConnPkt = somnPkt.SomnPkt()
addConnPkt.InitEmpty(somnPkt.SomnPacketType.AddConnection)
addConnPkt.PacketFields['ReqNodeID'] = self.nodeID
addConnPkt.PacketFields['ReqNodeIP'] = self.nodeIP
addConnPkt.PacketFields['ReqNodePort'] = self.nodePort
addConnPkt.PacketFields['AckSeq'] = random.randbits(16)
route = self._getRoute(DestNodeID)
if route > 0:
addConnPkt.PacketFields['Route'] = route
else:
self.printinfo("AddConnection Failed to get route")
def CreateNode(printCallback = None):
mesh = somnMesh(queue.Queue(), queue.Queue(), printCallback)
return mesh
if __name__ == "__main__":
mesh = CreateNode()
mesh.start()
| squidpie/somn | src/somnMesh.py | Python | mit | 23,564 |
package com.bandwidth.iris.sdk.model;
public class TelephoneNumberSearchFilters {
private String inAreaCode;
private String filterPattern;
private String inState;
private String inPostalCode;
private boolean isTollFree;
private int quantity = 5;
private boolean returnTelephoneNumberDetails = true;
private String inRateCenter;
private String inLata;
public boolean isReturnTelephoneNumberDetails() {
return returnTelephoneNumberDetails;
}
public void setReturnTelephoneNumberDetails(boolean returnTelephoneNumberDetails) {
this.returnTelephoneNumberDetails = returnTelephoneNumberDetails;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String getInAreaCode() {
return inAreaCode;
}
public void setInAreaCode(String inAreaCode) {
this.inAreaCode = inAreaCode;
}
public String getFilterPattern() {
return filterPattern;
}
public void setFilterPattern(String filterPattern) {
this.filterPattern = filterPattern;
}
public String getInState() {
return inState;
}
public void setInState(String inState) {
this.inState = inState;
}
public String getInPostalCode() {
return inPostalCode;
}
public void setInPostalCode(String inPostalCode) {
this.inPostalCode = inPostalCode;
}
public boolean isTollFree() {
return isTollFree;
}
public void setTollFree(boolean isTollFree) {
this.isTollFree = isTollFree;
}
public String getInRateCenter() {
return inRateCenter;
}
public void setInRateCenter(String inRateCenter) {
this.inRateCenter = inRateCenter;
}
public String getInLata() {
return inLata;
}
public void setInLata(String inLata) {
this.inLata = inLata;
}
}
| bandwidthcom/java-bandwidth-iris | src/main/java/com/bandwidth/iris/sdk/model/TelephoneNumberSearchFilters.java | Java | mit | 1,972 |
function listar_dir_envio(){
$.ajax({
cache: false,
url: administrador + "administrador_usuario.php?accion=listar_direccion_envio",
type: 'POST',
data: {"id_cliente": id_cliente_js},
dataType: "json",
beforeSend: function () {
//$("#result_informacion").html("Procesando, espere por favor..." );
},
success: function (data) {
$("#result_informacion").append("<div class='pleca-titulo space10'></div><div class='encabezado-descripcion'>Datos de envío</div>" +
"<table id='direcciones' cellspacing='0'><thead><tr><th>Dirección</th><th>Colonia</th><th>Codigo Postal</th><th>Ciudad</th><th>Estado</th><th> </th></tr></thead></table>");
$.each(data.direccion_envio, function(k,v){
var inter = '';
if(v.num_int){
inter = v.num_int;
}
var pe= ' ';
if(v.id_estatusSi == 3){
pe = "<div style='color: #D81830; height: 20px; font-size: 11px; font-family: italic; font-weight: bold'>pago express</div>";
}
$("#direcciones").append('<tr><td>'+ v.calle + ' ' +
v.num_ext + ' ' +
inter + pe +'</td><td>' +
v.colonia + '</td><td>' +
v.cp + '</td><td>' +
v.ciudad + '</td><td>' +
v.estado + '</td>'+
'<td valign="top"><div onclick=\"editar_dir_envio('+ v.id_consecutivoSi +')\"><a href="#">editar</a></div><div onclick=\"eliminar_dir_envio('+ v.id_consecutivoSi +')\"><a href="#">eliminar</a></div></td>'+
'</tr>');
});
$('#boton_datos').removeAttr('disabled');
}
});
}
function eliminar_dir_envio(id_env){
var conf = confirm("¿Estas seguro?");
if(conf){
$.ajax({
cache: false,
url: administrador + "administrador_usuario.php?accion=eliminar_direccion",
type: 'POST',
data: {"id_dir": id_env, "id_cliente": id_cliente_js},
beforeSend: function () {
$("#result_informacion").html("<div class='procesando'>Procesando, espere por favor...</div>" );
},
success: function (response) {
$("#result_informacion").html(response);
if($("#eliminar_direccion").text()== 1){
$("#result_informacion").html('<div class="encabezado-descripcion">Se elimino la información.</div>');
setTimeout('$("#boton_datos").click()', 2500);
}
}
});
}
}
function editar_dir_envio(id_dir){
$.ajax({
cache: false,
url: administrador + "administrador_usuario.php?accion=editar_dir_envio",
type: 'GET',
data: {"id_dir": id_dir, "id_cliente": id_cliente_js},
beforeSend: function () {
$("#result_informacion").html("<div class='procesando'>Procesando, espere por favor...</div>" );
},
success: function (response) {
$("#result_informacion").html(response);
/*
var forms = $("form[id*='registro']");
var reg_cp = /^([1-9]{2}|[0-9][1-9]|[1-9][0-9])[0-9]{3}$/;
var reg_email = /^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/;
var reg_nombres = /^[A-ZáéíóúÁÉÍÓÚÑñ \'.-]{1,30}$/i;
var reg_numeros = /^[A-Z0-9 -.#\/]{1,50}$/i;
var reg_direccion = /^[A-Z0-9 \'.,-áéíóúÁÉÍÓÚÑñ]{1,50}$/i;
var reg_telefono = /^[0-9 ()+-]{10,20}$/
var calle = $("#txt_calle");
var num_ext = $("#txt_numero");
var cp = $("#txt_cp");
var pais = $("#sel_pais");
var estado_t = $("#txt_estado");
var ciudad_t = $("#txt_ciudad");
var colonia_t = $("#txt_colonia");
var estado_s = $("#sel_estados");
var ciudad_s = $("#sel_ciudades");
var colonia_s = $("#sel_colonias");
var telefono= $("#txt_telefono");
var estado, ciudad, colonia;
$('.div_otro_pais').hide();
//onChange:
$('#sel_pais').change(function() {
//hacer un toggle si es necesario
var es_mx = false;
$.getJSON(ecommerce + "direccion_envio/es_mexico/" + $(this).val(),
function(data) {
if (!data.result) { //no es México
$('.div_mexico').hide();
$('.div_otro_pais').show();
} else {
$('.div_mexico').show();
$('.div_otro_pais').hide();
}
}
);
}).change(); //se lanza al inicio de la carga para verificar al inicio
$('#sel_estados').change(function() {
//actualizar ciudad y colonia
var clave_estado = $("#sel_estados option:selected").val();
//alert('change estado ' + clave_estado);
actualizar_ciudades(clave_estado);
//limpiar las colonias
$("#sel_colonias").empty();
$("<option></option>").attr("value", '').html('Selecionar').appendTo("#sel_colonias");
});
$('#sel_ciudades').change(function() {
//actualizar ciudad y colonia
var clave_estado = $("#sel_estados option:selected").val();
var ciudad = $("#sel_ciudades option:selected").val();
//alert('change estado ' + clave_estado + '' + 'change ciudad ' + ciudad + '');
actualizar_colonias(clave_estado, ciudad);
});
$('#sel_colonias').change(function() {
//actualizar cp en base a la colonia seleccionada
var clave_estado = $("#sel_estados option:selected").val();
var ciudad = $("#sel_ciudades option:selected").val();
var colonia = $("#sel_colonias option:selected").val();
actualizar_cp(clave_estado, ciudad, colonia);
});
//con el botón de llenar sólo se recupera y selecciona edo. y ciudad
$("#btn_cp").click(function() {
var text_selected = $("#sel_pais option:selected").text();
var val_selected = $("#sel_pais option:selected").val();
var cp = $.trim($("#txt_cp").val()); //.val();
//validar cp
if (!cp || !reg_cp.test($.trim(cp))) {
alert('Por favor ingresa un código válido');
return false
}
//var sel_estados = $("#sel_estados");
$.ajax({
type: "POST",
data: {'codigo_postal' : cp},
url: ecommerce + "direccion_envio/get_info_sepomex",
dataType: "json",
async: false,
success: function(data) {
//alert("success: " + data.msg);
if (typeof data.sepomex != null && data.sepomex.length != 0) { //regresa un array con las colonias
//alert('data is ok, tipo: ' + typeof(data));
var sepomex = data.sepomex; //colonias
var codigo_postal = sepomex[0].codigo_postal;
var clave_estado = sepomex[0].clave_estado;
var estado = sepomex[0].estado;
var ciudad = sepomex[0].ciudad;
$("#sel_estados").val(clave_estado);
//alert("Estado: " + estado + ", ciudad: " + ciudad + ", cp: " + codigo_postal);
//$("#sel_estados").trigger('change');
//carga del catálogo ciudades y selección
$.post( ecommerce + 'direccion_envio/get_ciudades',
// when the Web server responds to the request
{ 'estado': clave_estado},
function(datos) {
var ciudades = datos.ciudades;
$("#sel_ciudades").empty();
$("<option></option>").attr("value", '').html('Selecionar').appendTo("#sel_ciudades");
if (ciudades.length == undefined) { //DF sólo devuelve un obj de ciudad.
$("<option></option>").attr("value", ciudades.clave_ciudad).html(ciudades.ciudad).appendTo("#sel_ciudades");
$("#sel_ciudades").trigger('change'); //trigger cities' change event
} else { //ciudades.length == 'undefined'
$.each(ciudades, function(indice, ciudad) {
if (ciudad.clave_ciudad != '') {
$("<option></option>").attr("value", ciudad.clave_ciudad).html(ciudad.ciudad).appendTo("#sel_ciudades");
}
});
}
//select choosen city
$("#sel_ciudades").val(ciudad);
//trigger ciudades change
//$("#sel_ciudades").trigger('change');
//Cargar las colonias
$("#sel_colonias").empty();
if (sepomex.length > 1)
$("<option></option>").attr("value", '').html('Selecionar').appendTo("#sel_colonias");
$.each(sepomex, function(indice, colonia) {
if (colonia.colonia != '') {
$("<option></option>").attr("value", colonia.colonia).html(colonia.colonia).appendTo("#sel_colonias");
}
});
},
"json"
);
} else if (data.sepomex.length == 0) {
$("#sel_estados").val('');
$('#sel_estados').trigger('change');
alert("El código no devolvió resultados");
//Remover información del formulario
}
},
error: function(data) {
alert("error: " + data.error);
},
complete: function(data) {
},
//async: false,
cache: false
});
});
*/
}
});
}
function enviar_dir_envio(id_dir){
var txt_calle = $('#txt_calle').val();
var txt_numero = $('#txt_numero').val();
var txt_num_int = $('#txt_num_int').val();
var txt_cp = $('#txt_cp').val();
var sel_pais = $('#sel_pais').val();
var txt_estado = $('#txt_estado').val();
var txt_ciudad = $('#txt_ciudad').val();
var txt_colonia = $('#txt_colonia').val();
var sel_estados = $('#sel_estados').val();
var sel_ciudades = $('#sel_ciudades').val();
var sel_colonias = $('#sel_colonias').val();
var txt_telefono = $('#txt_telefono').val();
var txt_referencia = $('#txt_referencia').val();
if($("#chk_default").is(':checked')){
var chk_default = 1;
}
else{
var chk_default = 0;
}
var parametros = {
"txt_calle" : txt_calle,
"txt_numero" : txt_numero,
"txt_num_int" : txt_num_int,
"txt_cp" : txt_cp,
"sel_pais" : sel_pais,
"txt_estado" : txt_estado,
"txt_ciudad" : txt_ciudad,
"txt_colonia" : txt_colonia,
"sel_estados" : sel_estados,
"sel_ciudades" : sel_ciudades,
"sel_colonias" : sel_colonias,
"txt_telefono" : txt_telefono,
"txt_referencia" : txt_referencia,
"chk_default" : chk_default
}
$.ajax({
cache: false,
data: parametros,
url: administrador + "administrador_usuario.php?accion=editar_dir_envio&id_dir=" + id_dir + "&id_cliente=" + id_cliente_js,
type: 'POST',
beforeSend: function () {
$("#result_informacion").html("<div class='procesando'>Procesando, espere por favor...</div>");
},
success: function (response) {
$("#result_informacion").html(response);
if($("#update_correcto").text()== 1){
alert('llega');
$("#result_informacion").html('<div class="encabezado-descripcion">Tus datos se han actualizado correctamente.</div>');
setTimeout('$("#boton_datos").click()', 2500);
}
}
});
}
function actualizar_ciudades(clave_estado) {
// var ecommerce = "http://localhost/ecommerce/";
$.post( ecommerce + 'direccion_envio/get_ciudades',
// when the Web server responds to the request
{ 'estado': clave_estado},
function(datos) {
var ciudades = datos.ciudades;
$("#sel_ciudades").empty();
$("<option></option>").attr("value", '').html('Selecionar').appendTo("#sel_ciudades");
if (ciudades != null) {
if (ciudades.length == undefined) { //DF sólo devuelve un obj de ciudad.
$("<option></option>").attr("value", ciudades.clave_ciudad).html(ciudades.ciudad).appendTo("#sel_ciudades");
$("#sel_ciudades").trigger('change'); //trigger cities' change event
} else { //ciudades.length == 'undefined'
$.each(ciudades, function(indice, ciudad) {
if (ciudad.clave_ciudad != '') {
$("<option></option>").attr("value", ciudad.clave_ciudad).html(ciudad.ciudad).appendTo("#sel_ciudades");
}
});
}
}
},
"json"
);
}
function actualizar_colonias(clave_estado, ciudad) {
//var ecommerce = "http://localhost/ecommerce/";
$.post( ecommerce + 'direccion_envio/get_colonias',
// when the Web server responds to the request
{ 'estado': clave_estado, 'ciudad': ciudad },
function(datos) {
var colonias = datos.colonias;
$("#sel_colonias").empty();
$("<option></option>").attr("value", '').html('Selecionar').appendTo("#sel_colonias");
if (colonias != null) {
$.each(colonias, function(indice, colonia) {
$("<option></option>").attr("value", colonia.colonia).html(colonia.colonia).appendTo("#sel_colonias");
});
}
},
"json"
);
}
function actualizar_cp(clave_estado, ciudad, colonia) {
//var ecommerce = "http://localhost/ecommerce/";
$.post( ecommerce + 'direccion_envio/get_colonias',
// when the Web server responds to the request
{ 'estado': clave_estado, 'ciudad': ciudad},
function(datos) {
var colonias = datos.colonias;
$.each(colonias, function(indice, col) {
if (colonia == col.colonia)
$("#txt_cp").val(col.codigo_postal);
//$("<option></option>").attr("value", colonia.colonia).html(colonia.colonia).appendTo("#sel_colonias");
});
},
"json"
);
}
| heladiofog/tienda0mx | js/admin_usuario_dir_envio.js | JavaScript | mit | 13,953 |
/// <reference path='../ddt.ts' />
import ddt = require('../ddt');
import chai = require('chai');
describe('DDTElement', function() {
var expect = chai.expect;
var DDTElement = ddt.DDTElement;
describe('#getNode()', function() {
it('should return the node it represents', function() {
var el = document.createElement('p');
var $el = $(el);
var dEl = new DDTElement($el);
expect(dEl.getNode()).to.equal(el);
});
});
describe('#offsetTop()', function() {
it('should return the top offset of an element', function() {
var $el = $(document.createElement('div'))
.css({
top : 10,
left : 5,
position : 'absolute'
})
.appendTo('body');
var dEl = new DDTElement($el);
expect(dEl.offsetTop()).to.equal(10);
});
it('should work for the document', function() {
var dEl = new DDTElement($(document));
expect(dEl.offsetTop()).to.equal(0);
});
});
describe('#hide(), #show()', function() {
beforeEach(function() {
ddt.DragAndDropTable.createSelectors();
ddt.DragAndDropTable.hasCreatedSelectors = false;
});
afterEach(ddt.DDTCSS.cleanup);
it('should hide/show an element', function() {
var $el = $(document.createElement('p'))
.appendTo('body');
var dEl = new DDTElement($el);
dEl.hide();
expect($el.css('visibility')).to.equal('hidden');
dEl.show();
expect($el.css('visibility')).to.equal('visible');
});
});
describe('#getVerticalBorders()', function() {
it('should work', function() {
var $el = $(document.createElement('div'))
.css({ border : '10px solid black '});
expect(DDTElement.getVerticalBorders($el)).to.equal(20);
});
});
});
| parallax/ddt | test/DDTElement.ts | TypeScript | mit | 2,056 |
var casper = require('casper').create();
var utils = require('utils');
// casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36');
var x = require('casper').selectXPath;
casper.on("resource.error", function(resourceError) {
console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
});
casper.start('http://www.apple.com/');
casper.wait(3000, function() {
var title = casper.getTitle();
console.log('>>> PageTitle: ' + title);
console.log('>>> PageHTML:\n' + casper.getHTML());
});
casper.run(function() {
this.exit(0);
});
| li-xinyang/FE_Phantom | 1Darkness/c00_wulala.js | JavaScript | mit | 770 |
<?php
/*
* This file is part of php-cache organization.
*
* (c) 2015 Aaron Scherer <aequasi@gmail.com>, Tobias Nyholm <tobias.nyholm@gmail.com>
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace Cache\AdapterBundle\Factory;
use Cache\Adapter\Doctrine\DoctrineCachePool;
use Doctrine\Common\Cache\FilesystemCache;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* @author Tobias Nyholm <tobias.nyholm@gmail.com>
*/
final class DoctrineFilesystemFactory extends AbstractDoctrineAdapterFactory
{
/**
* {@inheritdoc}
*/
public function getAdapter(array $config)
{
$client = new FilesystemCache($config['directory'], $config['extension'], (int) $config['umask']);
return new DoctrineCachePool($client);
}
/**
* {@inheritdoc}
*/
protected static function configureOptionResolver(OptionsResolver $resolver)
{
$resolver->setDefaults([
'extension' => FilesystemCache::EXTENSION,
'umask' => '0002',
]);
$resolver->setRequired(['directory']);
$resolver->setAllowedTypes('directory', ['string']);
$resolver->setAllowedTypes('extension', ['string']);
$resolver->setAllowedTypes('umask', ['string', 'int']);
}
}
| php-cache/adapter-bundle | src/Factory/DoctrineFilesystemFactory.php | PHP | mit | 1,340 |
<?php
namespace Abbaye\IndexBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Agences
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="Abbaye\IndexBundle\Entity\AgencesRepository")
*/
class Agences
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="Nom", type="string", length=255)
*/
private $nom;
/**
* @var \DateTime
*
* @ORM\Column(name="Date", type="date")
*/
private $date;
/**
* @var string
*
* @ORM\Column(name="Description", type="text")
*/
private $description;
/**
* @var string
*
* @ORM\Column(name="Tel", type="string", length=255)
*/
private $tel;
/**
* @var string
*
* @ORM\Column(name="Fax", type="string", length=255)
*/
private $fax;
/**
* @var string
*
* @ORM\Column(name="Adresse", type="text", nullable=true)
*/
private $adresse;
/**
* @var string
*
* @ORM\Column(name="Email", type="string", length=255)
*/
private $email;
/**
* @var string
*
* @ORM\Column(name="Permalien", type="string", length=255, unique=true)
*/
private $permalien;
/**
* @var string
*
* @ORM\Column(name="Logo", type="string", length=255)
* @ORM\JoinColumn(nullable=false)
*/
private $logo;
/**
* @ORM\Column(name="Defaut", type="boolean")
*/
private $defaut;
/**
* @ORM\OneToMany(targetEntity="Abbaye\IndexBundle\Entity\Tarifs", mappedBy="agences",cascade={"persist"})
*/
private $tarifs;
private $file;
public function __construct()
{
$this->date = new \Datetime();
$this->defaut = false;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nom
*
* @param string $nom
* @return Agences
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* @return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set date
*
* @param \DateTime $date
* @return Agences
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* @return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* Set description
*
* @param string $description
* @return Agences
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set tel
*
* @param string $tel
* @return Agences
*/
public function setTel($tel)
{
$this->tel = $tel;
return $this;
}
/**
* Get tel
*
* @return string
*/
public function getTel()
{
return $this->tel;
}
/**
* Set fax
*
* @param string $fax
* @return Agences
*/
public function setFax($fax)
{
$this->fax = $fax;
return $this;
}
/**
* Get fax
*
* @return string
*/
public function getFax()
{
return $this->fax;
}
/**
* Set adresse
*
* @param string $adresse
* @return Agences
*/
public function setAdresse($adresse)
{
$this->adresse = $adresse;
return $this;
}
/**
* Get adresse
*
* @return string
*/
public function getAdresse()
{
return $this->adresse;
}
/**
* Set email
*
* @param string $email
* @return Agences
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set permalien
*
* @param string $permalien
* @return Agences
*/
public function setPermalien($permalien)
{
$this->permalien = $permalien;
return $this;
}
/**
* Get permalien
*
* @return string
*/
public function getPermalien()
{
return $this->permalien;
}
/**
* Set logo
*
* @param string $logo
* @return Agences
*/
public function setLogo($logo)
{
$this->logo = $logo;
return $this;
}
/**
* Get logo
*
* @return string
*/
public function getLogo()
{
return $this->logo;
}
/**
* Set defaut
*
* @param boolean $defaut
* @return Agences
*/
public function setDefaut($defaut)
{
$this->defaut = $defaut;
return $this;
}
/**
* Get defaut
*
* @return boolean
*/
public function getDefaut()
{
return $this->defaut;
}
/**
* Add tarifs
*
* @param \Abbaye\IndexBundle\Entity\Tarifs $tarifs
* @return Agences
*/
public function addTarif(\Abbaye\IndexBundle\Entity\Tarifs $tarifs)
{
$this->tarifs[] = $tarifs;
return $this;
}
/**
* Remove tarifs
*
* @param \Abbaye\IndexBundle\Entity\Tarifs $tarifs
*/
public function removeTarif(\Abbaye\IndexBundle\Entity\Tarifs $tarifs)
{
$this->tarifs->removeElement($tarifs);
}
/**
* Get tarifs
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getTarifs()
{
return $this->tarifs;
}
public function setFile($file)
{
$this->file = $file;
return $this;
}
public function getFile()
{
return $this->file;
}
public function upload()
{
// Si jamais il n'y a pas de fichier (champ facultatif)
if (null === $this->file) {
return;
}
// On garde le nom original du fichier de l'internaute
$name = $this->file->getClientOriginalName();
// On déplace le fichier envoyé dans le répertoire de notre choix
$this->file->move($this->getUploadRootDir(), $name);
// On sauvegarde le nom de fichier dans notre attribut $url
$this->logo = $this->getUploadDir().'/'.$name;
}
public function getUploadDir()
{
// On retourne le chemin relatif vers l'image pour un navigateur
return 'uploads/img';
}
protected function getUploadRootDir()
{
// On retourne le chemin relatif vers l'image pour notre code PHP
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
public function translatePermalien()
{
$rendu = $this->nom;
while(preg_match('#(.+) (.+)#i', $rendu))
{
$rendu = preg_replace('#(.+) (.+)#i', '$1-$2', $rendu);
}
while(preg_match('#(.+)[ÈÉÊËèéêë](.+)#i', $rendu))
{
$rendu = preg_replace('#(.+)[ÈÉÊËèéêë](.+)#i', '$1e$2', $rendu);
}
while(preg_match('#(.+)[ÀÁÂÃÄÅàáâãäå](.+)#i', $rendu))
{
$rendu = preg_replace('#(.+)[ÀÁÂÃÄÅàáâãäå](.+)#i', '$1a$2', $rendu);
}
while(preg_match('#(.+)[ÒÓÔÕÖØòóôõöø](.+)#i', $rendu))
{
$rendu = preg_replace('#(.+)[ÒÓÔÕÖØòóôõöø](.+)#i', '$1o$2', $rendu);
}
while(preg_match('#(.+)[Çç](.+)#i', $rendu))
{
$rendu = preg_replace('#(.+)[Çç](.+)#i', '$1c$2', $rendu);
}
while(preg_match('#(.+)[ÌÍÎÏìíîï](.+)#i', $rendu))
{
$rendu = preg_replace('#(.+)[ÌÍÎÏìíîï](.+)#i', '$1i$2', $rendu);
}
while(preg_match('#(.+)[ÙÚÛÜùúûü](.+)#i', $rendu))
{
$rendu = preg_replace('#(.+)[ÙÚÛÜùúûü](.+)#i', '$1u$2', $rendu);
}
while(preg_match('#(.+)[ÿ](.+)#i', $rendu))
{
$rendu = preg_replace('#(.+)[ÿ](.+)#i', '$1y$2', $rendu);
}
while(preg_match('#(.+)[Ññ](.+)#i', $rendu))
{
$rendu = preg_replace('#(.+)[Ññ](.+)#i', '$1n$2', $rendu);
}
while(preg_match('#(.+)\'(.+)#i', $rendu))
{
$rendu = preg_replace('#(.+)\'(.+)#i', '$1-$2', $rendu);
}
while(preg_match('#(.+)°(.+)#i', $rendu))
{
$rendu = preg_replace('#(.+)°(.+)#i', '$1-$2', $rendu);
}
$this->permalien = $rendu;
}
} | EpicKiwi/AutoEcoleDeLabbaye | src/Abbaye/IndexBundle/Entity/Agences.php | PHP | mit | 8,652 |
goog.provide('ol.source.GeoJSON');
goog.require('ol.format.GeoJSON');
goog.require('ol.source.StaticVector');
/**
* @classdesc
* Static vector source in GeoJSON format
*
* @constructor
* @extends {ol.source.StaticVector}
* @fires ol.source.VectorEvent
* @param {olx.source.GeoJSONOptions=} opt_options Options.
* @api
*/
ol.source.GeoJSON = function(opt_options) {
var options = goog.isDef(opt_options) ? opt_options : {};
goog.base(this, {
attributions: options.attributions,
extent: options.extent,
format: new ol.format.GeoJSON({
defaultDataProjection: options.defaultProjection
}),
logo: options.logo,
object: options.object,
projection: options.projection,
text: options.text,
url: options.url,
urls: options.urls
});
};
goog.inherits(ol.source.GeoJSON, ol.source.StaticVector);
| Koriyama-City/papamama | js/v3.0.0/ol/ol/source/geojsonsource.js | JavaScript | mit | 889 |
package main
// list all of the multipels of m below max and returns them on the ret channel
func listMultiples(m, max int, ret chan int) {
if m == 0 {
return
}
count := 0
tmp := 0
for {
tmp = count * m
if tmp >= max {
break
}
count++
ret <- tmp
}
close(ret)
}
// range over each channel until they have been closed. and return the sum of all values returned
func collect(c []chan int) int {
r := make(chan int)
intSet := make(map[int]struct{})
// fan in the recieved values
for i := range c {
go func(f chan int) {
tmp := 0
for tmp = range f {
r <- tmp
}
r <- -1
}(c[i])
}
i := 0
tmp := 0
// sum values recieved on r until the done signal (-1) has been recieved by all
for i < len(c) {
tmp = <-r
if tmp == -1 {
i++
} else {
intSet[tmp] = struct{}{}
}
}
// add up all of the keys in the set
sum := 0
for k, _ := range intSet {
sum += k
}
return sum
}
func main() {
r := []chan int{
make(chan int),
make(chan int),
}
go listMultiples(3, 1000, r[0])
go listMultiples(5, 1000, r[1])
print(collect(r))
}
| eliothedeman/euler | 1/main.go | GO | mit | 1,097 |
/*
Suppose you save $100 each month into a savings account with the annual
interest rate 5%. Thus, the monthly interest rate is 0.05/12 = 0.00417.
After the first month, the value in the account becomes
100 * (1 + 0.00417) = 100.417
After the second month, the value in the account becomes
(100 + 100.417) * (1 + 0.00417) = 201.252
After the third month, the value in the account becomes
(100 * 201.252) * (1 + 0.00417) = 302.507
and so on.
Write a program that prompts the user to enter a monthly saving amount and
displays the account value after the sixth month.
*/
import java.util.Scanner;
public class E2_13 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the monthly saving amount: ");
double monthlySavingAmount = input.nextDouble();
double monthlyInterestRate = 0.05/12;
double accountValue = accountValue(monthlySavingAmount, monthlyInterestRate,
6);
System.out.printf("After the sixth month, the account value is $%.2f\n",
accountValue);
}
private static double accountValue(double savings, double rate, int months) {
double account = 0.0;
for (int i = 0; i < months; i++) {
account = (account + savings) * (1 + rate);
}
return account;
}
}
| maxalthoff/intro-to-java-exercises | 02/E2_13/E2_13.java | Java | mit | 1,311 |
<?php
$home = null;
$application = null;
$employee = null;
$evaluation = null;
$message = null;
switch ($active) {
case 'home':
$home = '-active accent ';
break;
case 'employee':
$employee = '-active accent';
break;
case 'evaluation':
$evaluation = '-active accent';
break;
case 'message':
$message = '-active accent';
break;
default:
# code...
break;
}
?>
<div class="fixed-top">
<nav class="navbar navbar-expand-lg navbar-light bg-light border border-black pt-2 pb-2 pl-5">
<a class="navbar-brand open-sans pl-3 accent f-bold" href="#">
<img src="<?php echo base_url()?>assets/img/brand_logo.png">
Human Resource Management System
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse pr-5" id="navbarNavAltMarkup">
<div class="navbar-nav ml-auto">
<a href="#" class="nav-item nav-link active">
<i class="medium material-icons float-left text-lgray" style="font-size: 2rem;">notifications_none</i>
</a>
<li class="nav-item dropdown mr-1">
<a class="nav-item nav-link active dropdown-toggle" data-toggle="dropdown" href="#">
<img class="responsive-img pr-1" src="<?php echo base_url()?>assets/img/dp.png">
</a>
<!-- dropdown items here -->
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="/me">Profile</a>
<a class="dropdown-item" href="<?php echo base_url('/logout') ?>">Logout</a>
</div>
<!-- end of dropdown -->
</li>
</div>
</div>
</nav>
<ul class="nav navbar-menu shadow-light -twitter pt-2 pb-0 pl-5 m-0">
<li class="item <?php echo $home?>"><a class="link no-deco" href="<?php echo base_url() ?>">Home</a></li>
<!-- <li class="item <?php echo $employee?>"><a class="link no-deco " href='/employee'>Employee</a></li> -->
<li class="nav-item dropdown item <?php echo $employee?>">
<a class="nav-item nav-link active link no-deco" style="padding-top: 15px; padding-bottom: 16px;" data-toggle="dropdown" href="#">
Employee
</a>
<div class="dropdown-menu dropdown-menu-right">
<a class="dropdown-item" href="<?php echo base_url('/preemployment') ?>">Job Postings</a>
<a class="dropdown-item" href="<?php echo base_url('/employee') ?>">Employment</a>
<a class="dropdown-item" href="<?php echo base_url('/postemployment') ?>">Downloadable Resources</a>
</div>
</li>
<li class="item <?php echo $evaluation?>"><a class="link no-deco" href="<?php echo base_url('/evaluation') ?>">Evaluation</a></li>
<li class="item <?php echo $message?>"><a class="link no-deco" href="<?php echo base_url('/message') ?>">Message</a></li>
</ul>
</div>
| alohajaycee/hris_development | application/views/include_navigation.php | PHP | mit | 2,878 |
import React from 'react';
import styled from 'styled-components';
const FooterSection = styled.section`
padding: 0.4em 0em;
text-align: right;
`;
class Footer extends React.Component {
render() {
return <FooterSection>{ this.props.children }</FooterSection>;
}
}
export default Footer | sepro/React-Pomodoro | src/js/components/styled-components/footer.js | JavaScript | mit | 302 |