repo_name
stringlengths 6
115
| branch_name
stringclasses 217
values | path
stringlengths 2
728
| content
stringlengths 1
5.16M
|
|---|---|---|---|
heshmatpour/tamrin2
|
refs/heads/master
|
/lcd.c
|
#include "lcd.h"
#include "stm32f4xx_hal.h"
#define D0_PIN_Start 1
#define LCD_DATA_MASK (LCD_D7|LCD_D6|LCD_D5|LCD_D4)
static GPIO_TypeDef* PORT_LCD;
static uint8_t state;
static uint16_t D[8];
static GPIO_TypeDef* port_EN;
static GPIO_TypeDef* port_RS;
static uint16_t PIN_RS, PIN_EN;
void lcd_init(lcd_t *lcd)
{
switch(mode)
{
case 1:
for(uint8_t i=0 ;i<8 ;i=i+1 )
{
D[i]= lcd.data_pins[i];
}
break;
default:
for(uint8_t i=0 ;i<4 ;i=i+1 )
{
D[i]= lcd.data_pins[i];
}
break;}
PIN_EN=lcd.en_pin;
PIN_RS=lcd.rs_pin;
state=mode;
}
void lcd_putchar(lcd_t *lcd, uint8_t character)
{
unsigned char temp=0;
unsigned int temp1=0;
temp=character;
temp=(temp>>4)&0x0F;
temp1=(temp<<20)&LCD_DATA_MASK;
delay(10);
}
void lcd_puts(lcd_t *lcd,char *str)
{
HAL_Delay(T);
while(*str != 0)
{
lcd_putchar(lcd , *str);
str++;
}
}
void lcd_clear (lcd_t *lcd)
{
HAL_Delay(T);
HAL_GPIO_WritePin(GPIOB,(1<<rs_pin),GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOD,(0xFF<<D0_PIN_Start),GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOD,(0x01<<D0_PIN_Start),GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOB,(1<<en_pin),GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOB,(1<<en_pin),GPIO_PIN_RESET);
}
void lcd_set_curser(lcd_t *lcd, uint16_t row, uint16_t col)
{
uint16_t maskData;
maskData = (col-1)&0x0F;
if(row==1)
{
maskData |= (0x80);
write(lcd ,maskData);
}
else
{
maskData |= (0xc0);
write(lcd ,maskData);
}
}
|
kswgit/ctfs
|
refs/heads/master
|
/0ctf2017/pages.py
|
from pwn import *
import time
context.update(arch='x86', bits=64)
iteration = 0x1000
cache_cycle = 0x10000000
shellcode = asm('''
_start:
mov rdi, 0x200000000
mov rsi, 0x300000000
mov rbp, 0
loop_start:
rdtsc
shl rdx, 32
or rax, rdx
push rax
mov rax, rdi
mov rdx, %d
a:
mov rcx, 0x1000
a2:
prefetcht1 [rax+rcx]
loop a2
dec edx
cmp edx, 0
ja a
b:
rdtsc
shl rdx, 32
or rax, rdx
pop rbx
sub rax, rbx
cmp rax, %d
jb exists
mov byte ptr [rsi], 1
jmp next
exists:
mov byte ptr [rsi], 0
next:
inc rsi
inc rbp
add rdi, 0x2000
cmp rbp, 64
jne loop_start
end:
int3
''' % (iteration, cache_cycle))
HOST, PORT = '0.0.0.0', 31337
HOST, PORT = '202.120.7.198', 13579
r = remote(HOST, PORT)
p = time.time()
r.send(p32(len(shellcode)) + shellcode)
print r.recvall()
print time.time() - p
|
kaedelulu/U10316015_HW4_11_10
|
refs/heads/master
|
/TestStack.java
|
/**
* Name : 呂芝瑩
* ID : U10316015
* EX : 11.10
*/
import java.util.Scanner;
public class TestStack {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
MyStack stack = new MyStack(); //invoke stack
for ( int i = 0 ; i < 5 ; i++ ){
stack.push( input.nextLine() );
}
System.out.println(stack.getSize() + " strings are: ");
while (!stack.isEmpty())
System.out.println(stack.pop());
}
}
|
veralindstrom/clara
|
refs/heads/master
|
/clara.js
|
$('#login').click(function() {
window.location.href='clara2.html';
});
var username = document.getElementById("username");
localStorage.setItem("username", username);
// Retrieve
document.getElementById("valkommen").innerHTML = "Vlkommen " + username;
|
adamwiguna/tugas1
|
refs/heads/master
|
/tugas.js
|
window.onload = function (event) {
var wrapIcon = document.querySelector("#wrapicon");
var page = 1;
var limit = 3;
var url = "https://jsonplaceholder.typicode.com/posts";
var serverUrl = url + '?_page=' + page + '&_limit=' + limit;
fetch(serverUrl)
.then(
function (resp) {
return resp.json();
}
)
.then(
function (data) {
//console.log(data);
data.forEach(function (val, index) {
//console.log(val);
var div = document.createElement('div');
div.className = "icon-item";
var blogTitle = document.createElement('h3');
var detail = document.createElement('a');
detail.href = 'detail.html';
detail.innerHTML = 'Detail';
var blogBody = document.createElement('p');
blogTitle.name = "title";
blogTitle.innerHTML = val.title;
blogTitle.style.height = "100px";
blogBody.innerText = val.body;
div.appendChild(blogTitle);
div.appendChild(blogBody);
wrapIcon.appendChild(div);
});
});
function getBlogs(url, page = 1, limit = 3) {
console.log('ambil data...')
var serverUrl = url + '?_page=' + page + '&_limit=' + limit;
fetch(serverUrl)
.then(
function (resp) {
return resp.json();
}
)
.then(
function (data) {
//console.log(data);
data.forEach(function (val, index) {
//console.log(val);
var blogTitle = document.createElement('h3');
var detail = document.createElement('a');
detail.href = 'detail.html';
detail.innerHTML = 'Detail';
var blogBody = document.createElement('p');
blogTitle.name = "title";
blogTitle.innerHTML = '<a href="detail.html?id=' + val.id + '">' + val.title + '</a>';
blogBody.innerText = val.body;
wrapper.appendChild(blogTitle);
wrapper.appendChild(blogBody);
});
//display load more
loadmore.style.display = 'block';
});
//display load more
loadmore.style.display = 'block';
}
function getDetail() {
}
var contactForm = document.querySelector('#contactform')
contactForm.addEventListener("submit", function (event) {
console.log('form submitted');
event.preventDefault();
var formName = document.querySelector('#form-name');
var formEmail = document.querySelector('#form-email');
var formMessage = document.querySelector('#form-message');
var formData = {
name: formName.value,
email: formEmail.value,
message: formMessage.value,
}
//console.log(formName.value);
fetch('http://localhost:3000/contacts', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
})
.then(function (resp) {
return resp.json();
})
.then(function (data) {
//succesfully submitted
console.log(data);
})
.catch(function (error) {
//something error happened
console.error(error);
});
});
console.log('selesai');
}
|
MissAle17/dsc-1-05-06-selecting-data-lab-online-ds-sp-000
|
refs/heads/master
|
/insert.sql
|
INSERT INTO planets (name, color, num_of_moons, mass, rings)
VALUES ('Mercury', 'gray',0,0.55,1),
('Venus', 'yellow',0,0.82,1),
('Earth','blue',1,1.00,1),
('Mars','red',2,0.11,1),
('Jupiter','orange',53,317.90,1),
('Saturn','hazel',62,95.19,0),
('Uranus','light blue',27,14.54,0),
('Neptune','dark blue',14,17.15,0),
('Pluto','brown',5,0.003,1);
|
homka506/digitalproducts
|
refs/heads/master
|
/src/assets/js/app.js
|
import $ from 'jquery';
import 'what-input';
// Foundation JS relies on a global varaible. In ES6, all imports are hoisted
// to the top of the file so if we used`import` to import Foundation,
// it would execute earlier than we have assigned the global variable.
// This is why we have to use CommonJS require() here since it doesn't
// have the hoisting behavior.
window.jQuery = $;
// require('foundation-sites');
// If you want to pick and choose which modules to include, comment out the above and uncomment
// the line below
import './lib/foundation-explicit-pieces';
import './lib/slick.min.js';
let worksSlider = $(".ba-slider__works");
worksSlider.slick({
ainfinite: false,
dots: true,
arrows:true,
prevArrow: worksSlider.find('[data-prev]'),
nextArrow: worksSlider.find('[data-next]')
});
$(document).foundation();
function baMap() {
//create map and asign it to the baMap var
let mapCenter = {
lat: 40.678177,
lng: -73.944160
};
let baMap = new google.maps.Map(document.getElementById('ba-map'), {
center: mapCenter,
zoom: 12,
icon: 'img/marker.svg'
});
// The marker, positioned in mapcenter
let cities = {
rome: {
lat: 41.902782,
lng: 12.496365
},
paris: {
lat: 48.856613,
lng: 2.352222
},
madrid: {
lat: 40.416775,
lng: -3.703790
},
}
let mapMarkers = [];
for (let key in cities) {
var marker = new google.maps.Marker({
position: mapCenter,
map: baMap,
icon: 'img/marker.svg'
});
mapMarkers[key] = marker; //save markers in object
}
//on select city
$('#city-select').on('change', function (e) {
baMap.panTo(cities[this.value]);
});
} // function ba-map
$(document).ready(function (e) {
baMap();
})();
let teamSlider = $('.ba-team-slider');
teamSlider.slick({
centerPadding: '60px',
slidesToShow: 1,
ainfinite: false,
dots: true,
prevArrow: teamSlider.find('[data-prev]'),
nextArrow: teamSlider.find('[data-next]'),
responsive: [
{
breakpoint: 768,
settings: {
arrows: true,
centerMode: true,
centerPadding: '40px',
slidesToShow: 3
}
},
{
breakpoint: 480,
settings: {
arrows: true,
centerMode: true,
centerPadding: '40px',
slidesToShow: 1
}
}
]
});
|
pablor0mero/Placester_Test_Pablo_Romero
|
refs/heads/master
|
/main.py
|
# For this solution I'm using TextBlob, using it's integration with WordNet.
from textblob import TextBlob
from textblob import Word
from textblob.wordnet import VERB
import nltk
import os
import sys
import re
import json
results = { "results" : [] }
#Override NLTK data path to use the one I uploaded in the folder
dir_path = os.path.dirname(os.path.realpath(__file__))
nltk_path = dir_path + os.path.sep + "nltk_data"
nltk.data.path= [nltk_path]
#Text to analyze
TEXT = """
Take this paragraph of text and return an alphabetized list of ALL unique words. A unique word is any form of a word often communicated
with essentially the same meaning. For example,
fish and fishes could be defined as a unique word by using their stem fish. For each unique word found in this entire paragraph,
determine the how many times the word appears in total.
Also, provide an analysis of what sentence index position or positions the word is found.
The following words should not be included in your analysis or result set: "a", "the", "and", "of", "in", "be", "also" and "as".
Your final result MUST be displayed in a readable console output in the same format as the JSON sample object shown below.
"""
TEXT = TEXT.lower()
WORDS_NOT_TO_CONSIDER = ["a", "the", "and", "of", "in", "be", "also", "as"]
nlpText= TextBlob(TEXT)
def getSentenceIndexesForWord(word, sentences):
sentenceIndexes = []
for index, sentence in enumerate(sentences):
count = sum(1 for _ in re.finditer(r'\b%s\b' % re.escape(word.lower()), sentence))
if count > 0:
sentenceIndexes.append(index)
return sentenceIndexes
#1: Get all words, excluding repetitions and all the sentences in the text
nlpTextWords = sorted(set(nlpText.words))
nlpTextSentences = nlpText.raw_sentences
#2 Get results
synonymsList = []
allreadyReadWords = []
for word in nlpTextWords:
if word not in WORDS_NOT_TO_CONSIDER and word not in allreadyReadWords:
timesInText = nlpText.word_counts[word]
#Get sentence indexes where the word can be found
sentenceIndexes = getSentenceIndexesForWord(word, nlpTextSentences)
#Check for synonyms
for word2 in nlpTextWords:
if word2 not in WORDS_NOT_TO_CONSIDER and ( word.lower() != word2.lower() and len(list(set(word.synsets) & set(word2.synsets))) > 0 ):
#If I find a synonym of the word I add it to the list of words allready read and add the times that synonym appeared in the text to the total
#count of the unique word and the corresponding sentence indexes
allreadyReadWords.append(word2)
timesInText = timesInText + nlpText.word_counts[word2]
sentenceIndexes += getSentenceIndexesForWord(word2,nlpTextSentences)
allreadyReadWords.append(word)
results["results"].append({"word" : word.lemmatize(), #I return the lemma of the word because TextBlob's stems seem to be wrong for certain words
"total-occurances": timesInText,
"sentence-indexes": sorted(set(sentenceIndexes))})
print(json.dumps(results, indent=4))
|
phu-bui/Nhan_dien_bien_bao_giao_thong
|
refs/heads/master
|
/main.py
|
import tkinter as tk
from tkinter import filedialog
from tkinter import *
from PIL import Image, ImageTk
import numpy
from keras.models import load_model
model = load_model('BienBao.h5')
class_name = {
1:'Speed limit (20km/h)',
2:'Speed limit (30km/h)',
3:'Speed limit (50km/h)',
4:'Speed limit (60km/h)',
5:'Speed limit (70km/h)',
6:'Speed limit (80km/h)',
7:'End of speed limit (80km/h)',
8:'Speed limit (100km/h)',
9:'Speed limit (120km/h)',
10:'No passing',
11:'No passing veh over 3.5 tons',
12:'Right-of-way at intersection',
13:'Priority road',
14:'Yield',
15:'Stop',
16:'No vehicles',
17:'Veh > 3.5 tons prohibited',
18:'No entry',
19:'General caution',
20:'Dangerous curve left',
21:'Dangerous curve right',
22:'Double curve',
23:'Bumpy road',
24:'Slippery road',
25:'Road narrows on the right',
26:'Road work',
27:'Traffic signals',
28:'Pedestrians',
29:'Children crossing',
30:'Bicycles crossing',
31:'Beware of ice/snow',
32:'Wild animals crossing',
33:'End speed + passing limits',
34:'Turn right ahead',
35:'Turn left ahead',
36:'Ahead only',
37:'Go straight or right',
38:'Go straight or left',
39:'Keep right',
40:'Keep left',
41:'Roundabout mandatory',
42:'End of no passing',
43:'End no passing veh > 3.5 tons'
}
top=tk.Tk()
top.geometry('800x600')
top.title('Phan loai bien bao giao thong')
top.configure(background='#CDCDCD')
label = Label(top, background = '#CDCDCD', font=('arial',15,'bold'))
label.place(x=0, y=0, relwidth = 1, relheight = 1)
sign_image = Label(top)
def classify(file_path):
global label_packed
image = Image.open(file_path)
image = image.resize((30, 30))
image = numpy.expand_dims(image, axis=0)
image = numpy.array(image)
print(image.shape)
pred = model.predict_classes([image])[0]
sign = class_name[pred+1]
print(sign)
label.configure(foreground = '#011638', text = sign)
def show_classify_button(file_path):
classify_button = Button(top,text='Phan loai', command = lambda : classify(file_path), padx=10, pady=5)
classify_button.configure(background='GREEN', foreground = 'white', font = ('arial', 10, 'bold'))
classify_button.place(relx = 0.79, rely = 0.46)
def upload_image():
try:
file_path = filedialog.askopenfilename()
uploaded = Image.open(file_path)
uploaded.thumbnail(((top.winfo_width()/2.25),
(top.winfo_height()/2.25)))
im = ImageTk.PhotoImage(uploaded)
sign_image.configure(image= im)
sign_image.image = im
label.configure(text='')
show_classify_button(file_path)
except:
pass
upload = Button(top, text='Upload an image', command=upload_image, padx = 10, pady = 5)
upload.configure(background='#364156', foreground = 'white', font = ('arial', 10, 'bold'))
upload.pack(side = BOTTOM, pady = 50)
sign_image.pack(side=BOTTOM, expand = True)
label.pack(side = BOTTOM, expand = True)
heading = Label(top, text = 'Bien bao giao thong cua ban', pady = 20, font = ('arial', 20, 'bold'))
heading.configure(background = '#CDCDCD', foreground = '#364156')
heading.pack()
top.mainloop()
|
jaspereel/vcard
|
refs/heads/master
|
/api.php
|
<?php
session_start();
$_SESSION['name']=$_POST['name'];
$_SESSION['position']=$_POST['position'];
$_SESSION['skill']=$_POST['skill'];
$_SESSION['mail']=$_POST['mail'];
$_SESSION['mobile']=$_POST['mobile'];
$_SESSION['module']=$_POST['module'];
if (!empty($_FILES)) {
copy($_FILES['photo']['tmp_name'], "photo/". $_FILES['photo']['name']);
}
$_SESSION['pname']=$_FILES['photo']['name'];
header('location:preview.php');
?>
|
jaspereel/vcard
|
refs/heads/master
|
/preview.php
|
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Vcard產生器-Preview</title>
<link rel=stylesheet href="css/<?= $_SESSION['module'] ?>.css">
<!--font-awsome -->
<link rel="stylesheet" href="css/all.min.css" />
</head>
<body>
<div id="container">
<div id="left">
<div class="photo">
<?php echo '<img src="photo/' . $_SESSION['pname'] . '"class="photo_cir">'; ?>
<div class="name"><?= $_SESSION['name'] ?></div>
</div>
</div>
<div id="right">
<div class="title"><i class="fas fa-map-marker"></i> 職稱 Position</div>
<div class="itr"><?= $_SESSION['position'] ?></div>
<div class="title"><i class="fas fa-briefcase"></i> 技能 Skill</div>
<div class="itr"><?= $_SESSION['skill'] ?></div>
<div class="title"><i class="fas fa-envelope"></i> 電子信箱 E-mail</div>
<div class="itr"><?= $_SESSION['mail'] ?></div>
<div class="title"><i class="fas fa-mobile-alt"></i> 手機 Mobile</div>
<div class="itr"><?= $_SESSION['mobile'] ?></div>
</div>
</div>
<br>
<button onclick="window.history.go(-1)" style="display:block; margin:20px auto">回頁面</button>
</body>
</html>
|
leenismail/GPA-Calculator-
|
refs/heads/master
|
/cli/GPA.java
|
import java.util.Scanner;
public class GPA {
public static void main(String[] args) {
int course;
int grade;
int CourseSum=0;//Sum of all courses
double CmltivSum=0;//Cumulative grades sum
Scanner s = new Scanner(System.in);
System.out.println("Please enter number of semesters:");
int semester = s.nextInt();
for (int j = 0; j < semester; j++) {
double SmstrSum=0;//Sum of grades in each semester
System.out.println("For semester number "+(j+1)+":");
System.out.println(" Enter the number of passed courses:");
course = s.nextInt();
CourseSum=CourseSum+course;
for (int i = 0; i <course; i++) {
System.out.println(" Enter grade number" +(i+1)+ ":");
grade = s.nextInt();
if (grade>=35) {
CmltivSum=CmltivSum+grade;
SmstrSum=SmstrSum+grade;
}
else {
System.out.println(" Invalid Input!, Please enter a mark above 35.");
i=i-1;
}
}
double totalSem=(((SmstrSum/course)/100)*4);
System.out.println("\n Semester GPA: "+totalSem+"/4\n");
}
double totalCum=(((CmltivSum/CourseSum)/100)*4);
System.out.println(" Cumulative GPA: "+totalCum+"/4");
}
}
|
drenovac/superail
|
refs/heads/main
|
/config/routes.rb
|
Rails.application.routes.draw do
root 'static_public#landing_page'
# get 'static_public/landing_page' # this is the generic form
# get 'static_public/privacy' # convert this to more sensible looking paths
get 'privacy', to: 'static_public#privacy'
# get 'static_public/terms'
get 'terms', to: 'static_public#terms'
end
|
josemiche11/reversebycondition
|
refs/heads/master
|
/reversebycondition.py
|
'''
Input- zoho123
Output- ohoz123
'''
char= input("Enter the string: ")
char2= list(char)
num= "1234567890"
list1= [0]*len(char)
list2=[]
for i in range(len(char)):
if char2[i] not in num:
list2.append( char2.index( char2[i]))
char2[i]= "*"
list2.reverse()
k=0
for j in range( len(char) ):
if j in list2:
list1[j]= char[list2[k]]
k= k+1
else:
list1[j]= char[j]
ch=""
for l in range(len(list1)):
ch= ch+ list1[l]
print(ch)
|
MoisesWillianCorreia/calculadora
|
refs/heads/main
|
/atividade 02/parte.01.html/01.js
|
var div = document.getElementById("q1");
var input = document.createElement("input");
var input2 = document.createElement("input");
var buttom = document.createElement("buttom");
var p = document.createElement("p");
input.setAttribute("id","valorMinimo");
input.setAttribute("type","number");
input2.setAttribute("id","valorMaximo");
input2.setAttribute("type","number");
buttom.setAttribute("id","buttom");
buttom.setAttribute("content","clique aqui");
p.setAttribute("id","resultado");
div.appendChild(input);
div.appendChild(input2);
div.appendChild(buttom);
div.appendChild(p);
buttom.addEventListener("click",multiplicar);
function multiplicar()
{
console.log("entrou")
// var imputMinimo = document.getElementById("valorMinimo");
// var imputMaximo = document.getElementById("valorMaximo");
var valorMinimo = document.getElementById("valorMinimo").value;
var valorMaximo = document.getElementById("valorMaximo").value;
var n1 = parseInt(valorMinimo)
var n2 = parseInt(valorMaximo)
console.log(n1);
console.log(n2);
for (let index = n1; index <= n2; index++) {
if (index %2 == 0 && index %3 == 0 ) {
console.log(index + " e multiplo de 2 e 3")
}
}
}
function sortear()
{
var min= imputMinimo.getElementById("minimo").value;
var max= imputMaximo.getElementById("maximo").value;
var sorteio = Math.floor(Math.random() * (max - min) + min);
document.getElementById("resultado").innerHTML = sorteio;
}
|
brapse/reindr
|
refs/heads/master
|
/src/reindr.js
|
//##########################################
//
// Reindr
//
// Html generation helpers
// By: Sean Braithwaite
//
// NOTE: won't work in IE (js 1.6 dependencies)
// Try not to depend on jquery for now
Array.prototype.each = function(func){
for(var i=0; i < this.length; i++){
func(this[i]);
}
return this;
};
Function.prototype.args = function(){
var sig = this.toString().match(/function \((.*)\)/)[1];
return sig.split(', ');
}
Function.prototype.body = function(){
return this.toString().replace(/\n/g, "").match(/{(.*)}/)[1];
}
// #########################
//
var reindr = function(t_func){
var object_size_count = function(obj){
var count = 0;
for(var prop in obj){
if(obj.hasOwnProperty(prop)){
count++;
}
}
return count;
};
// #######################
var tag_function = function(tag, attrs, content){
var tag_attributes = [];
if(typeof(attrs) == 'object'){
for(var prop in attrs){
if(attrs.hasOwnProperty(prop)){
tag_attributes.push(prop + '="' + attrs[prop] + '"');
}
}
}
html = '';
html += '<' + tag;
if(tag_attributes.length > 0){
html += ' ' + tag_attributes.join(' ');
}
if(typeof(content) == 'string' && content.length > 0){
html += '>' + content + '</' + tag + '>';
}else{
html += '/>'
}
return html;
};
// #######################
var tag_function_generator = function(tag){
return function(attrs, content){
if(object_size_count(attrs) > 0){
return function(a, c){
return tag_function(tag, attrs, c);
}
}else{
return tag_function(tag, attrs, content);
}
}
};
// #######################
var render = function(node){
if(typeof(node) == "undefined" || !node.length || node.length == 0){
return '';
}else if(typeof(node) == "string"){
return node;
}else if(typeof(node[0]) == "function"){
//an element with children
var tag = node.shift();
return tag({}, render(node));
}else{
//children
return node.map(function(el){ return render(el) }).join("\n");
}
}
var body = t_func.body();
var supported_tags = ['div', 'p', 'span', 'a', 'ul', 'li', 'table', 'tr', 'td'];
var wrapper = new Function('div', 'p', 'span', 'a', 'ul', 'li', 'table', 'tr', 'td', body);
var tag_functions = supported_tags.map(function(tag){
return tag_function_generator(tag);
});
var stack = wrapper.apply(null, tag_functions);
return render(stack);
};
|
brapse/reindr
|
refs/heads/master
|
/README.markdown
|
Reindr: Monadic html generation from javascript
========================
Generate html with a chain of functions, similar to how jquery does selectors.
The Reindr() (shortcutted as $R()) function will generate a monad that acts as a chain of nested html elements.
Calling render() on a chain will output html.
<pre><code>
var r = $R().div.span.text("Hello World").render();
should give you <div><span>Hello Word</span></div>
</code></pre>
Experimental. Undocumented, only slightly tested.
|
guillelo11/AngularQuiz
|
refs/heads/master
|
/AngularQuiz.js
|
angular.module('appPreguntas', [])
.controller('controladorPreguntas', ['$scope', function ($scope) {
$scope.questions = [
{
id : 1,
text:'¿Cuál es la capital de Australia?',
validAnswer : 3,
userAnswer : null,
status : '',
answers: [
{id : 1, text : 'Sydney'},
{id : 2, text : 'Melbourne'},
{id : 3, text : 'Canberra'}
]
},
{
id : 2,
text:'¿Cuál es el río más largo de Europa?',
validAnswer : 1,
userAnswer : null,
status : '',
answers: [
{id : 1, text : 'Volga'},
{id : 2, text : 'Danubio'},
{id : 3, text : 'Ebro'},
{id : 4, text : 'Sena'}
]
},
{
id : 3,
text:'¿Cuál fue la capital de Alemania Occidental?',
validAnswer : 4,
userAnswer : null,
status : '',
answers: [
{id : 1, text : 'Berlin'},
{id : 2, text : 'München'},
{id : 3, text : 'Köln'},
{id : 4, text : 'Bonn'},
{id : 5, text : 'Frankfurt'}
]
},
{
id : 4,
text:'¿Cuál es la capital de Noruega?',
validAnswer : 3,
userAnswer : null,
status : '',
answers: [
{id : 1, text : 'Bergen'},
{id : 2, text : 'Malmö'},
{id : 3, text : 'Oslo'},
{id : 4, text : 'Hamburg'}
]
},
{
id : 5,
text:'¿Qué países tienen frontera con Luxemburgo?',
validAnswer : [1, 2, 4],
userAnswer : [],
status : '',
answers: [
{id : 1, text : 'Francia'},
{id : 2, text : 'Alemania'},
{id : 3, text : 'Holanda'},
{id : 4, text : 'Bélgica'}
]
},
{
id : 6,
text:'¿Qué rio pasa por Berlin?',
validAnswer : 2,
userAnswer : null,
status : '',
answers: [
{id : 1, text : 'Rhein'},
{id : 2, text : 'Spree'},
{id : 3, text : 'Elbe'}
]
},
{
id : 7,
text:'¿Cuál es la capital de Slovakia?',
validAnswer : 4,
userAnswer : null,
status : '',
answers: [
{id : 1, text : 'Skopje'},
{id : 2, text : 'Ljubljana'},
{id : 3, text : 'Bucarest'},
{id : 4, text : 'Bratislava'}
]
},
{
id : 8,
text:'¿Qué paises pertenecen a la UE?',
validAnswer : [2, 4, 5],
userAnswer : [],
status : '',
answers: [
{id : 1, text : 'Suiza'},
{id : 2, text : 'Suecia'},
{id : 3, text : 'Noruega'},
{id : 4, text : 'Estonia'},
{id : 5, text : 'Malta'}
]
}
];
// Estatus del usuario
$scope.userStatus = '';
// Número de respuestas acertadas
$scope.validAnswers = 0;
// Total de respuestas
$scope.totalAnswers = 0;
// Valida las preguntas de una sola respuesta
$scope.validate = function (question) {
if (question.validAnswer == question.userAnswer) {
$scope.validAnswers ++;
question.status = 'ok';
// Cuando se acierta la pregunta añadir la clase para que se vea el acierto
$('.question-' + question.id).removeClass('panel-default').addClass('panel-success');
} else {
if (question.status == 'ok' && $scope.validAnswers > 0) {
$scope.validAnswers --;
}
question.status = 'error';
// Cuando se falla añadir la clase para mostrar que se ha fallado
$('.question-' + question.id).removeClass('panel-default').addClass('panel-danger');
}
$scope.totalAnswers ++;
// Deshabilitar para que no se pueda cambiar la respuesta
$('.question-' + question.id).attr('disabled', true);
updateUserStatus();
};
//Funcion que cuando se click en un checbox añade o quita respuestas a userAnswer
$scope.toggleSelection = function toggleSelection(question, answerId) {
//Comprueba el indice de la respuesta recien marcada (tanto para activar como para desactivar) (answerId) dentro del array de respuestas seleccionadas por el usuario para esa pregunta (userAnswer[] para question)
var idx = question.userAnswer.indexOf(answerId);
// Si esa respuesta ya esta dentro, entonces es que acaba de desactivarla y la quita del array de respuestas
if (idx > -1) {
question.userAnswer.splice(idx, 1);
}
// Si no esta dentro de userAnswer pues entonces la mete
else {
question.userAnswer.push(answerId);
}
};
// Valida las preguntas con múltiples respuestas
$scope.validateMultiple = function (question){
//Compara si los dos arrays validAnswer y userAnswer son iguales
//Hay que ordenar los arrays para realizar bien la comparacion
if(angular.equals(question.validAnswer.sort(), question.userAnswer.sort())){
//Una respuesta acertada
$scope.validAnswers++;
question.status = 'ok';
// Al igual que para validar una sola pregunta se añade la clase para mostrar acierto
$('.question-' + question.id).removeClass('panel-default').addClass('panel-success');
}else {
if (question.status == 'ok' && $scope.validAnswers > 0) {
$scope.validAnswers--;
}
$('.question-' + question.id).removeClass('panel-default').addClass('panel-danger');
question.status = 'error';
}
$scope.totalAnswers ++;
// Deshabilitar para que no se pueda cambiar la respuesta
$('.question-' + question.id).attr('disabled', true);
updateUserStatus();
};
function updateUserStatus() {
var avgValidAnswers = ($scope.validAnswers / $scope.questions.length) * 100;
if (avgValidAnswers === 0) {
$scope.userStatus = 'Muy mal!';
} else if (avgValidAnswers === 100) {
$scope.userStatus = 'Enhorabuena. Eres un crack!';
} else {
$scope.userStatus = 'Tienes que mejorar';
}
// Cuando se han respondido todas las preguntas se muestra un mensaje
if($scope.totalAnswers === $scope.questions.length) {
$('#resultado').modal('show');
}
}
}]);
|
guillelo11/AngularQuiz
|
refs/heads/master
|
/README.md
|
# AngularQuiz
AngularQuiz is a small project I made for class to learn AngularJS
|
GabinCleaver/Auto_Discord_Bump
|
refs/heads/main
|
/README.md
|
# Auto Discord Bump
❗ Un auto bump pour discord totalement fait en Python par moi, et en français.
💖 Enjoy !
🎫 Mon Discord: Gabin#7955

|
GabinCleaver/Auto_Discord_Bump
|
refs/heads/main
|
/autobump.py
|
import requests
import time
token = "TOKEN"
headers = {
'User-Agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7',
'Authorization' : token
}
id = input(f"[?] Salon ID: ")
print("")
while True:
requests.post(
f"https://discord.com/api/channels/{id}/messages",
headers = headers,
json = {"content" : "!d bump"}
)
print("[+] Serveur Bumpé")
time.sleep(121 * 60)
|
Mucheap/Autoinsta
|
refs/heads/main
|
/config.php
|
<?php
/*
By @Mucheap
GitHub : https://github.com/Mucheap/Autoinsta.git
Email : appscomposer@gmail.com
*/
$username = 'INSTAGRAM_USERNAME';
$password = 'INSTAGRAM_PASSWORD';
$image_description = 'Your Description Here ...';
$imgurl = 'https://picsum.photos/700/?random';
$photoFilename = "img/rand.jpg";
|
Ashutosh-Choubey/RBA-MobileApp
|
refs/heads/master
|
/android/app/src/main/kotlin/com/example/RBA/MainActivity.kt
|
package com.example.RBA
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
|
Lasyin/batch-resize
|
refs/heads/master
|
/batch_resize.py
|
import os
import sys
import argparse
from PIL import Image # From Pillow (pip install Pillow)
def resize_photos(dir, new_x, new_y, scale):
if(not os.path.exists(dir)):
# if not in full path format (/usrers/user/....)
# check if path is in local format (folder is in current working directory)
if(not os.path.exists(os.path.join(os.getcwd(), dir))):
print(dir + " does not exist.")
exit()
else:
# path is not a full path, but folder exists in current working directory
# convert path to full path
dir = os.path.join(os.getcwd(), dir)
i = 1 # image counter for print statements
for f in os.listdir(dir):
if(not f.startswith('.') and '.' in f):
# accepted image types. add more types if you need to support them!
accepted_types = ["jpg", "png", "bmp"]
if(f[-3:].lower() in accepted_types):
# checks last 3 letters of file name to check file type (png, jpg, bmp...)
# TODO: need to handle filetypes of more than 3 letters (for example, jpeg)
path = os.path.join(dir, f)
img = Image.open(path)
if(scale > 0):
w, h = img.size
newIm = img.resize((w*scale, h*scale))
else:
newIm = img.resize((new_x, new_y))
newIm.save(path)
print("Image #" + str(i) + " finsihed resizing: " + path)
i=i+1
else:
print(f + " of type: " + f[-3:].lower() + " is not an accepted file type. Skipping.")
print("ALL DONE :) Resized: " + str(i) + " photos")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-d", "-directory", help="(String) Specify the folder path of images to resize")
parser.add_argument("-s", "-size", help="(Integer) New pixel value of both width and height. To specify width and height seperately, use -x and -y.")
parser.add_argument("-x", "-width", help="(Integer) New pixel value of width")
parser.add_argument("-y", "-height", help="(Integer) New pixel value of height")
parser.add_argument("-t", "-scale", help="(Integer) Scales pixel sizes.")
args = parser.parse_args()
if(not args.d or ((not args.s) and (not args.x and not args.y) and (not args.t))):
print("You have error(s)...\n")
if(not args.d):
print("+ DIRECTORY value missing Please provide a path to the folder of images using the argument '-d'\n")
if((not args.s) and (not args.x or not args.y) and (not args.t)):
print("+ SIZE value(s) missing! Please provide a new pixel size. Do this by specifying -s (width and height) OR -x (width) and -y (height) values OR -t (scale) value")
exit()
x = 0
y = 0
scale = 0
if(args.s):
x = int(args.s)
y = int(args.s)
elif(args.x and args.y):
x = int(args.x)
y = int(args.y)
elif(args.t):
scale = int(args.t)
print("Resizing all photos in: " + args.d + " to size: " + str(x)+"px,"+str(y)+"px")
resize_photos(args.d, x, y, scale)
|
Lasyin/batch-resize
|
refs/heads/master
|
/README.md
|
# batch-resize
Python script to resize every image in a folder to a specified size.
# Arguments
<pre>
-h or -help
- List arguments and their meanings
-s or -size
- New pixel value of both width and height.
-x or -width
- New pixel value of width
-y or -height
- New pixel value of height
-t or -scale
- Scales pixel sizes
</pre>
<hr/>
# Example Usage
<pre>
python batch_resize.py -d folder_name -s 128
-> Resizes all images in 'folder_name' to 128x128px
python batch_resize.py -d full/path/to/image_folder -x 128 -y 256
-> Resizes all images in 'image_folder' (listed as a full path, do this if you're not in the current working directory) to 128x256px
python batch_resize.py -d folder_name -t 2
-> Resizes all images in 'folder_name' to twice their original size
</pre>
<hr />
## Accepted Image Types:
<pre>
- Jpg, Png, Bmp (more can easily be added by editing the 'accepted_types' list in the python file)
</pre>
<hr />
# Dependencies
<pre>
- Pillow, a fork of PIL.
- Download from pip:
- pip install Pillow
- Link to their Github:
- https://github.com/python-pillow/Pillow
</pre>
|
kesamercy/diving-Competition-project
|
refs/heads/master
|
/README.md
|
# diving-Competition-project
Program to calculate score for a diver based on 7 judges
Problem Statement
Create a class that describes one dive in a competition in the sport of diving.
A dive has a competitor name and a competitor number associated with it.
The dive also has a degree of difficulty and a score from each of the seven judges.
Each score awarded is between 0 and 10, where each score may be a floating-point value.
The highest and lowest scores are thrown out and the remaining scores are added together.
The sum is then multiplied by the degree of difficulty for that dive.
The degree of difficulty ranges from 1.2 to 3.8 points.
The total is then multiplied by 0.6 to determine the diver’s score.
The class must include the appropriate methods to support object oriented programming as well as the following problem specific methods:
• Class for diving competition.
• Declare Attributes
• Initialize using a Constructor
• Use Methods
• Set methods
• Get methods
• Print data
• Method for Competitor name and competitor number
• The Degree of difficulty is 1.2 – 3.8
• Score from judges is 0 and 10 double
• Take out the highest score
• Take out the lowest score
• Add the rest
• Multiply the sum by the degree of difficulty
• Total is multipled by 0.6 to determine divers score
• A method name inputValidScore that inputs one valid score for one judge for one diver.
• A method named inputAllScores that creates an array to store the scores for all judges for the diver. This method will fill the array with a valid score from each judge.
• A method named inputValidDegreeOfDifficulty that inputs a valid degree of difficulty for the dive.
• A method named calculateScore that will calculate the score for the diver based on the scores from all judges and the degree of difficulty.
• A method that will input the diver information including the name and the competition number.
• A method that prints out all attributes in the class.
• INPUT DIVER INFORMATION as a method no return statement so it is void
Create a main method that is in a separate class including no attributes and no other methods besides main. A main method that creates a Dive object, inputs all information about the dive, and then prints out all information for the dive.
• Input all information basically call the class
• Print out all information of the class
Additional Directions
• You must not use any Array class or Array method included in the Java libraries to solve this problem
• Console input and output must be used to solve this problem.
• When you are satisfied that your solution works then use the following input values to run your program to create your output file.
Diver Name Use your actual name
Diver Number 327
Degree of difficulty 2.7
Judge #1 score 7.5
Judge #2 score 9.5
Judge #3 score 5.7
Judge #4 score 8.25
Judge #5 score 6.72
Judge #6 score 10.0
Judge #7 score 3.46
• Part I. Program Design
o Rewrite the problem statement in your own words using short bulleted phrases
o Create a class skeleton for this problem – show your attribute declarations and appropriate comment descriptions. Also show comment header blocks for your methods. You do not include the code for the methods at this point Note you do not have to include MyUtilityClass and its methods in the design work.
o Post your completed design work for this problem in Blackboard before class begins on the due date listed in the syllabus.
• Part II. Completed Program
o You must complete all of the code for this program and run the program using the specific input values defined in these instructions to generate an output file.
o Print out a copy of your output file and also your source code in all classes except for MyUtilityClass to turn in for this homework on the due date listed in the syllabus.
|
kesamercy/diving-Competition-project
|
refs/heads/master
|
/OneDiveClass.java
|
//
// OneDive
// The purpose of this class is to describe one class
//
// Author: Nekesa Mercy
// Date: 11/02/16
//
package divingCompetitionPackage;
public class OneDiveClass {
//declare attributes
private String name; // the name of the diver
private int competitonNum; // the competition number for the diver
private double[ ]allScores; // all the scores for one diver from all the judges
private double degreeOfDifficulty; // the degree of difficulty for the dive
private double finalScore; // the final score for the diver
private double oneScore; // one score for the diver from the judge
private double maxScore; // the maximum score the diver
private double minScore; // the minimum score for the diver
//declare constants here
private double MAXIMUMSCORE = 10.0;
private double MINIMUMSCORE = 0.0;
private double MAXIMUMDEGDIFFICULTY = 3.8;
private double MINIMUMDEGREEDIFFICULTY = 1.2;
private double NUMTOMULTIPLY = 0.6;
private int NUMJUDGES = 7;
// OneDive
// the purpose of this method is to initialize all attributes
// Input: none
// Return: none
//
public OneDiveClass( ){
int cntr;
name = "none yet";
competitonNum = 0;
degreeOfDifficulty = 0.0;
finalScore = 0.0;
maxScore = 0.0;
minScore = 0.0;
oneScore = 0.0;
//create space for the array
allScores = new double[NUMJUDGES];
for(cntr = 0; cntr < allScores.length; ++cntr){
allScores[cntr] = 0;
}// end for
}// end OneDive
//
// OneDive
// the purpose of this method is to initialize all new attributes
//
// Input: nme // the name
// compNum // the competetion number
// sc // scores
// allSc // array for all the scores for one person
// degDiff // the degree of difficulty
// finSc // the final score
// Return: none
//
public void OneDive(String nme, int compNum, double[]allsc, double degDiff, double finSc ){
int cntr;
name = nme;
competitonNum = compNum;
degreeOfDifficulty = degDiff;
finalScore = finSc;
allScores = new double[NUMJUDGES];
for(cntr = 0; cntr < allScores.length; ++cntr){
allScores[cntr] = allsc[cntr];
}// end for
}// end OneDive
//
// setName
// The purpose of this method is to set a new name for the diver
//
// input: nme // the new name
// return: none
//
public void setName(String nme){
name = nme;
}// end setName
//
// setCompetitionNum
// The purpose of this method is to set a new value for the competition number for the diver
//
// input: compNum // the new competition number
// return:none
//
public void setCompetitionNum(int compNum){
competitonNum = compNum;
}// end competitionNum
//
// setDegreeOfDIfficulty
// The purpose of this method is to set new values for the degree of difficulty
//
// input: degreeOfDifficulty // the array for the new value for the degree of difficulty
// return: none
//
public void setDegreeOfDifficulty(double degDiff){
degreeOfDifficulty = degDiff;
}// end setDegreeOfDifficulty
//
// getName
// The purpose of this method is to return the name
//
// input: none
// return: name // the name
//
public String getName( ){
return(name);
}// end getName
//
// getCompetitionNum
// The purpose of this method is to return the competition number
//
// input: none
// return: competitionNum // the competition number
//
public int getCompetitionNum( ){
return(competitonNum);
}// end getCompetitionNum
//
// getAllScores
// The purpose of this method is to return the array for all the scores for one diver
//
// input: none
// return: allScores // all the scores for one diver
//
public double[] getAllScore( ){
return(allScores);
}// end getAllSocres
//
// getDegreeOfDifficulty
// The purpose of this method is to return the value for the degree of difficulty
//
// input: none
// return: degreeOfDifficulty // the value for the degree of difficulty
//
public double getDegreeOfDifficulty( ){
return(degreeOfDifficulty);
}// end getDegreeOfDifficulty
//
// getFinalScore
// The purpose of this method is to return the final score for the diver
//
// input: none
// return: finalScore // the final score for the diver
//
public double getFinalScore( ){
return(finalScore);
}// end getFinalScore
//
// printData
// The purpose of this method is to print out all the attributes of the class
//
// Input: none
// return: none
public void printData(){
int cntr;
System.out.println("The name of the diver is " + name);
System.out.println("The competition number for the diver is " + competitonNum);
for(cntr = 0; cntr < allScores.length; ++cntr){
System.out.println("The scores for the diver are " + allScores[cntr]);
}// end for
System.out.println("The degree of difficulty is " + degreeOfDifficulty);
System.out.println("The final score for the diver is " + finalScore);
}// end printData
//
// inputDiverinfo
// The purpose of this method is to input the diver's information
//
// input: none
// return: none
public void inputDiverInfo( ){
//input the name of the diver
name = MyUtilityClass.inputString("Enter the name of the diver");
//input the competition number of the diver
competitonNum = MyUtilityClass.inputInteger("Enter the competition number of the diver");
}// end inputDiverInfo
//
// inputAllScores
// The purpose of this method is to input all scores for all the judges for the diver
//
// Input: none
// return : none
//
public void inputAllScores( ){
int cntr;
for(cntr = 0; cntr < allScores.length; ++cntr){
do{
if((allScores[cntr] >= MINIMUMSCORE) ||(allScores[cntr] <= MAXIMUMSCORE)){
allScores[cntr] = MyUtilityClass.inputDouble("Enter the score for the diver ");
}// end if
else{
System.out.println("Error, invalid socre " + allScores[cntr]);
}// end else
}while((allScores[cntr] < MINIMUMSCORE) ||(allScores[cntr] > MAXIMUMSCORE) );
}// end for
}// end inputAllScores
//
// inputValidDegreeOfDificulty
// The purpose of this method is to input a valid degree of difficulty for the dive
//
// Input: none
// return : none
//
public void inputValidDegreeOfDifficulty( ){
do{
if((degreeOfDifficulty >= MINIMUMDEGREEDIFFICULTY)||(degreeOfDifficulty <= MAXIMUMDEGDIFFICULTY )){
degreeOfDifficulty = MyUtilityClass.inputDouble("Enter the degree of difficulty for the diver ");
}// end if
else{
System.out.println("Error, invalid number for degree of difficulty " + degreeOfDifficulty);
}// end else
}while((degreeOfDifficulty < MINIMUMDEGREEDIFFICULTY)||(degreeOfDifficulty > MAXIMUMDEGDIFFICULTY ));
}// end inputValidDegreeOfDifficulty
//
// findMaxScoreOneDive
//
// The purpose of this method is to find the highest score for one diver
//
// Input: allScores // array that holds all scores for one diver
//
// REturn: maxScore // highest score for that bowler
//
public double findMaxScoreOneDive(double[] allScores){
int cntr;
for (cntr = 0; cntr < allScores.length; ++cntr)
{
if (allScores[cntr] > maxScore)
{
maxScore = allScores[cntr];
}// end if
}// end for
return(maxScore);
}// end findMaxScoreOneDive
//
// findMinScoreOneDive
//
// The purpose of this method is to find the lowest score for one diver
//
// Input: allScores // array that holds all scores for one diver
//
// REturn: minScore // lowest score for one diver
//
public double findMinScoreOneDive(double[]allScores){
int cntr;
for (cntr = 0; cntr < allScores.length;++cntr)
{
if (allScores[cntr] < minScore)
{
minScore = allScores[cntr];
}// end if
}// end for
return(minScore);
}// end findMinScoreOneDive
// calculateScore
// The purpose of this method is to calculate the score of the diver based on the scores from the judges and the degree of difficulty
//
// Input: allScores // all the scores from all the judges from one diver
// degreeOfDifficulty // the value for the level of difficulty for the dive
// maxScore // the maximum score
// minScore // the minimum score
// return : finalScore // over all score for the diver based on the scores from the judges
//
public double calculateFinalScore( ){
//declare variables
double sumExtremes;
double totalFinal;
double firstTotal;
double total;
int cntr;
//initialize variables
sumExtremes = 0.0;
totalFinal = 0.0;
firstTotal = 0.0;
total = 0;
//calculate the sum of the minimum and maximum
sumExtremes = maxScore + minScore;
//find the total score for all the scores
for(cntr = 0; cntr < allScores.length; cntr++ ){
total += allScores[cntr];
}// end for
//subtract the sum of the max and min from the total score
firstTotal = total - sumExtremes;
//multiply the new total by the degree of difficulty
totalFinal = firstTotal * degreeOfDifficulty;
//multiply that score by the generic number to multiply the total
finalScore = totalFinal * NUMTOMULTIPLY;
return(finalScore);
}// end calculateScore
//
// runOneDiveClass
// The purpose of this method is to run the one dive class
//
// Input : none
// Return: none
//
public void runOneDiveClass( ){
int cntr;
//input diver information
inputDiverInfo();
//input the degree of difficulty
inputValidDegreeOfDifficulty( );
//input the scores from the judges
inputAllScores( );
//calculate the score
calculateFinalScore( );
//print data
printData( );
}// end runOneDiveClass
}// end OneDiveClass
|
ariksu/pyhfss_parser
|
refs/heads/master
|
/setup.py
|
from setuptools import setup
setup(
name='pyhfss_parser',
version='0.0.0',
packages=['', 'venv.Lib.site-packages.py', 'venv.Lib.site-packages.py._io', 'venv.Lib.site-packages.py._log',
'venv.Lib.site-packages.py._code', 'venv.Lib.site-packages.py._path',
'venv.Lib.site-packages.py._process', 'venv.Lib.site-packages.py._vendored_packages',
'venv.Lib.site-packages.pip', 'venv.Lib.site-packages.pip._vendor',
'venv.Lib.site-packages.pip._vendor.idna', 'venv.Lib.site-packages.pip._vendor.pytoml',
'venv.Lib.site-packages.pip._vendor.certifi', 'venv.Lib.site-packages.pip._vendor.chardet',
'venv.Lib.site-packages.pip._vendor.chardet.cli', 'venv.Lib.site-packages.pip._vendor.distlib',
'venv.Lib.site-packages.pip._vendor.distlib._backport', 'venv.Lib.site-packages.pip._vendor.msgpack',
'venv.Lib.site-packages.pip._vendor.urllib3', 'venv.Lib.site-packages.pip._vendor.urllib3.util',
'venv.Lib.site-packages.pip._vendor.urllib3.contrib',
'venv.Lib.site-packages.pip._vendor.urllib3.contrib._securetransport',
'venv.Lib.site-packages.pip._vendor.urllib3.packages',
'venv.Lib.site-packages.pip._vendor.urllib3.packages.backports',
'venv.Lib.site-packages.pip._vendor.urllib3.packages.ssl_match_hostname',
'venv.Lib.site-packages.pip._vendor.colorama', 'venv.Lib.site-packages.pip._vendor.html5lib',
'venv.Lib.site-packages.pip._vendor.html5lib._trie',
'venv.Lib.site-packages.pip._vendor.html5lib.filters',
'venv.Lib.site-packages.pip._vendor.html5lib.treewalkers',
'venv.Lib.site-packages.pip._vendor.html5lib.treeadapters',
'venv.Lib.site-packages.pip._vendor.html5lib.treebuilders', 'venv.Lib.site-packages.pip._vendor.lockfile',
'venv.Lib.site-packages.pip._vendor.progress', 'venv.Lib.site-packages.pip._vendor.requests',
'venv.Lib.site-packages.pip._vendor.packaging', 'venv.Lib.site-packages.pip._vendor.cachecontrol',
'venv.Lib.site-packages.pip._vendor.cachecontrol.caches',
'venv.Lib.site-packages.pip._vendor.webencodings', 'venv.Lib.site-packages.pip._vendor.pkg_resources',
'venv.Lib.site-packages.pip._internal', 'venv.Lib.site-packages.pip._internal.req',
'venv.Lib.site-packages.pip._internal.vcs', 'venv.Lib.site-packages.pip._internal.utils',
'venv.Lib.site-packages.pip._internal.models', 'venv.Lib.site-packages.pip._internal.commands',
'venv.Lib.site-packages.pip._internal.operations', 'venv.Lib.site-packages.attr',
'venv.Lib.site-packages.pluggy', 'venv.Lib.site-packages._pytest', 'venv.Lib.site-packages._pytest.mark',
'venv.Lib.site-packages._pytest._code', 'venv.Lib.site-packages._pytest.config',
'venv.Lib.site-packages._pytest.assertion', 'venv.Lib.site-packages.colorama',
'venv.Lib.site-packages.atomicwrites', 'venv.Lib.site-packages.parsimonious',
'venv.Lib.site-packages.parsimonious.tests', 'venv.Lib.site-packages.more_itertools',
'venv.Lib.site-packages.more_itertools.tests', 'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip.req',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip.vcs',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip.utils',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip.compat',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip.models',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.distlib',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.distlib._backport',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.colorama',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.html5lib',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.html5lib._trie',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.html5lib.filters',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.html5lib.treewalkers',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.html5lib.treeadapters',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.html5lib.treebuilders',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.lockfile',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.progress',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.requests',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.requests.packages',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.requests.packages.chardet',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.requests.packages.urllib3',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.requests.packages.urllib3.util',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.requests.packages.urllib3.contrib',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.requests.packages.urllib3.packages',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.requests.packages.urllib3.packages.ssl_match_hostname',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.packaging',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.cachecontrol',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.cachecontrol.caches',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.webencodings',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip._vendor.pkg_resources',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip.commands',
'venv.Lib.site-packages.pip-9.0.1-py3.7.egg.pip.operations'],
url='',
license='MIT',
author='Ariksu',
author_email='ariksu@gmail.com',
description='Attempt to write peg-parser for .hfss'
)
|
ruanjiayu/githubFirstPush
|
refs/heads/master
|
/README.md
|
# githubFirstPush
第一次提交到github仓库的步骤以及遇到的问题
## 1. 当你本地已经存在代码的情况下,使用下面的方式来提交代码
1. 在本地使用git init
2. git remote add origin https://github.com/xxx
3. git pull origin master
4. git add .
5. git push -u origin master
## 2. 当你在github上提前先创建好了库
1. git clone https://github.com/xxx
## 3. 问题
### 3.1 git commit提交修改好的文件时候,提示`Changes not staged for commit`
- 使用`git status` 来查看本地修改好的文件是否已将放入暂存区
- 如果发现没有加入暂存区,那么你可以使用`git add .`或者 `git add fileName`来加入暂存区
- 最后你可以使用`git commit -m "xxxxx"`来提交暂存区的数据到本地库,当然你可以直接可以使用`git commit -am "xxxx""`来进行直接的提交
### 3.2 已经加入暂存区的文件如何撤回,保留工作区内的文件
- 使用`git rm --cached fileName` 可以撤回相对应的文件。
- 使用`git rm -r --cached .` 可以撤回所有的文件
### 3.3 删除工作区内的文件,并且进行提交上传。注意:要删除的文件是没有修改过的,就是说和当前版本库文件的内容相同
- 使用`git rm fileName`,可以删除工作区内的文件,并且加入到暂存
- 使用`git commit -m "xxxxxx"`将删除了的文件提交到暂存区
### 3.4 强制删除工作区和暂存区内对应的文件,并将删除好后的状态提交到暂存区
- 使用`git rm -f fileName`,可以删除工作区内的文件,并且加入到暂存区
|
ruanjiayu/githubFirstPush
|
refs/heads/master
|
/src/main/java/com/xian/demo/Hello.java
|
package com.xian.demo;
/**
* @Description:
* @Author: Xian
* @CreateDate: 2019/8/29 11:00
* @Version: 0.0.1-SHAPSHOT
*/
public class Hello {
public static void main(String[] args) {
System.out.println("hello world");
}
}
|
whaid/FPS-Player
|
refs/heads/master
|
/Script/RaycastShoot.cs
|
using UnityEngine;
using System.Collections;
public class RaycastShoot : MonoBehaviour
{
public int weaponDamage = 1;
public int weaponRange = 100;
public float fireRate = 0.1f;
private float nextFire = 0;
private Ray ray;
private RaycastHit hit;
private WaitForSeconds shotDuration = new WaitForSeconds(0.07f);
private AudioSource gunAudio;
void Start()
{
gunAudio = GetComponent<AudioSource>();
}
void Update()
{
if (Input.GetButtonDown("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
StartCoroutine(ShotEffect());
Vector2 screenCenterPoint = new Vector2(Screen.width / 2, Screen.height / 2);
ray = Camera.main.ScreenPointToRay(screenCenterPoint);
if (Physics.Raycast(ray, out hit, weaponRange))
{
Debug.Log("Hit!");
ShootableRobot health = hit.collider.GetComponent<ShootableRobot>();
if (health != null)
{
health.Damage(weaponDamage);
}
}
}
}
private IEnumerator ShotEffect()
{
Debug.Log("shot!");
gunAudio.Play();
yield return shotDuration;
}
}
|
whaid/FPS-Player
|
refs/heads/master
|
/Script/AnimationPlayer.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AnimationPlayer : MonoBehaviour {
private Animator anim;
private AudioSource soundReload;
// Use this for initialization
void Start ()
{
anim = GetComponent<Animator>();
soundReload = GetComponent<AudioSource>();
}
// Update is called once per frame
void Update ()
{
anim.SetBool("isWalking", false);
if (Input.GetButton("Vertical") || Input.GetButton("Horizontal"))
{
anim.SetBool("isWalking", true);
}
if (anim.GetBool("isWalking") && Input.GetButtonDown("Fire3"))
{
anim.SetBool("isWalking", false);
anim.SetBool("isRunning", true);
}
if(anim.GetBool("isRunning") && Input.GetButtonUp("Fire3"))
{
anim.SetBool("isRunning", false);
}
}
}
|
Glitchfix/TransposeMatrixIndorse
|
refs/heads/master
|
/README.md
|
# Transpose a matrix
### Prerequisites
- `pip3 install -r requirements.txt`
## Usage
Start the server
```
python3 server.py
```
Hit the URL `127.0.0.1:5000/transpose` with a POST request
Request format:
```
{
"matrix": [[1,2],[3,4]]
}
```
Response format:
```
{"error":"","result":[[1,3],[2,4]]}
```
|
Glitchfix/TransposeMatrixIndorse
|
refs/heads/master
|
/server.py
|
from flask import Flask, render_template, request, jsonify
from flask_cors import CORS
import json
import numpy as np
app = Flask(__name__)
CORS(app)
@app.route('/transpose', methods=["POST"])
def homepage():
data = request.json
result = None
error = ""
try:
mat = data["matrix"]
mat = np.array(mat)
result = mat.T.tolist()
error = ""
except KeyError as e:
error = "Key %s not found" % (str(e))
pass
except Exception as e:
error = str(e)
pass
return jsonify({"result": result, "error": error})
app.run()
|
hsk/xterm.js
|
refs/heads/master
|
/src/xterm.ts
|
/**
* xterm.js: xterm, in the browser
* Originally forked from (with the author's permission):
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
* The original design remains. The terminal itself
* has been extended to include xterm CSI codes, among
* other features.
* @license MIT
*/
import { CompositionHelper } from './CompositionHelper';
import { EventEmitter } from './EventEmitter';
import { Viewport } from './Viewport';
import { rightClickHandler, pasteHandler, copyHandler } from './handlers/Clipboard';
import { CircularList } from './utils/CircularList';
import { C0 } from './EscapeSequences';
import { InputHandler } from './InputHandler';
import { Parser } from './Parser';
import { Renderer } from './Renderer';
import { Linkifier } from './Linkifier';
import { CharMeasure } from './utils/CharMeasure';
import * as Browser from './utils/Browser';
import { CHARSETS } from './Charsets';
import { IBrowser, IInputHandler, ITerminal, ICircularList, LinkMatcherOptions } from './Interfaces';
import { LinkMatcherHandler } from './Types';
declare var define: any;
declare var require: (id:string|string[],callback?:(...params:any[])=>any)=>any;
/**
* Terminal Emulation References:
* http://vt100.net/
* http://invisible-island.net/xterm/ctlseqs/ctlseqs.txt
* http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
* http://invisible-island.net/vttest/
* http://www.inwap.com/pdp10/ansicode.txt
* http://linux.die.net/man/4/console_codes
* http://linux.die.net/man/7/urxvt
*/
// Let it work inside Node.js for automated testing purposes.
var document = (typeof window != 'undefined') ? window.document : null;
/**
* The amount of write requests to queue before sending an XOFF signal to the
* pty process. This number must be small in order for ^C and similar sequences
* to be responsive.
*/
var WRITE_BUFFER_PAUSE_THRESHOLD = 5;
/**
* The number of writes to perform in a single batch before allowing the
* renderer to catch up with a 0ms setTimeout.
*/
var WRITE_BATCH_SIZE = 300;
/**
* Terminal
*/
class Terminal extends EventEmitter implements ITerminal {
public colors:string[];
public options:any;
public parent:HTMLElement;
public geometry:number[];
public convertEol:boolean;
public queue:string;
public scrollTop:number;
public scrollBottom:number;
public customKeydownHandler:(string)=>any;
// modes
public applicationKeypad:boolean;
public applicationCursor:boolean;
public originMode:boolean;
public insertMode:boolean;
public wraparoundMode:boolean; // defaults: xterm - true, vt100 - false
public normal:boolean;
// misc
public refreshStart:number;
public refreshEnd:number;
public savedX:number;
public savedY:number;
//public savedCols:number;
// charset
public charset:string;
public gcharset:string;
public glevel:number;
public charsets:string[];
// mouse properties
public decLocator:boolean;
public x10Mouse:boolean;
public vt200Mouse:boolean;
public vt300Mouse:boolean;
public normalMouse:boolean;
public mouseEvents:boolean;
public sendFocus:boolean;
public utfMouse:boolean;
public sgrMouse:boolean;
public urxvtMouse:boolean;
// stream
public readable:boolean;
public writable:boolean;
public curAttr:number;
public params:any[];
public currentParam:number;
public prefix:string;
public postfix:string;
public inputHandler:IInputHandler;
public parser:Parser;
// Reuse renderer if the Terminal is being recreated via a Terminal.reset call.
public renderer:Renderer;
public linkifier:Linkifier;
// user input states
public writeInProgress:boolean;
public xoffSentToCatchUp:boolean;
// Whether writing has been stopped as a result of XOFF
public writeStopped:boolean;
// leftover surrogate high from previous write invocation
public surrogate_high:string;
public tabs:object;
scrollback:number;
// Store if user went browsing history in scrollback
public userScrolling: boolean;
element: HTMLElement;
rowContainer: HTMLElement;
textarea: HTMLTextAreaElement;
ybase: number;
ydisp: number;
lines: ICircularList<any>;
rows: number;
cols: number;
browser: IBrowser;
writeBuffer: string[];
children: HTMLElement[];
cursorHidden: boolean;
cursorState: number;
x: number;
y: number;
defAttr: number;
cancel:(ev: Event, force?: boolean)=>any;
public viewport:Viewport;
public context:any;
public document:HTMLDocument;
public body:HTMLElement;
public theme:string;
public viewportElement:HTMLElement;
public viewportScrollArea:HTMLElement;
public helperContainer:HTMLElement;
public compositionView:HTMLElement;
public compositionHelper:CompositionHelper;
public charSizeStyleElement:HTMLElement;
public charMeasure:CharMeasure;
public visualBell:string;
public popOnBell:string;
public debug:boolean;
public termName:string;
static cancelEvents:boolean;
/**
* Creates a new `Terminal` object.
*
* @param {object} options An object containing a set of options, the available options are:
* - `cursorBlink` (boolean): Whether the terminal cursor blinks
* - `cols` (number): The number of columns of the terminal (horizontal size)
* - `rows` (number): The number of rows of the terminal (vertical size)
*
* @public
* @class Xterm Xterm
* @alias module:xterm/src/xterm
*/
constructor(options:any) {
super();
var self = this;
/*
if (!(this instanceof Terminal)) {
return new Terminal(arguments[0], arguments[1], arguments[2]);
}
*/
self.browser = Browser;
self.cancel = Terminal.cancel;
EventEmitter.call(this);
if (typeof options === 'number') {
options = {
cols: arguments[0],
rows: arguments[1],
handler: arguments[2]
};
}
options = options || {};
Object.keys(Terminal.defaults).forEach(function(key) {
if (options[key] == null) {
options[key] = Terminal.options[key];
if (Terminal[key] !== Terminal.defaults[key]) {
options[key] = Terminal[key];
}
}
self[key] = options[key];
});
if (options.colors.length === 8) {
options.colors = options.colors.concat(Terminal._colors.slice(8));
} else if (options.colors.length === 16) {
options.colors = options.colors.concat(Terminal._colors.slice(16));
} else if (options.colors.length === 10) {
options.colors = options.colors.slice(0, -2).concat(
Terminal._colors.slice(8, -2), options.colors.slice(-2));
} else if (options.colors.length === 18) {
options.colors = options.colors.concat(
Terminal._colors.slice(16, -2), options.colors.slice(-2));
}
this.colors = options.colors;
this.options = options;
// this.context = options.context || window;
// this.document = options.document || document;
this.parent = options.body || options.parent || (
document ? document.getElementsByTagName('body')[0] : null
);
this.cols = options.cols || options.geometry[0];
this.rows = options.rows || options.geometry[1];
this.geometry = [this.cols, this.rows];
if (options.handler) {
this.on('data', options.handler);
}
/**
* The scroll position of the y cursor, ie. ybase + y = the y position within the entire
* buffer
*/
this.ybase = 0;
/**
* The scroll position of the viewport
*/
this.ydisp = 0;
/**
* The cursor's x position after ybase
*/
this.x = 0;
/**
* The cursor's y position after ybase
*/
this.y = 0;
this.cursorState = 0;
this.cursorHidden = false;
this.queue = '';
this.scrollTop = 0;
this.scrollBottom = this.rows - 1;
this.customKeydownHandler = null;
// modes
this.applicationKeypad = false;
this.applicationCursor = false;
this.originMode = false;
this.insertMode = false;
this.wraparoundMode = true; // defaults: xterm - true, vt100 - false
this.normal = null;
// charset
this.charset = null;
this.gcharset = null;
this.glevel = 0;
this.charsets = [null];
// stream
this.readable = true;
this.writable = true;
this.defAttr = (0 << 18) | (257 << 9) | (256 << 0);
this.curAttr = this.defAttr;
this.params = [];
this.currentParam = 0;
this.prefix = '';
this.postfix = '';
this.inputHandler = new InputHandler(this);
this.parser = new Parser(this.inputHandler, this);
// Reuse renderer if the Terminal is being recreated via a Terminal.reset call.
this.renderer = this.renderer || null;
this.linkifier = this.linkifier || null;;
// user input states
this.writeBuffer = [];
this.writeInProgress = false;
/**
* Whether _xterm.js_ sent XOFF in order to catch up with the pty process.
* This is a distinct state from writeStopped so that if the user requested
* XOFF via ^S that it will not automatically resume when the writeBuffer goes
* below threshold.
*/
this.xoffSentToCatchUp = false;
/** Whether writing has been stopped as a result of XOFF */
this.writeStopped = false;
// leftover surrogate high from previous write invocation
this.surrogate_high = '';
/**
* An array of all lines in the entire buffer, including the prompt. The lines are array of
* characters which are 2-length arrays where [0] is an attribute and [1] is the character.
*/
this.lines = new CircularList(this.scrollback);
var i = this.rows;
while (i--) {
this.lines.push(this.blankLine());
}
this.setupStops();
// Store if user went browsing history in scrollback
this.userScrolling = false;
}
/**
* back_color_erase feature for xterm.
*/
eraseAttr():number {
// if (this.is('screen')) return this.defAttr;
return (this.defAttr & ~0x1ff) | (this.curAttr & 0x1ff);
}
/**
* Colors
*/
// Colors 0-15
static tangoColors:string[] = [
// dark:
'#2e3436',
'#cc0000',
'#4e9a06',
'#c4a000',
'#3465a4',
'#75507b',
'#06989a',
'#d3d7cf',
// bright:
'#555753',
'#ef2929',
'#8ae234',
'#fce94f',
'#729fcf',
'#ad7fa8',
'#34e2e2',
'#eeeeec'
];
// Colors 0-15 + 16-255
// Much thanks to TooTallNate for writing this.
static colors:string[] = (function() {
var colors = Terminal.tangoColors.slice()
, r = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
, i
, k;
// 16-231
i = 0;
for (; i < 216; i++) {
out(r[(i / 36) % 6 | 0], r[(i / 6) % 6 | 0], r[i % 6]);
}
// 232-255 (grey)
i = 0;
for (; i < 24; i++) {
k = 8 + i * 10;
out(k, k, k);
}
function out(r, g, b) {
colors.push('#' + hex(r) + hex(g) + hex(b));
}
function hex(c) {
c = c.toString(16);
return c.length < 2 ? '0' + c : c;
}
return colors;
})();
static _colors:string[] = Terminal.colors.slice();
static vcolors:string[] = (function() {
var out = []
, colors = Terminal.colors
, i = 0
, color;
for (; i < 256; i++) {
color = parseInt(colors[i].substring(1), 16);
out.push([
(color >> 16) & 0xff,
(color >> 8) & 0xff,
color & 0xff
]);
}
return out;
})();
/**
* Options
*/
static defaults = {
colors: Terminal.colors,
theme: 'default',
convertEol: false,
termName: 'xterm',
geometry: [80, 24],
cursorBlink: false,
cursorStyle: 'block',
visualBell: false,
popOnBell: false,
scrollback: 1000,
screenKeys: false,
debug: false,
cancelEvents: false,
disableStdin: false,
useFlowControl: false,
tabStopWidth: 8
// programFeatures: false,
// focusKeys: false,
};
static options:any = {};
static focus:Terminal = null;
/**
* Focus the terminal. Delegates focus handling to the terminal's DOM element.
*/
focus(): void {
return this.textarea.focus();
}
/**
* Retrieves an option's value from the terminal.
* @param {string} key The option key.
*/
getOption(key:string):any {
if (!(key in Terminal.defaults)) {
throw new Error('No option with key "' + key + '"');
}
if (typeof this.options[key] !== 'undefined') {
return this.options[key];
}
return this[key];
}
/**
* Sets an option on the terminal.
* @param {string} key The option key.
* @param {string} value The option value.
*/
setOption(key:string, value:any):void {
if (!(key in Terminal.defaults)) {
throw new Error('No option with key "' + key + '"');
}
switch (key) {
case 'scrollback':
if (this.options[key] !== value) {
if (this.lines.length > value) {
const amountToTrim = this.lines.length - value;
const needsRefresh = (this.ydisp - amountToTrim < 0);
this.lines.trimStart(amountToTrim);
this.ybase = Math.max(this.ybase - amountToTrim, 0);
this.ydisp = Math.max(this.ydisp - amountToTrim, 0);
if (needsRefresh) {
this.refresh(0, this.rows - 1);
}
}
this.lines.maxLength = value;
this.viewport.syncScrollArea();
}
break;
}
this[key] = value;
this.options[key] = value;
switch (key) {
case 'cursorBlink': this.element.classList.toggle('xterm-cursor-blink', value); break;
case 'cursorStyle':
// Style 'block' applies with no class
this.element.classList.toggle(`xterm-cursor-style-underline`, value === 'underline');
this.element.classList.toggle(`xterm-cursor-style-bar`, value === 'bar');
break;
case 'tabStopWidth': this.setupStops(); break;
}
};
/**
* Binds the desired focus behavior on a given terminal object.
*
* @static
*/
static bindFocus(term:Terminal):void {
on(term.textarea, 'focus', function (ev) {
if (term.sendFocus) {
term.send(C0.ESC + '[I');
}
term.element.classList.add('focus');
term.showCursor();
Terminal.focus = term;
term.emit('focus', {terminal: term});
});
};
/**
* Blur the terminal. Delegates blur handling to the terminal's DOM element.
*/
blur():void {
return this.textarea.blur();
};
/**
* Binds the desired blur behavior on a given terminal object.
*
* @static
*/
static bindBlur(term:Terminal):void {
on(term.textarea, 'blur', function (ev) {
term.refresh(term.y, term.y);
if (term.sendFocus) {
term.send(C0.ESC + '[O');
}
term.element.classList.remove('focus');
Terminal.focus = null;
term.emit('blur', {terminal: term});
});
};
/**
* Initialize default behavior
*/
initGlobal():void {
var term = this;
Terminal.bindKeys(this);
Terminal.bindFocus(this);
Terminal.bindBlur(this);
// Bind clipboard functionality
on(this.element, 'copy', function (ev) {
copyHandler.call(this, ev, term);
});
on(this.textarea, 'paste', function (ev) {
pasteHandler.call(this, ev, term);
});
on(this.element, 'paste', function (ev) {
pasteHandler.call(this, ev, term);
});
function rightClickHandlerWrapper (ev) {
rightClickHandler.call(this, ev, term);
}
if (term.browser.isFirefox) {
on(this.element, 'mousedown', function (ev) {
if (ev.button == 2) {
rightClickHandlerWrapper(ev);
}
});
} else {
on(this.element, 'contextmenu', rightClickHandlerWrapper);
}
}
/**
* Apply key handling to the terminal
*/
static bindKeys(term:Terminal):void {
on(term.element, 'keydown', function(ev) {
if (document.activeElement != this) {
return;
}
term.keyDown(ev);
}, true);
on(term.element, 'keypress', function(ev) {
if (document.activeElement != this) {
return;
}
term.keyPress(ev);
}, true);
on(term.element, 'keyup', function(ev) {
function wasMondifierKeyOnlyEvent(ev:KeyboardEvent):boolean {
return ev.keyCode === 16 || // Shift
ev.keyCode === 17 || // Ctrl
ev.keyCode === 18; // Alt
}
if (!wasMondifierKeyOnlyEvent(ev)) {
term.focus();
}
}, true);
on(term.textarea, 'keydown', function(ev) {
term.keyDown(ev);
}, true);
on(term.textarea, 'keypress', function(ev) {
term.keyPress(ev);
// Truncate the textarea's value, since it is not needed
this.value = '';
}, true);
on(term.textarea, 'compositionstart', term.compositionHelper.compositionstart.bind(term.compositionHelper));
on(term.textarea, 'compositionupdate', term.compositionHelper.compositionupdate.bind(term.compositionHelper));
on(term.textarea, 'compositionend', term.compositionHelper.compositionend.bind(term.compositionHelper));
term.on('refresh', term.compositionHelper.updateCompositionElements.bind(term.compositionHelper));
term.on('refresh', function (data) {
term.queueLinkification(data.start, data.end)
});
}
/**
* Insert the given row to the terminal or produce a new one
* if no row argument is passed. Return the inserted row.
* @param {HTMLElement} row (optional) The row to append to the terminal.
*/
insertRow(row?:HTMLElement):HTMLElement {
if (typeof row != 'object') {
row = document.createElement('div');
}
this.rowContainer.appendChild(row);
this.children.push(row);
return row;
};
/**
* Opens the terminal within an element.
*
* @param {HTMLElement} parent The element to create the terminal within.
*/
open(parent:HTMLElement):void {
var self=this, i=0, div;
this.parent = parent || this.parent;
if (!this.parent) {
throw new Error('Terminal requires a parent element.');
}
// Grab global elements
this.context = this.parent.ownerDocument.defaultView;
this.document = this.parent.ownerDocument;
this.body = this.document.getElementsByTagName('body')[0];
//Create main element container
this.element = this.document.createElement('div');
this.element.classList.add('terminal');
this.element.classList.add('xterm');
this.element.classList.add('xterm-theme-' + this.theme);
this.element.classList.toggle('xterm-cursor-blink', this.options.cursorBlink);
this.element.style.height
this.element.setAttribute('tabindex', '0');
this.viewportElement = document.createElement('div');
this.viewportElement.classList.add('xterm-viewport');
this.element.appendChild(this.viewportElement);
this.viewportScrollArea = document.createElement('div');
this.viewportScrollArea.classList.add('xterm-scroll-area');
this.viewportElement.appendChild(this.viewportScrollArea);
// Create the container that will hold the lines of the terminal and then
// produce the lines the lines.
this.rowContainer = document.createElement('div');
this.rowContainer.classList.add('xterm-rows');
this.element.appendChild(this.rowContainer);
this.children = [];
this.linkifier = new Linkifier(document, this.children);
// Create the container that will hold helpers like the textarea for
// capturing DOM Events. Then produce the helpers.
this.helperContainer = document.createElement('div');
this.helperContainer.classList.add('xterm-helpers');
// TODO: This should probably be inserted once it's filled to prevent an additional layout
this.element.appendChild(this.helperContainer);
this.textarea = document.createElement('textarea');
this.textarea.classList.add('xterm-helper-textarea');
this.textarea.setAttribute('autocorrect', 'off');
this.textarea.setAttribute('autocapitalize', 'off');
this.textarea.setAttribute('spellcheck', 'false');
this.textarea.tabIndex = 0;
this.textarea.addEventListener('focus', function() {
self.emit('focus', {terminal: self});
});
this.textarea.addEventListener('blur', function() {
self.emit('blur', {terminal: self});
});
this.helperContainer.appendChild(this.textarea);
this.compositionView = document.createElement('div');
this.compositionView.classList.add('composition-view');
this.compositionHelper = new CompositionHelper(this.textarea, this.compositionView, this);
this.helperContainer.appendChild(this.compositionView);
this.charSizeStyleElement = document.createElement('style');
this.helperContainer.appendChild(this.charSizeStyleElement);
for (; i < this.rows; i++) {
this.insertRow();
}
this.parent.appendChild(this.element);
this.charMeasure = new CharMeasure(document, this.helperContainer);
this.charMeasure.on('charsizechanged', function () {
self.updateCharSizeCSS();
});
this.charMeasure.measure();
this.viewport = new Viewport(this, this.viewportElement, this.viewportScrollArea, this.charMeasure);
this.renderer = new Renderer(this);
// Setup loop that draws to screen
this.refresh(0, this.rows - 1);
// Initialize global actions that
// need to be taken on the document.
this.initGlobal();
// Ensure there is a Terminal.focus.
this.focus();
on(this.element, 'click', function() {
var selection = document.getSelection(),
collapsed = selection.isCollapsed,
isRange = typeof collapsed == 'boolean' ? !collapsed : selection.type == 'Range';
if (!isRange) {
self.focus();
}
});
// Listen for mouse events and translate
// them into terminal mouse protocols.
this.bindMouse();
/**
* This event is emitted when terminal has completed opening.
*
* @event open
*/
this.emit('open');
};
/**
* Attempts to load an add-on using CommonJS or RequireJS (whichever is available).
* @param {string} addon The name of the addon to load
* @static
*/
static loadAddon(addon:string, callback?:(...params:any[])=>any):any {
if (typeof exports === 'object' && typeof module === 'object') {
// CommonJS
return require('./addons/' + addon + '/' + addon);
} else if (typeof define == 'function') {
// RequireJS
return require(['./addons/' + addon + '/' + addon], callback);
} else {
console.error('Cannot load a module without a CommonJS or RequireJS environment.');
return false;
}
};
/**
* Updates the helper CSS class with any changes necessary after the terminal's
* character width has been changed.
*/
updateCharSizeCSS(): void {
this.charSizeStyleElement.textContent = '.xterm-wide-char{width:' + (this.charMeasure.width * 2) + 'px;}';
}
/**
* XTerm mouse events
* http://invisible-island.net/xterm/ctlseqs/ctlseqs.html#Mouse%20Tracking
* To better understand these
* the xterm code is very helpful:
* Relevant files:
* button.c, charproc.c, misc.c
* Relevant functions in xterm/button.c:
* BtnCode, EmitButtonCode, EditorButton, SendMousePosition
*/
bindMouse():void {
var el = this.element, self = this, pressed = 32;
// mouseup, mousedown, wheel
// left click: ^[[M 3<^[[M#3<
// wheel up: ^[[M`3>
function sendButton(ev) {
var button
, pos;
// get the xterm-style button
button = getButton(ev);
// get mouse coordinates
pos = getCoords(ev);
if (!pos) return;
sendEvent(button, pos);
switch (ev.overrideType || ev.type) {
case 'mousedown':
pressed = button;
break;
case 'mouseup':
// keep it at the left
// button, just in case.
pressed = 32;
break;
case 'wheel':
// nothing. don't
// interfere with
// `pressed`.
break;
}
}
// motion example of a left click:
// ^[[M 3<^[[M@4<^[[M@5<^[[M@6<^[[M@7<^[[M#7<
function sendMove(ev) {
var button = pressed
, pos;
pos = getCoords(ev);
if (!pos) return;
// buttons marked as motions
// are incremented by 32
button += 32;
sendEvent(button, pos);
}
// encode button and
// position to characters
function encode(data, ch) {
if (!self.utfMouse) {
if (ch === 255) return data.push(0);
if (ch > 127) ch = 127;
data.push(ch);
} else {
if (ch === 2047) return data.push(0);
if (ch < 127) {
data.push(ch);
} else {
if (ch > 2047) ch = 2047;
data.push(0xC0 | (ch >> 6));
data.push(0x80 | (ch & 0x3F));
}
}
}
// send a mouse event:
// regular/utf8: ^[[M Cb Cx Cy
// urxvt: ^[[ Cb ; Cx ; Cy M
// sgr: ^[[ Cb ; Cx ; Cy M/m
// vt300: ^[[ 24(1/3/5)~ [ Cx , Cy ] \r
// locator: CSI P e ; P b ; P r ; P c ; P p & w
function sendEvent(button, pos) {
// self.emit('mouse', {
// x: pos.x - 32,
// y: pos.x - 32,
// button: button
// });
if (self.vt300Mouse) {
// NOTE: Unstable.
// http://www.vt100.net/docs/vt3xx-gp/chapter15.html
button &= 3;
pos.x -= 32;
pos.y -= 32;
var data = C0.ESC + '[24';
if (button === 0) data += '1';
else if (button === 1) data += '3';
else if (button === 2) data += '5';
else if (button === 3) return;
else data += '0';
data += '~[' + pos.x + ',' + pos.y + ']\r';
self.send(data);
return;
}
if (self.decLocator) {
// NOTE: Unstable.
button &= 3;
pos.x -= 32;
pos.y -= 32;
if (button === 0) button = 2;
else if (button === 1) button = 4;
else if (button === 2) button = 6;
else if (button === 3) button = 3;
self.send(C0.ESC + '['
+ button
+ ';'
+ (button === 3 ? 4 : 0)
+ ';'
+ pos.y
+ ';'
+ pos.x
+ ';'
+ (pos.page || 0)
+ '&w');
return;
}
if (self.urxvtMouse) {
pos.x -= 32;
pos.y -= 32;
pos.x++;
pos.y++;
self.send(C0.ESC + '[' + button + ';' + pos.x + ';' + pos.y + 'M');
return;
}
if (self.sgrMouse) {
pos.x -= 32;
pos.y -= 32;
self.send(C0.ESC + '[<'
+ (((button & 3) === 3 ? button & ~3 : button) - 32)
+ ';'
+ pos.x
+ ';'
+ pos.y
+ ((button & 3) === 3 ? 'm' : 'M'));
return;
}
var dt = [];
encode(dt, button);
encode(dt, pos.x);
encode(dt, pos.y);
self.send(C0.ESC + '[M' + String.fromCharCode.apply(String, dt));
}
function getButton(ev) {
var button
, shift
, meta
, ctrl
, mod;
// two low bits:
// 0 = left
// 1 = middle
// 2 = right
// 3 = release
// wheel up/down:
// 1, and 2 - with 64 added
switch (ev.overrideType || ev.type) {
case 'mousedown':
button = ev.button != null
? +ev.button
: ev.which != null
? ev.which - 1
: null;
if (self.browser.isMSIE) {
button = button === 1 ? 0 : button === 4 ? 1 : button;
}
break;
case 'mouseup':
button = 3;
break;
case 'DOMMouseScroll':
button = ev.detail < 0
? 64
: 65;
break;
case 'wheel':
button = ev.wheelDeltaY > 0
? 64
: 65;
break;
}
// next three bits are the modifiers:
// 4 = shift, 8 = meta, 16 = control
shift = ev.shiftKey ? 4 : 0;
meta = ev.metaKey ? 8 : 0;
ctrl = ev.ctrlKey ? 16 : 0;
mod = shift | meta | ctrl;
// no mods
if (self.vt200Mouse) {
// ctrl only
mod &= ctrl;
} else if (!self.normalMouse) {
mod = 0;
}
// increment to SP
button = (32 + (mod << 2)) + button;
return button;
}
// mouse coordinates measured in cols/rows
function getCoords(ev) {
var x, y, w, h, el;
// ignore browsers without pageX for now
if (ev.pageX == null) return;
x = ev.pageX;
y = ev.pageY;
el = self.element;
// should probably check offsetParent
// but this is more portable
while (el && el !== self.document.documentElement) {
x -= el.offsetLeft;
y -= el.offsetTop;
el = 'offsetParent' in el
? el.offsetParent
: el.parentNode;
}
// convert to cols/rows
x = Math.ceil(x / self.charMeasure.width);
y = Math.ceil(y / self.charMeasure.height);
// be sure to avoid sending
// bad positions to the program
if (x < 0) x = 0;
if (x > self.cols) x = self.cols;
if (y < 0) y = 0;
if (y > self.rows) y = self.rows;
// xterm sends raw bytes and
// starts at 32 (SP) for each.
x += 32;
y += 32;
return {
x: x,
y: y,
type: 'wheel'
};
}
on(el, 'mousedown', function(ev) {
if (!self.mouseEvents) return;
// send the button
sendButton(ev);
// ensure focus
self.focus();
// fix for odd bug
//if (self.vt200Mouse && !self.normalMouse) {
if (self.vt200Mouse) {
ev.overrideType = 'mouseup';
sendButton(ev);
return self.cancel(ev);
}
// bind events
if (self.normalMouse) on(self.document, 'mousemove', sendMove);
// x10 compatibility mode can't send button releases
if (!self.x10Mouse) {
on(self.document, 'mouseup', function up(ev) {
sendButton(ev);
if (self.normalMouse) off(self.document, 'mousemove', sendMove);
off(self.document, 'mouseup', up);
return self.cancel(ev);
});
}
return self.cancel(ev);
});
//if (self.normalMouse) {
// on(self.document, 'mousemove', sendMove);
//}
on(el, 'wheel', function(ev) {
if (!self.mouseEvents) return;
if (self.x10Mouse
|| self.vt300Mouse
|| self.decLocator) return;
sendButton(ev);
return self.cancel(ev);
});
// allow wheel scrolling in
// the shell for example
on(el, 'wheel', function(ev) {
if (self.mouseEvents) return;
self.viewport.onWheel(ev);
return self.cancel(ev);
});
}
/**
* Destroys the terminal.
*/
destroy():void {
this.readable = false;
this.writable = false;
this._events = {};
this.handler = function() {};
this.write = function() {};
if (this.element && this.element.parentNode) {
this.element.parentNode.removeChild(this.element);
}
//this.emit('close');
};
/**
* Tells the renderer to refresh terminal content between two rows (inclusive) at the next
* opportunity.
* @param {number} start The row to start from (between 0 and this.rows - 1).
* @param {number} end The row to end at (between start and this.rows - 1).
*/
refresh(start:number, end:number):void {
if (this.renderer) {
this.renderer.queueRefresh(start, end);
}
};
/**
* Queues linkification for the specified rows.
* @param {number} start The row to start from (between 0 and this.rows - 1).
* @param {number} end The row to end at (between start and this.rows - 1).
*/
queueLinkification(start:number, end:number):void {
if (this.linkifier) {
for (let i = start; i <= end; i++) {
this.linkifier.linkifyRow(i);
}
}
}
/**
* Display the cursor element
*/
showCursor():void {
if (!this.cursorState) {
this.cursorState = 1;
this.refresh(this.y, this.y);
}
}
/**
* Scroll the terminal down 1 row, creating a blank line.
*/
scroll():void {
var row;
// Make room for the new row in lines
if (this.lines.length === this.lines.maxLength) {
this.lines.trimStart(1);
this.ybase--;
if (this.ydisp !== 0) {
this.ydisp--;
}
}
this.ybase++;
// TODO: Why is this done twice?
if (!this.userScrolling) {
this.ydisp = this.ybase;
}
// last line
row = this.ybase + this.rows - 1;
// subtract the bottom scroll region
row -= this.rows - 1 - this.scrollBottom;
if (row === this.lines.length) {
// Optimization: pushing is faster than splicing when they amount to the same behavior
this.lines.push(this.blankLine());
} else {
// add our new line
this.lines.splice(row, 0, this.blankLine());
}
if (this.scrollTop !== 0) {
if (this.ybase !== 0) {
this.ybase--;
if (!this.userScrolling) {
this.ydisp = this.ybase;
}
}
this.lines.splice(this.ybase + this.scrollTop, 1);
}
// this.maxRange();
this.updateRange(this.scrollTop);
this.updateRange(this.scrollBottom);
/**
* This event is emitted whenever the terminal is scrolled.
* The one parameter passed is the new y display position.
*
* @event scroll
*/
this.emit('scroll', this.ydisp);
}
/**
* Scroll the display of the terminal
* @param {number} disp The number of lines to scroll down (negatives scroll up).
* @param {boolean} suppressScrollEvent Don't emit the scroll event as scrollDisp. This is used
* to avoid unwanted events being handled by the veiwport when the event was triggered from the
* viewport originally.
*/
scrollDisp(disp:number, suppressScrollEvent?:boolean):void {
if (disp < 0) {
this.userScrolling = true;
} else if (disp + this.ydisp >= this.ybase) {
this.userScrolling = false;
}
this.ydisp += disp;
if (this.ydisp > this.ybase) {
this.ydisp = this.ybase;
} else if (this.ydisp < 0) {
this.ydisp = 0;
}
if (!suppressScrollEvent) {
this.emit('scroll', this.ydisp);
}
this.refresh(0, this.rows - 1);
}
/**
* Scroll the display of the terminal by a number of pages.
* @param {number} pageCount The number of pages to scroll (negative scrolls up).
*/
scrollPages(pageCount:number):void {
this.scrollDisp(pageCount * (this.rows - 1));
}
/**
* Scrolls the display of the terminal to the top.
*/
scrollToTop():void {
this.scrollDisp(-this.ydisp);
}
/**
* Scrolls the display of the terminal to the bottom.
*/
scrollToBottom():void {
this.scrollDisp(this.ybase - this.ydisp);
}
/**
* Writes text to the terminal.
* @param {string} text The text to write to the terminal.
*/
write(data:string):void {
this.writeBuffer.push(data);
// Send XOFF to pause the pty process if the write buffer becomes too large so
// xterm.js can catch up before more data is sent. This is necessary in order
// to keep signals such as ^C responsive.
if (this.options.useFlowControl && !this.xoffSentToCatchUp && this.writeBuffer.length >= WRITE_BUFFER_PAUSE_THRESHOLD) {
// XOFF - stop pty pipe
// XON will be triggered by emulator before processing data chunk
this.send(C0.DC3);
this.xoffSentToCatchUp = true;
}
if (!this.writeInProgress && this.writeBuffer.length > 0) {
// Kick off a write which will write all data in sequence recursively
this.writeInProgress = true;
// Kick off an async innerWrite so more writes can come in while processing data
var self = this;
setTimeout(function () {
self.innerWrite();
});
}
}
innerWrite():void {
var writeBatch = this.writeBuffer.splice(0, WRITE_BATCH_SIZE);
while (writeBatch.length > 0) {
var data = writeBatch.shift();
var l = data.length, i = 0, j, cs, ch, code, low, ch_width, row;
// If XOFF was sent in order to catch up with the pty process, resume it if
// the writeBuffer is empty to allow more data to come in.
if (this.xoffSentToCatchUp && writeBatch.length === 0 && this.writeBuffer.length === 0) {
this.send(C0.DC1);
this.xoffSentToCatchUp = false;
}
this.refreshStart = this.y;
this.refreshEnd = this.y;
this.parser.parse(data);
this.updateRange(this.y);
this.refresh(this.refreshStart, this.refreshEnd);
}
if (this.writeBuffer.length > 0) {
// Allow renderer to catch up before processing the next batch
var self = this;
setTimeout(function () {
self.innerWrite();
}, 0);
} else {
this.writeInProgress = false;
}
}
/**
* Writes text to the terminal, followed by a break line character (\n).
* @param {string} text The text to write to the terminal.
*/
writeln(data:string):void {
this.write(data + '\r\n');
}
/**
* Attaches a custom keydown handler which is run before keys are processed, giving consumers of
* xterm.js ultimate control as to what keys should be processed by the terminal and what keys
* should not.
* @param {function} customKeydownHandler The custom KeyboardEvent handler to attach. This is a
* function that takes a KeyboardEvent, allowing consumers to stop propogation and/or prevent
* the default action. The function returns whether the event should be processed by xterm.js.
*/
attachCustomKeydownHandler(customKeydownHandler:(string)=>any):void {
this.customKeydownHandler = customKeydownHandler;
}
/**
* Attaches a http(s) link handler, forcing web links to behave differently to
* regular <a> tags. This will trigger a refresh as links potentially need to be
* reconstructed. Calling this with null will remove the handler.
* @param {LinkHandler} handler The handler callback function.
*/
attachHypertextLinkHandler(handler:LinkMatcherHandler):void {
if (!this.linkifier) {
throw new Error('Cannot attach a hypertext link handler before Terminal.open is called');
}
this.linkifier.attachHypertextLinkHandler(handler);
// Refresh to force links to refresh
this.refresh(0, this.rows - 1);
}
/**
* Registers a link matcher, allowing custom link patterns to be matched and
* handled.
* @param {RegExp} regex The regular expression to search for, specifically
* this searches the textContent of the rows. You will want to use \s to match
* a space ' ' character for example.
* @param {LinkHandler} handler The callback when the link is called.
* @param {LinkMatcherOptions} [options] Options for the link matcher.
* @return {number} The ID of the new matcher, this can be used to deregister.
*/
registerLinkMatcher(regex: RegExp, handler: LinkMatcherHandler, options?:LinkMatcherOptions): number {
if (this.linkifier) {
var matcherId = this.linkifier.registerLinkMatcher(regex, handler, options);
this.refresh(0, this.rows - 1);
return matcherId;
}
}
/**
* Deregisters a link matcher if it has been registered.
* @param {number} matcherId The link matcher's ID (returned after register)
*/
deregisterLinkMatcher(matcherId:number):void {
if (this.linkifier) {
if (this.linkifier.deregisterLinkMatcher(matcherId)) {
this.refresh(0, this.rows - 1);
}
}
}
/**
* Handle a keydown event
* Key Resources:
* - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
* @param {KeyboardEvent} ev The keydown event to be handled.
*/
keyDown(ev:KeyboardEvent):boolean {
if (this.customKeydownHandler && this.customKeydownHandler(ev) === false) {
return false;
}
if (!this.compositionHelper.keydown.bind(this.compositionHelper)(ev)) {
if (this.ybase !== this.ydisp) {
this.scrollToBottom();
}
return false;
}
var self = this;
var result = this.evaluateKeyEscapeSequence(ev);
if (result.key === C0.DC3) { // XOFF
this.writeStopped = true;
} else if (result.key === C0.DC1) { // XON
this.writeStopped = false;
}
if (result.scrollDisp) {
this.scrollDisp(result.scrollDisp);
return this.cancel(ev, true);
}
if (isThirdLevelShift(this, ev)) {
return true;
}
if (result.cancel) {
// The event is canceled at the end already, is this necessary?
this.cancel(ev, true);
}
if (!result.key) {
return true;
}
this.emit('keydown', ev);
this.emit('key', result.key, ev);
this.showCursor();
this.handler(result.key);
return this.cancel(ev, true);
}
/**
* Returns an object that determines how a KeyboardEvent should be handled. The key of the
* returned value is the new key code to pass to the PTY.
*
* Reference: http://invisible-island.net/xterm/ctlseqs/ctlseqs.html
* @param {KeyboardEvent} ev The keyboard event to be translated to key escape sequence.
*/
evaluateKeyEscapeSequence(ev:any):{cancel:boolean,key:string,scrollDisp:number} {
var result = {
// Whether to cancel event propogation (NOTE: this may not be needed since the event is
// canceled at the end of keyDown
cancel: false,
// The new key even to emit
key: undefined,
// The number of characters to scroll, if this is defined it will cancel the event
scrollDisp: undefined
};
var modifiers = ev.shiftKey << 0 | ev.altKey << 1 | ev.ctrlKey << 2 | ev.metaKey << 3;
switch (ev.keyCode) {
case 8:
// backspace
if (ev.shiftKey) {
result.key = C0.BS; // ^H
break;
}
result.key = C0.DEL; // ^?
break;
case 9:
// tab
if (ev.shiftKey) {
result.key = C0.ESC + '[Z';
break;
}
result.key = C0.HT;
result.cancel = true;
break;
case 13:
// return/enter
result.key = C0.CR;
result.cancel = true;
break;
case 27:
// escape
result.key = C0.ESC;
result.cancel = true;
break;
case 37:
// left-arrow
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'D';
// HACK: Make Alt + left-arrow behave like Ctrl + left-arrow: move one word backwards
// http://unix.stackexchange.com/a/108106
// macOS uses different escape sequences than linux
if (result.key == C0.ESC + '[1;3D') {
result.key = (this.browser.isMac) ? C0.ESC + 'b' : C0.ESC + '[1;5D';
}
} else if (this.applicationCursor) {
result.key = C0.ESC + 'OD';
} else {
result.key = C0.ESC + '[D';
}
break;
case 39:
// right-arrow
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'C';
// HACK: Make Alt + right-arrow behave like Ctrl + right-arrow: move one word forward
// http://unix.stackexchange.com/a/108106
// macOS uses different escape sequences than linux
if (result.key == C0.ESC + '[1;3C') {
result.key = (this.browser.isMac) ? C0.ESC + 'f' : C0.ESC + '[1;5C';
}
} else if (this.applicationCursor) {
result.key = C0.ESC + 'OC';
} else {
result.key = C0.ESC + '[C';
}
break;
case 38:
// up-arrow
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'A';
// HACK: Make Alt + up-arrow behave like Ctrl + up-arrow
// http://unix.stackexchange.com/a/108106
if (result.key == C0.ESC + '[1;3A') {
result.key = C0.ESC + '[1;5A';
}
} else if (this.applicationCursor) {
result.key = C0.ESC + 'OA';
} else {
result.key = C0.ESC + '[A';
}
break;
case 40:
// down-arrow
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'B';
// HACK: Make Alt + down-arrow behave like Ctrl + down-arrow
// http://unix.stackexchange.com/a/108106
if (result.key == C0.ESC + '[1;3B') {
result.key = C0.ESC + '[1;5B';
}
} else if (this.applicationCursor) {
result.key = C0.ESC + 'OB';
} else {
result.key = C0.ESC + '[B';
}
break;
case 45:
// insert
if (!ev.shiftKey && !ev.ctrlKey) {
// <Ctrl> or <Shift> + <Insert> are used to
// copy-paste on some systems.
result.key = C0.ESC + '[2~';
}
break;
case 46:
// delete
if (modifiers) {
result.key = C0.ESC + '[3;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[3~';
}
break;
case 36:
// home
if (modifiers)
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'H';
else if (this.applicationCursor)
result.key = C0.ESC + 'OH';
else
result.key = C0.ESC + '[H';
break;
case 35:
// end
if (modifiers)
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'F';
else if (this.applicationCursor)
result.key = C0.ESC + 'OF';
else
result.key = C0.ESC + '[F';
break;
case 33:
// page up
if (ev.shiftKey) {
result.scrollDisp = -(this.rows - 1);
} else {
result.key = C0.ESC + '[5~';
}
break;
case 34:
// page down
if (ev.shiftKey) {
result.scrollDisp = this.rows - 1;
} else {
result.key = C0.ESC + '[6~';
}
break;
case 112:
// F1-F12
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'P';
} else {
result.key = C0.ESC + 'OP';
}
break;
case 113:
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'Q';
} else {
result.key = C0.ESC + 'OQ';
}
break;
case 114:
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'R';
} else {
result.key = C0.ESC + 'OR';
}
break;
case 115:
if (modifiers) {
result.key = C0.ESC + '[1;' + (modifiers + 1) + 'S';
} else {
result.key = C0.ESC + 'OS';
}
break;
case 116:
if (modifiers) {
result.key = C0.ESC + '[15;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[15~';
}
break;
case 117:
if (modifiers) {
result.key = C0.ESC + '[17;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[17~';
}
break;
case 118:
if (modifiers) {
result.key = C0.ESC + '[18;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[18~';
}
break;
case 119:
if (modifiers) {
result.key = C0.ESC + '[19;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[19~';
}
break;
case 120:
if (modifiers) {
result.key = C0.ESC + '[20;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[20~';
}
break;
case 121:
if (modifiers) {
result.key = C0.ESC + '[21;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[21~';
}
break;
case 122:
if (modifiers) {
result.key = C0.ESC + '[23;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[23~';
}
break;
case 123:
if (modifiers) {
result.key = C0.ESC + '[24;' + (modifiers + 1) + '~';
} else {
result.key = C0.ESC + '[24~';
}
break;
default:
// a-z and space
if (ev.ctrlKey && !ev.shiftKey && !ev.altKey && !ev.metaKey) {
if (ev.keyCode >= 65 && ev.keyCode <= 90) {
result.key = String.fromCharCode(ev.keyCode - 64);
} else if (ev.keyCode === 32) {
// NUL
result.key = String.fromCharCode(0);
} else if (ev.keyCode >= 51 && ev.keyCode <= 55) {
// escape, file sep, group sep, record sep, unit sep
result.key = String.fromCharCode(ev.keyCode - 51 + 27);
} else if (ev.keyCode === 56) {
// delete
result.key = String.fromCharCode(127);
} else if (ev.keyCode === 219) {
// ^[ - Control Sequence Introducer (CSI)
result.key = String.fromCharCode(27);
} else if (ev.keyCode === 220) {
// ^\ - String Terminator (ST)
result.key = String.fromCharCode(28);
} else if (ev.keyCode === 221) {
// ^] - Operating System Command (OSC)
result.key = String.fromCharCode(29);
}
} else if (!this.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) {
// On Mac this is a third level shift. Use <Esc> instead.
if (ev.keyCode >= 65 && ev.keyCode <= 90) {
result.key = C0.ESC + String.fromCharCode(ev.keyCode + 32);
} else if (ev.keyCode === 192) {
result.key = C0.ESC + '`';
} else if (ev.keyCode >= 48 && ev.keyCode <= 57) {
result.key = C0.ESC + (ev.keyCode - 48);
}
}
break;
}
return result;
};
/**
* Set the G level of the terminal
* @param g
*/
setgLevel(g:number):void {
this.glevel = g;
this.charset = this.charsets[g];
};
/**
* Set the charset for the given G level of the terminal
* @param g
* @param charset
*/
setgCharset(g:number, charset:string):void {
this.charsets[g] = charset;
if (this.glevel === g) {
this.charset = charset;
}
};
/**
* Handle a keypress event.
* Key Resources:
* - https://developer.mozilla.org/en-US/docs/DOM/KeyboardEvent
* @param {KeyboardEvent} ev The keypress event to be handled.
*/
keyPress(ev:KeyboardEvent):boolean {
var key;
this.cancel(ev);
if (ev.charCode) {
key = ev.charCode;
} else if (ev.which == null) {
key = ev.keyCode;
} else if (ev.which !== 0 && ev.charCode !== 0) {
key = ev.which;
} else {
return false;
}
if (!key || (
(ev.altKey || ev.ctrlKey || ev.metaKey) && !isThirdLevelShift(this, ev)
)) {
return false;
}
key = String.fromCharCode(key);
this.emit('keypress', key, ev);
this.emit('key', key, ev);
this.showCursor();
this.handler(key);
return false;
};
/**
* Send data for handling to the terminal
* @param {string} data
*/
send(data:string):void {
var self = this;
if (!this.queue) {
setTimeout(function() {
self.handler(self.queue);
self.queue = '';
}, 1);
}
this.queue += data;
};
/**
* Ring the bell.
* Note: We could do sweet things with webaudio here
*/
bell():void {
if (!this.visualBell) return;
var self = this;
this.element.style.borderColor = 'white';
setTimeout(function() {
self.element.style.borderColor = '';
}, 10);
if (this.popOnBell) this.focus();
};
/**
* Log the current state to the console.
*/
log():void {
if (!this.debug) return;
if (!this.context.console || !this.context.console.log) return;
var args = Array.prototype.slice.call(arguments);
this.context.console.log.apply(this.context.console, args);
};
/**
* Log the current state as error to the console.
*/
error():void {
if (!this.debug) return;
if (!this.context.console || !this.context.console.error) return;
var args = Array.prototype.slice.call(arguments);
this.context.console.error.apply(this.context.console, args);
};
/**
* Resizes the terminal.
*
* @param {number} x The number of columns to resize to.
* @param {number} y The number of rows to resize to.
*/
resize(x:number, y:number):void {
if (isNaN(x) || isNaN(y)) {
return;
}
var line
, el
, i
, j
, ch
, addToY;
if (x === this.cols && y === this.rows) {
return;
}
if (x < 1) x = 1;
if (y < 1) y = 1;
// resize cols
j = this.cols;
if (j < x) {
ch = [this.defAttr, ' ', 1]; // does xterm use the default attr?
i = this.lines.length;
while (i--) {
while (this.lines.get(i).length < x) {
this.lines.get(i).push(ch);
}
}
} else { // (j > x)
i = this.lines.length;
while (i--) {
while (this.lines.get(i).length > x) {
this.lines.get(i).pop();
}
}
}
this.cols = x;
this.setupStops(this.cols);
// resize rows
j = this.rows;
addToY = 0;
if (j < y) {
el = this.element;
while (j++ < y) {
// y is rows, not this.y
if (this.lines.length < y + this.ybase) {
if (this.ybase > 0 && this.lines.length <= this.ybase + this.y + addToY + 1) {
// There is room above the buffer and there are no empty elements below the line,
// scroll up
this.ybase--;
addToY++
if (this.ydisp > 0) {
// Viewport is at the top of the buffer, must increase downwards
this.ydisp--;
}
} else {
// Add a blank line if there is no buffer left at the top to scroll to, or if there
// are blank lines after the cursor
this.lines.push(this.blankLine());
}
}
if (this.children.length < y) {
this.insertRow();
}
}
} else { // (j > y)
while (j-- > y) {
if (this.lines.length > y + this.ybase) {
if (this.lines.length > this.ybase + this.y + 1) {
// The line is a blank line below the cursor, remove it
this.lines.pop();
} else {
// The line is the cursor, scroll down
this.ybase++;
this.ydisp++;
}
}
if (this.children.length > y) {
el = this.children.shift();
if (!el) continue;
el.parentNode.removeChild(el);
}
}
}
this.rows = y;
// Make sure that the cursor stays on screen
if (this.y >= y) {
this.y = y - 1;
}
if (addToY) {
this.y += addToY;
}
if (this.x >= x) {
this.x = x - 1;
}
this.scrollTop = 0;
this.scrollBottom = y - 1;
this.charMeasure.measure();
this.refresh(0, this.rows - 1);
this.normal = null;
this.geometry = [this.cols, this.rows];
this.emit('resize', {terminal: this, cols: x, rows: y});
};
/**
* Updates the range of rows to refresh
* @param {number} y The number of rows to refresh next.
*/
updateRange(y:number):void {
if (y < this.refreshStart) this.refreshStart = y;
if (y > this.refreshEnd) this.refreshEnd = y;
// if (y > this.refreshEnd) {
// this.refreshEnd = y;
// if (y > this.rows - 1) {
// this.refreshEnd = this.rows - 1;
// }
// }
};
/**
* Set the range of refreshing to the maximum value
*/
maxRange():void {
this.refreshStart = 0;
this.refreshEnd = this.rows - 1;
};
/**
* Setup the tab stops.
* @param {number} i
*/
setupStops(i?:number):void {
if (i != null) {
if (!this.tabs[i]) {
i = this.prevStop(i);
}
} else {
this.tabs = {};
i = 0;
}
for (; i < this.cols; i += this.getOption('tabStopWidth')) {
this.tabs[i] = true;
}
};
/**
* Move the cursor to the previous tab stop from the given position (default is current).
* @param {number} x The position to move the cursor to the previous tab stop.
*/
prevStop(x?:number):number {
if (x == null) x = this.x;
while (!this.tabs[--x] && x > 0);
return x >= this.cols
? this.cols - 1
: x < 0 ? 0 : x;
};
/**
* Move the cursor one tab stop forward from the given position (default is current).
* @param {number} x The position to move the cursor one tab stop forward.
*/
nextStop(x?:number):number {
if (x == null) x = this.x;
while (!this.tabs[++x] && x < this.cols);
return x >= this.cols
? this.cols - 1
: x < 0 ? 0 : x;
};
/**
* Erase in the identified line everything from "x" to the end of the line (right).
* @param {number} x The column from which to start erasing to the end of the line.
* @param {number} y The line in which to operate.
*/
eraseRight(x:number, y:number):void {
var line = this.lines.get(this.ybase + y);
if (!line) {
return;
}
var ch = [this.eraseAttr(), ' ', 1]; // xterm
for (; x < this.cols; x++) {
line[x] = ch;
}
this.updateRange(y);
}
/**
* Erase in the identified line everything from "x" to the start of the line (left).
* @param {number} x The column from which to start erasing to the start of the line.
* @param {number} y The line in which to operate.
*/
eraseLeft(x:number, y:number):void {
var line = this.lines.get(this.ybase + y);
if (!line) {
return;
}
var ch = [this.eraseAttr(), ' ', 1]; // xterm
x++;
while (x--) {
line[x] = ch;
}
this.updateRange(y);
}
/**
* Clears the entire buffer, making the prompt line the new first line.
*/
clear():void {
if (this.ybase === 0 && this.y === 0) {
// Don't clear if it's already clear
return;
}
this.lines.set(0, this.lines.get(this.ybase + this.y));
this.lines.length = 1;
this.ydisp = 0;
this.ybase = 0;
this.y = 0;
for (var i = 1; i < this.rows; i++) {
this.lines.push(this.blankLine());
}
this.refresh(0, this.rows - 1);
this.emit('scroll', this.ydisp);
};
/**
* Erase all content in the given line
* @param {number} y The line to erase all of its contents.
*/
eraseLine(y:number):void {
this.eraseRight(0, y);
};
/**
* Return the data array of a blank line
* @param {number} cur First bunch of data for each "blank" character.
*/
blankLine(cur?:boolean):any[][] {
var attr = cur
? this.eraseAttr()
: this.defAttr;
var ch = [attr, ' ', 1] // width defaults to 1 halfwidth character
, line = []
, i = 0;
for (; i < this.cols; i++) {
line[i] = ch;
}
return line;
};
/**
* If cur return the back color xterm feature attribute. Else return defAttr.
* @param {object} cur
*/
ch(cur:object):[number,string,number] {
return cur
? [this.eraseAttr(), ' ', 1]
: [this.defAttr, ' ', 1];
};
/**
* Evaluate if the current erminal is the given argument.
* @param {object} term The terminal to evaluate
*/
is(term:string):boolean {
var name = this.termName;
return (name + '').indexOf(term) === 0;
};
/**
* Emit the 'data' event and populate the given data.
* @param {string} data The data to populate in the event.
*/
handler(data:string):void {
// Prevents all events to pty process if stdin is disabled
if (this.options.disableStdin) {
return;
}
// Input is being sent to the terminal, the terminal should focus the prompt.
if (this.ybase !== this.ydisp) {
this.scrollToBottom();
}
this.emit('data', data);
}
/**
* Emit the 'title' event and populate the given title.
* @param {string} title The title to populate in the event.
*/
handleTitle(title:string):void {
/**
* This event is emitted when the title of the terminal is changed
* from inside the terminal. The parameter is the new title.
*
* @event title
*/
this.emit('title', title);
}
/**
* ESC
*/
/**
* ESC D Index (IND is 0x84).
*/
index():void {
this.y++;
if (this.y > this.scrollBottom) {
this.y--;
this.scroll();
}
// If the end of the line is hit, prevent this action from wrapping around to the next line.
if (this.x >= this.cols) {
this.x--;
}
}
/**
* ESC M Reverse Index (RI is 0x8d).
*
* Move the cursor up one row, inserting a new blank line if necessary.
*/
reverseIndex():void {
var j;
if (this.y === this.scrollTop) {
// possibly move the code below to term.reverseScroll();
// test: echo -ne '\e[1;1H\e[44m\eM\e[0m'
// blankLine(true) is xterm/linux behavior
this.lines.shiftElements(this.y + this.ybase, this.rows - 1, 1);
this.lines.set(this.y + this.ybase, this.blankLine(true));
this.updateRange(this.scrollTop);
this.updateRange(this.scrollBottom);
} else {
this.y--;
}
}
/**
* ESC c Full Reset (RIS).
*/
reset():void {
this.options.rows = this.rows;
this.options.cols = this.cols;
var customKeydownHandler = this.customKeydownHandler;
Terminal.call(this, this.options);
this.customKeydownHandler = customKeydownHandler;
this.refresh(0, this.rows - 1);
this.viewport.syncScrollArea();
}
/**
* ESC H Tab Set (HTS is 0x88).
*/
tabSet():void {
this.tabs[this.x] = true;
}
/**
* Helpers
*/
static on(el:EventTarget|EventTarget[], type:string, handler:(...args:any[])=>any, capture?:boolean):void {
var els:EventTarget[] = Array.isArray(el) ? el : [el];
els.forEach(function (element) {
element.addEventListener(type, handler, capture || false);
});
}
static off(el:EventTarget, type:string, handler:(...args:any[])=>any, capture?:boolean):void {
el.removeEventListener(type, handler, capture || false);
}
static cancel(ev:Event, force?:boolean):boolean {
if (!this.cancelEvents && !force) {
return;
}
ev.preventDefault();
ev.stopPropagation();
return false;
}
static EventEmitter = EventEmitter;
static inherits(child:any, parent:any):void {
function f() {
this.constructor = child;
}
f.prototype = parent.prototype;
child.prototype = new f;
}
static matchColor_cache:object = {};
matchColor(r1:number, g1:number, b1:number):number {
// http://stackoverflow.com/questions/1633828
function distance(r1, g1, b1, r2, g2, b2) {
return Math.pow(30 * (r1 - r2), 2)
+ Math.pow(59 * (g1 - g2), 2)
+ Math.pow(11 * (b1 - b2), 2);
};
var hash = (r1 << 16) | (g1 << 8) | b1;
if (Terminal.matchColor_cache[hash] != null) {
return Terminal.matchColor_cache[hash];
}
var ldiff = Infinity
, li = -1
, i = 0
, c
, r2
, g2
, b2
, diff;
for (; i < Terminal.vcolors.length; i++) {
c = Terminal.vcolors[i];
r2 = c[0];
g2 = c[1];
b2 = c[2];
diff = distance(r1, g1, b1, r2, g2, b2);
if (diff === 0) {
li = i;
break;
}
if (diff < ldiff) {
ldiff = diff;
li = i;
}
}
return Terminal.matchColor_cache[hash] = li;
}
}
Object.keys(Terminal.defaults).forEach(function(key:string):void {
Terminal[key] = Terminal.defaults[key];
Terminal.options[key] = Terminal.defaults[key];
});
function isThirdLevelShift(term:Terminal, ev:KeyboardEvent):boolean {
var thirdLevelKey =
(term.browser.isMac && ev.altKey && !ev.ctrlKey && !ev.metaKey) ||
(term.browser.isMSWindows && ev.altKey && ev.ctrlKey && !ev.metaKey);
if (ev.type == 'keypress') {
return thirdLevelKey;
}
// Don't invoke for arrows, pageDown, home, backspace, etc. (on non-keypress events)
return thirdLevelKey && (!ev.keyCode || ev.keyCode > 47);
}
/**
* Adds an event listener to the terminal.
*
* @param {string} event The name of the event. TODO: Document all event types
* @param {function} callback The function to call when the event is triggered.
*/
var on = Terminal.on;
var off = Terminal.off;
var cancel = Terminal.cancel;
module.exports = Terminal;
|
Sevasun/subscribe-form
|
refs/heads/master
|
/js/main.js
|
// init
document.addEventListener('DOMContentLoaded', function() {
let form = document.querySelector('.subscribe-form');
let input = form.querySelector('input[type="email"]');
let regExp = /^[a-z]+[a-z0-9_\.-]*@\w+\.[a-z]{2,8}$/i;
form.setAttribute('novalidate', 'novalidate');
input.addEventListener('input', () => {
form.classList.remove('error');
});
form.addEventListener('submit', (e) => {
e.preventDefault();
if(input['value'].match(regExp) === null) {
form.classList.add('error');
} else {
sendForm();
}
return false;
});
function showThankYouMessage() {
let message = document.createElement('div');
message.classList.add('thank-message');
message.innerHTML = 'Thank you!';
form.appendChild(message);
form.classList.add('success');
};
function clearForm() {
input.value = "";
return input.value;
}
function sendForm() {
let data = new FormData();
data.append('email', input.value);
let request = fetch('http://sereda.in.ua/mail.php', {
method: 'POST',
body: data
})
.then(() => clearForm())
.then(() => showThankYouMessage())
.catch((error) => console.log(error));
};
});
|
Sevasun/subscribe-form
|
refs/heads/master
|
/README.md
|
# subscribe-form
simple subscribe form with validation and thank-you message
|
dtkeijser/ChapAppFirebase
|
refs/heads/master
|
/app/src/main/java/com/example/chapapp/registerlogin/LoginActivity.kt
|
package com.example.chapapp.registerlogin
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.example.chapapp.R
import com.google.firebase.auth.FirebaseAuth
import kotlinx.android.synthetic.main.activity_login.*
class LoginActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
btn_login.setOnClickListener{
val email = tv_email_login.text.toString()
val password = tv_password_login.text.toString()
Log.d( "Login", "Attempt login with email/pw: $email/***")
FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password)
//make new intent to go to new activity
.addOnCompleteListener { finish() }
// .addOnFailureListener { }
}
tv_back_reg.setOnClickListener {
finish()
}
}
}
|
dtkeijser/ChapAppFirebase
|
refs/heads/master
|
/app/src/main/java/com/example/chapapp/messages/ChatLogActivity.kt
|
package com.example.chapapp.messages
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.example.chapapp.NewMessageActivity
import com.example.chapapp.R
import com.example.chapapp.models.ChatMessage
import com.example.chapapp.models.User
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.ChildEventListener
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.FirebaseDatabase
import com.squareup.picasso.Picasso
import com.xwray.groupie.GroupAdapter
import com.xwray.groupie.Item
import com.xwray.groupie.ViewHolder
import kotlinx.android.synthetic.main.activity_chat_log.*
import kotlinx.android.synthetic.main.chat_from_row_left.view.*
import kotlinx.android.synthetic.main.chat_to_row_right.view.*
class ChatLogActivity : AppCompatActivity() {
companion object {
val TAG = "ChatLogActivity"
}
val adapter = GroupAdapter<ViewHolder>()
var toUser: User? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chat_log)
rv_chat_log.adapter = adapter
toUser = intent.getParcelableExtra<User>(NewMessageActivity.USER_KEY)
supportActionBar?.title = toUser?.username
// setupDummyData()
ListenForMessages()
btn_send_chat_log.setOnClickListener {
Log.d(TAG, "Attempt to send message")
performSendMessage()
}
}
private fun ListenForMessages() {
val fromId = FirebaseAuth.getInstance().uid
val toId = toUser?.uid
val ref = FirebaseDatabase.getInstance().getReference("/user-messages/$fromId/$toId")
ref.addChildEventListener(object : ChildEventListener {
override fun onChildAdded(snapshot: DataSnapshot, previousChildName: String?) {
val chatMessage = snapshot.getValue(ChatMessage::class.java)
if (chatMessage != null) {
Log.d(TAG, chatMessage.text)
if (chatMessage.fromId == FirebaseAuth.getInstance().uid) {
val currentUser = LatestMessagesActivity.currentUser ?: return
adapter.add(ChatFromItem(chatMessage.text, currentUser))
} else {
//val toUser = intent.getParcelableExtra<User>(NewMessageActivity.USER_KEY)
adapter.add(ChatToItem(chatMessage.text, toUser!!))
}
}
rv_chat_log.scrollToPosition(adapter.itemCount -1)
}
override fun onChildChanged(snapshot: DataSnapshot, previousChildName: String?) {
}
override fun onChildRemoved(snapshot: DataSnapshot) {
}
override fun onChildMoved(snapshot: DataSnapshot, previousChildName: String?) {
}
override fun onCancelled(error: DatabaseError) {
}
})
}
private fun performSendMessage() {
val text = et_chat_log.text.toString()
// Pushes to messages
// val reference = FirebaseDatabase.getInstance().getReference("/messages").push()
val fromId = FirebaseAuth.getInstance().uid
val user = intent.getParcelableExtra<User>(NewMessageActivity.USER_KEY)
val toId = user!!.uid
val reference = FirebaseDatabase.getInstance().getReference("/user-messages/$fromId/$toId").push()
val toReference = FirebaseDatabase.getInstance().getReference("/user-messages/$toId/$fromId").push()
if (fromId == null) return
val chatMessage =
ChatMessage(reference.key!!, text, fromId, toId, System.currentTimeMillis() / 1000)
reference.setValue(chatMessage)
.addOnSuccessListener {
Log.d(TAG, "Saved our chat message: ${reference.key}")
et_chat_log.text.clear()
rv_chat_log.scrollToPosition(adapter.itemCount -1)
}
toReference.setValue(chatMessage)
val latestMessageRef = FirebaseDatabase.getInstance().getReference("/latest-messages/$fromId/$toId")
latestMessageRef.setValue(chatMessage)
val latestMessageToRef = FirebaseDatabase.getInstance().getReference("/latest-messages/$toId/$fromId")
latestMessageToRef.setValue(chatMessage)
}
// private fun setupDummyData() {
// val adapter = GroupAdapter<ViewHolder>()
// adapter.add(ChatFromItem("from MESSAGES"))
// adapter.add(ChatToItem("TO MESSAGE"))
// adapter.add(ChatFromItem("YEAHHHHHHHHH"))
// adapter.add(ChatToItem("HELLOOOO"))
// adapter.add(ChatFromItem("BOOOOOOOOOOOOOOOOOOOOOOOOOOOOO"))
//
//
// rv_chat_log.adapter = adapter
// }
}
class ChatFromItem(val text: String, val user: User) : Item<ViewHolder>() {
override fun bind(viewHolder: ViewHolder, position: Int) {
viewHolder.itemView.tv_chat_from_row_right.text = text
//load image into chat
val uri = user.profileImageUrL
val targetImageView = viewHolder.itemView.iv_chat_from_row_left
Picasso.get().load(uri).into(targetImageView)
}
override fun getLayout(): Int {
return R.layout.chat_from_row_left
}
}
class ChatToItem(val text: String, val user: User) : Item<ViewHolder>() {
override fun bind(viewHolder: ViewHolder, position: Int) {
viewHolder.itemView.tv_chat_to_row_right.text = text
val uri = user.profileImageUrL
val targetImageView = viewHolder.itemView.iv_chat_to_row_right
Picasso.get().load(uri).into(targetImageView)
}
override fun getLayout(): Int {
return R.layout.chat_to_row_right
}
}
|
dtkeijser/ChapAppFirebase
|
refs/heads/master
|
/settings.gradle
|
include ':app'
rootProject.name = "ChapApp"
|
giogonzo/react-intl
|
refs/heads/master
|
/src/components/useIntl.ts
|
import {useContext} from 'react'
import {Context} from './injectIntl'
import {invariantIntlContext} from '../utils'
import {IntlShape} from '../types'
export default function useIntl(): IntlShape {
const intl = useContext(Context)
invariantIntlContext(intl)
return intl
}
|
giogonzo/react-intl
|
refs/heads/master
|
/src/error.ts
|
import {MessageDescriptor} from './types'
export const enum ReactIntlErrorCode {
FORMAT_ERROR = 'FORMAT_ERROR',
UNSUPPORTED_FORMATTER = 'UNSUPPORTED_FORMATTER',
INVALID_CONFIG = 'INVALID_CONFIG',
MISSING_DATA = 'MISSING_DATA',
MISSING_TRANSLATION = 'MISSING_TRANSLATION',
}
export class ReactIntlError extends Error {
public readonly code: ReactIntlErrorCode
public readonly descriptor?: MessageDescriptor
constructor(
code: ReactIntlErrorCode,
message: string,
descriptor?: MessageDescriptor,
exception?: Error
) {
super(
`[React Intl Error ${code}] ${message} ${
exception ? `\n${exception.stack}` : ''
}`
)
this.code = code
this.descriptor = descriptor
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(this, ReactIntlError)
}
}
}
|
altopalido/yelp_python
|
refs/heads/master
|
/README.md
|
# yelp_python
Web Application development with python and SQLite. Using www.yelp.com user reviews Database.
|
altopalido/yelp_python
|
refs/heads/master
|
/yelp_python/settings.py
|
# Madis Settings
MADIS_PATH='/Users/alexiatopalidou/Desktop/erg/madis/src'
# Webserver Settings
# IMPORTANT: The port must be available.
web_port = 9090 # must be integer (this is wrong:'9090')
|
altopalido/yelp_python
|
refs/heads/master
|
/yelp_python/app.py
|
# ----- CONFIGURE YOUR EDITOR TO USE 4 SPACES PER TAB ----- #
import settings
import sys
def connection():
''' User this function to create your connections '''
import sys
sys.path.append(settings.MADIS_PATH)
import madis
con = madis.functions.Connection('/Users/alexiatopalidou/Desktop/erg/yelp_python/yelp.db')
return con
def classify_review(reviewid):
#check for compatible data type
try:
val=str(reviewid)
except ValueError:
return [("Error! Insert correct data type.")]
# Create a new connection
global con
con=connection()
# Create cursors on the connection
#alternative: create the desired list after every textwindow, posterms, negterms query
cur=con.cursor()
cura=con.cursor()
curb=con.cursor()
cur1=con.cursor()
cur2=con.cursor()
#check for existance of given data inside the yelp.db
curcheck=con.cursor()
cur.execute("SELECT var('reviewid',?)",(reviewid,))
check=curcheck.execute("SELECT review_id from reviews where review_id=?",(val,))
try:
ch=check.next()
except StopIteration:
return [("Error! Insert valid Review id.",)]
#sql query with textwindow - one for each occasion (terms with 1, 2 or 3 words)
res=cur.execute("SELECT textwindow(text,0,0,1) from reviews where review_id=var('reviewid');")
resa=cura.execute("SELECT textwindow(text,0,0,2) from reviews where review_id=var('reviewid');")
resb=curb.execute("SELECT textwindow(text,0,0,3) from reviews where review_id=var('reviewid');")
#get positive/negative terms
res1=cur1.execute("SELECT * from posterms;")
res2=cur2.execute("SELECT * from negterms;")
#create lists that store a)all reviews terms, b)positive terms and c)negative terms
k=[]
for n in res:
k.append(n)
for n in resa:
k.append(n)
for n in resb:
k.append(n)
m=[]
for z in res1:
m.append(z)
o=[]
for p in res2:
o.append(p)
#check if the review is positive or negative
x=0
for i in k:
for j in m:
if i==j:
x=x+1
y=0
for i in k:
for j in o:
if i==j:
y=y+1
if x>y:
rsl='positive'
elif x<y:
rsl='negative'
else:
rsl='neutral'
#return a list with the results
res=cur.execute("SELECT b.name, ? from business b, reviews r where r.business_id=b.business_id and r.review_id=?",(rsl, val,))
l=[("business_name","result")]
for i in res:
l.append(i)
return l
def classify_review_plain_sql(reviewid):
# Create a new connection
con=connection()
# Create a cursor on the connection
cur=con.cursor()
return [("business_name","result")]
def updatezipcode(business_id,zipcode):
#check for compatible data type
try:
val=str(business_id)
val2=int(zipcode)
except ValueError:
return [("Error! Insert correct data type.",)]
# Create a new connection
global con
con=connection()
# Create a cursor on the connection
cur=con.cursor()
#check for existance of given data inside the yelp.db or allowance of data value
curcheck=con.cursor()
cur.execute("select var('business_id',?)", (val,))
check=curcheck.execute("SELECT business_id from business where business_id=?;",(val,))
try:
ch=check.next()
except StopIteration:
return [("Error! Insert valid Business Id.",)]
if val2>99999999999999999999: #we do not actually need that
return [("Error! Insert valid Zip code.",)]
#execute main sql query
res=cur.execute("UPDATE business set zip_code=? where business_id=?;",(val2,val,))
#return ok or comment that return and de-comment the bottom return for the business_id and the new zip_code
return [('ok',)]
#res=cur.execute("SELECT business_id, zip_code from business where business_id=?;",(val,))
#l=[("business_id", "zip_code"),]
#for i in res:
# l.append(i)
#return l
def selectTopNbusinesses(category_id,n):
#check for compatible data type
try:
val=int(category_id)
val2=int(n)
except ValueError:
return [("Error! Insert correct data type",)]
# Create a new connection
global con
con=connection()
# Create a cursor on the connection
cur=con.cursor()
#check for existance of given data inside the yelp.db
curcheck=con.cursor()
cur.execute("SELECT var('category_id',?)", (val,))
check=curcheck.execute("SELECT category_id from category where category_id=?;",(val,))
try:
ch=check.next()
except StopIteration:
return [("Error! Insert valid Category Id.",)]
if val2<0:
return [("Error! Choose >=0 businesses to return.",)]
#execute main sql query
res=cur.execute("SELECT b.business_id, count(rpn.positive) from reviews_pos_neg rpn, reviews r, business b, business_category bc, category c where rpn.review_id=r.review_id and r.business_id=b.business_id and b.business_id=bc.business_id and bc.category_id=c.category_id and c.category_id=? group by b.business_id order by count(rpn.positive) desc;",(val,))
#return a list with the results
l=[("business_id", "number_of_reviews",)]
for i in res:
l.append(i)
return l[0:val2+1]
def traceUserInfuence(userId,depth):
# Create a new connection
con=connection()
# Create a cursor on the connection
cur=con.cursor()
return [("user_id",),]
|
shlsheth263/malware-detection-using-ANN
|
refs/heads/master
|
/python/gui.py
|
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
import test_python3
class Root(Tk):
def __init__(self):
super(Root, self).__init__()
self.title("Malware Detection")
self.minsize(500, 300)
self.labelFrame = ttk.LabelFrame(self, text = " Open File")
self.labelFrame.grid(column = 0, row = 1, padx = 200, pady = 20)
self.button()
def button(self):
self.button = ttk.Button(self.labelFrame, text = "Browse A File",command = self.fileDialog)
self.button.grid(column = 1, row = 1)
def fileDialog(self):
self.filename = filedialog.askopenfilename(initialdir = "/", title = "Select A File")
self.label = ttk.Label(self.labelFrame, text = "")
self.label.grid(column = 1, row = 2)
self.label.configure(text = self.filename)
root = Root()
root.mainloop()
|
shlsheth263/malware-detection-using-ANN
|
refs/heads/master
|
/python/test_python3_cli.py~
|
#!/usr/bin/env python
import sys
import time
import pandas as pd
import pepy
import binascii
import numpy as np
from hashlib import md5
import sklearn
from tkinter import *
from tkinter import ttk
from tkinter import filedialog
from tensorflow.keras.models import load_model
def test(p):
exe = {}
print("Signature: %s" % int(p.signature))
exe['Signature'] = int(p.signature)
exe['Magic'] = int(p.magic)
print("Machine: %s (%s)" % (int(p.machine), p.get_machine_as_str()))
exe['Machine'] = int(p.machine), p.get_machine_as_str()
print("Number of sections: %s" % p.numberofsections)
exe['Number of Sections'] = p.numberofsections
print("Number of symbols: %s" % p.numberofsymbols)
exe['Number of symbols'] = p.numberofsymbols
print("Characteristics: %s" % int(p.characteristics))
exe['characteristics'] = int(p.characteristics)
exe['timestamp'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(p.timedatestamp))
print("Timedatestamp: %s" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(p.timedatestamp)))
exe['CodeSize'] = int(p.codesize)
print("Size of code: %s" % int(p.codesize))
exe['SizeofInitial'] = int(p.initdatasize)
print("Size of initialized data: %s" % int(p.initdatasize))
exe['UninitSize'] = int(p.uninitdatasize)
print("Size of uninitialized data: %s" % int(p.uninitdatasize))
exe['Baseofcode'] = int(p.baseofcode)
print("Base address of code: %s" % int(p.baseofcode))
try:
exe['baseaddr'] = int(p.baseofdata)
print("Base address of data: %s" % int(p.baseofdata))
except:
# Not available on PE32+, ignore it.
pass
exe['imagebase'] = int(p.imagebase)
print("Image base address: %s" % int(p.imagebase))
exe['sectionalign'] = int(p.sectionalignement)
print("Section alignment: %s" % int(p.sectionalignement))
exe['filealign'] = int(p.filealignment)
print("File alignment: %s" % int(p.filealignment))
exe['imagesize'] = int(p.imagesize)
print("Size of image: %s" % int(p.imagesize))
exe['headersize'] = int(p.headersize)
print("Size of headers: %s" % int(p.headersize))
exe['checksum'] = int(p.checksum)
print("Checksum: %s" % int(p.checksum))
exe['dllchar'] = int(p.dllcharacteristics)
print("DLL characteristics: %s" % int(p.dllcharacteristics))
exe['stacksize'] = int(p.stackreservesize)
print("Size of stack reserve: %s" % int(p.stackreservesize))
exe['stackcommit'] = int(p.stackcommitsize)
print("Size of stack commit: %s" % int(p.stackcommitsize))
exe['heapsize'] = int(p.heapreservesize)
print("Size of heap reserve: %s" % int(p.heapreservesize))
exe['heapcommit'] = int(p.heapcommitsize)
print("Size of heap commit: %s" % int(p.heapcommitsize))
exe['rva'] = int(p.rvasandsize)
print("Number of RVA and sizes: %s" % int(p.rvasandsize))
ep = p.get_entry_point()
byts = p.get_bytes(ep, 8)
print("Bytes at %s: %s" % (int(ep), ' '.join(['%#2x' % b for b in byts])))
sections = p.get_sections()
print("Sections: (%i)" % len(sections))
for sect in sections:
print("[+] %s" % sect.name)
print("\tBase: %s" % int(sect.base))
print("\tLength: %s" % sect.length)
print("\tVirtual address: %s" % int(sect.virtaddr))
print("\tVirtual size: %i" % sect.virtsize)
print("\tNumber of Relocations: %i" % sect.numrelocs)
print("\tNumber of Line Numbers: %i" % sect.numlinenums)
print("\tCharacteristics: %s" % int(sect.characteristics))
if sect.length:
print("\tFirst 10 bytes: 0x%s" % binascii.hexlify(sect.data[:10]))
print("\tMD5: %s" % md5(sect.data).hexdigest())
imports = p.get_imports()
print("Imports: (%i)" % len(imports))
l = []
for imp in imports:
l.append((imp.sym, imp.name, int(imp.addr)))
# exe['symbol'] = imp.sym,imp.name,int(imp.addr)
print("[+] Symbol: %s (%s %s)" % (imp.sym, imp.name, int(imp.addr)))
exe['symbol'] = l
exports = p.get_exports()
print("Exports: (%i)" % len(exports))
for exp in exports:
exe['module'] = exp.mod, exp.func, int(exp.addr)
print("[+] Module: %s (%s %s)" % (exp.mod, exp.func, int(exp.addr)))
relocations = p.get_relocations()
print("Relocations: (%i)" % len(relocations))
for reloc in relocations:
print("[+] Type: %s (%s)" % (reloc.type, int(reloc.addr)))
resources = p.get_resources()
print("Resources: (%i)" % len(resources))
for resource in resources:
print("[+] MD5: (%i) %s" % (len(resource.data), md5(resource.data).hexdigest()))
if resource.type_str:
print("\tType string: %s" % resource.type_str)
else:
print("\tType: %s (%s)" % (int(resource.type), resource.type_as_str()))
if resource.name_str:
print("\tName string: %s" % resource.name_str)
else:
print("\tName: %s" % int(resource.name))
if resource.lang_str:
print("\tLang string: %s" % resource.lang_str)
else:
print("\tLang: %s" % int(resource.lang))
print("\tCodepage: %s" % int(resource.codepage))
print("\tRVA: %s" % int(resource.RVA))
print("\tSize: %s" % int(resource.size))
return exe
class Root(Tk):
def __init__(self):
super(Root, self).__init__()
self.mean_entropy = 6.69
self.mean_size = 6.895724 * 10 ** 6
self.mean_pointer = 5.513845 * 10 ** 5
self.mean_petype = 267
self.mean_optionalHeader = 224
self.mean_timestamp = 1.223333 * 10 ** 9
self.var = [2.45814868e+00, 5.78522477e+05, 4.59263747e-02, 3.94699109e+00
, 5.56093128e+05, 4.23275300e-02, 4.28793369e+00, 5.09558456e+05
, 4.26259209e-02, 4.52582805e+00, 5.00721420e+05, 4.38214743e-02
, 4.80847515e+00, 3.36937892e+05, 3.42121736e-02, 5.08079739e+00
, 2.82976405e+05, 3.27880482e-02, 5.19862150e+00, 2.51661820e+05
, 3.03001968e-02, 5.49108651e+00, 2.74803628e+05, 2.34008748e-02
, 5.65433567e+00, 2.61551950e+05, 2.20549168e-02, 5.82167673e+00
, 2.75945872e+05, 1.92542233e-02, 5.39081620e+00, 2.43941220e+05
, 1.66215197e-02, 5.25240971e+00, 2.13100610e+05, 1.38812852e-02
, 4.97209114e+00, 1.79580514e+05, 1.12734193e-02, 4.91835550e+00
, 1.81600442e+05, 9.08298818e-03, 4.67832320e+00, 1.75802757e+05
, 7.47834940e-03, 4.43536234e+00, 1.83062732e+05, 5.76560040e-03
, 3.36212748e+00, 1.05659050e+05, 4.12555574e-03, 3.44924796e+00
, 1.24784300e+05, 3.04785086e-03, 2.55147211e+00, 1.04770043e+05
, 2.20631168e-03, 2.63965525e+00, 1.31953132e+05, 1.50017798e-03
, 1.35032309e+13, 5.91049166e+13, 2.74411618e+08, 2.27146205e+08
, 1.30716250e+00, 1.02203650e+06, 1.64823331e+17, 9.70130473e+00
, 0.00000000e+00, 6.95117702e+14, 6.26391725e+00, 6.32965418e+14
, 0.00000000e+00, 1.39712067e+15, 3.09269595e+15, 2.53964553e+12
, 1.60595659e+06, 2.89297402e+14, 2.38878188e+15, 0.00000000e+00
, 1.35741026e+13, 8.21475966e+16, 8.55336176e-02, 1.57953396e-02
, 1.06058200e-02, 8.71010278e-03, 7.42508784e-03, 6.52156777e-03
, 5.72855385e-03, 4.99552441e-03, 4.36254449e-03, 3.93076962e-03
, 3.63767050e-03, 3.37999893e-03, 3.20280197e-03, 3.04227928e-03
, 2.93082120e-03, 2.85412932e-03, 2.79797761e-03, 2.71092621e-03
, 2.61535713e-03, 2.55340228e-03, 2.48501139e-03, 2.42902100e-03
, 2.36850195e-03, 2.29861381e-03, 2.23819994e-03, 2.17795827e-03
, 2.11676028e-03, 2.06515542e-03, 2.01478973e-03, 1.96564128e-03
, 1.91556309e-03, 1.86943149e-03, 1.83240435e-03, 1.79120738e-03
, 1.75672559e-03, 1.71652747e-03, 1.68120594e-03, 1.65315473e-03
, 1.62036128e-03, 1.59368312e-03, 1.56195259e-03, 1.53480747e-03
, 1.50568561e-03, 1.48263107e-03, 1.46131105e-03, 1.43606408e-03
, 1.41276985e-03, 1.39413270e-03, 1.37646323e-03, 1.35706705e-03]
self.mean = [3.38644034e+00, 7.43425464e+02, 6.40294006e-01, 3.41446464e+00
, 7.43311042e+02, 3.93069798e-01, 3.44198895e+00, 7.65279393e+02
, 3.30402571e-01, 3.37149071e+00, 7.42151971e+02, 2.99447860e-01
, 3.17242069e+00, 5.44187845e+02, 2.54659310e-01, 3.13009675e+00
, 4.84051874e+02, 2.31965387e-01, 3.03159921e+00, 4.77210895e+02
, 2.11030105e-01, 2.91210220e+00, 4.75812355e+02, 1.79221157e-01
, 2.48661283e+00, 4.07247419e+02, 1.46988188e-01, 2.35089123e+00
, 4.09849329e+02, 1.27373824e-01, 2.05407365e+00, 3.31339017e+02
, 1.09869680e-01, 1.83130422e+00, 2.84458239e+02, 9.13302463e-02
, 1.65633359e+00, 2.43290193e+02, 7.70382677e-02, 1.53908652e+00
, 2.37653259e+02, 6.49126524e-02, 1.40798980e+00, 2.15514487e+02
, 5.50734013e-02, 1.27721807e+00, 2.05804280e+02, 4.48429695e-02
, 9.54851129e-01, 1.16369741e+02, 3.33964758e-02, 9.08127297e-01
, 1.24898928e+02, 2.66482729e-02, 6.62233444e-01, 1.04622009e+02
, 1.90757276e-02, 6.01659959e-01, 1.28183120e+02, 1.37406010e-02
, 1.70803755e+05, 8.91260553e+05, 1.89259938e+04, 1.02192320e+04
, 6.69685927e+00, 8.22232244e+02, 1.63555414e+08, 3.32080948e+02
, 2.67000000e+02, 5.19991299e+05, 5.71698208e+00, 2.24746765e+05
, 2.67000000e+02, 6.57049714e+05, 6.93815969e+06, 6.83251704e+05
, 1.59274898e+03, 2.44727973e+06, 1.63751281e+06, 2.24000000e+02
, 1.71372990e+05, 1.22412702e+09, 3.23793663e-01, 1.76607058e-01
, 1.55393276e-01, 1.45630353e-01, 1.37842988e-01, 1.31876001e-01
, 1.25851666e-01, 1.20359017e-01, 1.15054661e-01, 1.10336582e-01
, 1.05885689e-01, 1.01550953e-01, 9.65836144e-02, 9.22891413e-02
, 8.80601110e-02, 8.45020529e-02, 8.11572167e-02, 7.87433791e-02
, 7.69100818e-02, 7.45285251e-02, 7.27705280e-02, 7.10439361e-02
, 6.96190823e-02, 6.82907176e-02, 6.71648772e-02, 6.60168642e-02
, 6.49738245e-02, 6.39356689e-02, 6.31187099e-02, 6.23316077e-02
, 6.14790592e-02, 6.07008932e-02, 5.98904188e-02, 5.90441028e-02
, 5.82944078e-02, 5.76313235e-02, 5.69379230e-02, 5.60963207e-02
, 5.53104343e-02, 5.47383798e-02, 5.40714718e-02, 5.34539907e-02
, 5.28624994e-02, 5.23242945e-02, 5.18031428e-02, 5.11818326e-02
, 5.05779398e-02, 4.99491364e-02, 4.95038547e-02, 4.90042634e-02]
self.mean=np.array(self.mean)
self.var=np.array(self.var)
def fileDialog(self):
x = test(pepy.parse(self.filename))
importedDLL = set()
importedSymbols = set()
for row in x['symbol']:
importedSymbols.add(row[0])
importedDLL.add(row[1])
self.x_list = [x['Baseofcode'], x['baseaddr'], x['characteristics'], x['dllchar'], self.mean_entropy,
x['filealign'], x['imagebase'], list(importedDLL), list(importedSymbols), x['Machine'][0],
x['Magic'], x['rva'], x['Number of Sections'], x['Number of symbols'], self.mean_petype,
self.mean_pointer, self.mean_size, x['CodeSize'], x['headersize'], x['imagesize'],
x['SizeofInitial'], self.mean_optionalHeader, x['UninitSize'], self.mean_timestamp]
y = ""
z = ""
m = np.array(self.x_list)
imported_dlls = m[7]
imported_syms = m[8]
m = np.delete(m, 7)
m = np.delete(m, 7)
m = np.reshape(m, (1, m.shape[0]))
print("m:", m)
x_test = m
n_x_test = np.zeros(shape=(x_test.shape[0], 132))
for i in range(0, x_test.shape[0]):
if i % 1000 == 0:
print(i)
row = df.iloc[i + 40001, :]
row_dlls = imported_dlls
row_syms = imported_syms
row_dlss_str=""
row_syms_str=""
for ele in row_dlls:
row_dlss_str += ele.lower() +" "
for ele in row_syms:
row_syms_str += ele.lower() +" "
print(row_dlss_str)
print(row_syms_str)
dll_tfidfs = dll_vec.transform([row_dlss_str, ]).toarray()[0]
dll_tfidf_pairs = []
for num, dll in enumerate(row_dlss_str.split()):
if num == 20:
break
dll_tfidf = dll_tfidfs[list(dll_vec.get_feature_names()).index(dll)]
dll_tfidf_pairs.append([dll_tfidf, list(dll_vec.get_feature_names()).index(dll)])
dll_tfidf_pairs = np.array(dll_tfidf_pairs)
# print(dll_tfidf_pairs)
dll_tfidf_pairs = dll_tfidf_pairs[dll_tfidf_pairs[:, 0].argsort()[::-1]]
for j, pair in enumerate(dll_tfidf_pairs):
name = dll_vec.get_feature_names()[int(pair[1])]
if name in scrape_dict:
n_x_test[i, 3 * j] = scrape_dict[name][0]
n_x_test[i, 3 * j + 1] = scrape_dict[name][1]
n_x_test[i, 3 * j + 2] = pair[0]
else:
n_x_test[i, 3 * j] = 1
n_x_test[i, 3 * j + 1] = 4
n_x_test[i, 3 * j + 2] = pair[0]
# print(ip1_train)
sym_tfidf = sym_vec.transform([row_syms_str, ]).toarray()[0]
sym_tfidf = sorted(sym_tfidf, reverse=True)[:50]
ip2_train = np.append(x_test[i], sym_tfidf)
n_x_test[i, 60:] = ip2_train
num = model.predict((n_x_test - self.mean) / (self.var ** 0.5 + 0.069))
print("NUM" + str(num))
if num >= 0 and num <= 0.3:
y = "Low"
z = "Good to use"
elif num > 0.3 and num <= 0.6:
y = "Medium"
z = "Can be used"
elif num > 0.6 and num <= 1:
y = "High"
z = "Avoid Using"
else:
y = "Out of range"
z = "Cant determine"
self.label.config(text="Recommendation : " + y)
self.label = ttk.Label(self.labelFrame, text="")
self.label.grid(column=1, row=3)
self.label.config(text=z)
df = pd.read_csv("brazilian-malware.csv")
df = df.drop(columns=["Identify", "SHA1", "FirstSeenDate"])
idll = df.loc[:, "ImportedDlls"]
idll = set(idll)
dlls = set()
for row in idll:
for dll in row.split():
dlls.add(dll)
isyms = df.loc[:, "ImportedSymbols"]
isyms = set(isyms)
syms = set()
for row in isyms:
for dll in row.split():
syms.add(dll)
df_temp = df.drop(columns=["ImportedDlls", "ImportedSymbols"])
x_train = np.array(df_temp.drop(columns=["Label"]).iloc[:40001, :])
y_train = np.array(df_temp.iloc[:40001, :].loc[:, "Label"])
x_test = np.array(df_temp.drop(columns=["Label"]).iloc[40001:, :])
y_test = np.array(df_temp.iloc[40001:, :].loc[:, "Label"])
from sklearn.feature_extraction.text import TfidfVectorizer
dll_vec = TfidfVectorizer(smooth_idf=False, analyzer="word", tokenizer=lambda x: x.split())
x = dll_vec.fit_transform(list(df.loc[:, "ImportedDlls"]))
sym_vec = TfidfVectorizer(smooth_idf=False, analyzer="word", tokenizer=lambda x: x.split())
x = sym_vec.fit_transform(list(df.loc[:, "ImportedSymbols"]))
df_scrape = pd.read_csv("spithack1.csv").drop(['Description'], axis=1)
np_scrape = df_scrape.values
scrape_dict = {}
for i, row in enumerate(np_scrape):
if not row[1] == "-1":
name = row[0].replace("_dll", ".dll")
pop = -1
if "Very Low" in row[1]:
pop = 1
if "Low" in row[1]:
pop = 2
if "Medium" in row[1]:
pop = 3
if "High" in row[1]:
pop = 4
if "Very High" in row[1]:
pop = 5
if pop == -1:
print("err", row[1])
exp = row[2].replace(",", "")
scrape_dict[name] = [pop, int(exp)]
model = load_model('acc_97_44.h5')
|
cindy01/sandbox
|
refs/heads/master
|
/index.php
|
<?php
/*class BankAccount{
public $balance = 10.5;
public function DisplayBalance(){
return 'Balance: '. $this->balance;
}
public function Withdraw($amount){
if($this->balance < $amount){
echo ' Not enough money!';
}else{
$this->balance = $this->balance-$amount;
}
}
}
$alex = new BankAccount;
$alex ->Withdraw(15);
echo $alex ->DisplayBalance();
*/
/*class BankAccount{
//protected $balance = 3500;
protected $_balance = 3500;
public $balance = 2500;
public function DisplayBalance(){
return $this->_balance;
}
}
$cindy = new BankAccount;
echo $cindy->DisplayBalance();
echo $cindy->balance;*/
/*class Circle {
const pi = 3.141;
public function Area($radius){
//return self::pi * ($radius * $radius);
return $this::pi * ($radius * $radius);
}
}
$cindy = new Circle;
echo $cindy->Area(5);
echo $cindy::pi;
*/
/*class Test{
public function __construct($something){
$this->SaySomething($something);
}
public function SaySomething($something){
echo $something;
}
}
$test= new Test('Some text here');
//$test->SaySomething();*/
/*
class BankAccount{
public $balance = 0;
public $type = '';
public function DisplayBalance(){
return 'Balance: '. $this->balance;
}
public function SetType($input){
$this->type = $input;
}
public function Withdraw($amount){
if($this->balance < $amount){
echo ' Not enough money!<br>';
}else{
$this->balance = $this->balance-$amount;
}
}
public function Deposit($amount){
$this->balance = $this->balance + $amount;
}
}
class SavingAccount extends BankAccount{
public $type = '18-25';
}
$billy = new BankAccount;
$billy->SetType('18-25');
echo $billy->type;
*/
/*$ben = new SavingAccount;
$ben->Deposit(3000);
echo $ben->type.'<br>';
echo $ben->DisplayBalance();
$cindy = new BankAccount;
$cindy->Deposit(1000);
$cindy->Withdraw(240);
$cindy->Withdraw(140);
$billy = new BankAccount;
$billy->Deposit(2000);
$billy->Withdraw(240);
$billy->Withdraw(140);
$cindy->Withdraw(140);
$billy->Deposit(4000);
$billy_saving = new SavingAccount;
$billy->Withdraw(14000);
echo $billy_saving->type;
echo 'Cindy '.$cindy->DisplayBalance().'<br>';
echo 'Billy '.$billy->DisplayBalance();*/
/*class DatabaseConnect {
public function __construct($db_host,$db_username,$db_password){
echo 'Attemting connection<br>';
//echo $db_host.'<br>'.$db_username.'<br>'.$db_password;
if(!@$this->Connect($db_host,$db_username,$db_password)){
echo 'Connection failed';
}else if($this->Connect($db_host,$db_username,$db_password)){
echo 'Connected to '. $db_host;
}
}
public function Connect($db_host,$db_username,$db_password){
if (!mysqli_connect($db_host,$db_username,$db_password)){
return false;
}else{
return true;
}
}
}
$connection = new DatabaseConnect('localhost','root','');*/
//require_once('myclass.php');
//require_once('math.php');
//$cindy = new Myclass('Cindy','Park');
//$John = new Myclass('John','Lock');
//var_dump($cindy);
//var_dump($John);
//$John->dosomething();
//$ben = new Math;
//echo $ben->add(5,10,12,13);
//
//echo Math::add(2,3)
include('myclass.php');
//$class1 = new Myclass;
//print_r(MyClass::checkImage('envato.jpg'));
//MyClass::checkImage('envato.jpg');
//MyClass::checkImage('envato.jpg');
//MyClass::checkImage('envato.jpg');
//print_r(MyClass::checkImage('envato.jpg'));
//echo Myclass::getNumUploaded()."<br>";
//
//$instance = new Myclass();
//echo Myclass::getNumUploaded();
//
//echo Myclass::getNumUploaded();
?>
|
arun8785/ArunkumarAlgorithmsAssignmentSolution
|
refs/heads/main
|
/arunkumarAlgorithmsAssignmentSolution/src/com/stockers/model/StockDetails.java
|
package com.stockers.model;
import java.util.Scanner;
public class StockDetails {
private int noOfCompanies;
public double[] shrPrice;
public boolean[] shrGrowth;
public StockDetails(int noOfCompanies) {
this.noOfCompanies = noOfCompanies;
}
public double getnoOfCompanies() {
return noOfCompanies;
}
public void noOfCompanies(int noOfCompanies) {
this.noOfCompanies = noOfCompanies;
}
public void AddShareDetails() {
double[] shrPrice;
boolean[] shrGrowth;
shrPrice = new double[noOfCompanies];
shrGrowth = new boolean[noOfCompanies];
@SuppressWarnings("resource")
Scanner sr = new Scanner(System.in);
for(int i=0;i<noOfCompanies;i++) {
int j=i+1;
System.out.println("Enter current stock price of the company " + j);
shrPrice[i] = sr.nextDouble();
System.out.println("Whether company's stock price rose today compare to yesterday?");
shrGrowth[i] = sr.nextBoolean();
}
this.shrPrice = shrPrice;
this.shrGrowth = shrGrowth;
}
}
|
jamesspwalker/week_07_day_2_hw_musical
|
refs/heads/master
|
/src/views/instrument_info_view.js
|
const PubSub = require('../helpers/pub_sub.js');
const InstrumentInfoView = function(container){
this.container = container;
};
InstrumentInfoView.prototype.bindEvents = function(){
PubSub.subscribe('InstrumentFamilies:selected-instrument-ready', (evt) => {
const instrument = evt.detail;
this.render(instrument);
});
};
InstrumentInfoView.prototype.render = function(family){
const infoParagraph = document.createElement('p');
infoParagraph.textContent = `${family.description}`;
this.container.innerHTML = '';
this.container.appendChild(infoParagraph);
};
module.exports = InstrumentInfoView;
|
francois-blanchard/Memo_project_flash
|
refs/heads/master
|
/README.md
|
Memo_project_flash
==================
Jeu de Memo
|
francois-blanchard/Memo_project_flash
|
refs/heads/master
|
/js/script.js
|
function TestAs(s,n){
alert("test: "+s+" : "+n);
}
|
Phalanxia/recs
|
refs/heads/master
|
/src/BuiltInPlugins/init.lua
|
return {
CollectionService = require(script.CollectionService),
ComponentChangedEvent = require(script.ComponentChangedEvent),
}
|
Phalanxia/recs
|
refs/heads/master
|
/rotriever.toml
|
name = "RECS"
author = "AmaranthineCodices <git@amaranthinecodices.me>"
license = "MIT"
content_root = "src"
version = "1.0.0"
[dependencies]
TestEZ = { git = "https://github.com/Roblox/testez", rev = "master" }
t = { git = "https://github.com/osyrisrblx/t", rev = "master" }
|
Phalanxia/recs
|
refs/heads/master
|
/README.md
|
# RECS
A work-in-progress successor to [RobloxComponentSystem](https://github.com/tiffany352/RobloxComponentSystem). Primary differences:
* Systems exist as a formalized concept
* Components have very little attached behavior
* Singleton components exist
|
mon0li/ICEspeed
|
refs/heads/master
|
/ice.sh
|
#!/bin/bash
speed=$(echo "$(curl -s "https://www.ombord.info/api/jsonp/position/" | grep "speed" | cut -d'"' -f 4)*3.6" | bc -l)
d=$(date)
echo "$d $speed km/h"
|
JoeChan/openbgp
|
refs/heads/master
|
/README.md
|
# openbgp
[](https://github.com/openbgp/openbgp/blob/master/LICENSE)
[](https://travis-ci.org/openbgp/openbgp)
[](https://codeclimate.com/github/openbgp/openbgp)
### What is openbgp?
OpenBGP is a Python implementation for BGP Protocol. It was born in Cisco around 2011, we use it to establish BGP connections with all kinds of
routers (include real Cisco/HuaWei/Juniper routers and some router simulators in Cisco like IOL/IOU) and receive/parse BGP messages for future analysis.
We write it in strict accordance with the specifications of RFCs.
This software can be used on Linux/Unix, Mac OS and Windows systems.
### Features
* It can establish BGP session based on IPv4 address (TCP Layer) in active mode(as TCP client);
* Support TCP MD5 authentication(IPv4 and does not support Windows now);
* BGP capabilities support: 4 Bytes ASN, IPv4 address family, Route Refresh(Cisco Route Refresh);
* Decode all BGP messages to human readable strings and write files to disk(configurable);
### Quick Start
We recommend run `openbgp` through python virtual-env from source code.
```bash
$ virtualenv openbgp-virl
$ source openbgp-virl/bin/activate
$ git clone https://github.com/openbgp/openbgp
$ cd openbgp
$ pip install -r requirements.txt
$ cd bin
$ python openbgpd -h
usage: openbgpd [-h] [--bgp-local_addr BGP_LOCAL_ADDR]
[--bgp-local_as BGP_LOCAL_AS] [--bgp-md5 BGP_MD5]
[--bgp-norib] [--bgp-remote_addr BGP_REMOTE_ADDR] [--bgp-rib]
[--bgp-remote_as BGP_REMOTE_AS] [--config-dir DIR]
[--config-file PATH] [--log-config-file LOG_CONFIG_FILE]
[--log-dir LOG_DIR] [--log-file LOG_FILE]
[--log-file-mode LOG_FILE_MODE] [--nouse-stderr]
[--use-stderr] [--verbose] [--version] [--noverbose]
optional arguments:
-h, --help show this help message and exit
--config-dir DIR Path to a config directory to pull *.conf files from.
This file set is sorted, so as to provide a
predictable parse order if individual options are
over-ridden. The set is parsed after the file(s)
specified via previous --config-file, arguments hence
over-ridden options in the directory take precedence.
--config-file PATH Path to a config file to use. Multiple config files
can be specified, with values in later files taking
precedence. The default files used are: None.
--log-config-file LOG_CONFIG_FILE
Path to a logging config file to use
--log-dir LOG_DIR log file directory
--log-file LOG_FILE log file name
--log-file-mode LOG_FILE_MODE
default log file permission
--nouse-stderr The inverse of --use-stderr
--use-stderr log to standard error
--verbose show debug output
--version show program's version number and exit
--noverbose The inverse of --verbose
bgp options:
--bgp-local_addr BGP_LOCAL_ADDR
The local address of the BGP
--bgp-local_as BGP_LOCAL_AS
The Local BGP AS number
--bgp-md5 BGP_MD5 The MD5 string use to auth
--bgp-norib The inverse of --rib
--bgp-remote_addr BGP_REMOTE_ADDR
The remote address of the peer
--bgp-rib Whether maintain BGP rib table
--bgp-remote_as BGP_REMOTE_AS
The remote BGP peer AS number
```
For example:
```bash
$ python openbgpd --bgp-local_addr=1.1.1.1 --bgp-local_as=65001 --bgp-remote_addr=1.1.1.2 --bgp-remote_as=65001 --bgp-md5=test --config-file=../etc/openbgp/openbgp.ini
```
BGP message example:
in `openbgp.ini`, you can point out if you want to store the parsing BGP message to local disk and where you want to put them in.
```
[message]
# how to process parsed BGP message?
# Whether the BGP message is written to disk
# write_disk = True
# the BGP messages storage path
# write_dir = /home/bgpmon/data/bgp/
write_dir = ./
# The Max size of one BGP message file, the unit is MB
# write_msg_max_size = 500
```
```
$ more 1429257741.41.msg
[1429258235.343657, 1, 1, {'bgpID': '192.168.45.1', 'Version': 4, 'holdTime': 180, 'ASN': 23650, 'Capabilities': {'GracefulRestart': False, 'ciscoMultiSession': False, 'ciscoRouteRefresh': True, '4byteAS': True, 'AFI_SAFI': [(1, 1)], '7
0': '', 'routeRefresh': True}}, (0, 0)]
[1429258235.346803, 2, 4, None, (0, 0)]
[1429258235.349598, 3, 4, None, (0, 0)]
[1429258235.349837, 4, 2, {'ATTR': {1: 0, 2: [(2, [64639, 64660])], 3: '192.168.24.1', 4: 0, 5: 100}, 'WITHDRAW': [], 'NLRI': ['192.168.1.0/24']}, (1, 1)]
```
The structure of each line is:
```
[timestamp, sequence number, message type, message content, address family]
```
For message type:
```
MSG_OPEN = 1
MSG_UPDATE = 2
MSG_NOTIFICATION = 3
MSG_KEEPALIVE = 4
MSG_ROUTEREFRESH = 5
MSG_CISCOROUTEREFRESH = 128
```
### Support
Send email to penxiao@cisco.com, or use GitHub issue system.
### TODO
* support more address family (IPv6, VPNv4, VPNv6, etc.)
* support RESTful API
* support sending BGP message through API
* unittest
* others
|
JoeChan/openbgp
|
refs/heads/master
|
/openbgp/common/constants.py
|
# Copyright 2015 Cisco Systems, Inc.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
""" All BGP constant values """
# some handy things to know
BGP_MAX_PACKET_SIZE = 4096
BGP_MARKER_SIZE = 16 # size of BGP marker
BGP_HEADER_SIZE = 19 # size of BGP header, including marker
BGP_MIN_OPEN_MSG_SIZE = 29
BGP_MIN_UPDATE_MSG_SIZE = 23
BGP_MIN_NOTIFICATION_MSG_SIZE = 21
BGP_MIN_KEEPALVE_MSG_SIZE = BGP_HEADER_SIZE
BGP_TCP_PORT = 179
BGP_ROUTE_DISTINGUISHER_SIZE = 8
# BGP message types
BGP_OPEN = 1
BGP_UPDATE = 2
BGP_NOTIFICATION = 3
BGP_KEEPALIVE = 4
BGP_ROUTE_REFRESH = 5
BGP_CAPABILITY = 6
BGP_ROUTE_REFRESH_CISCO = 0x80
BGP_SIZE_OF_PATH_ATTRIBUTE = 2
# attribute flags, from RFC1771
BGP_ATTR_FLAG_OPTIONAL = 0x80
BGP_ATTR_FLAG_TRANSITIVE = 0x40
BGP_ATTR_FLAG_PARTIAL = 0x20
BGP_ATTR_FLAG_EXTENDED_LENGTH = 0x10
# SSA flags
BGP_SSA_TRANSITIVE = 0x8000
BGP_SSA_TYPE = 0x7FFF
# SSA Types
BGP_SSA_L2TPv3 = 1
BGP_SSA_mGRE = 2
BGP_SSA_IPSec = 3
BGP_SSA_MPLS = 4
BGP_SSA_L2TPv3_IN_IPSec = 5
BGP_SSA_mGRE_IN_IPSec = 6
# AS_PATH segment types
AS_SET = 1 # RFC1771
AS_SEQUENCE = 2 # RFC1771
AS_CONFED_SET = 4 # RFC1965 has the wrong values, corrected in
AS_CONFED_SEQUENCE = 3 # draft-ietf-idr-bgp-confed-rfc1965bis-01.txt
# OPEN message Optional Parameter types
BGP_OPTION_AUTHENTICATION = 1 # RFC1771
BGP_OPTION_CAPABILITY = 2 # RFC2842
# attribute types
BGPTYPE_ORIGIN = 1 # RFC1771
BGPTYPE_AS_PATH = 2 # RFC1771
BGPTYPE_NEXT_HOP = 3 # RFC1771
BGPTYPE_MULTI_EXIT_DISC = 4 # RFC1771
BGPTYPE_LOCAL_PREF = 5 # RFC1771
BGPTYPE_ATOMIC_AGGREGATE = 6 # RFC1771
BGPTYPE_AGGREGATOR = 7 # RFC1771
BGPTYPE_COMMUNITIES = 8 # RFC1997
BGPTYPE_ORIGINATOR_ID = 9 # RFC2796
BGPTYPE_CLUSTER_LIST = 10 # RFC2796
BGPTYPE_DPA = 11 # work in progress
BGPTYPE_ADVERTISER = 12 # RFC1863
BGPTYPE_RCID_PATH = 13 # RFC1863
BGPTYPE_MP_REACH_NLRI = 14 # RFC2858
BGPTYPE_MP_UNREACH_NLRI = 15 # RFC2858
BGPTYPE_EXTENDED_COMMUNITY = 16 # Draft Ramachandra
BGPTYPE_NEW_AS_PATH = 17 # draft-ietf-idr-as4bytes
BGPTYPE_NEW_AGGREGATOR = 18 # draft-ietf-idr-as4bytes
BGPTYPE_SAFI_SPECIFIC_ATTR = 19 # draft-kapoor-nalawade-idr-bgp-ssa-00.txt
BGPTYPE_TUNNEL_ENCAPS_ATTR = 23 # RFC5512
BGPTYPE_LINK_STATE = 99
BGPTYPE_ATTRIBUTE_SET = 128
# VPN Route Target #
BGP_EXT_COM_RT_0 = 0x0002 # Route Target,Format AS(2bytes):AN(4bytes)
BGP_EXT_COM_RT_1 = 0x0102 # Route Target,Format IPv4 address(4bytes):AN(2bytes)
BGP_EXT_COM_RT_2 = 0x0202 # Route Target,Format AS(4bytes):AN(2bytes)
# Route Origin (SOO site of Origin)
BGP_EXT_COM_RO_0 = 0x0003 # Route Origin,Format AS(2bytes):AN(4bytes)
BGP_EXT_COM_RO_1 = 0x0103 # Route Origin,Format IP address:AN(2bytes)
BGP_EXT_COM_RO_2 = 0x0203 # Route Origin,Format AS(2bytes):AN(4bytes)
# BGP Flow Spec
BGP_EXT_TRA_RATE = 0x8006 # traffic-rate 2-byte as#, 4-byte float
BGP_EXT_TRA_ACTION = 0x8007 # traffic-action bitmask
BGP_EXT_REDIRECT = 0x8008 # redirect 6-byte Route Target
BGP_EXT_TRA_MARK = 0x8009 # traffic-marking DSCP value
# BGP cost cummunity
BGP_EXT_COM_COST = 0x4301
# BGP link bandwith
BGP_EXT_COM_LINK_BW = 0x4004
# NLRI type as define in BGP flow spec RFC
BGPNLRI_FSPEC_DST_PFIX = 1 # RFC 5575
BGPNLRI_FSPEC_SRC_PFIX = 2 # RFC 5575
BGPNLRI_FSPEC_IP_PROTO = 3 # RFC 5575
BGPNLRI_FSPEC_PORT = 4 # RFC 5575
BGPNLRI_FSPEC_DST_PORT = 5 # RFC 5575
BGPNLRI_FSPEC_SRC_PORT = 6 # RFC 5575
BGPNLRI_FSPEC_ICMP_TP = 7 # RFC 5575
BGPNLRI_FSPEC_ICMP_CD = 8 # RFC 5575
BGPNLRI_FSPEC_TCP_FLAGS = 9 # RFC 5575
BGPNLRI_FSPEC_PCK_LEN = 10 # RFC 5575
BGPNLRI_FSPEC_DSCP = 11 # RFC 5575
BGPNLRI_FSPEC_FRAGMENT = 12 # RFC 5575
# BGP message Constants
VERSION = 4
PORT = 179
HDR_LEN = 19
MAX_LEN = 4096
# BGP messages type
MSG_OPEN = 1
MSG_UPDATE = 2
MSG_NOTIFICATION = 3
MSG_KEEPALIVE = 4
MSG_ROUTEREFRESH = 5
MSG_CISCOROUTEREFRESH = 128
# BGP Capabilities Support
SUPPORT_4AS = False
CISCO_ROUTE_REFRESH = False
NEW_ROUTE_REFRESH = False
GRACEFUL_RESTART = False
# AFI_SAFI mapping
AFI_SAFI_DICT = {
(1, 1): 'ipv4',
(1, 4): 'label_ipv4',
(1, 128): 'vpnv4',
(2, 1): 'ipv6',
(2, 4): 'label_ipv6',
(2, 128): 'vpnv6'
}
AFI_SAFI_STR_DICT = {
'ipv4': (1, 1),
'ipv6': (1, 2)
}
# BGP FSM State
ST_IDLE = 1
ST_CONNECT = 2
ST_ACTIVE = 3
ST_OPENSENT = 4
ST_OPENCONFIRM = 5
ST_ESTABLISHED = 6
# BGP Timer (seconds)
DELAY_OPEN_TIME = 10
ROUTE_REFRESH_TIME = 10
LARGER_HOLD_TIME = 4 * 60
CONNECT_RETRY_TIME = 30
IDLEHOLD_TIME = 30
HOLD_TIME = 120
stateDescr = {
ST_IDLE: "IDLE",
ST_CONNECT: "CONNECT",
ST_ACTIVE: "ACTIVE",
ST_OPENSENT: "OPENSENT",
ST_OPENCONFIRM: "OPENCONFIRM",
ST_ESTABLISHED: "ESTABLISHED"
}
# Notification error codes
ERR_MSG_HDR = 1
ERR_MSG_OPEN = 2
ERR_MSG_UPDATE = 3
ERR_HOLD_TIMER_EXPIRED = 4
ERR_FSM = 5
ERR_CEASE = 6
# Notification suberror codes
ERR_MSG_HDR_CONN_NOT_SYNC = 1
ERR_MSG_HDR_BAD_MSG_LEN = 2
ERR_MSG_HDR_BAD_MSG_TYPE = 3
ERR_MSG_OPEN_UNSUP_VERSION = 1
ERR_MSG_OPEN_BAD_PEER_AS = 2
ERR_MSG_OPEN_BAD_BGP_ID = 3
ERR_MSG_OPEN_UNSUP_OPT_PARAM = 4
ERR_MSG_OPEN_UNACCPT_HOLD_TIME = 6
ERR_MSG_OPEN_UNSUP_CAPA = 7 # RFC 5492
ERR_MSG_OPEN_UNKNO = 8
ERR_MSG_UPDATE_MALFORMED_ATTR_LIST = 1
ERR_MSG_UPDATE_UNRECOGNIZED_WELLKNOWN_ATTR = 2
ERR_MSG_UPDATE_MISSING_WELLKNOWN_ATTR = 3
ERR_MSG_UPDATE_ATTR_FLAGS = 4
ERR_MSG_UPDATE_ATTR_LEN = 5
ERR_MSG_UPDATE_INVALID_ORIGIN = 6
ERR_MSG_UPDATE_INVALID_NEXTHOP = 8
ERR_MSG_UPDATE_OPTIONAL_ATTR = 9
ERR_MSG_UPDATE_INVALID_NETWORK_FIELD = 10
ERR_MSG_UPDATE_MALFORMED_ASPATH = 11
ERR_MSG_UPDATE_UNKOWN_ATTR = 12
AttributeID_dict = {
1: 'ORIGIN',
2: 'AS_PATH',
3: 'NEXT_HOP',
4: 'MULTI_EXIT_DISC',
5: 'LOCAL_PREF',
6: 'ATOMIC_AGGREGATE',
7: 'AGGREGATOR',
8: 'COMMUNITY',
9: 'ORIGINATOR_ID',
10: 'CLUSTER_LIST',
14: 'MP_REACH_NLRI',
15: 'MP_UNREACH_NLRI',
16: 'EXTENDED_COMMUNITY',
17: 'AS4_PATH',
18: 'AS4_AGGREGATOR'
}
ATTRSTR_DICT = {
'AGGREGATOR': 7,
'AS4_AGGREGATOR': 18,
'AS4_PATH': 17,
'AS_PATH': 2,
'ATOMIC_AGGREGATE': 6,
'CLUSTER_LIST': 10,
'COMMUNITY': 8,
'EXTENDED_COMMUNITY': 16,
'LOCAL_PREFERENCE': 5,
'MP_REACH_NLRI': 14,
'MP_UNREACH_NLRI': 15,
'MULTI_EXIT_DISC': 4,
'NEXT_HOP': 3,
'ORIGIN': 1,
'ORIGINATOR_ID': 9}
TCP_MD5SIG_MAXKEYLEN = 80
SS_PADSIZE_IPV4 = 120
TCP_MD5SIG = 14
SS_PADSIZE_IPV6 = 100
SIN6_FLOWINFO = 0
SIN6_SCOPE_ID = 0
COMMUNITY_DICT = False
|
JoeChan/openbgp
|
refs/heads/master
|
/requirements.txt
|
oslo.config==1.6.0
Twisted==15.0.0
ipaddr==2.1.11
|
bdhillon23/Cucumber_First
|
refs/heads/master
|
/Cucumber/src/test/java/com/dhillon/Cucumber/steps/Login2.java
|
package com.dhillon.Cucumber.steps;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class Login2 {
@Given("^User(\\d+) navigate to the stackoverflow website on the login page$")
public void user2_navigate_to_the_stackoverflow_website_on_the_login_page(int arg1) throws Throwable {
System.out.println("User 2 navigate to the stackoverflow website on the login page");
}
@When("^user(\\d+) clicks on the login button$")
public void user2_clicks_on_the_login_button(int arg1) throws Throwable {
System.out.println("User 2 navigate to the stackoverflow website on the login page");
}
@When("^user(\\d+) enters valid username ,password$")
public void user2_enters_valid_username_password(int arg1) throws Throwable {
System.out.println("User 2 navigate to the stackoverflow website on the login page");
}
@When("^clicks(\\d+) on the login page\\.$")
public void clicks2_on_the_login_page(int arg1) throws Throwable {
System.out.println("User 2 navigate to the stackoverflow website on the login page");
}
@Then("^System(\\d+) should allow user to login successfully\\.$")
public void system2_should_allow_user_to_login_successfully(int arg1) throws Throwable {
System.out.println("User 2 navigate to the stackoverflow website on the login page");
}
}
|
bdhillon23/Cucumber_First
|
refs/heads/master
|
/Cucumber/src/test/java/com/dhillon/Cucumber/runner/MainRunner.java
|
package com.dhillon.Cucumber.runner;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
@RunWith(Cucumber.class)
@CucumberOptions(
features = {"C:\\Users\\balwinder\\git\\Cucumber\\Cucumber\\src\\test\\java\\com\\dhillon\\Cucumber\\features\\Login.feature","C:\\Users\\balwinder\\git\\Cucumber\\Cucumber\\src\\test\\java\\com\\dhillon\\Cucumber\\features\\Login2.feature"},
glue = {"com.dhillon.Cucumber.steps"},
monochrome =true,
tags={},
plugin={"pretty" , "html:target/cucumber","json:target/cucumber.json","com.cucumber.listener.ExtentCucumberFormatter:target/report.html"}
)
public class MainRunner {
}
|
fruitsamples/iGetKeys
|
refs/heads/master
|
/iGKTest.c
|
/*
File: MLTEUserPane.c
Description:
This file contains the main application program for the MLTEUserPane
example. This application creates a dialog window and installs a scrolling
text user pane in the dialog. You will notice that since the implementation
of these scrolling text fields is based on the user pane control manager
api, this program makes very few calls for maintaining the edit
fields. those calls are made by the control manager.
Routines in this file are responsible for handling events directed
at the application.
Where calls are explicitly made to routines defined in the
file mUPControl.h, I have added comments beginning with
the phrase:
Call to mUPControl.h
Copyright:
Copyright 2000 Apple Computer, Inc. All rights reserved.
Disclaimer:
IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under Apples
copyrights in this original Apple software (the "Apple Software"), to use,
reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions of
the Apple Software. Neither the name, trademarks, service marks or logos of
Apple Computer, Inc. may be used to endorse or promote products derived from the
Apple Software without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or implied,
are granted by Apple herein, including but not limited to any patent rights that
may be infringed by your derivative works or by other works in which the Apple
Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
(INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Change History (most recent first):
Fri, Jan 28, 2000 -- created
*/
#ifdef __APPLE_CC__
#include <Carbon/Carbon.h>
#else
#include <Carbon.h>
#endif
#include "iGKTest.h"
#include "iGetKeys.h"
#include "MapDialog.h"
Boolean gRunning = true;
Boolean gTesting = false;
typedef struct {
short itemNo;
short keycode;
short state;
ControlHandle itemControl;
char* name;
short namelen;
} ItemKeyCode;
ItemKeyCode gItemKeyCheckboxes[] = {
{ 4, kVirtualCapsLockKey, 0, NULL, "Caps Lock", 9},
{ 5, kVirtualShiftKey, 0, NULL, "Shift", 5},
{ 6, kVirtualControlKey, 0, NULL, "Control", 7},
{ 7, kVirtualOptionKey, 0, NULL, "Option", 6},
{ 8, kVirtualCommandKey, 0, NULL, "Command", 7},
{ 9, kVirtualHelpKey, 0, NULL, "Help", 4},
{ 10, kVirtualDeleteKey, 0, NULL, "Delete", 6},
{ 11, kVirtualTabKey, 0, NULL, "Tab", 3},
{ 12, kVirtualEnterKey, 0, NULL, "Enter", 5},
{ 13, kVirtualReturnKey, 0, NULL, "Return", 6},
{ 14, kVirtualEscapeKey, 0, NULL, "Escape", 6},
{ 15, kVirtualForwardDeleteKey, 0, NULL, "FwdDelete", 6},
{ 16, kVirtualHomeKey, 0, NULL, "Home", 4},
{ 17, kVirtualEndKey, 0, NULL, "End", 3},
{ 18, kVirtualPageUpKey, 0, NULL, "Page Up", 7},
{ 19, kVirtualPageDownKey, 0, NULL, "Page Down", 9},
{ 20, kVirtualLeftArrowKey, 0, NULL, "Arrow Left", 10},
{ 21, kVirtualRightArrowKey, 0, NULL, "Arrow Right", 11},
{ 22, kVirtualUpArrowKey, 0, NULL, "Arrow Up", 8},
{ 23, kVirtualDownArrowKey, 0, NULL, "Arrow Down", 10}
};
enum {
kGKCharacterListItem = 3,
kNumCheckBoxes = (sizeof(gItemKeyCheckboxes)/sizeof(ItemKeyCode))
};
DialogPtr gGKDialog = NULL;
DialogMapRecPtr gItemMap = NULL;
enum {
kTestDialogID = 130,
kCancelTestItem = 1,
kTestListItem = 2
};
DialogPtr gTestDialog = NULL;
DialogMapRecPtr gTestMap = NULL;
void ProcessNextEvent(void);
typedef struct {
Boolean asciiEntry;
Boolean state;
short code;
} KeyEntryTable;
static void BeginTestingSequence(void) {
ItemKeyCode *itemp;
short itemt, i;
Handle itemh;
Rect itemb;
Str255 s;
Size outActualSize;
ControlHandle listbox;
Ascii2KeyCodeTable ttable;
Cell theCell;
ListHandle gTestList = NULL;
Boolean isDown, product, changed, tableChanged;
KeyEntryTable keyTable[64], *entryp;
short keyTableSize;
/* get the test dialog, separate the list control */
gTestDialog = GetNewDialog(kTestDialogID, NULL, (WindowPtr)(-1));
NewDialogItemMap(gTestDialog, &gTestMap);
GetDialogItemAsControl(gTestDialog, kTestListItem, &listbox);
GetControlData(listbox, kControlEntireControl, kControlListBoxListHandleTag, sizeof(gTestList), &gTestList, &outActualSize);
SetListSelectionFlags(gTestList, 0);
/* list of ascii codes to test */
GetDialogItem( gGKDialog, kGKCharacterListItem, &itemt, &itemh, &itemb );
GetDialogItemText( itemh, s );
/* set up the ascii translation table */
InitAscii2KeyCodeTable( &ttable );
/* set up our local translation table */
keyTableSize = 0;
entryp = keyTable;
/* gather letters typed in table */
for (i=0; i<s[0]; i++) {
/* display in list */
SetPt(&theCell, 0, LAddRow(1, 3000, gTestList));
LSetCell(&s[i+1], 1, theCell, gTestList);
/* add new key table entry */
entryp->asciiEntry = true;
entryp->code = s[i+1];
entryp->state = false;
keyTableSize++;
entryp++;
}
/* gather checkboxes into table */
for (i=0, itemp=gItemKeyCheckboxes; i<kNumCheckBoxes; itemp++, i++)
if (itemp->state) {
/* display in list */
SetPt(&theCell, 0, LAddRow(1, 3000, gTestList));
LSetCell(itemp->name, itemp->namelen, theCell, gTestList);
/* add new key table entry */
entryp->asciiEntry = false;
entryp->code = itemp->keycode;
entryp->state = false;
keyTableSize++;
entryp++;
}
/* display the window */
ShowWindow(GetDialogWindow(gTestDialog));
/* while the window is visible, re-display the keys */
gTesting = true;
while (gTesting) {
/* validate the ascii translation table */
ValidateAscii2KeyCodeTable( &ttable, &tableChanged);
/* set the drawing environment */
SetPortWindowPort(GetDialogWindow(gTestDialog));
product = true;
changed = false;
for (i = 0, entryp=keyTable; i < keyTableSize; entryp++, i++) {
/* search the table for key transitions */
if (entryp->asciiEntry)
isDown = TestForAsciiKeyDown( &ttable, entryp->code );
else isDown = TestForKeyDown(entryp->code);
if (isDown != entryp->state) {
entryp->state = isDown;
SetPt(&theCell, 0, i);
LSetSelect(isDown, theCell, gTestList);
changed = true;
}
if ( ! isDown ) product = false;
}
/* redraw the list if it changed */
if (changed) Draw1Control(listbox);
/* beep and exit if all the keys are down */
if ( product ) {
SysBeep(1);
gTesting = false;
}
/* process the next event */
ProcessNextEvent();
}
/* close and return to the caller */
DisposeDialog(gTestDialog);
gTestDialog = NULL;
gTestList = NULL;
}
static void GKKeyTestDialog(EventRecord *ev, DialogPtr theDialog, short itemHit) {
if (itemHit == kCancelTestItem)
gTesting = false;
}
static void GKConfigDialog(EventRecord *ev, DialogPtr theDialog, short itemHit) {
long i;
ItemKeyCode *itemp;
/* check box clicks handled first */
for (i=0, itemp=gItemKeyCheckboxes; i<kNumCheckBoxes; itemp++, i++)
if (itemp->itemNo == itemHit) {
itemp->state = ( (itemp->state + 1) & 1 );
SetControlValue(itemp->itemControl, itemp->state);
return;
}
/* button clicks */
if (itemHit == 1) {
gRunning = false;
} else if (itemHit == 2) {
BeginTestingSequence();
}
}
/* QuitAppleEventHandler is our quit Apple event handler. this routine
is called when a quit Apple event is sent to our application. Here,
we set the gRunning flag to false. NOTE: it is not appropriate to
call ExitToShell here. Instead, by setting the flag to false we
fall through the bottom of our main event loop. */
static pascal OSErr QuitAppleEventHandler(const AppleEvent *appleEvt, AppleEvent* reply, long refcon) {
gRunning = false;
return noErr;
}
void ProcessNextEvent(void) {
EventRecord ev;
DialogPtr theDialog;
WindowPtr theWindow;
short itemHit, partCode;
/* get the next event */
if ( ! WaitNextEvent(everyEvent, &ev, GetCaretTime(), NULL) )
ev.what = nullEvent;
/* mouse events */
if ( ev.what == mouseDown ) {
partCode = FindWindow(ev.where, &theWindow);
switch (partCode) {
case inGrow:
if (theWindow == GetDialogWindow(gGKDialog)) {
GrowMappedDialog(ev.where, gGKDialog, gItemMap);
} else if (theWindow == GetDialogWindow(gTestDialog)) {
GrowMappedDialog(ev.where, gTestDialog, gTestMap);
}
break;
case inGoAway:
if (theWindow == GetDialogWindow(gGKDialog)) {
if (TrackGoAway(theWindow, ev.where))
gRunning = false;
}
break;
case inDrag:
{ Rect boundsRect = {0,0, 32000, 32000};
DragWindow(theWindow, ev.where, &boundsRect);
}
break;
}
if (partCode == inGrow || partCode == inGoAway || partCode == inDrag)
ev.what = nullEvent;
}
/* apple events */
if ( ev.what == kHighLevelEvent ) {
AEProcessAppleEvent(&ev);
ev.what = nullEvent;
}
/* key downs during testing... */
if (gTesting && (ev.what == keyDown || ev.what == autoKey))
ev.what = nullEvent;
/* handle dialog events */
if (IsDialogEvent(&ev))
if ( DialogSelect(&ev, &theDialog, &itemHit))
if (theDialog == gGKDialog)
GKConfigDialog(&ev, theDialog, itemHit);
else if (theDialog == gTestDialog)
GKKeyTestDialog(&ev, theDialog, itemHit);
}
/* the main program */
int main(void) {
long i;
ItemKeyCode *itemp;
/* set up */
InitCursor();
AEInstallEventHandler(kCoreEventClass, kAEQuitApplication, NewAEEventHandlerUPP(QuitAppleEventHandler), 0, false);
/* set up the menu bar */
SetMenuBar(GetNewMBar(kMenuBarID));
DrawMenuBar();
/* open the dialog window */
gGKDialog = GetNewDialog(kMainDialogBox, NULL, (WindowPtr)(-1));
NewDialogItemMap(gGKDialog, &gItemMap);
for (i=0, itemp=gItemKeyCheckboxes; i<kNumCheckBoxes; itemp++, i++) {
GetDialogItemAsControl(gGKDialog, itemp->itemNo, &itemp->itemControl);
}
ShowWindow(GetDialogWindow(gGKDialog));
/* loop processing events until.... */
while ( gRunning )
ProcessNextEvent();
/* close the dialog. */
DisposeDialog(gGKDialog);
DeleteDialogItemMap(gItemMap);
/* done */
ExitToShell();
return 0;
}
|
fruitsamples/iGetKeys
|
refs/heads/master
|
/MapDialog.h
|
/*
File: MapDialog.h
Description:
MapDialog provides an easily accessable set of routines that allow your
application to resize dialog windows reposition their contents to similarily
located positions in the window after it has been resized.
Copyright:
Copyright 2001 Apple Computer, Inc. All rights reserved.
Disclaimer:
IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under Apples
copyrights in this original Apple software (the "Apple Software"), to use,
reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions of
the Apple Software. Neither the name, trademarks, service marks or logos of
Apple Computer, Inc. may be used to endorse or promote products derived from the
Apple Software without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or implied,
are granted by Apple herein, including but not limited to any patent rights that
may be infringed by your derivative works or by other works in which the Apple
Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
(INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Change History (most recent first):
Mon, Jan 15, 2001 -- created
*/
#ifndef __MAPDIALOG__
#define __MAPDIALOG__
#ifdef __APPLE_CC__
#include <Carbon/Carbon.h>
#else
#include <Carbon.h>
#endif
/* the position of each item in the dialog is recorded inside of a
DialogMapItem record. It is assumed that the dialog was created
using a control heirarchy, so every item has a control associated
with it. The control handle is cached here, along with the item's
coordinates */
typedef struct {
ControlHandle theItem; /* handle to the control */
Rect bounds; /* the control's bounds */
Rect ibounds; /* the dialog item's bounds */
} DialogMapItem;
/* DialogMapRecord contains a list of DialogMapItem records
together with the original coordinates of the dialog window. If the
dialog is ever resized, the items are remapped from the dialog's original
boundary into the new window boundary. */
typedef struct {
Rect bounds; /* the dialog's window bounds */
long count; /* the number of items in the dialog */
DialogMapItem itemb[1]; /* a list of items */
} DialogMapRecord, *DialogMapRecPtr;
/* NewDialogItemMap creates a new DialogMapRecord for all of the
items in the dialog. This DialogMapRecord can later be passed to RemapDialog
to reposition the dialog items after the dialog window has been resized. */
OSStatus NewDialogItemMap(DialogPtr theDialog, DialogMapRecPtr *theItems);
/* DeleteDialogItemMap disposes of a DialogMapRecord allocated by
NewDialogItemMap. */
void DeleteDialogItemMap(DialogMapRecPtr theItems);
/* RemapDialog repositions all of the items in the dialog according
proportionately to the new dialog size. */
OSStatus RemapDialog(DialogPtr theDialog, DialogMapRecPtr theItems);
/* GrowMappedDialog calls grow-window and tracks the mouse movement
and then calls RemapDialog to reposition all of the items if the size of the
window changes. */
void GrowMappedDialog(Point globalWhere, DialogPtr theDialog, DialogMapRecPtr theItems);
#ifdef __cplusplus
}
#endif
#endif
|
fruitsamples/iGetKeys
|
refs/heads/master
|
/MapDialog.c
|
/*
File: iGetKeys.c
Description:
Internationally Savy GetKeys test type routines for your entertainment
and enjoyment.
Copyright:
Copyright 2001 Apple Computer, Inc. All rights reserved.
Disclaimer:
IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc.
("Apple") in consideration of your agreement to the following terms, and your
use, installation, modification or redistribution of this Apple software
constitutes acceptance of these terms. If you do not agree with these terms,
please do not use, install, modify or redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and subject
to these terms, Apple grants you a personal, non-exclusive license, under Apples
copyrights in this original Apple software (the "Apple Software"), to use,
reproduce, modify and redistribute the Apple Software, with or without
modifications, in source and/or binary forms; provided that if you redistribute
the Apple Software in its entirety and without modifications, you must retain
this notice and the following text and disclaimers in all such redistributions of
the Apple Software. Neither the name, trademarks, service marks or logos of
Apple Computer, Inc. may be used to endorse or promote products derived from the
Apple Software without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or implied,
are granted by Apple herein, including but not limited to any patent rights that
may be infringed by your derivative works or by other works in which the Apple
Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION
OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
(INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Change History (most recent first):
Mon, Jan 15, 2001 -- created
*/
#ifdef __APPLE_CC__
#include <Carbon/Carbon.h>
#else
#include <Carbon.h>
#include <stddef.h>
#endif
#include "MapDialog.h"
OSStatus NewDialogItemMap(DialogPtr theDialog, DialogMapRecPtr *theItems) {
long i, n;
DialogMapRecPtr items;
DialogMapItem *itemip;
OSStatus err;
short itemt;
Handle itemh;
/* known state */
items = NULL;
SetPortWindowPort(GetDialogWindow(theDialog));
/* allocate our list */
n = CountDITL(theDialog);
items = (DialogMapRecPtr) NewPtr(offsetof(DialogMapRecord, itemb) + sizeof(DialogMapItem) * n);
if (items == NULL) { err = memFullErr; goto bail; }
/* bounds */
GetPortBounds(GetWindowPort(GetDialogWindow(theDialog)), &items->bounds);
/* count */
items->count = n;
/* items */
for (i=1, itemip = items->itemb; i<=n; itemip++, i++) {
err = GetDialogItemAsControl( theDialog, i, &itemip->theItem);
if (err != noErr) goto bail;
GetControlBounds(itemip->theItem, &itemip->bounds);
GetDialogItem( theDialog, i, &itemt, &itemh, &itemip->ibounds);
}
/* save result */
*theItems = items;
return noErr;
bail:
if (items != NULL) DisposePtr((Ptr) items);
return err;
}
void DeleteDialogItemMap(DialogMapRecPtr theItems) {
DisposePtr((Ptr) theItems);
}
OSStatus RemapDialog(DialogPtr theDialog, DialogMapRecPtr theItems) {
long i;
DialogMapItem *itemip;
short itemt;
Handle itemh;
Rect newbounds, temp, theemptyrect = {0, 0, 0, 0};
RgnHandle clipSave;
/* set the port and get the map-to bounds */
SetPortWindowPort(GetDialogWindow(theDialog));
GetPortBounds(GetWindowPort(GetDialogWindow(theDialog)), &newbounds);
/* turn off drawing until we're done shuffling items */
GetClip((clipSave = NewRgn()));
ClipRect(&theemptyrect);
/* items */
for (i=1, itemip = theItems->itemb; i <= theItems->count; itemip++, i++) {
/* adjust control rectangle */
temp = itemip->bounds;
MapRect(&temp, &theItems->bounds, &newbounds);
MoveControl(itemip->theItem, temp.left, temp.top);
SizeControl(itemip->theItem, temp.right - temp.left, temp.bottom - temp.top);
/* adjust item rectangle */
GetDialogItem( theDialog, i, &itemt, &itemh, &temp);
temp = itemip->ibounds;
MapRect(&temp, &theItems->bounds, &newbounds);
SetDialogItem( theDialog, i, itemt, itemh, &temp);
}
/* restore drawing */
SetClip(clipSave);
DisposeRgn(clipSave);
/* clear the old contents */
SetPortWindowPort(GetDialogWindow(theDialog));
EraseRect(&newbounds);
DrawDialog(theDialog);
ValidWindowRect(GetDialogWindow(theDialog), &newbounds);
//InvalWindowRect(GetDialogWindow(theDialog), &newbounds);
/* done */
return noErr;
}
void GrowMappedDialog(Point globalWhere, DialogPtr theDialog, DialogMapRecPtr theItems) {
Rect sizerect;
long grow_result;
WindowPtr theWindow;
theWindow = GetDialogWindow(theDialog);
SetRect(&sizerect, theItems->bounds.right, theItems->bounds.bottom, 32767, 32767);
grow_result = GrowWindow(theWindow, globalWhere, &sizerect);
if (grow_result != 0) {
SizeWindow(theWindow, LoWord(grow_result), HiWord(grow_result), true);
RemapDialog(theDialog, theItems);
}
}
|
scottcarr/RustyCode
|
refs/heads/master
|
/src/services/commandService.ts
|
import * as vscode from 'vscode';
import * as cp from 'child_process';
import * as path from 'path';
import kill = require('tree-kill');
import findUp = require('find-up');
import PathService from './pathService';
//import {IConnection} from 'vscode-languageserver';
const errorRegex = /^(.*):(\d+):(\d+):\s+(\d+):(\d+)\s+(warning|error|note|help):\s+(.*)$/;
interface RustError {
filename: string;
startLine: number;
startCharacter: number;
endLine: number;
endCharacter: number;
severity: string;
message: string;
}
class ChannelWrapper {
private owner: CargoTask;
private channel: vscode.OutputChannel;
constructor(channel: vscode.OutputChannel) {
this.channel = channel;
}
public append(task: CargoTask, message: string): void {
if (task === this.owner) {
this.channel.append(message);
}
}
public clear(task: CargoTask): void {
if (task === this.owner) {
this.channel.clear();
}
}
public show(): void {
this.channel.show(true);
}
public setOwner(owner: CargoTask): void {
this.owner = owner;
}
}
class CargoTask {
private channel: ChannelWrapper;
private process: cp.ChildProcess;
private arguments: string[];
private interrupted: boolean;
private useJSON: boolean
// i could just add a member thats a vector
// of the diagnostics we've accumulated on this Task
constructor(args: string[], channel: ChannelWrapper, useJSON: boolean = false) {
this.arguments = args;
this.channel = channel;
this.interrupted = false;
this.useJSON = useJSON;
}
private outputDiagnostic(json: any) {
// my way is actually somewhat worse because
// the diagnostics never get added to vscode's diagnostics
// use this.diagonstics.set(uri, diagnostics[])
try {
let file_link = vscode.workspace.rootPath + "/" + json["spans"][0]["file_name"];
// if you put file:// before the file name the clicking stops working!
file_link = file_link + "(" + json["spans"][0]["line_start"] + "," + json["spans"][0]["column_start"] + ")\n";
this.channel.append(this, file_link);
} catch (e) {
if (e instanceof TypeError) { }
else { throw e; }
}
let msg = json["level"] + ": " + json["message"] + "\n";
this.channel.append(this, msg);
for (let s of json["spans"]) {
for (let t of s["text"]) {
let text = t["text"] + "\n";
this.channel.append(this, text);
let hi_start = t["highlight_start"];
let hi_end = t["highlight_end"];
let hi = ' '.repeat(hi_start - 1);
hi = hi + '^'.repeat(hi_end - hi_start) + "\n";
this.channel.append(this, hi);
}
}
for (let child of json["children"]) {
this.outputDiagnostic(child)
}
}
private tryParseDiagnosticsJSON(line: string): boolean {
try {
let parsed = JSON.parse(line);
this.outputDiagnostic(parsed);
return true;
} catch (e) {
if (e instanceof SyntaxError) {
return false
} else {
throw e;
}
}
}
public execute(cwd: string): Thenable<string> {
return new Promise((resolve, reject) => {
const cargoPath = PathService.getCargoPath();
const startTime = Date.now();
const task = 'cargo ' + this.arguments.join(' ');
let output = '';
let unprocessed = '';
this.channel.clear(this);
this.channel.append(this, `Running "${task}":\n`);
this.process = cp.spawn(cargoPath, this.arguments, { cwd });
this.process.stdout.on('data', data => {
this.channel.append(this, data.toString());
});
this.process.stderr.on('data', data => {
output += data.toString();
unprocessed += data.toString();
while (this.useJSON && unprocessed.indexOf("\n") != -1) {
let nl_idx = unprocessed.indexOf("\n");
let line = unprocessed.substring(0, nl_idx);
unprocessed = unprocessed.slice(nl_idx+1);
if (line.startsWith("{") && this.tryParseDiagnosticsJSON(line)) {
} else {
this.channel.append(this, line + "\n");
}
}
});
this.process.on('error', error => {
if (error.code === 'ENOENT') {
vscode.window.showInformationMessage('The "cargo" command is not available. Make sure it is installed.');
}
});
this.process.on('exit', code => {
this.process.removeAllListeners();
this.process = null;
const endTime = Date.now();
this.channel.append(this, `\n"${task}" completed with code ${code}`);
this.channel.append(this, `\nIt took approximately ${(endTime - startTime) / 1000} seconds`);
if (code === 0 || this.interrupted) {
resolve(this.interrupted ? '' : output);
} else {
if (code !== 101) {
vscode.window.showWarningMessage(`Cargo unexpectedly stopped with code ${code}`);
}
reject(output);
}
});
});
}
public kill(): Thenable<any> {
return new Promise(resolve => {
if (!this.interrupted && this.process) {
kill(this.process.pid, 'SIGINT', resolve);
this.interrupted = true;
}
});
}
}
export default class CommandService {
private static diagnostics: vscode.DiagnosticCollection = vscode.languages.createDiagnosticCollection('rust');
private static channel: ChannelWrapper = new ChannelWrapper(vscode.window.createOutputChannel('Cargo'));
private static currentTask: CargoTask;
public static formatCommand(commandName: string, ...args: string[]): vscode.Disposable {
return vscode.commands.registerCommand(commandName, () => {
this.runCargo(args, true, true, false);
});
}
public static formatCommandJSON(commandName: string, ...args: string[]): vscode.Disposable {
let json_args = ["--", "--error-format", "json", "-Z", "unstable-options"];
args = args.concat(json_args);
return vscode.commands.registerCommand(commandName, () => {
this.runCargo(args, true, true, true);
});
}
public static buildExampleCommand(commandName: string, release: boolean): vscode.Disposable {
return vscode.commands.registerCommand(commandName, () => {
this.buildExample(release);
});
}
public static runExampleCommand(commandName: string, release: boolean): vscode.Disposable {
return vscode.commands.registerCommand(commandName, () => {
this.runExample(release);
});
}
public static stopCommand(commandName: string): vscode.Disposable {
return vscode.commands.registerCommand(commandName, () => {
if (this.currentTask) {
this.currentTask.kill();
}
});
}
private static determineExampleName(): string {
let showDocumentIsNotExampleWarning = () => {
vscode.window.showWarningMessage('Current document is not an example');
};
let filePath = vscode.window.activeTextEditor.document.uri.fsPath;
let dir = path.basename(path.dirname(filePath));
if (dir !== 'examples') {
showDocumentIsNotExampleWarning();
return '';
}
let filename = path.basename(filePath);
if (!filename.endsWith('.rs')) {
showDocumentIsNotExampleWarning();
return '';
}
return path.basename(filename, '.rs');
}
private static buildExample(release: boolean): void {
let exampleName = this.determineExampleName();
if (exampleName.length === 0) {
return;
}
let args = ['build', '--example', exampleName];
if (release) {
args.push('--release');
}
this.runCargo(args, true, true);
}
private static runExample(release: boolean): void {
let exampleName = this.determineExampleName();
if (exampleName.length === 0) {
return;
}
let args = ['run', '--example', exampleName];
if (release) {
args.push('--release');
}
this.runCargo(args, true, true);
}
private static parseDiagnostics(cwd: string, output: string): void {
let errors: { [filename: string]: RustError[] } = {};
for (let line of output.split('\n')) {
let match = line.match(errorRegex);
if (match) {
let filename = match[1];
if (!errors[filename]) {
errors[filename] = [];
}
errors[filename].push({
filename: filename,
startLine: Number(match[2]) - 1,
startCharacter: Number(match[3]) - 1,
endLine: Number(match[4]) - 1,
endCharacter: Number(match[5]) - 1,
severity: match[6],
message: match[7]
});
}
}
this.diagnostics.clear();
if (!Object.keys(errors).length) {
return;
}
for (let filename of Object.keys(errors)) {
let fileErrors = errors[filename];
let diagnostics = fileErrors.map((error) => {
let range = new vscode.Range(error.startLine, error.startCharacter, error.endLine, error.endCharacter);
let severity: vscode.DiagnosticSeverity;
if (error.severity === 'warning') {
severity = vscode.DiagnosticSeverity.Warning;
} else if (error.severity === 'error') {
severity = vscode.DiagnosticSeverity.Error;
} else if (error.severity === 'note') {
severity = vscode.DiagnosticSeverity.Information;
} else if (error.severity === 'help') {
severity = vscode.DiagnosticSeverity.Hint;
}
return new vscode.Diagnostic(range, error.message, severity);
});
let uri = vscode.Uri.file(path.join(cwd, filename));
this.diagnostics.set(uri, diagnostics);
}
}
private static runCargo(args: string[], force = false, visible = false, useJSON = false): void {
if (force && this.currentTask) {
this.channel.setOwner(null);
this.currentTask.kill().then(() => {
this.runCargo(args, force, visible);
});
return;
} else if (this.currentTask) {
return;
}
this.currentTask = new CargoTask(args, this.channel, useJSON);
if (visible) {
this.channel.setOwner(this.currentTask);
this.channel.show();
}
CommandService.cwd().then((value: string | Error) => {
if (typeof value === 'string') {
this.currentTask.execute(value).then(output => {
this.parseDiagnostics(value, output);
}, output => {
this.parseDiagnostics(value, output);
}).then(() => {
this.currentTask = null;
});
} else {
vscode.window.showErrorMessage(value.message);
}
});
}
private static cwd(): Promise<string|Error> {
if (vscode.window.activeTextEditor === null) {
return Promise.resolve(new Error('No active document'));
} else {
const fileName = vscode.window.activeTextEditor.document.fileName;
if (!fileName.startsWith(vscode.workspace.rootPath)) {
return Promise.resolve(new Error('Current document not in the workspace'));
}
return findUp('Cargo.toml', {cwd: path.dirname(fileName)}).then((value: string) => {
if (value === null) {
return new Error('There is no Cargo.toml near active document');
} else {
return path.dirname(value);
}
});
}
}
}
|
scottcarr/RustyCode
|
refs/heads/master
|
/WISHLIST.md
|
1. Clickable Errors
2. Quick fixes (when the error has one)
3. Explain why when rustfmt fails
|
smellycats/SX-CarRecgServer
|
refs/heads/master
|
/run.py
|
from car_recg import app
from car_recg.recg_ser import RecgServer
from ini_conf import MyIni
if __name__ == '__main__':
rs = RecgServer()
rs.main()
my_ini = MyIni()
sys_ini = my_ini.get_sys_conf()
app.config['THREADS'] = sys_ini['threads']
app.config['MAXSIZE'] = sys_ini['threads'] * 16
app.run(host='0.0.0.0', port=sys_ini['port'], threaded=True)
del rs
del my_ini
|
smellycats/SX-CarRecgServer
|
refs/heads/master
|
/car_recg/config.py
|
# -*- coding: utf-8 -*-
import Queue
class Config(object):
# 密码 string
SECRET_KEY = 'hellokitty'
# 服务器名称 string
HEADER_SERVER = 'SX-CarRecgServer'
# 加密次数 int
ROUNDS = 123456
# token生存周期,默认1小时 int
EXPIRES = 7200
# 数据库连接 string
SQLALCHEMY_DATABASE_URI = 'mysql://root:root@127.0.0.1/hbc_store'
# 数据库连接绑定 dict
SQLALCHEMY_BINDS = {}
# 用户权限范围 dict
SCOPE_USER = {}
# 白名单启用 bool
WHITE_LIST_OPEN = True
# 白名单列表 set
WHITE_LIST = set()
# 处理线程数 int
THREADS = 4
# 允许最大数队列为线程数16倍 int
MAXSIZE = THREADS * 16
# 图片下载文件夹 string
IMG_PATH = 'img'
# 图片截取文件夹 string
CROP_PATH = 'crop'
# 超时 int
TIMEOUT = 5
# 识别优先队列 object
RECGQUE = Queue.PriorityQueue()
# 退出标记 bool
IS_QUIT = False
# 用户字典 dict
USER = {}
# 上传文件保存路径 string
UPLOAD_PATH = 'upload'
class Develop(Config):
DEBUG = True
class Production(Config):
DEBUG = False
class Testing(Config):
TESTING = True
|
smellycats/SX-CarRecgServer
|
refs/heads/master
|
/car_recg/views.py
|
# -*- coding: utf-8 -*-
import os
import Queue
import random
from functools import wraps
import arrow
from flask import g, request
from flask_restful import reqparse, Resource
from passlib.hash import sha256_crypt
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from car_recg import app, db, api, auth, limiter, logger, access_logger
from models import Users, Scope
import helper
def verify_addr(f):
"""IP地址白名单"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not app.config['WHITE_LIST_OPEN'] or request.remote_addr == '127.0.0.1' or request.remote_addr in app.config['WHITE_LIST']:
pass
else:
return {'status': '403.6',
'message': u'禁止访问:客户端的 IP 地址被拒绝'}, 403
return f(*args, **kwargs)
return decorated_function
@auth.verify_password
def verify_password(username, password):
if username.lower() == 'admin':
user = Users.query.filter_by(username='admin').first()
else:
return False
if user:
return sha256_crypt.verify(password, user.password)
return False
def verify_token(f):
"""token验证装饰器"""
@wraps(f)
def decorated_function(*args, **kwargs):
if not request.headers.get('Access-Token'):
return {'status': '401.6', 'message': 'missing token header'}, 401
token_result = verify_auth_token(request.headers['Access-Token'],
app.config['SECRET_KEY'])
if not token_result:
return {'status': '401.7', 'message': 'invalid token'}, 401
elif token_result == 'expired':
return {'status': '401.8', 'message': 'token expired'}, 401
g.uid = token_result['uid']
g.scope = set(token_result['scope'])
return f(*args, **kwargs)
return decorated_function
def verify_scope(scope):
def scope(f):
"""权限范围验证装饰器"""
@wraps(f)
def decorated_function(*args, **kwargs):
if 'all' in g.scope or scope in g.scope:
return f(*args, **kwargs)
else:
return {}, 405
return decorated_function
return scope
class Index(Resource):
def get(self):
return {
'user_url': '%suser{/user_id}' % (request.url_root),
'scope_url': '%suser/scope' % (request.url_root),
'token_url': '%stoken' % (request.url_root),
'recg_url': '%sv1/recg' % (request.url_root),
'uploadrecg_url': '%sv1/uploadrecg' % (request.url_root),
'state_url': '%sv1/state' % (request.url_root)
}, 200, {'Cache-Control': 'public, max-age=60, s-maxage=60'}
class RecgListApiV1(Resource):
def post(self):
parser = reqparse.RequestParser()
parser.add_argument('imgurl', type=unicode, required=True,
help='A jpg url is require', location='json')
parser.add_argument('coord', type=list, required=True,
help='A coordinates array is require',
location='json')
args = parser.parse_args()
# 回调用的消息队列
que = Queue.Queue()
if app.config['RECGQUE'].qsize() > app.config['MAXSIZE']:
return {'message': 'Server Is Busy'}, 449
imgname = '%32x' % random.getrandbits(128)
imgpath = os.path.join(app.config['IMG_PATH'], '%s.jpg' % imgname)
try:
helper.get_url_img(request.json['imgurl'], imgpath)
except Exception as e:
logger.error('Error url: %s' % request.json['imgurl'])
return {'message': 'URL Error'}, 400
app.config['RECGQUE'].put((10, request.json, que, imgpath))
try:
recginfo = que.get(timeout=15)
os.remove(imgpath)
except Queue.Empty:
return {'message': 'Timeout'}, 408
except Exception as e:
logger.error(e)
else:
return {
'imgurl': request.json['imgurl'],
'coord': request.json['coord'],
'recginfo': recginfo
}, 201
class StateListApiV1(Resource):
def get(self):
return {
'threads': app.config['THREADS'],
'qsize': app.config['RECGQUE'].qsize()
}
class UploadRecgListApiV1(Resource):
def post(self):
# 文件夹路径 string
filepath = os.path.join(app.config['UPLOAD_PATH'],
arrow.now().format('YYYYMMDD'))
if not os.path.exists(filepath):
os.makedirs(filepath)
try:
# 上传文件命名 随机32位16进制字符 string
imgname = '%32x' % random.getrandbits(128)
# 文件绝对路径 string
imgpath = os.path.join(filepath, '%s.jpg' % imgname)
f = request.files['file']
f.save(imgpath)
except Exception as e:
logger.error(e)
return {'message': 'File error'}, 400
# 回调用的消息队列 object
que = Queue.Queue()
# 识别参数字典 dict
r = {'coord': []}
app.config['RECGQUE'].put((9, r, que, imgpath))
try:
recginfo = que.get(timeout=app.config['TIMEOUT'])
except Queue.Empty:
return {'message': 'Timeout'}, 408
except Exception as e:
logger.error(e)
else:
return {'coord': r['coord'], 'recginfo': recginfo}, 201
api.add_resource(Index, '/')
api.add_resource(RecgListApiV1, '/v1/recg')
api.add_resource(StateListApiV1, '/v1/state')
api.add_resource(UploadRecgListApiV1, '/v1/uploadrecg')
|
sanjar8855/cactuscorp
|
refs/heads/master
|
/result.html
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CactusJobs.uz</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<header>
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html"><img src="images/logo-cactus-4.png" id="logo"></a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li><a href="#">Подработки</a></li>
<li><a href="#">Предложения работы в IT сфере</a></li>
<li><a href="#">Профили работодателей</a></li>
<li><a href="#">Создатель резюме</a></li>
<li><a href="#">Заработок</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">Войти в систему</a></li>
<li><a href="#" id="acc">Завести аккаунт</a></li>
<li><a href="#" id="for-com">Для компаний</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
</header>
<div class="result container">
<div class="row">
<div class="poisk col-lg-12">
<form class="form-inline">
<div class="form-group col-lg-6">
<label for="exampleInputName2">ПОИСК</label>
<input type="text" class="form-control" id="exampleInputName2" placeholder="Должность, компания, ключевое слово">
</div>
<div class="form-group col-lg-4">
<input type="email" class="form-control" id="exampleInputEmail2" placeholder="Город">
</div>
<button type="submit" class="btn btn-default"> <span class="glyphicon glyphicon-search"> Искать</span></button>
</form>
</div>
</div>
<!-- -->
<div class="vakansiyalar row">
<div class="col-lg-3">
<h1>Показывать вакансии</h1>
<select class="form-control">
<option>За все время</option>
<option>За день</option>
</select>
</div>
<div class="col-lg-9">
<h1>Работа для студентов</h1>
<p>Найдено: 2329</p>
</div>
</div>
<br>
<!-- -->
<div class="filtr row">
<div class="col-lg-3">
<div class="head">
<h1>Текущие фильтры</h1>
</div>
<div class="content">
<div>
<h1>Город</h1>
<ul>
<li><a href="#">Ташкент</a></li>
<li><a href="#">Фергана</a></li>
<li><a href="#">Ургенч</a></li>
<li><a href="#">Самарканд</a></li>
<li><a href="#">Наманган</a></li>
<li><a href="#">Андижан</a></li>
<li><a href="#">Показать все</a></li>
</ul>
</div>
<div>
<h1>Зарплата</h1>
<ul>
<li><a href="#">От 500 000 сум</a></li>
<li><a href="#">От 1 000 000 сум</a></li>
<li><a href="#">От 1 500 000 сум</a></li>
<li><a href="#">От 2 000 000 сум</a></li>
<li><a href="#">От 2 500 000 сум</a></li>
<li><a href="#">От 3 000 000 сум</a></li>
<li><a href="#">От 4 000 000 сум</a></li>
<li><a href="#">От 5 000 000 сум</a></li>
</ul>
</div>
<div>
<h1>График работы</h1>
<ul>
<li><a href="#">Гибкий</a></li>
<li><a href="#">Фиксированный</a></li>
<li><a href="#">Сменный</a></li>
</ul>
</div>
<div>
<h1>Занятость</h1>
<ul>
<li><a href="#">Полная</a></li>
<li><a href="#">Частичная</a></li>
<li><a href="#">Разовая</a></li>
</ul>
</div>
<div>
<h1>Характер работы</h1>
<ul>
<li><a href="#">На территории работодателя</a></li>
<li><a href="#">Разьездной</a></li>
<li><a href="#">Работу на дому</a></li>
</ul>
</div>
</div>
</div>
<!-- -->
<div class="headtext col-lg-6">
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<div class="col-lg-12">
<h1><a href="vakansiya.html">Андроид разработчик</a></h1>
<h2>3 400 000 сум.+</h2>
<p>Фергана | 16 ноябрь 2020, 15:00</p>
<a href="#">Откликнуться</a>
<a href="#">Посмотреть контакты</a>
</div>
<nav>
<ul class="pagination">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
<li class="active"><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>
</div>
<!-- -->
<div class="col-lg-3">
<p>В данном разделе предложения о
работе в Ташкенте, Фергане, Ургенче
или в любом другом городе Узбекистана
найдут выпускники, студенты и тд.
Если вы еще учитесь и ищите подработку
работу в выходные дни или удаленную
работу - этот раздел для вас! На партале
есть удобные инструменты поиска: расширенный
поиск и пазличные фильтры благодаря которым
можно сформировать точный запрос? Укажите
тип занятости, график, желаемый размер заработной
платы, образование и специальность. </p>
</div>
</div>
<!-- -->
</div>
<footer class="col-lg-12">
<div class="container">
<div class="row">
<div class="col-lg-3">
<h1>Для компаний</h1>
<ul>
<li><a href="#">Добавить обьявления</a></li>
<li><a href="#">Помощь компаниям</a></li>
</ul>
</div>
<div class="col-lg-3">
<h1>CactusJobs.</h1>
<ul>
<li><a href="#">О нас</a></li>
<li><a href="#">Реклама</a></li>
<li><a href="#">Партнеры</a></li>
<li><a href="#">Архив предложений</a></li>
</ul>
</div>
<div class="col-lg-3">
<h1>Информация</h1>
<ul>
<li><a href="#">Политика конфиденциальности</a></li>
<li><a href="#">Политика использования файлов cookie</a></li>
<li><a href="#">Настройка файлов cookie</a></li>
</ul>
</div>
<div class="col-lg-3">
<h1>Скачать приложение</h1>
<ul>
<li><a href="#"><img src="images/apk-ios.jpg"></a></li>
<!-- <li><a href="#"><img src="images/appstore.png"></a></li> -->
</ul>
</div>
</div>
</div>
</footer>
<script src="js/jQuery.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
|
sanjar8855/cactuscorp
|
refs/heads/master
|
/telegram.php
|
<?php
/* https://api.telegram.org/bot1430206287:AAGHi-PVElHdLIBhzNhAlv0nkivxnvH8jnM/getUpdates*/
$tel_nomer=$_POST['number']
$token = "1430206287:AAGHi-PVElHdLIBhzNhAlv0nkivxnvH8jnM";
$chat_id = "49394018";
$arr= array(
'Vakansiya ID: ' => '156',
'Фирма: ' => 'Raqamli Texnologiyalar Markazi',
'Нужен: ' => 'Андроид разработчик',
'Telefon №: ' => $tel_nomer,
);
foreach($arr as $key => $value){
$txt .= "<b>".$key."</b>".$value."%0A";
};
$sendToTelegram = fopen("https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}", "r");
if($sendToTelegram){
header('Location: vakansiya.html');
} else {
echo "Error";
}
?>
|
promit13/KindrTest
|
refs/heads/master
|
/src/config/images.js
|
export const commendImage = require('../assets/commendWhite.png');
export const shoutoutImage = require('../assets/shoutoutWhite.png');
export const commentImage = require('../assets/commentWhite.png');
export const applaudImage = require('../assets/applaudWhite.png');
export const emailImage = require('../assets/emailWhite.png');
export const plusImage = require('../assets/plusWhite.png');
export const settingsImage = require('../assets/settingsWhite.png');
export const commendImageBlack = require('../assets/commend.png');
export const shoutoutImageBlack = require('../assets/shoutout.png');
export const commentImageBlack = require('../assets/comment.png');
export const applaudImageBlack = require('../assets/applaud.png');
export const homeImageBlack = require('../assets/homeBlack.png');
export const searchImageBlack = require('../assets/searchBlack.png');
export const createImageBlack = require('../assets/createBlack.png');
export const projectsImageBlack = require('../assets/projectsBlack.png');
export const profileImageBlack = require('../assets/profileBlack.png');
export const homeImagePink = require('../assets/homePink.png');
export const searchImagePink = require('../assets/searchPink.png');
export const createImagePink = require('../assets/createPink.png');
export const projectsImagePink = require('../assets/projectsPink.png');
export const profileImagePink = require('../assets/profilePink.png');
export const charityImage = require('../assets/charityImage.jpeg');
export const manchesterLogoImage = require('../assets/manchesterLogo.png');
export default abc = 'test';
|
promit13/KindrTest
|
refs/heads/master
|
/src/config/data.js
|
const projectSingle = {
url: 'https://homepages.cae.wisc.edu/~ece533/images/fruits.png',
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
title: 'Monthly mediataion ...',
time: '2 days ago',
};
export const testImageArray = [
{url: require('../assets/imageOne.jpeg')},
{url: require('../assets/imageTwo.jpg')},
{url: require('../assets/imageThree.jpg')},
{url: require('../assets/imageFour.jpg')},
{url: require('../assets/imageFive.jpg')},
{url: require('../assets/imageSix.jpg')},
{url: require('../assets/imageSeven.jpg')},
{url: require('../assets/imageEight.jpg')},
{url: require('../assets/imageNine.jpg')},
{url: require('../assets/imageTen.jpg')},
{url: require('../assets/imageEleven.jpg')},
{url: require('../assets/imageTwelve.jpg')},
];
export const projectArray = [
{
url: require('../assets/project1.jpg'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: false,
isVerified: false,
id: '0',
interest: 'Zero Hunger',
title: 'Adapt a turtle...',
coins: '47',
time: '4 hrs ago',
date: '04/05/21',
projectTypeUrl: require('../assets/planetBlue.png'),
isPlanet: true,
},
{
url: require('../assets/project2.jpg'),
title: 'Adapting a pengu..',
time: '1 day ago',
coins: '45',
projectTypeUrl: require('../assets/peoplePink.png'),
date: '01/05/21',
isPlanet: false,
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '0',
interest: 'Zero Hunger',
},
{
url: require('../assets/project3.jpg'),
title: 'Houseplants prod...',
time: '24 hrs ago',
coins: '39',
date: '30/04/21',
projectTypeUrl: require('../assets/planetBlue.png'),
isPlanet: true,
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: false,
isVerified: false,
id: '0',
interest: 'Zero Hunger',
},
{
url: require('../assets/project4.jpg'),
title: 'Save the Rainfo...',
time: '4 hrs ago',
coins: '90',
projectTypeUrl: require('../assets/peoplePink.png'),
date: '29/04/21',
isPlanet: false,
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '0',
interest: 'Zero Hunger',
},
{
url: require('../assets/project5.jpg'),
title: 'Treeplanting to co...',
time: '4 hrs ago',
coins: '60',
date: '26/04/21',
projectTypeUrl: require('../assets/planetBlue.png'),
isPlanet: true,
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: false,
isVerified: false,
id: '0',
interest: 'Zero Hunger',
},
{
url: require('../assets/project6.jpg'),
title: 'Adapt a turtle...',
time: '4 hrs ago',
coins: '20',
date: '15/04/21',
projectTypeUrl: require('../assets/peoplePink.png'),
isPlanet: false,
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '0',
interest: 'Zero Hunger',
},
{
url: require('../assets/project7.jpg'),
title: 'Adapt a turtle...',
coins: '47',
time: '4 hrs ago',
date: '04/05/21',
projectTypeUrl: require('../assets/planetBlue.png'),
isPlanet: true,
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: false,
isVerified: false,
id: '0',
interest: 'Zero Hunger',
},
{
url: require('../assets/project8.jpg'),
title: 'Houseplants prod...',
time: '1 day ago',
coins: '45',
date: '01/05/21',
projectTypeUrl: require('../assets/peoplePink.png'),
isPlanet: false,
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '0',
interest: 'Zero Hunger',
},
{
url: require('../assets/project9.jpg'),
title: 'WWF planet aware...',
time: '24 hrs ago',
coins: '39',
date: '30/04/21',
projectTypeUrl: require('../assets/planetBlue.png'),
isPlanet: true,
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: false,
isVerified: false,
id: '0',
interest: 'Zero Hunger',
},
{
url: require('../assets/project10.jpg'),
title: 'Save the sloths to...',
time: '4 hrs ago',
coins: '90',
date: '29/04/21',
projectTypeUrl: require('../assets/peoplePink.png'),
isPlanet: false,
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '0',
interest: 'Zero Hunger',
},
{
url: require('../assets/project11.jpg'),
title: 'Cleaning Sust...',
time: '4 hrs ago',
coins: '60',
date: '26/04/21',
projectTypeUrl: require('../assets/planetBlue.png'),
isPlanet: true,
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: false,
isVerified: false,
id: '0',
interest: 'Zero Hunger',
},
{
url: require('../assets/project12.jpg'),
title: 'Growing home gro...',
time: '4 hrs ago',
coins: '20',
date: '15/04/21',
projectTypeUrl: require('../assets/peoplePink.png'),
isPlanet: false,
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '0',
interest: 'Zero Hunger',
},
{
url: require('../assets/project1.jpg'),
title: 'Adapt a turtle...',
coins: '47',
time: '4 hrs ago',
date: '04/05/21',
projectTypeUrl: require('../assets/planetBlue.png'),
isPlanet: true,
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: false,
isVerified: false,
id: '0',
interest: 'Zero Hunger',
},
{
url: require('../assets/project2.jpg'),
title: 'Adapting a penguin..',
time: '1 day ago',
coins: '45',
date: '01/05/21',
projectTypeUrl: require('../assets/peoplePink.png'),
isPlanet: false,
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '0',
interest: 'Zero Hunger',
},
{
url: require('../assets/project3.jpg'),
title: 'Houseplants produc...',
time: '24 hrs ago',
coins: '39',
date: '30/04/21',
projectTypeUrl: require('../assets/planetBlue.png'),
isPlanet: true,
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: false,
isVerified: false,
id: '0',
interest: 'Zero Hunger',
},
{
url: require('../assets/project12.jpg'),
title: 'Growing home gro...',
time: '4 hrs ago',
coins: '20',
date: '15/04/21',
projectTypeUrl: require('../assets/peoplePink.png'),
isPlanet: false,
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '0',
interest: 'Zero Hunger',
},
{
url: require('../assets/project1.jpg'),
title: 'Adapt a turtle...',
coins: '47',
time: '4 hrs ago',
date: '04/05/21',
projectTypeUrl: require('../assets/planetBlue.png'),
isPlanet: true,
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: false,
isVerified: false,
id: '0',
interest: 'Zero Hunger',
},
{
url: require('../assets/project2.jpg'),
title: 'Adapting a penguin..',
time: '1 day ago',
coins: '45',
date: '01/05/21',
projectTypeUrl: require('../assets/peoplePink.png'),
isPlanet: false,
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '0',
interest: 'Zero Hunger',
},
{
url: require('../assets/project3.jpg'),
title: 'Houseplants produc...',
time: '24 hrs ago',
coins: '39',
date: '30/04/21',
projectTypeUrl: require('../assets/planetBlue.png'),
isPlanet: true,
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: false,
isVerified: false,
id: '0',
interest: 'Zero Hunger',
},
{
url: require('../assets/project2.jpg'),
title: 'Adapting a penguin..',
time: '1 day ago',
coins: '45',
date: '01/05/21',
projectTypeUrl: require('../assets/peoplePink.png'),
isPlanet: false,
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '0',
interest: 'Zero Hunger',
},
];
export const walletArray = [
{
url: require('../assets/search10.jpg'),
title: 'Meditation to rel...',
coins: '47',
time: '4 hrs ago',
date: '04/05/21',
isPlanet: true,
},
{
url: require('../assets/search1.jpg'),
title: 'Cycle for mental...',
time: '1 day ago',
coins: '45',
date: '01/05/21',
isPlanet: false,
},
{
url: require('../assets/search7.jpg'),
title: 'Self Care Day',
time: '24 hrs ago',
coins: '39',
date: '30/04/21',
isPlanet: true,
},
{
url: require('../assets/search3.jpg'),
title: 'Girl Power',
time: '4 hrs ago',
coins: '90',
date: '29/04/21',
isPlanet: false,
},
{
url: require('../assets/search5.jpg'),
title: 'Helping OAPs with tech',
time: '4 hrs ago',
coins: '60',
date: '26/04/21',
isPlanet: true,
},
{
url: require('../assets/search7.jpg'),
title: 'Weekly Meditation',
time: '4 hrs ago',
coins: '20',
date: '15/04/21',
isPlanet: false,
},
{
url: require('../assets/search10.jpg'),
title: 'Meditation to rel...',
coins: '47',
time: '4 hrs ago',
date: '04/05/21',
isPlanet: true,
},
{
url: require('../assets/search1.jpg'),
title: 'Cycle for mental...',
time: '1 day ago',
coins: '45',
date: '01/05/21',
isPlanet: false,
},
{
url: require('../assets/search7.jpg'),
title: 'Self Care Day',
time: '24 hrs ago',
coins: '39',
date: '30/04/21',
isPlanet: true,
},
{
url: require('../assets/search3.jpg'),
title: 'Girl Power',
time: '4 hrs ago',
coins: '90',
date: '29/04/21',
isPlanet: false,
},
{
url: require('../assets/search5.jpg'),
title: 'Helping OAPs with tech',
time: '4 hrs ago',
coins: '60',
date: '26/04/21',
isPlanet: true,
},
{
url: require('../assets/search7.jpg'),
title: 'Weekly Meditation',
time: '4 hrs ago',
coins: '20',
date: '15/04/21',
isPlanet: false,
},
{
url: require('../assets/search3.jpg'),
title: 'Girl Power',
time: '4 hrs ago',
coins: '90',
date: '29/04/21',
isPlanet: true,
},
{
url: require('../assets/search5.jpg'),
title: 'Helping OAPs with tech',
time: '4 hrs ago',
coins: '60',
date: '26/04/21',
isPlanet: false,
},
{
url: require('../assets/search7.jpg'),
title: 'Weekly Meditation',
time: '4 hrs ago',
coins: '20',
date: '15/04/21',
isPlanet: true,
},
{
url: require('../assets/search3.jpg'),
title: 'Girl Power',
time: '4 hrs ago',
coins: '90',
date: '29/04/21',
isPlanet: false,
},
{
url: require('../assets/search5.jpg'),
title: 'Helping OAPs with tech',
time: '4 hrs ago',
coins: '60',
date: '26/04/21',
isPlanet: true,
},
{
url: require('../assets/search7.jpg'),
title: 'Weekly Meditation',
time: '4 hrs ago',
coins: '20',
date: '15/04/21',
isPlanet: false,
},
];
export const searchArray = [
{
title: 'peopleproject',
total: 208,
images: [
{
url: require('../assets/search7.jpg'),
title: 'Meditation to rel...',
time: '4 hrs ago',
projectTypeUrl: require('../assets/peoplePink.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/peoplePink.png'),
hasButton: false,
isVerified: false,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
{
url: require('../assets/search12.jpg'),
title: 'Cycle for mental...',
time: '1 day ago',
projectTypeUrl: require('../assets/planetBlue.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
{
url: require('../assets/search11.jpg'),
title: 'Manchester marat...',
time: '24 hrs ago',
projectTypeUrl: require('../assets/peoplePink.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/peoplePink.png'),
hasButton: false,
isVerified: false,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
{
url: require('../assets/search8.jpg'),
title: 'Meditation to rel...',
time: '4 hrs ago',
projectTypeUrl: require('../assets/planetBlue.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
{
url: require('../assets/search9.jpg'),
title: 'Meditation to rel...',
time: '4 hrs ago',
projectTypeUrl: require('../assets/peoplePink.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/peoplePink.png'),
hasButton: false,
isVerified: false,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
],
},
{
title: 'selflove',
total: 256,
images: [
{
url: require('../assets/search1.jpg'),
title: 'Self Care Day',
time: '4 hrs ago',
projectTypeUrl: require('../assets/planetBlue.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
{
url: require('../assets/search2.jpg'),
title: 'Enjoy the great out...',
time: '1 day ago',
projectTypeUrl: require('../assets/peoplePink.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/peoplePink.png'),
hasButton: false,
isVerified: false,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
{
url: require('../assets/search3.jpg'),
title: 'Girl Power',
time: '24 hrs ago',
projectTypeUrl: require('../assets/planetBlue.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
{
url: require('../assets/search8.jpg'),
title: 'Meditation to rel...',
time: '4 hrs ago',
projectTypeUrl: require('../assets/peoplePink.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/peoplePink.png'),
hasButton: false,
isVerified: false,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
{
url: require('../assets/search9.jpg'),
title: 'Meditation to rel...',
time: '4 hrs ago',
projectTypeUrl: require('../assets/planetBlue.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
],
},
{
title: 'communitysupport',
total: 799,
images: [
{
url: require('../assets/search10.jpg'),
title: 'Community Supp...',
time: '4 hrs ago',
projectTypeUrl: require('../assets/peoplePink.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/peoplePink.png'),
hasButton: false,
isVerified: false,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
{
url: require('../assets/search6.jpg'),
title: 'Technology Heroes...',
time: '1 day ago',
projectTypeUrl: require('../assets/planetBlue.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
{
url: require('../assets/search5.jpg'),
title: 'Be Kind to those...',
time: '24 hrs ago',
projectTypeUrl: require('../assets/peoplePink.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/peoplePink.png'),
hasButton: false,
isVerified: false,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
{
url: require('../assets/search8.jpg'),
title: 'Meditation to rel...',
time: '4 hrs ago',
projectTypeUrl: require('../assets/planetBlue.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
{
url: require('../assets/search9.jpg'),
title: 'Meditation to rel...',
time: '4 hrs ago',
projectTypeUrl: require('../assets/peoplePink.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/peoplePink.png'),
hasButton: false,
isVerified: false,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
],
},
{
title: 'healthylifestyle',
total: 256,
images: [
{
url: require('../assets/search8.jpg'),
title: 'Sustainable Cloth...',
time: '4 hrs ago',
projectTypeUrl: require('../assets/planetBlue.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/peoplePink.png'),
hasButton: true,
isVerified: true,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
{
url: require('../assets/search4.jpg'),
title: 'Smoothie Week...',
time: '1 day ago',
projectTypeUrl: require('../assets/peoplePink.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/peoplePink.png'),
hasButton: false,
isVerified: false,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
{
url: require('../assets/search9.jpg'),
title: 'Health Check In',
time: '24 hrs ago',
projectTypeUrl: require('../assets/planetBlue.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
{
url: require('../assets/search8.jpg'),
title: 'Meditation to rel...',
time: '4 hrs ago',
projectTypeUrl: require('../assets/peoplePink.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/peoplePink.png'),
hasButton: false,
isVerified: false,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
{
url: require('../assets/search9.jpg'),
title: 'Meditation to rel...',
time: '4 hrs ago',
projectTypeUrl: require('../assets/planetBlue.png'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsofthearth',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '0',
date: '05.05.21',
interest: 'Zero Hunger',
},
],
},
];
export const inboxArray = [
{
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'Beth Hall',
id: '0',
time: '34m',
type: 'project',
},
{
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'Sarah Alderidge',
id: '0',
time: '1w',
type: 'post',
},
{
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'Yvonne Chin',
id: '0',
time: '1h',
type: 'project',
},
{
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'Susanna Fonte',
id: '0',
time: '1d',
type: 'post',
},
{
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'Matt Williams',
id: '0',
time: '2d',
type: 'project',
},
{
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'Beth Hall',
id: '0',
time: '34m',
type: 'project',
},
{
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'Sarah Alderidge',
id: '0',
time: '1w',
type: 'post',
},
{
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'Yvonne Chin',
id: '0',
time: '1h',
type: 'project',
},
{
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'Susanna Fonte',
id: '0',
time: '1d',
type: 'post',
},
{
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'Matt Williams',
id: '0',
time: '2d',
type: 'project',
},
];
export const imageArray = [
{
url: require('../assets/homeSlideOne.jpg'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'wunder',
title: 'Healthy Eating',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: false,
isVerified: false,
id: '0',
time: '4 hrs ago',
date: '05.05.21',
interest: 'Zero Hunger',
},
{
url: require('../assets/homeSlideTwo.jpg'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'greatermondst',
title: 'Peaceful walk this morning',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/peoplePink.png'),
hasButton: true,
isVerified: true,
id: '1',
time: '4 hrs ago',
date: '05.05.21',
interest: 'Good Health & Wellbeing',
},
{
url: require('../assets/imageNine.jpg'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'friendsoftheearth',
title: 'Peaceful walk this morning',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: false,
isVerified: true,
id: '2',
time: '4 hrs ago',
date: '05.05.21',
interest: 'Quality Education',
},
{
url: require('../assets/imageFour.jpg'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'vic_azerrence',
title: 'Peaceful walk this morning',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/peoplePink.png'),
hasButton: true,
isVerified: false,
id: '3',
time: '4 hrs ago',
date: '03.05.21',
interest: 'Gender Equality',
},
{
url: require('../assets/imageThree.jpg'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'tescoofficial',
title: 'Peaceful walk this morning',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: false,
isVerified: true,
id: '4',
time: '4 hrs ago',
date: '01.05.21',
interest: 'Clean water & Sanitation',
},
{
url: require('../assets/imageTwelve.jpg'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'sam_williams',
title: 'Peaceful walk this morning',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/peoplePink.png'),
hasButton: true,
isVerified: false,
id: '5',
time: '4 hrs ago',
date: '02.05.21',
interest: 'Climate Action',
},
{
url: require('../assets/imageFive.jpg'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'millissaharris10',
title: 'Peaceful walk this morning',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: true,
id: '6',
time: '4 hrs ago',
date: '05.05.21',
interest: 'Good Health & Wellbeing',
},
{
url: require('../assets/imageSeven.jpg'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'nora_osborn',
title: 'Peaceful walk this morning',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/peoplePink.png'),
hasButton: false,
isVerified: true,
id: '7',
time: '4 hrs ago',
date: '05.05.21',
interest: 'Quality Education',
},
{
url: require('../assets/imageSix.jpg'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'Promit',
title: 'Peaceful walk this morning',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: false,
id: '8',
time: '4 hrs ago',
date: '03.05.21',
interest: 'Gender Equality',
},
{
url: require('../assets/imageTwo.jpg'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'Promit',
title: 'Peaceful walk this morning',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/peoplePink.png'),
hasButton: false,
isVerified: true,
id: '9',
time: '4 hrs ago',
date: '01.05.21',
interest: 'Clean water & Sanitation',
},
{
url: require('../assets/imageNine.jpg'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'Promit',
title: 'Peaceful walk this morning',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/planetBlue.png'),
hasButton: true,
isVerified: false,
id: '10',
time: '4 hrs ago',
date: '02.05.21',
interest: 'Climate Action',
},
{
url: require('../assets/imageOne.jpeg'),
profileImageUrl: 'https://reactnative.dev/img/tiny_logo.png',
name: 'Promit',
title: 'Peaceful walk this morning',
detail: 'Walking through the park earlier, found friendly squirrel ',
worldImage: require('../assets/peoplePink.png'),
hasButton: false,
isVerified: false,
id: '11',
time: '4 hrs ago',
date: '05.05.21',
interest: 'Zero Hunger',
},
];
export const newPostItemArray = [
{
title: 'Tag People',
showRightIcon: true,
showLeftIcon: false,
},
{
title: 'Location',
showRightIcon: true,
showLeftIcon: false,
},
{
title: 'People',
showRightIcon: false,
showLeftIcon: false,
},
{
title: 'Planet',
showRightIcon: false,
showLeftIcon: false,
},
{
title: 'Save for later?',
showRightIcon: false,
showLeftIcon: false,
},
{
title: 'Advanced Settings',
showRightIcon: true,
showLeftIcon: false,
},
];
export const aboutItemArray = [
{
title: 'Data Policy',
iconName: 'twitter',
iconType: 'entypo',
showRightIcon: true,
showLeftIcon: false,
},
{
title: 'Terms of Use',
iconName: 'twitter',
iconType: 'entypo',
showRightIcon: true,
showLeftIcon: false,
},
];
export const helpItemsArray = [
{
title: 'Report a problem',
iconName: 'sc-facebook',
iconType: 'evilicon',
showRightIcon: true,
showLeftIcon: false,
},
{
title: 'Help Centre',
iconName: 'instagram',
iconType: 'feather',
showRightIcon: true,
showLeftIcon: false,
},
{
title: 'Support requests',
iconName: 'twitter',
iconType: 'entypo',
showRightIcon: true,
showLeftIcon: false,
},
{
title: 'Privacy and security help',
iconName: 'twitter',
iconType: 'entypo',
showRightIcon: true,
showLeftIcon: false,
},
];
export const socialItemsArray = [
{
title: 'Facebook',
iconName: 'sc-facebook',
iconType: 'evilicon',
showRightIcon: true,
showLeftIcon: true,
},
{
title: 'Instagram',
iconName: 'instagram',
iconType: 'feather',
showRightIcon: true,
showLeftIcon: true,
},
{
title: 'Twitter',
iconName: 'twitter',
iconType: 'entypo',
showRightIcon: true,
showLeftIcon: true,
},
];
export const privacyItemArray = [
{
title: 'Private Account',
iconName: 'account',
iconType: 'material-community',
showRightIcon: false,
showLeftIcon: false,
},
{
title: 'Interactions',
iconName: 'account',
iconType: 'material-community',
showRightIcon: true,
showLeftIcon: false,
},
{
title: 'Mentions',
iconName: 'account',
iconType: 'material-community',
showRightIcon: true,
showLeftIcon: false,
},
{
title: 'Restricted Accounts',
iconName: 'account',
iconType: 'material-community',
showRightIcon: true,
showLeftIcon: false,
},
{
title: 'Blocked Accounts',
iconName: 'account',
iconType: 'material-community',
showRightIcon: true,
showLeftIcon: false,
},
{
title: 'Muted Accounts',
iconName: 'account',
iconType: 'material-community',
showRightIcon: true,
showLeftIcon: false,
},
{
title: 'Accounts you Follow',
iconName: 'account',
iconType: 'material-community',
showRightIcon: true,
showLeftIcon: false,
},
];
export const interestsArray = [
{
title: 'Zero Hunger',
iconName: 'coffee',
iconType: 'feather',
showRightIcon: false,
showLeftIcon: true,
},
{
title: 'Good Health & Wellbeing',
iconName: 'plus',
iconType: 'font-awesome',
showRightIcon: false,
showLeftIcon: true,
},
{
title: 'Quality Education',
iconName: 'book-open',
iconType: 'feather',
showRightIcon: false,
showLeftIcon: true,
},
{
title: 'Gender Equality',
iconName: 'transgender-alt',
iconType: 'font-awesome-5',
showRightIcon: false,
showLeftIcon: true,
},
{
title: 'Clean Water & Sanitation',
iconName: 'water',
iconType: 'ionicon',
showRightIcon: false,
showLeftIcon: true,
},
{
title: 'Climate Action',
iconName: 'align-horizontal-middle',
iconType: 'entypo',
showRightIcon: false,
showLeftIcon: true,
},
{
title: 'Life on Land',
iconName: 'foot',
iconType: 'foundation',
showRightIcon: false,
showLeftIcon: true,
},
{
title: 'LGBTQ+',
iconName: 'rainbow',
iconType: 'entypo',
showRightIcon: false,
showLeftIcon: true,
},
];
export const notificationsItemArray = [
{
title: 'Pause All',
iconName: 'account',
iconType: 'material-community',
showRightIcon: false,
showLeftIcon: false,
},
{
title: 'Coins Received',
iconName: 'account',
iconType: 'material-community',
showRightIcon: false,
showLeftIcon: false,
},
{
title: 'Applauds',
iconName: 'account',
iconType: 'material-community',
showRightIcon: false,
showLeftIcon: false,
},
{
title: 'Comments',
iconName: 'account',
iconType: 'material-community',
showRightIcon: false,
showLeftIcon: false,
},
{
title: 'Followers',
iconName: 'account',
iconType: 'material-community',
showRightIcon: false,
showLeftIcon: false,
},
];
export const settingsItemArray = [
{
title: 'Account',
navigateTo: 'Account',
iconName: 'account',
iconType: 'material-community',
showRightIcon: true,
showLeftIcon: true,
},
{
title: 'Notifications',
navigateTo: 'Notifications',
iconName: 'notifications',
iconType: 'ionicon',
showRightIcon: true,
showLeftIcon: true,
},
{
title: 'Privacy and Security',
navigateTo: 'PrivacyAndSecurity',
iconName: 'lock',
iconType: 'entypo',
showRightIcon: true,
showLeftIcon: true,
},
{
title: 'Manage Payments',
navigateTo: 'ManagePayments',
iconName: 'payment',
iconType: 'material',
showRightIcon: true,
showLeftIcon: true,
},
{
title: 'Connect to Socials',
navigateTo: 'ConnectToSocials',
iconName: 'share-google',
iconType: 'evilicon',
showRightIcon: true,
showLeftIcon: true,
},
{
title: 'Help and Support',
navigateTo: 'HelpAndSupport',
iconName: 'headset-mic',
iconType: 'material',
showRightIcon: true,
showLeftIcon: true,
},
{
title: 'About',
navigateTo: 'About',
iconName: 'question',
iconType: 'antdesign',
showRightIcon: true,
showLeftIcon: true,
},
];
export default projectSingle;
|
promit13/KindrTest
|
refs/heads/master
|
/src/config/color.js
|
export const primaryRed = '#FD1053';
|
promit13/KindrTest
|
refs/heads/master
|
/src/config/router.js
|
import React from 'react';
import {
View,
Text,
TouchableOpacity,
Image,
StyleSheet,
Button,
} from 'react-native';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import {getFocusedRouteNameFromRoute} from '@react-navigation/native';
import {Icon} from 'react-native-elements';
import {Home} from '../screens/Home';
import {Profile} from '../screens/Profile';
import {Projects} from '../screens/Projects';
import {Search} from '../screens/Search';
import {Add} from '../screens/Add';
import {Settings} from '../screens/Settings';
import {Notifications} from '../screens/Notifications';
import {PrivacyAndSecurity} from '../screens/PrivacyAndSecurity';
import {ConnectToSocials} from '../screens/ConnectToSocials';
import {HelpAndSupport} from '../screens/HelpAndSupport';
import {About} from '../screens/About';
import {NewPost} from '../screens/NewPost';
import {WelcomeScreen} from '../screens/WelcomeScreen';
import {Introduction} from '../screens/Introduction';
import {AgeIdentity} from '../screens/AgeIdentity';
import {UploadDocument} from '../screens/UploadDocument';
import {EmailMobileUpload} from '../screens/EmailMobileUpload';
import {VerifyAccount} from '../screens/VerifyAccount';
import {CreateUsername} from '../screens/CreateUsername';
import {EnableLocation} from '../screens/EnableLocation';
import {AccountCreated} from '../screens/AccountCreated';
import {AddName} from '../screens/AddName';
import {ParentsContactInfo} from '../screens/ParentsContactInfo';
import {WelcomeUnderSixteen} from '../screens/WelcomeUnderSixteen';
import {VerifyParentsAccount} from '../screens/VerifyParentsAccount';
import {Interests} from '../screens/Interests';
import {Account} from '../screens/Account';
import {LinkAccountScreen} from '../screens/LinkAccountScreen';
import {OrganisationRegEmail} from '../screens/OrganisationRegEmail';
import {OrganisationNameWebsite} from '../screens/OrganisationNameWebsite';
import {OrganisationAddPicture} from '../screens/OrganisationAddPicture';
import {EditInterests} from '../screens/EditInterests';
import {ManagePayments} from '../screens/ManagePayments';
import {CreateEvent} from '../screens/CreateEvent';
import {Inbox} from '../screens/Inbox';
import {Wallet} from '../screens/Wallet';
import {ProjectDetail} from '../screens/ProjectDetail';
import {Charity} from '../screens/Charity';
import {ProjectPage} from '../screens/ProjectPage';
import {SignUp} from '../screens/SignUp';
import {
homeImageBlack,
searchImageBlack,
createImageBlack,
projectsImageBlack,
homeImagePink,
searchImagePink,
createImagePink,
projectsImagePink,
profileImageBlack,
profileImagePink,
} from './images';
const Tab = createBottomTabNavigator();
import {createStackNavigator} from '@react-navigation/stack';
const Stack = createStackNavigator();
function SignupStack() {
return (
<Stack.Navigator>
<Stack.Screen
name="WelcomeScreen"
component={WelcomeScreen}
options={{headerShown: false}}
/>
<Stack.Screen
name="Signup"
component={SignUp}
options={{headerShown: false}}
/>
<Stack.Screen name="Add" component={Add} options={{headerShown: false}} />
<Stack.Screen
name="Settings"
component={Settings}
options={{headerShown: false}}
/>
<Stack.Screen
name="NewPost"
component={NewPost}
options={{headerShown: false}}
/>
<Stack.Screen
name="Introduction"
component={Introduction}
options={{headerShown: false}}
/>
<Stack.Screen
name="AgeIdentity"
component={AgeIdentity}
options={{headerShown: false}}
/>
<Stack.Screen
name="UploadDocument"
component={UploadDocument}
options={{headerShown: false}}
/>
<Stack.Screen
name="EmailMobileUpload"
component={EmailMobileUpload}
options={{headerShown: false}}
/>
<Stack.Screen
name="VerifyAccount"
component={VerifyAccount}
options={{headerShown: false}}
/>
<Stack.Screen
name="CreateUsername"
component={CreateUsername}
options={{headerShown: false}}
/>
<Stack.Screen
name="EnableLocation"
component={EnableLocation}
options={{headerShown: false}}
/>
<Stack.Screen
name="AccountCreated"
component={AccountCreated}
options={{headerShown: false}}
/>
<Stack.Screen
name="AddName"
component={AddName}
options={{headerShown: false}}
/>
<Stack.Screen
name="ParentsContactInfo"
component={ParentsContactInfo}
options={{headerShown: false}}
/>
<Stack.Screen
name="WelcomeUnderSixteen"
component={WelcomeUnderSixteen}
options={{headerShown: false}}
/>
<Stack.Screen
name="VerifyParentsAccount"
component={VerifyParentsAccount}
options={{headerShown: false}}
/>
<Stack.Screen
name="Interests"
component={Interests}
options={{headerShown: false}}
/>
<Stack.Screen
name="Wallet"
component={Wallet}
options={{headerShown: false}}
/>
<Stack.Screen
name="ProjectDetail"
component={ProjectDetail}
options={{headerShown: false}}
/>
<Stack.Screen
name="Projects"
component={Projects}
options={{headerShown: false}}
/>
<Stack.Screen
name="Charity"
component={Charity}
options={{headerShown: false}}
/>
</Stack.Navigator>
);
}
function ProfileStack() {
return (
<Stack.Navigator>
<Stack.Screen
name="Profile"
component={Profile}
options={{headerShown: false}}
/>
<Stack.Screen
name="LinkAccountScreen"
component={LinkAccountScreen}
options={{headerShown: false}}
/>
<Stack.Screen
name="AccountCreated"
component={AccountCreated}
options={{headerShown: false}}
/>
<Stack.Screen
name="OrganisationRegEmail"
component={OrganisationRegEmail}
options={{headerShown: false}}
/>
<Stack.Screen
name="OrganisationNameWebsite"
component={OrganisationNameWebsite}
options={{headerShown: false}}
/>
<Stack.Screen
name="OrganisationAddPicture"
component={OrganisationAddPicture}
options={{headerShown: false}}
/>
<Stack.Screen
name="CreateEvent"
component={CreateEvent}
options={{headerShown: false}}
/>
<Stack.Screen
name="Inbox"
component={Inbox}
options={{headerShown: false}}
/>
<Stack.Screen
name="Settings"
component={Settings}
options={{headerShown: false}}
/>
<Stack.Screen
name="Notifications"
component={Notifications}
options={{headerShown: false}}
/>
<Stack.Screen
name="PrivacyAndSecurity"
component={PrivacyAndSecurity}
options={{headerShown: false}}
/>
<Stack.Screen
name="ConnectToSocials"
component={ConnectToSocials}
options={{headerShown: false}}
/>
<Stack.Screen
name="HelpAndSupport"
component={HelpAndSupport}
options={{headerShown: false}}
/>
<Stack.Screen
name="ManagePayments"
component={ManagePayments}
options={{headerShown: false}}
/>
<Stack.Screen
name="About"
component={About}
options={{headerShown: false}}
/>
<Stack.Screen
name="Account"
component={Account}
options={{headerShown: false}}
/>
<Stack.Screen
name="EditInterests"
component={EditInterests}
options={{headerShown: false}}
/>
<Stack.Screen
name="Wallet"
component={Wallet}
options={{headerShown: false}}
/>
<Stack.Screen
name="Charity"
component={Charity}
options={{headerShown: false}}
/>
</Stack.Navigator>
);
}
function SearchStack() {
return (
<Stack.Navigator>
<Stack.Screen
name="Search"
component={Search}
options={{headerShown: false}}
/>
<Stack.Screen
name="Project"
component={Projects}
options={{headerShown: false}}
/>
<Stack.Screen
name="Profile"
component={Profile}
options={{headerShown: false}}
/>
<Stack.Screen
name="LinkAccountScreen"
component={LinkAccountScreen}
options={{headerShown: false}}
/>
<Stack.Screen
name="AccountCreated"
component={AccountCreated}
options={{headerShown: false}}
/>
<Stack.Screen
name="OrganisationRegEmail"
component={OrganisationRegEmail}
options={{headerShown: false}}
/>
<Stack.Screen
name="OrganisationNameWebsite"
component={OrganisationNameWebsite}
options={{headerShown: false}}
/>
<Stack.Screen
name="OrganisationAddPicture"
component={OrganisationAddPicture}
options={{headerShown: false}}
/>
<Stack.Screen
name="CreateEvent"
component={CreateEvent}
options={{headerShown: false}}
/>
<Stack.Screen
name="Inbox"
component={Inbox}
options={{headerShown: false}}
/>
<Stack.Screen
name="Settings"
component={Settings}
options={{headerShown: false}}
/>
<Stack.Screen
name="Notifications"
component={Notifications}
options={{headerShown: false}}
/>
<Stack.Screen
name="PrivacyAndSecurity"
component={PrivacyAndSecurity}
options={{headerShown: false}}
/>
<Stack.Screen
name="ConnectToSocials"
component={ConnectToSocials}
options={{headerShown: false}}
/>
<Stack.Screen
name="HelpAndSupport"
component={HelpAndSupport}
options={{headerShown: false}}
/>
<Stack.Screen
name="ManagePayments"
component={ManagePayments}
options={{headerShown: false}}
/>
<Stack.Screen
name="About"
component={About}
options={{headerShown: false}}
/>
<Stack.Screen
name="Account"
component={Account}
options={{headerShown: false}}
/>
<Stack.Screen
name="EditInterests"
component={EditInterests}
options={{headerShown: false}}
/>
<Stack.Screen
name="Wallet"
component={Wallet}
options={{headerShown: false}}
/>
<Stack.Screen
name="ProjectDetail"
component={ProjectDetail}
options={{headerShown: false}}
/>
<Stack.Screen
name="ProjectPage"
component={ProjectPage}
options={{headerShown: false}}
/>
<Stack.Screen
name="Charity"
component={Charity}
options={{headerShown: false}}
/>
</Stack.Navigator>
);
}
function ProjectStack() {
return (
<Stack.Navigator>
<Stack.Screen
name="Project"
component={Projects}
options={{headerShown: false}}
/>
<Stack.Screen
name="Profile"
component={Profile}
options={{headerShown: false}}
/>
<Stack.Screen
name="LinkAccountScreen"
component={LinkAccountScreen}
options={{headerShown: false}}
/>
<Stack.Screen
name="AccountCreated"
component={AccountCreated}
options={{headerShown: false}}
/>
<Stack.Screen
name="OrganisationRegEmail"
component={OrganisationRegEmail}
options={{headerShown: false}}
/>
<Stack.Screen
name="OrganisationNameWebsite"
component={OrganisationNameWebsite}
options={{headerShown: false}}
/>
<Stack.Screen
name="OrganisationAddPicture"
component={OrganisationAddPicture}
options={{headerShown: false}}
/>
<Stack.Screen
name="CreateEvent"
component={CreateEvent}
options={{headerShown: false}}
/>
<Stack.Screen
name="Inbox"
component={Inbox}
options={{headerShown: false}}
/>
<Stack.Screen
name="Settings"
component={Settings}
options={{headerShown: false}}
/>
<Stack.Screen
name="Notifications"
component={Notifications}
options={{headerShown: false}}
/>
<Stack.Screen
name="PrivacyAndSecurity"
component={PrivacyAndSecurity}
options={{headerShown: false}}
/>
<Stack.Screen
name="ConnectToSocials"
component={ConnectToSocials}
options={{headerShown: false}}
/>
<Stack.Screen
name="HelpAndSupport"
component={HelpAndSupport}
options={{headerShown: false}}
/>
<Stack.Screen
name="ManagePayments"
component={ManagePayments}
options={{headerShown: false}}
/>
<Stack.Screen
name="About"
component={About}
options={{headerShown: false}}
/>
<Stack.Screen
name="Account"
component={Account}
options={{headerShown: false}}
/>
<Stack.Screen
name="EditInterests"
component={EditInterests}
options={{headerShown: false}}
/>
<Stack.Screen
name="Wallet"
component={Wallet}
options={{headerShown: false}}
/>
<Stack.Screen
name="ProjectDetail"
component={ProjectDetail}
options={{headerShown: false}}
/>
<Stack.Screen
name="ProjectPage"
component={ProjectPage}
options={{headerShown: false}}
/>
<Stack.Screen
name="Charity"
component={Charity}
options={{headerShown: false}}
/>
</Stack.Navigator>
);
}
function HomeStack() {
return (
<Stack.Navigator>
<Stack.Screen
name="Home"
component={Home}
options={{headerShown: false}}
/>
<Stack.Screen
name="Project"
component={Projects}
options={{headerShown: false}}
/>
<Stack.Screen
name="Profile"
component={Profile}
options={{headerShown: false}}
/>
<Stack.Screen
name="LinkAccountScreen"
component={LinkAccountScreen}
options={{headerShown: false}}
/>
<Stack.Screen
name="AccountCreated"
component={AccountCreated}
options={{headerShown: false}}
/>
<Stack.Screen
name="OrganisationRegEmail"
component={OrganisationRegEmail}
options={{headerShown: false}}
/>
<Stack.Screen
name="OrganisationNameWebsite"
component={OrganisationNameWebsite}
options={{headerShown: false}}
/>
<Stack.Screen
name="OrganisationAddPicture"
component={OrganisationAddPicture}
options={{headerShown: false}}
/>
<Stack.Screen
name="CreateEvent"
component={CreateEvent}
options={{headerShown: false}}
/>
<Stack.Screen
name="Inbox"
component={Inbox}
options={{headerShown: false}}
/>
<Stack.Screen
name="Settings"
component={Settings}
options={{headerShown: false}}
/>
<Stack.Screen
name="Notifications"
component={Notifications}
options={{headerShown: false}}
/>
<Stack.Screen
name="PrivacyAndSecurity"
component={PrivacyAndSecurity}
options={{headerShown: false}}
/>
<Stack.Screen
name="ConnectToSocials"
component={ConnectToSocials}
options={{headerShown: false}}
/>
<Stack.Screen
name="HelpAndSupport"
component={HelpAndSupport}
options={{headerShown: false}}
/>
<Stack.Screen
name="ManagePayments"
component={ManagePayments}
options={{headerShown: false}}
/>
<Stack.Screen
name="About"
component={About}
options={{headerShown: false}}
/>
<Stack.Screen
name="Account"
component={Account}
options={{headerShown: false}}
/>
<Stack.Screen
name="EditInterests"
component={EditInterests}
options={{headerShown: false}}
/>
<Stack.Screen
name="Wallet"
component={Wallet}
options={{headerShown: false}}
/>
<Stack.Screen
name="ProjectDetail"
component={ProjectDetail}
options={{headerShown: false}}
/>
<Stack.Screen
name="Charity"
component={Charity}
options={{headerShown: false}}
/>
<Stack.Screen
name="ProjectPage"
component={ProjectPage}
options={{headerShown: false}}
/>
</Stack.Navigator>
);
}
// function ProfileStack() {
// return (
// <Tab.Navigator>
// <Tab.Screen name="Profile" component={Profile} />
// <Tab.Screen name="LinkAccountScreen" component={LinkAccountScreen} />
// <Tab.Screen name="AccountCreated" component={AccountCreated} />
// <Tab.Screen
// name="OrganisationRegEmail"
// component={OrganisationRegEmail}
// />
// <Tab.Screen
// name="OrganisationNameWebsite"
// component={OrganisationNameWebsite}
// />
// <Tab.Screen
// name="OrganisationAddPicture"
// component={OrganisationAddPicture}
// />
// <Tab.Screen name="CreateEvent" component={CreateEvent} />
// <Tab.Screen name="Inbox" component={Inbox} />
// <Tab.Screen name="Settings" component={Settings} />
// <Tab.Screen name="Notifications" component={Notifications} />
// <Tab.Screen name="PrivacyAndSecurity" component={PrivacyAndSecurity} />
// <Tab.Screen name="ConnectToSocials" component={ConnectToSocials} />
// <Tab.Screen name="HelpAndSupport" component={HelpAndSupport} />
// <Tab.Screen name="ManagePayments" component={ManagePayments} />
// <Tab.Screen name="About" component={About} />
// <Tab.Screen name="Account" component={Account} />
// <Tab.Screen name="EditInterests" component={EditInterests} />
// </Tab.Navigator>
// );
// }
function AddStack() {
return (
<Stack.Navigator>
<Stack.Screen
name="NewPost"
component={NewPost}
options={{headerShown: false}}
/>
<Stack.Screen
name="Settings"
component={Settings}
options={{headerShown: false}}
/>
<Stack.Screen
name="ProjectDetail"
component={ProjectDetail}
options={{headerShown: false}}
/>
</Stack.Navigator>
);
}
export default function MyTabs() {
return (
<Tab.Navigator
screenOptions={({route}) => ({
tabBarLabel: () => {
if (route.name === 'add') {
return null;
}
return (
<Text style={{fontSize: 14, marginTop: -5, marginBottom: 5}}>
{route.name}
</Text>
);
},
tabBarIcon: ({focused, color, size}) => {
let iconName;
let imageSize;
if (route.name === 'home') {
iconName = focused ? homeImagePink : homeImageBlack;
imageSize = 30;
} else if (route.name === 'search') {
iconName = focused ? searchImagePink : searchImageBlack;
imageSize = 30;
} else if (route.name === 'add') {
iconName = focused ? createImagePink : createImageBlack;
imageSize = 40;
} else if (route.name === 'projects') {
iconName = focused ? projectsImagePink : projectsImageBlack;
imageSize = 30;
} else if (route.name === 'profile') {
iconName = focused ? profileImagePink : profileImageBlack;
imageSize = 30;
}
return (
<Image
source={iconName}
style={{height: imageSize, width: imageSize}}
/>
);
},
})}
tabBarOptions={{
style: {
borderRadius: 20,
backgroundColor: 'white',
position: 'absolute',
bottom: 40,
marginHorizontal: 20,
height: 60,
},
activeTintColor: 'red',
inactiveTintColor: 'black',
labelStyle: {fontSize: 12, marginTop: -5, marginBottom: 5},
}}>
<Tab.Screen
name="home"
component={HomeStack}
// options={() => ({
// tabBarLabel: 'home',
// tabBarIcon: ({color}) => (
// <Image source={homeImageBlack} style={{height: 30, width: 30}} />
// ),
// })}
/>
<Tab.Screen
name="search"
component={SearchStack}
// options={{
// tabBarLabel: 'search',
// tabBarIcon: ({color}) => (
// <Image source={searchImageBlack} style={{height: 30, width: 30}} />
// ),
// }}
/>
<Tab.Screen
name="add"
component={AddStack}
// options={{
// tabBarLabel: () => null,
// tabBarIcon: ({color}) => (
// <Image source={createImageBlack} style={{height: 50, width: 50}} />
// ),
// }}
/>
<Tab.Screen
name="projects"
component={ProjectStack}
// options={route => ({
// tabBarVisible: (route => {
// const routeName = getFocusedRouteNameFromRoute(route) ?? '';
// if (routeName === 'Projects') {
// return true;
// }
// return false;
// })(route),
// tabBarLabel: 'projects',
// tabBarIcon: ({color}) => (
// <Image
// source={projectsImageBlack}
// style={{height: 30, width: 30}}
// />
// ),
// })}
/>
<Tab.Screen
name="profile"
component={ProfileStack}
// options={{
// tabBarVisible: false,
// }}
//options={({route}) => ({
// tabBarVisible: route.state.index > 0 ? false : true,
// tabBarVisible: (route => {
// const routeName = getFocusedRouteNameFromRoute(route) ?? '';
// if (routeName === 'Profile') {
// return true;
// }
// return false;
// })(route),
// tabBarLabel: 'profile',
// tabBarIcon: () => (
// <Image
// style={styles.image}
// source={{
// uri: 'https://reactnative.dev/img/tiny_logo.png',
// }}
// />
// ),
// })}
/>
</Tab.Navigator>
);
}
export function MainStack() {
return (
<Stack.Navigator>
<Stack.Screen
name="Signup"
component={SignupStack}
options={{headerShown: false}}
/>
<Stack.Screen
name="SignedIn"
component={MyTabs}
options={{headerShown: false}}
/>
</Stack.Navigator>
);
}
function MyTabBar({state, descriptors, navigation}) {
const focusedOptions = descriptors[state.routes[state.index].key].options;
if (focusedOptions.tabBarVisible === false) {
return null;
}
return (
<View
style={{
flexDirection: 'row',
}}>
{state.routes.map((route, index) => {
const {options} = descriptors[route.key];
console.log(options.title);
const label =
options.tabBarLabel !== undefined
? options.tabBarLabel
: options.title !== undefined
? options.title
: route.name;
const isFocused = state.index === index;
const onPress = () => {
const event = navigation.emit({
type: 'tabPress',
target: route.key,
canPreventDefault: true,
});
if (!isFocused && !event.defaultPrevented) {
navigation.navigate(route.name);
}
};
const onLongPress = () => {
navigation.emit({
type: 'tabLongPress',
target: route.key,
});
};
return (
<TouchableOpacity
accessibilityRole="button"
accessibilityState={isFocused ? {selected: true} : {}}
accessibilityLabel={options.tabBarAccessibilityLabel}
testID={options.tabBarTestID}
onPress={onPress}
onLongPress={onLongPress}
style={{flex: 1}}>
<Text style={{color: isFocused ? '#673ab7' : '#222'}}>{label}</Text>
</TouchableOpacity>
);
})}
</View>
);
}
const styles = StyleSheet.create({
image: {
width: 24,
height: 24,
borderRadius: 24 / 2,
overflow: 'hidden',
},
});
|
openmrs-archive/openmrs-contrib-id-groups
|
refs/heads/master
|
/resource/mailinglists.js
|
$().ready(function(){
/* MAILING LISTS */
// At page load, the .email-selector-submit's are contained within templates,
// so jQuery can't access them director. So we watch for the bootstrap "shown
// popover" event and bind the submit selector then.
// $('.group-list').on('shown.bs.popover', function() {
// bindEmailSelectorSubmit();
// });
// bindEmailSelectorSubmit();
$('.view-subscriptions').each(function(button) {
$(this).popover({
html: true,
placement: 'bottom',
content: $(this).siblings('.email-selector').html(),
trigger: 'focus' // closes popover when user clicks outside
});
// Update the popover stored content when it closes
$(this).on('hide.bs.popover', function() {
var content = $(this).siblings('.popover').find('.popover-content').html();
$(this).prop('data-content', content);
});
});
// AJAX for subscribtion-update forms
function bindEmailSelectorSubmit() {
$('.email-selector-submit').click(function(event){
event.preventDefault();
var button = $(this),
icon = button.find('i[class*="icon-"]'),
form = $(this).parents('form'),
submitUrl = form.attr('action');
// show status in popover or beside button
var showStatus = function(message, failed){
var status = button.siblings('span.status');
status.html('');
setTimeout(function(){
status.html(message);
if (failed) status.addClass('failtext');
}, 50);
};
// make the ajax call
$.ajax({
url: submitUrl,
type: 'POST',
data: form.serialize(),
dataType: 'json',
beforeSend: function(){
button.addClass('active');
form.addClass('working');
showStatus('Working...');
},
error: function(jqXHR, textStatus, errorThrown){
button.removeClass('active');
form.removeClass('working');
showStatus('Error! ('+textStatus+' / '+errorThrown+')', true);
},
success: function(subs) {
button.removeClass('active');
form.removeClass('working');
showStatus('Updated.');
// change UI text/icons to reflect change
var input = form.find('input[name="address"]');
if (input.length == 1) { // no secondary emails
icon.removeClass();
if ($.inArray(input.attr('value'), subs) > -1) {
button.find('i').addClass('icon-envelope');
button.find('span').html('Unsubscribe');
}
else {
button.find('i').addClass('icon-envelope-alt');
button.find('span').html('Subscribe');
}
}
// check / enable email addresses that are now subscribed (sanity)
form.find('input[name="address"]').each(function(i, elem){
elem = $(elem);
var address = elem.attr('value');
if ($.inArray(address, subs) > -1) { // now subscribed
if (elem.attr('type') == 'checkbox') {elem.prop('checked', true);}
if (elem.attr('type') == 'hidden') {elem.prop('disabled', true);}
}
else { // now unsubscribed
if (elem.attr('type') == 'checkbox') {elem.prop('checked', false);}
if (elem.attr('type') == 'hidden') {elem.prop('disabled', false);}
}
});
setTimeout(function(){
// if (button.parents('.popover')) button.parents('.popover').removeClass('visible');
form.find('.view-subscriptions').popover('hide');
showStatus('');
}, 2000);
}
});
});
}
});
|
openmrs-archive/openmrs-contrib-id-groups
|
refs/heads/master
|
/index.js
|
module.exports = require('./lib/groups');
|
openmrs-archive/openmrs-contrib-id-groups
|
refs/heads/master
|
/lib/ga-provisioning.js
|
var https = require('https'),
util = require('util'),
xml2js = require('xml2js'),
emitter = require('events').EventEmitter,
Common = require(global.__apppath+'/openmrsid-common'),
db = Common.db,
log = Common.logger.add('provisioning');
var gaUsername, gaPassword, gaDomain; // connection information stored here
var connection = new emitter; // emits connected and disconnected events
authToken = '';
exports.connectionStatus = 0; // 0 = disconnected, 1 = connecting, 2 = connected, -1 = disabled
var GAError = function(message, status, constr) {
Error.captureStackTrace(this, constr || this);
this.status = status || 1;
this.message = message+' ('+status+')' || 'Google Apps API Error';
}
util.inherits(GAError, Error);
GAError.prototype.name = 'GAError';
var parseError = function(status, data, callback) {
var status, message;
// interpret HTTP status code
if (status == 200) return callback(null); // no error, skip the rest of this error code
else if (status == 201) {message = undefined; status = undefined;} // created
else if (status == 304) {message = undefined; status = undefined;} // resource hasn't changed
else if (status == 400) {message = 'Bad request to GData.'; status = 400;}
else if (status == 401) {message = 'Unauthorized resource requested.'; status = 401;}
else if (status == 403) {message = 'Unsupported parameter or failed authorization.'; status = 403;}
else if (status == 404) {message = 'GData resource not found.'; status = 404;}
else if (status == 409) {message = 'Resource version number conflict.'; status = 409;}
else if (status == 410) {message = 'Requested GData resource is no longer available.'; status = 410;}
else if (status == 500) {message = 'Internal GData server error.'; status = 500;}
// parse GData error
if (data && data.indexOf('<AppsForYourDomainErrors>') > -1) { // if Error msg exists in response
var parser = new xml2js.Parser({mergeAttrs: true});
parser.parseString(data, function(err, result){
log.trace('GData error detected');
if (err) return callback(err);
// error details
var code = result.error.errorCode,
reason = result.error.reason;
if (code == 1303 || 1301) { // "EntityNotValid" or "EntityDoesNotExist" - returns for addresses that have no subscriptions
log.trace('GData error was an "entity not valid" e.g. not important');
return callback(null); // this wasn't a meaningful error
}
else
return callback(new GAError(message+' (GData error '+code+': '+reason+')', status)); // send both errors
});
}
else {
if (message || status) // only if an HTTP error has occured
return callback(new GAError(message, status)); // no GData error
else return callback();
}
};
// AUTHENTICATION & CONNECTION // - keeps an up-to-date token available from GA
var connect = function(callback) {
if (typeof callback != 'function') callback = function(err){if (err) log.error(err);}
var finish = function(error, newToken) { // called once done
authToken = newToken;
connection.emit('connected');
exports.connectionStatus = 2; // ready to accept calls
setTimeout(function(){ // get a new token in 20 hrs (token expires in 24)
exports.reconnect();
}, 1000*60*60*20);
callback();
};
connection.emit('disconnected');
exports.connectionStatus = 1; // getting a new token
// connect to DB and get username/password/domain
db.find('GroupsConf', {key: ['username', 'password', 'domain']}, function(err, instances){
if (err) return callback(err);
// if paramaters are incorrect, abort connection
if (instances.length != 3) {
exports.connectionStatus = -1;
connection.emit('disabled');
return log.warn('Unable to connect to the Provisioning API: Login paramaters not found in DB. Aborting connection...');
}
// get user/pass/domain from DB data
instances.forEach(function(pref){
if (pref.key == 'username') gaUsername = pref.value;
else if (pref.key == 'password') gaPassword = pref.value;
else if (pref.key == 'domain') gaDomain = pref.value;
});
// prepare the login request
var options = {
host: 'google.com',
port: '443',
path: '/accounts/ClientLogin',
method: 'POST',
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
};
var data = '';
// send the login req
var req = https.request(options, function(res) {
log.info('Authenticating to Google Apps as '+gaUsername+'.');
log.trace('GA ClientLogin Status: '+res.statusCode);
//log.trace('GA ClientLogin Headers: '+JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function(chunk){ // collect response data
//log.trace('GA ClientLogin Body Chunk: '+chunk);
data += chunk;
});
res.on('end', function() { // extract auth token from response and call finish
//log.trace('all data received: '+data);
parseError(res.statusCode, data, function(error){
if (error) {
return callback(error);
}
var auth = /(Auth=)(\S*)/.exec(data)[0]; // parse token from data
log.trace('auth token: '+auth);
authToken = auth; // update global token
connection.emit('connected');
exports.connectionStatus = 2; // now ready to accept calls
setTimeout(connect, 1000*60*60*20); // get a new token in 20 hrs (token expires in 24)
callback();
});
});
});
req.on('error', function(e) {
log.error('GA ClientLogin Failure: '+e.message);
return callback(e);
});
req.write('&Email=' // POST login credentials
+encodeURIComponent(gaUsername)
+'&Passwd='+encodeURIComponent(gaPassword)
+'&accountType=HOSTED&service=apps');
req.end();
});
};
var verify = function(callback) { // verify connection to GA (in order to make calls)
callback = (!callback) ? new Function : callback;
var timeout = function() {
exports.connectionStatus = 0;
log.error('Timed out while waiting for GA client to reconnect');
callback(new GAError('Unable to verify connection to Google Apps.'));
}
if (exports.connectionStatus == 2) { // client already connected
exports.connectionStatus = 2;
log.trace('GA already connected');
callback();
}
else if (exports.connectionStatus == -1) { // connection disabled
exports.connectionStatus = -1;
callback(new Error('Google Groups connection disabled.'));
}
else { // in the process of reconnecting OR no connection found
log.debug('no GA connection found; status = waiting for reconnect');
if (exports.connectionStatus == 0) connect(function(error){
if (error) return callback(error);
exports.connectionStatus = 2;
}); // connect if not connected at all
var time = setTimeout(timeout, 5000);
connection.once('connected', function(){
exports.connectionStatus = 2;
log.trace('now connected, auth token in memory');
clearTimeout(time);
callback();
});
connection.once('disabled', function(){
exports.connectionStatus = -1;
clearTimeout(time);
callback(new Error('Google Groups connection disabled.'));
})
}
}
// API CALLS //
var setOptions = function(method, path) { // return a configured options object for HTTP request
var out = {
host: 'apps-apis.google.com',
port: 443,
path: path,
method: method,
headers: {'Content-Type': 'application/atom+xml',
'Authorization': 'GoogleLogin '+authToken}
};
//log.trace('request options: '+JSON.stringify(out));
return out;
};
var parseGroupFormat = function(input, callback) {
if (!callback instanceof Function) callback = new Function;
var out = []; // will populate with groups
// if no occupied entries in input (no groups) return an empty group array
if (!input.entry[0]) return callback(out);
// otherwise, parse each entry for group props
// each group appears as an "entry" in GData
input.entry.forEach(function(element, i, array){
var grp = {};
element['apps:property'].forEach(function(prop){
if (prop.name == 'groupId') {
grp.address = prop.value;
grp.urlName = grp.address.replace(/@.+$/, '').toLowerCase();
}
else if (prop.name == 'groupName') grp.name = prop.value;
else if (prop.name == 'emailPermission') grp.emailPermission = prop.value;
else if (prop.name == 'description') grp.description = prop.value;
else if (prop.name == 'permissionPreset') grp.permissionPreset = prop.value;
else if (prop.name == 'directMember') grp.directMember = prop.value;
});
out.push(grp);
}); // now finished
callback(out);
};
/*
Returns object containing groups for GA domain:
[
{
address: group@domain.com
name: Group Name
emailPermission: Member
permissionPreset: Custom
description: Text Description
} … etc.
]
*/
exports.getAllGroups = function(callback) {
if (!callback instanceof Function) callback = new Function;
verify(function(err){
if (err) return callback(err);
var options = setOptions('GET', '/a/feeds/group/2.0/'+encodeURIComponent(gaDomain));
var req = https.get(options, function(res) {
data = '';
res.on('data', function(chunk) {
//log.trace('chunk: '+chunk);
data += chunk;
});
res.on('end', function(err) {
if (err) return callback(err);
log.trace('getAllGroups api call closed');
parseError(res.statusCode, data, function(err){
if (err) return callback(err);
var parser = new xml2js.Parser({mergeAttrs: true});
parser.parseString(data, function(err, result) {
if (err) return callback(err);
var finish = function(out) { // called once all have been parsed
callback(null, out); // all done!
}
parseGroupFormat(result, finish); // parse THIS json into the data we need
});
});
});
});
req.on('error', function(err) {
log.error('GA getAllGroups Failure: '+err.message);
return callback(err);
});
});
}
/*
Returns object for an email address's (user's) groups:
[ {address: group1@domain.com, name: 'GROUP_ONE', emailPermission: 'Member', permissionPreset: 'Custom', Description: 'Text'},
{address: group2@domain.com, name: 'GROUP_TWO', emailPermission: 'Member', permissionPreset: 'Custom', Description: 'Text'}]
*/
exports.getGroupsByEmail = function(email, callback) {
if (!callback instanceof Function) callback = new Function;
verify(function(err){
if (err) return callback(err);
var options = setOptions('GET', 'https://apps-apis.google.com/a/feeds/group/2.0/'+encodeURIComponent(gaDomain)+'/?member='+email);
var req = https.get(options, function(res) {
var data = '';
res.on('data', function(chunk) {
log.trace('chunk: '+chunk); // this was slowing down the logger :(
data += chunk;
});
res.on('end', function(err) {
if (err) return callback(err);
log.trace('getGroupsByEmail api call closed');
parseError(res.statusCode, data, function(err){ // respond to GData API error
if (err) return callback(err);
var parser = new xml2js.Parser({mergeAttrs: true});
parser.parseString(data, function(err, result) { // convert xml response to traversable json
if (err) return callback(err);
var finish = function(out){
callback(null, out);
};
// force results to be an array - if user has one group, result will be a string and forEach() will fail
if (!(result.entry instanceof Array)) result.entry = [result.entry];
parseGroupFormat(result, finish);
});
});
});
});
req.on('error', function(err) {
log.error('GA getGroupsByEmail Failure: '+err.message);
return callback(err);
});
});
};
/*
Adds an email address to specified group, returning:
{"apps:property": {
"name": "memberId",
"value": "ewilliams995@gmail.com"
}}
*/
exports.addUser = function(email, group, callback) {
if (!callback instanceof Function) callback = new Function;
verify(function(err) {
if (err) return callback(err);
log.debug('adding '+email+' to '+group);
var options = setOptions('POST', 'https://apps-apis.google.com/a/feeds/group/2.0/'+encodeURIComponent(gaDomain)+'/'+group+'/member');
var req = https.request(options, function(res) {
var data = '';
res.on('data', function(chunk) {
//log.trace('chunk: '+chunk);
data += chunk;
});
res.on('end', function(err) {
if (err) return callback(err);
log.trace('addUser api call closed');
parseError(res.statusCode, data, function(err){ // respond to GData API error
if (err) return callback(err);
var parser = new xml2js.Parser({mergeAttrs: true});
parser.parseString(data, function(err, result) {
if (err) return callback(err);
callback(null, result);
});
});
});
});
req.on('error', function(err) {
log.error('GA addUser failure: '+err.message);
return callback(err);
});
req.write('<?xml version="1.0" encoding="UTF-8"?>'
+'<atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:apps="http://schemas.google.com/apps/2006" xmlns:gd="http://schemas.google.com/g/2005">'
+'<apps:property name="memberId" value="'+email+'"/></atom:entry>');
req.end();
});
};
/*
Removes email address from group, only returning data in an error
*/
exports.removeUser = function(email, group, callback) {
if (!callback instanceof Function) callback = new Function;
verify(function(err) {
if (err) return callback(err);
log.debug('removing '+email+' from '+group);
var options = setOptions('DELETE', 'https://apps-apis.google.com/a/feeds/group/2.0/'+encodeURIComponent(gaDomain)+'/'+group+'/member/'+email);
var req = https.request(options, function(res) {
var data = ''; // should not return any data, this is only to catch errors
res.on('data', function(chunk) {
//log.trace('chunk: '+chunk);
data += chunk;
});
res.on('end', function(err) {
if (err) return callback(err);
log.trace('removeUser api call closed');
parseError(res.statusCode, data, function(err){ // respond to GData API error
if (err) return callback(err);
else return callback();
});
});
});
req.on('error', function(err) {
log.error('GA removeUser Failure: '+err.message);
return callback(err);
});
req.end(); // terminate request; finish sending
});
};
// TESTING
/*
exports.getAllGroups(function(e, result){
if (e) return log.error("thrown error:\n "+e.message);
log.info('all the groups: ');
result.forEach(function(item) {
log.info("\n "+item.name+"\n ID: "+item.id+"\n Description: "+item.description);
});
});/
exports.getGroupsByEmail('elliott', function(err, result){
log.debug('callback called');
if (err) return log.error("thrown error:\n "+err.message);
log.debug(JSON.stringify(result));
result.forEach(function(item) {
log.info("\n "+item.name+"\n ID: "+item.id+"\n Description: "+item.description);
});
});
exports.addUser('elliott', 'test-group', function(err, result){
log.debug('callback');
if (err) return log.error("thrown error:\n "+err.message);
log.debug(JSON.stringify(result));
});
setTimeout(function(){
exports.removeUser('elliott', 'test-group', function(err) {
if (err) return log.error("thrown error:\n "+err.message);
log.debug('returned, no error');
});
}, 5000);
*/
|
openmrs-archive/openmrs-contrib-id-groups
|
refs/heads/master
|
/README.md
|
openmrs-contrib-dashboard-groups
================================
Google Groups integration module of ID Dashboard
**NOTE:** OpenMRS no longer uses Google Groups and now uses [OpenMRS Talk](http://talk.openmrs.org).
|
ReawenJS/discord-rpc
|
refs/heads/main
|
/README.md
|
# discord-rpc
Selamlar! <img src="https://raw.githubusercontent.com/MartinHeinz/MartinHeinz/master/wave.gif" width="30px">
Discord uygulaması arkada açık değilken çalışmaz.
Eğer hata alırsanız bu dosyaları hatanın içindeki klasöre atın. Örn: C:/Users/Administrator
<strong>Çalmayın demicem de altına bir yerine bunun linkini atın paylaşcaksanız</strong>
[<img src = "https://img.shields.io/badge/Reawen GITHUB-%231877F2.svg?&style=for-the-badge&logo=github&logoColor=white">](https://github.com/ReawenJS)
[<img src = "https://img.shields.io/badge/Reawen INSTAGRAM-%FFFFFF.svg?&style=for-the-badge&logo=instagram&logoColor=white">](https://instagram.com/helios_afkk)
|
ReawenJS/discord-rpc
|
refs/heads/main
|
/index.js
|
var rpc = require("discord-rpc")
const client = new rpc.Client({ transport: 'ipc' })
client.on('ready', () => {
client.request('SET_ACTIVITY', {
pid: process.pid,
activity : {
details : "Gözükecek şey burada yazıyorrrrrr",
assets : {
large_image : "Discord Developer Portal'da eklediğimiz resmin ismi.",
large_text : "Discord botları için DM." // bu gözükmeyebilir!!
},
buttons : [{label : "Instagram" , url : "https://www.instagram.com/helios_afkk/"},{label : "Github",url : "https://github.com/ReawenJS"}] //kendinize göre yazın
}
})
})
client.login({ clientId : "Discord Developer Portal'da oluşturduğumuz aplikasyon id'si" }).catch(console.error);
|
markoprog/ComShop
|
refs/heads/master
|
/kontakt.php
|
<script type="text/javascript">
function provera(){
var ime=document.getElementById("ime").value;
var mail = document.getElementById("email").value;
var poruka= document.getElementById("poruka").value;
var reg_ime=/^[A-Z][a-z]{1,14}$/;
var reg_mail=/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/;
var provera=true;
if(!reg_ime.test(ime)){
document.getElementById('ime').style.borderColor="#ff0000";
provera=false;
}
if(!reg_mail.test(mail)){
document.getElementById('email').style.borderColor="#ff0000";
provera=false;
}
if(poruka==''){
document.getElementById('poruka').style.borderColor="#ff0000";
provera=false;
}
return provera;
}
</script>
<!-- Content Row -->
<div class="row">
<!-- Map Column -->
<div class="col-md-8">
<!-- Embedded Google Map -->
<iframe width="100%" height="400px" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2830.2921228305345!2d20.45916480000001!3d44.81561310000002!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x475a7ab261fd751d%3A0xdbc9cb319522166f!2zMzIg0J7QsdC40LvQuNGb0LXQsiDQstC10L3QsNGGLCDQkdC10L7Qs9GA0LDQtA!5e0!3m2!1ssr!2srs!4v1432403977954" width="600" height="450" frameborder="0" style="border:0"></iframe>
</div>
<!-- Contact Details Column -->
<div class="col-md-4">
<br/><br/><br/><br/>
<span class='formular_slova'>Adresa:</span><span style='color:#337ab7; font-size:14px; font-style:italic;'> Obilićev venac 32</span> <br/><br/>
<span class='formular_slova'>Mob:</span><span style='color:#337ab7; font-size:14px; font-style:italic;'> +38166000000</span> <br/><br/>
<span class='formular_slova'>Fix:</span><span style='color:#337ab7; font-size:14px; font-style:italic;'> 011887000</span> <br/><br/>
<span class='formular_slova'>Fax:</span><span style='color:#337ab7; font-size:14px; font-style:italic;'> 0118870000</span> <br/><br/>
<span class='formular_slova'>E-mail:</span><span style='color:#337ab7; font-size:14px; font-style:italic;'> comshop@gmail.com</span> <br/><br/>
</div>
</div>
<!-- /.row -->
<!-- Contact Form -->
<!-- In order to set the email address and subject line for the contact form go to the bin/contact_me.php file. -->
<div class="row">
<div class="col-md-8">
<h4>Ako imate bilo kakve primedbe, sugestije i pohvale pišite nam!</h4>
<form name="sentMessage" id="contactForm" method="Post" action="index.php?page=kontakt" onSubmit="return provera();">
<div class="control-group form-group">
<div class="controls">
<label>Ime:</label>
<input type="text" class="form-control" id="ime" name="ime" required data-validation-required-message="Unesite vase ime.">
<p class="help-block"></p>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>E-mail adresa:</label>
<input type="email" class="form-control" id="email" name="email" required data-validation-required-message="Unesite email.">
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<label>Tekst poruke:</label>
<textarea rows="10" cols="100" class="form-control" id="poruka" required data-validation-required-message="Unesite poruku." maxlength="999" style="resize:none"></textarea>
</div>
</div>
<div id="success"></div>
<!-- For success/fail messages -->
<input type="submit" name='submit' id='posalji' class="btn btn-info" value="Pošalji poruku" onClick="provera();"/>
</form>
</div>
</div>
<?php
if(isset($_POST['posalji'])){
$ime=$_POST['ime'];
$mail=$_POST['email'];
$poruka=$_POST['poruka'];
$reg_ime="/^[A-Z][a-z]{1,14}$/";
$reg_mail="/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/";
$greske=array();
if(!preg_match($reg_ime,$ime)){
$greske[]="Greška!";
}
if(!preg_match($reg_mail,$mail)){
$greske[]="Greška!";
}
if($poruka==''){
$greske[]="Greška!";
}
if(count($greske)>0){
print "<ul style='color:red;'>";
foreach($greske as $greska){
print "<li>".$greska."</li>";
}
print "</ul>";
}
else{
mail('comshop@gmail.com','Poruka sa sajta',$poruka,$mail);
}
}
?>
|
markoprog/ComShop
|
refs/heads/master
|
/meni.php
|
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.php" style='font-size:24px;'><b><i>ComShop</i></b></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<?php
include ('konekcija.inc');
echo("<ul class='nav navbar-nav'>");
$upit1="select * from meni";
$rez1=mysql_query($upit1,$konekcija);
while($red1=mysql_fetch_array($rez1)){
echo("<li><a href=index.php?page=".$red1['putanja'].">".$red1['naziv']."</a></li>");
}
echo("</ul>");
?>
</div>
<!-- /.navbar-collapse -->
<div class="pull-right" style='margin-top:-38px'><input type="text" name='trazi' id='trazi' style="border-radius:5px;" placeholder='Naziv proizvoda...'/>
</div>
<div id="rezultat" class="pull-right" style="position:absolute; right:100px; background-color:#222; color:white; border-radius:2px;">
</div>
</div>
<!-- /.container -->
</nav>
|
markoprog/ComShop
|
refs/heads/master
|
/README.md
|
# ComShop
My work on university of course web programming php.
This is part of my site "ComShop" (login form, contact form and dynamic menu). The website is done dinamically in PHP and the data are drawn from the database.
|
markoprog/ComShop
|
refs/heads/master
|
/login.php
|
<div id='loginbox' class="mainbox col-md-4" style="width: 293px; margin-left:-295px;margin-top:350px;" >
<div class="panel panel-info" >
<div class="panel-heading">
<div class="panel-title">Logovanje</div>
</div>
<div style="padding-top:30px" class="panel-body" >
<div style="display:none" id="login-alert" class="alert alert-danger col-sm-12">
</div>
<form id="loginform" class="form-horizontal" role="form" method="POST" action="index.php?page=login">
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="login-username" type="text" class="form-control" name="korisnicko" value="" placeholder="username">
</div>
<div style="margin-bottom: 25px" class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
<input id="login-password" type="password" class="form-control" name="lozinka" placeholder="password">
</div>
<div style="margin-top:10px" class="form-group">
<!-- Button -->
<div class="col-sm-12 controls">
<input type="submit" value="Uloguj se" name="dugme_logovanje" class="btn btn-info"/>
<a id="btn-login" href="index.php?page=registracija" class="btn btn-info">Registruj se</a>
</div>
</div>
</form>
</div>
</div>
</div>
<?php
if(isset($_POST['dugme_logovanje'])){
include('konekcija.inc');
$username=trim($_POST['korisnicko']);
$password=md5(trim($_POST['lozinka']));
$greske=array();
$reg_username="/^[a-z0-9\_]+$/";
$reg_password="/[^\/.,<>:;*?A-Z]$/";
if(!preg_match($reg_username,$username)){
$greske[]="Za username se mogu koristiti samo mala slova, brojevi i _ !!!";
}
if(!preg_match($reg_password,$password)){
$greske[]="Za lozinku se mogu koristiti samo mala slova i brojevi !!!";
}
if(count($greske)==0){
$status=1;
$upit="select * from korisnici where korisnicko_ime='".$username."' and lozinka='".$password."' and status='".$status."'";
$rezultat=mysql_query($upit,$konekcija);
if(mysql_num_rows($rezultat)==1){
$red=mysql_fetch_array($rezultat);
$uloga=$red['uloga'];
$username=$red['korisnicko_ime'];
$id_kor=$red['id_korisnika'];
$ime=$red['ime'];
$prezime=$red['prezime'];
$mail=$red['email'];
$_SESSION['email']=$mail;
$_SESSION['uloga']=$uloga;
$_SESSION['korisnicko_ime']=$username;
$_SESSION['ime']=$ime;
$_SESSION['prezime']=$prezime;
$_SESSION['id_korisnika']=$id_kor;
switch($red['uloga']){
case 'admin': ?>
<script type="text/javascript">
window.location.assign("admin.php");
</script>
<?php break;
case 'korisnik': ?>
<script type="text/javascript">
window.location.assign("index.php");
</script>
<?php break;
}
}
else{
echo("U bazi ne postoji korisnik sa ovim nalogom!");
}
}
}
?>
|
HelloMeme/pippo
|
refs/heads/master
|
/pippo-core/src/main/java/ro/pippo/core/route/Router.java
|
/*
* Copyright (C) 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ro.pippo.core.route;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This class allows you to do route requests based on the HTTP verb (request method) and the request URI,
* in a manner similar to Sinatra or Express.
* Routes are matched in the order they are added/defined.
* Routing is the process of selecting the best matching candidate from a collection of routes for an incoming request.
*
* @author Decebal Suiu
*/
public interface Router {
/**
* Gets the current context path.
*
* @return the context path
*/
String getContextPath();
/**
* Sets the context path for url generation.
*
* @param contextPath
*/
void setContextPath(String contextPath);
Set<String> getIgnorePaths();
void ignorePaths(String... paths);
void addRoute(Route route);
void removeRoute(Route route);
void addRouteGroup(RouteGroup routeGroup);
void removeRouteGroup(RouteGroup routeGroup);
List<RouteMatch> findRoutes(String requestMethod, String requestUri);
List<Route> getRoutes();
/**
* Get uri with context path.
*
* @param relativeUri
* @return
*/
String uriFor(String relativeUri);
String uriFor(String nameOrUriPattern, Map<String, Object> parameters);
String uriPatternFor(Class<? extends ResourceHandler> resourceHandlerClass);
/**
* Returns the base path for the Pippo application.
*/
String getApplicationPath();
void setApplicationPath(String pippoPath);
}
|
HelloMeme/pippo
|
refs/heads/master
|
/pippo-metrics-parent/pippo-metrics/src/main/java/ro/pippo/metrics/MetricsRouteContext.java
|
/*
* Copyright (C) 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ro.pippo.metrics;
import com.codahale.metrics.MetricRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ro.pippo.core.Application;
import ro.pippo.core.Request;
import ro.pippo.core.Response;
import ro.pippo.core.route.DefaultRouteContext;
import ro.pippo.core.route.RouteContext;
import ro.pippo.core.route.Route;
import ro.pippo.core.route.RouteHandler;
import ro.pippo.core.route.RouteMatch;
import ro.pippo.core.util.LangUtils;
import java.lang.reflect.Method;
import java.util.List;
/**
* @author James Moger
*/
public class MetricsRouteContext extends DefaultRouteContext {
private static final Logger log = LoggerFactory.getLogger(MetricsRouteContext.class);
private final MetricRegistry metricRegistry;
public MetricsRouteContext(MetricRegistry metricRegistry, Application application, Request request,
Response response, List<RouteMatch> routeMatches) {
super(application, request, response, routeMatches);
this.metricRegistry = metricRegistry;
}
@Override
protected void handleRoute(Route route) {
RouteHandler handler = route.getRouteHandler();
try {
// TODO resolve
/*
Method method;
if (handler instanceof ControllerHandler) {
ControllerHandler controllerHandler = (ControllerHandler) handler;
method = controllerHandler.getMethod();
} else {
method = route.getRouteHandler().getClass().getMethod("handle", RouteContext.class);
}
*/
Method method = route.getRouteHandler().getClass().getMethod("handle", RouteContext.class);
String metricName = MetricRegistry.name(method.getDeclaringClass(), method.getName());
if (method.isAnnotationPresent(Metered.class)) {
log.debug("Found '{}' annotation on method '{}'", Metered.class.getSimpleName(), LangUtils.toString(method));
// route handler is Metered
Metered metered = method.getAnnotation(Metered.class);
if (!metered.value().isEmpty()) {
metricName = metered.value();
}
handler = new MeteredRouteHandler(metricName, route.getRouteHandler(), metricRegistry);
} else if (method.isAnnotationPresent(Timed.class)) {
log.debug("Found '{}' annotation on method '{}'", Timed.class.getSimpleName(), LangUtils.toString(method));
// route handler is Timed
Timed timed = method.getAnnotation(Timed.class);
if (!timed.value().isEmpty()) {
metricName = timed.value();
}
handler = new TimedRouteHandler(metricName, route.getRouteHandler(), metricRegistry);
} else if (method.isAnnotationPresent(Counted.class)) {
log.debug("Found '{}' annotation on method '{}'", Counted.class.getSimpleName(), LangUtils.toString(method));
// route handler is Counted
Counted counted = method.getAnnotation(Counted.class);
if (!counted.value().isEmpty()) {
metricName = counted.value();
}
handler = new CountedRouteHandler(metricName, counted.active(), route.getRouteHandler(), metricRegistry);
}
} catch (Exception e) {
log.error("Failed to get method?!", e);
}
handler.handle(this);
}
}
|
ACCEPT786/Second_Hand_Trading_System
|
refs/heads/master
|
/Register_submit.php
|
<?php
header("Content-Type: text/html; charset=utf-8");
$con = mysqli_connect("localhost","Second_Hand","pStjGTc347FDjfZW");
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con, Second_Hand);
mysqli_query($con,"set names 'utf8'");
$sql = "INSERT INTO Users_list (email, password)
VALUES ('$_POST[email]','$_POST[password]')";
if ($con->query($sql) === TRUE) {
echo "successfully registered.";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
$con->close();
|
ACCEPT786/Second_Hand_Trading_System
|
refs/heads/master
|
/search_submit.php
|
<?php
session_start();
header("Content-Type: text/html; charset=utf-8");
if(isset($_SESSION["Login_status"])&&$_SESSION["Login_status"] == "OK"){
$con = mysqli_connect("localhost","Second_Hand","pStjGTc347FDjfZW");
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con, Second_Hand);
mysqli_query($con,"set names 'utf8'");
$count=0;
$selection=$_POST["selection"];
$sql="SELECT $selection FROM Book_List;";
$result=$con->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
if($_POST["search1"] == $row[$selection]){
echo "Result found.";
$count++;
}
}
if($count==0){
echo "<script language=\"JavaScript\">alert(\"No result found. Return to the search page.\");</script>";
echo "<script>history.go(-1)</script>";
}
} else {
echo "0 result";
}
mysqli_close($con);
}
else
echo "<script language=\"JavaScript\">alert(\"Please login first!\");</script>";
echo "<meta http-equiv='Refresh' content='1;URL=Login.php'>";
|
MKH470/restaurant
|
refs/heads/master
|
/app/Http/Controllers/FoodController.php
|
<?php
namespace App\Http\Controllers;
use App\Category;
use App\Food;
use App\Http\Requests\FoodRequest;
use Illuminate\Http\Request;
class FoodController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$food= Food::latest()->paginate(3);
return view('food.all',compact('food'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('food.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(FoodRequest $request)
{
//----------Image preparation for uploading and storing
$image =$request->file('image');
$image_name = time().'.'.$image->getClientOriginalExtension();
$image_path=public_path('/images/food');
$image->move($image_path,$image_name );
//------------------------------------------------------------
Food::create([
"image"=>$image_name,
"name"=>$request->input('name'),
"description"=>$request->input('description'),
"price"=>$request->input('price'),
"category_id"=>$request->input('category'),
]);
return redirect('food')->with(['success' => 'category has been added successfully ']);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$food=Food::find($id);
return view('food.edit' ,compact('food'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$request->validate([
'image'=>'mimes:png,jpg,jpeg',
'name' => 'required|max:100',
'description' => 'required',
'price' => 'required|numeric',
'category'=>'required'
]);
$food =Food::find($id);
$image_name=$food->image;
if($request->hasFile('image')){
$image =$request->file('image');
$image_name = time().'.'.$image->getClientOriginalExtension();
$image_path=public_path('/images/food');
$image->move($image_path,$image_name );
}else{
$image_name=$food->image;
}
$food->image = $image_name ;
$food->name = $request->get('name');
$food->description= $request->get('description');
$food->price = $request->get('price');
$food->category_id = $request->get('category');
//---2------$food->update(['name'=>$request->get('name'),.....
$food->save();
return redirect('food')->with(['success'=>'updated successfully']);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$food= Food::find($id);
$food->delete();
return redirect()->back()->with(['success'=>'deleted successfully']);
}
public function listFood(){
$categories= Category::with('food')->get();
return view('food.list',compact('categories'));
}
public function view($id){
$food = Food::find($id);
return view('food.detail', compact('food'));
}
}
|
MKH470/restaurant
|
refs/heads/master
|
/app/Http/Requests/FoodRequest.php
|
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class FoodRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'image'=>'required|mimes:png,jpg,jpeg',
'name' => 'required|max:100',
'description' => 'required',
'price' => 'required|numeric',
'category'=>'required',
];
}
public function messages()
{
return [
'image.required' => 'image required',
'name.required' => ' name required',
'price.numeric' => 'Bid price must be numbers',
'price.required' => 'price field required',
'description.required' => 'description field required ',
'image.mimes' => 'Invalid image',
'category.required'=>'category is required',
];
}
}
|
Akram898/elmawkaa-colne
|
refs/heads/master
|
/js/index.js
|
//*****DataBase ******** */
// Get Value of the objects using DOM
const name = document.getElementById("customerName");
const element = document.getElementById("element");
const mobile = document.getElementById("mobile");
const orderBtn = document.getElementById("order-btn");
const database = firebase.database();
const rootRef = database.ref("orders");
// ADD Order to Databas
orderBtn.addEventListener("click", (e) => {
if (
name.value != "" &&
element.value != "" &&
mobile.value != "" &&
confirm(
"طلبك هو : \n الاسم :" +
name.value +
",\n الصنف: " +
element.value +
",\n الرقم: " +
mobile.value
)
) {
e.preventDefault();
const autoID = rootRef.push().key;
rootRef.child(autoID).set({
customer_name: name.value,
Element_type: element.value,
mobile_number: mobile.value,
});
window.location.reload();
alert("شكرا, تم استلام طلبك سنتواصل معك قريبا");
} else {
alert("من فضلك استكمل البيانات");
}
});
//******************* */
// // Get Data from data base
// const orderId = document.getElementById("order-id");
// const getName = document.getElementById("get-name");
// const getElement = document.getElementById("get-element");
// const getMob = document.getElementById("get-mob");
// const preObj = document.getElementById("object");
// rootRef.on("value", (snap) => {
// // console.log(snap.val());
// object.innerText = JSON.stringify(snap, null, 3);
// });
|
Akram898/elmawkaa-colne
|
refs/heads/master
|
/js/showdata.js
|
// Get Data from data base
// Get Value of the objects using DOM
const name = document.getElementById("customerName");
const element = document.getElementById("element");
const mobile = document.getElementById("mobile");
const orderBtn = document.getElementById("order-btn");
const database = firebase.database();
const rootRef = database.ref("orders");
const orderId = document.getElementById("order-id");
const getName = document.getElementById("get-name");
const getElement = document.getElementById("get-element");
const getMob = document.getElementById("get-mob");
const preObj = document.getElementById("object");
rootRef.on("value", (snap) => {
// console.log(snap.val());
object.innerText = JSON.stringify(snap, null, 3);
});
|
Akram898/elmawkaa-colne
|
refs/heads/master
|
/js/form.js
|
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyD71TirSoLtyo7cDIQ5VfhKx2-4yG8SIlo",
authDomain: "almawkaa-clone.firebaseapp.com",
databaseURL: "https://almawkaa-clone.firebaseio.com",
projectId: "almawkaa-clone",
storageBucket: "almawkaa-clone.appspot.com",
messagingSenderId: "574372635564",
appId: "1:574372635564:web:5956c2260f420854729009",
measurementId: "G-80VYTB63R0",
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
//*****Auth */
//Get elements By DOM
// const btnSignup = document.getElementById("signup-btn");
// const btnSignin = document.getElementById("signin-btn");
// const btnLogout = document.getElementById("logout");
//Validate email
// var mailformat = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/;
// //Validate if numbers
// var passformat = /[0-9]/g;
const auth = firebase.auth();
function signUp() {
const txtEmail = document.getElementById("email");
const txtPassword = document.getElementById("password");
const promise = auth.createUserWithEmailAndPassword(
txtEmail.value,
txtPassword.value
);
promise.catch((e) => alert.log(e.message));
alert("Signed Up Successfully");
}
function signIn() {
const txtEmail = document.getElementById("email");
const txtPassword = document.getElementById("password");
const promise2 = auth.signInWithEmailAndPassword(
txtEmail.value,
txtPassword.value
);
promise.catch((e) => alert.log(e.message));
alert(txtEmail.value + "is Signed In");
}
// const txtEmail = document.getElementById("email");
// const txtPassword = document.getElementById("password");
// const promise2 = auth.signInWithEmailAndPassword(
// txtEmail.value,
// txtPassword.value
// );
// promise.catch((e) => alert.log(e.message));
// alert(txtEmail.value + "is Signed In");
// }
// function signOut() {
// auth.signOut;
// alert("Signed Out");
// }
// Another try still not working
//const validate = document.getElementById("password-validation");
// if (txtEmail.value != "" && txtPassword.value.length >= 5) {
// const promise = auth.createUserWithEmailAndPassword(
// txtEmail.value,
// txtPassword.value
// );
// promise.catch((e) => alert.log(e.message));
// alert("Signed Up Successfully");
// } else {
// alert("Wrong Inputs : Wrong Email or password less than 5 characters");
// //validate.classList.remove("hide");
//}
//Sign Up method
// if (txtEmail.value.match(mailformat) && txtPassword.value.length >= 5) {
// const promise = auth.createUserWithEmailAndPassword(
// txtEmail.value,
// txtPassword.value
// );
// promise.catch((e) => alert.log(e.message));
// alert("Signed Up Successfully");
// } else {
// alert("Wrong Inputs : Wrong Email or password less than 5 characters");
// //validate.classList.remove("hide");
// }
//**********Sign UP**************
// btnSignup.addEventListener("click", (e) => {
// const email = txtEmail.value;
// const pass = txtPassword.value;
// //Sign Up method
// const promise = auth.createUserWithEmailAndPassword(email, pass);
// promise.catch((e) => alert.log(e.message));
// alert("Signed Up Successfully");
// });
// //Sngn In Btn Function
// btnSignin.addEventListener("click", (e) => {
// //get email & password
// const email = txtEmail.value;
// const pass = txtPassword.value;
// //catch from Database
// const promise = auth.signInWithEmailANdPassword(email, pass);
// promise.catch((e) => console.log(e.message));
// });
// //Log Out btn
// btnLogout.addEventListener("click", (e) => {
// firebase.auth().signOut();
// });
// //Add realtime listen
// firebase.auth().onAuthStateChanged((firebaseUser) => {
// if (firebaseUser) {
// console.log(firebaseUser);
// btnLogout.classList.remove("hide");
// } else {
// console.log("not Logged In");
// btnLogout.classList.add("hide");
// }
// });
|
xuan10000/CloudMusic
|
refs/heads/master
|
/README.md
|
#### Vue升级到2.0,使用Vue2.0做了个音乐播放器,
#### 实现了基本功能,有时间会持续更新。
#### dist文件为打包后文件夹,可下载到本地,直接运行index.html。服务运行,sev.js.
>技术使用Vue2.0版本,Vue全家桶 <br />
>Vue-cli搭建 <br />
>Vue-router,vuex <br />
>axios <br />
>muse-ui slider
####后端用的node.js进行api转发,默认端口:8088
###### api: [网易云api](https://api.imjad.cn/cloudmusic/index.html)
### 功能实现
>播放列表 <br />
>播放队列 <br />
>上一首,下一首 <br />
>歌词同步 <br />
>...
### Build Setup
### 安装依赖
npm install
### 运行项目,默认端口:8080
npm run dev
### 启动服务
node sev.js
### 效果





|
xuan10000/CloudMusic
|
refs/heads/master
|
/src/store/store.js
|
import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex);
export const store=new Vuex.Store({
state:{
id:0,
url:'',
title:'',
code:'',
widthline:0,
currentTime:0,
duration:0,
isPlay:false,
picUrl:'',
picName:'',
index:0,
currentIndex:0,
now:-1,
nowId:-1,
playList:[],
lyric:'',
Lrc:[],
Lrcs:'',
paused:"../../static/img/playing.png"
},
getters:{
id:state=>state.id,
title:state=>state.title,
url:state=>state.url,
code:state=>state.code,
widthline:state=>state.widthline,
currentTime:state=>state.currentTime,
duration:state=>state.duration,
isPlay:state=>state.isPlay,
picUrl:state=>state.picUrl,
picName:state=>state.picName,
index:state=>state.index,
now:state=>state.now,
nowId:state=>state.nowId,
playList:state=>state.playList,
currentIndex:state=>state.currentIndex,
lyric:state=>state.lyric,
Lrc:state=>state.Lrc,
Lrcs:state=>state.Lrcs,
paused:state=>state.paused,
},
mutations:{
setid:(state,id)=>{state.id=id},
settitle:(state,name)=>{state.title=name},
seturl:(state,url)=>{state.url=url},
setwidthline:(state,widthline)=>{state.widthline=widthline},
setcurrentTime:(state,currentTime)=>{state.currentTime=currentTime},
setduration:(state,duration)=>{state.duration=duration},
setIsPlay:(state,isPlay)=>{state.isPlay=isPlay},
setPicUrl:(state,picUrl)=>{state.picUrl=picUrl},
setPicName:(state,picName)=>{state.picName=picName},
setNow:(state,now)=>{state.now=now},
setNowId:(state,nowId)=>{state.nowId=nowId},
setlyric:(state,lyric)=>{state.lyric=lyric},
setLrcs:(state,Lrcs)=>{state.Lrcs=Lrcs},
setPaused:(state,paused)=>{state.paused=paused},
setLrc:(state,Lrc)=>{
state.Lrc=Lrc;
var Lrcs='';
for(var i=0;i<Lrc.length;i++){
Lrcs+='<li data-id='+i+' class="LrcList">'+Lrc[i][1]+'</li>';
}
state.Lrcs=Lrcs;
},
setPreCurrentIndex:(state,currentIndex)=>{
state.currentIndex--;
if (state.currentIndex <0) {
state.currentIndex = state.playList.length-1
}
},
setCurrentIndex:(state,currentIndex)=>{
state.currentIndex++;
if (state.currentIndex >= state.playList.length) {
state.currentIndex = 0
}
},
setPlayList:(state,item)=>{
var pushed=false;
state.playList.forEach(function(e,i){
if(item.id==e.id){
pushed=true;
state.currentIndex = i;
}
})
if(!pushed){
state.currentIndex = state.playList.length;
state.playList.push({'id':item.id,'name':state.title,'current':state.currentIndex,'old':item.now});
}
},
removePlayList:(state,index)=>{
state.playList.splice(index,1);
if(state.playList==0){
state.url='';
state.title='';
state.widthline=0;
state.isPlay=false;
state.paused='../../static/img/pasued.png';
state.Lrcs='';
}
}
},
actions:{
pre:({state,commit})=>{
var id,title;
commit('setPreCurrentIndex');
id=state.playList[state.currentIndex].id;
title=state.playList[state.currentIndex].name;
commit('setNowId',id);
axios.get('http://localhost:8088/song',{
params: {
"type":'song',
id:id,
br:128000
}
}).then(function(res){
commit('seturl',res.data.data[0].url);
commit('settitle',title);
});
axios.get('http://localhost:8088/song',{
params: {
"type":'lyric',
id:id,
br:128000
}
}).then(function(res){
commit('setlyric','');
commit('setlyric',res.data.lrc.lyric);
});
},
next:({state,commit})=>{
var id,title;
commit('setCurrentIndex');
id=state.playList[state.currentIndex].id;
title=state.playList[state.currentIndex].name;
commit('setNowId',id);
axios.get('http://localhost:8088/song',{
params: {
"type":'song',
id:id,
br:128000
}
}).then(function(res){
commit('seturl',res.data.data[0].url);
commit('settitle',title);
});
axios.get('http://localhost:8088/song',{
params: {
"type":'lyric',
id:id,
br:128000
}
}).then(function(res){
commit('setlyric','');
commit('setlyric',res.data.lrc.lyric);
});
}
}
})
|
mateusz-git/Zad3-MobilnyKalendarzWEEIA
|
refs/heads/master
|
/README.md
|
# Dokumentacja
## Zadanie 3 - Mobilny Kalendarz WEEIA
### Endpoint
Metoda : GET
Ścieżka : /calendar?year={year}&month={month}
Parametr : year(typ int) - rok dla którego ma być pobrany plik
Parametr : month(typ int) - miesiąc dla którego ma być pobrany plik
Opis : Zwraca plik z rozszerzeniem .ics, który zawiera wydarzenia z danego miesiąca i roku pobranego ze strony ``http://www.weeia.p.lodz.pl/ ``
## Przykłady użycia
``
http://localhost:8080/calendar?year=2020&month=10
``
Odpowiedź : Otrzymujemy plik Calendar_weeia.ics dla października 2020 z wydarzeniami i kod odpowiedzi 200
``
http://localhost:8080/calendar?year=2020&month=14
``
Odpowiedź : Otrzymujemy komunikat ,,Month is incorrect,, i kod odpowiedzi 502
``
http://localhost:8080/calendar?year=2222&month=10
``
Odpowiedź : Otrzymujemy komunikat ,,Year is incorrect,, i kod odpowiedzi 502
|
mateusz-git/Zad3-MobilnyKalendarzWEEIA
|
refs/heads/master
|
/src/main/java/com/example/Mobilny/Kalendarz/WEEIA/Controller.java
|
package com.example.Mobilny.Kalendarz.WEEIA;
import biweekly.Biweekly;
import biweekly.ICalendar;
import biweekly.component.VEvent;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@RestController
public class Controller {
private final static String FILE_NAME = "Calendar_weeia";
@GetMapping("/calendar")
public ResponseEntity getCalendar(@RequestParam int year, @RequestParam int month) throws IOException, ParseException {
if (year <= 1900 || year >= 2100)
return ResponseEntity.status(HttpStatus.BAD_GATEWAY).body("Year is incorrect");
if (month <= 0 || month > 12)
return ResponseEntity.status(HttpStatus.BAD_GATEWAY).body("Month is incorrect");
String monthString = String.valueOf(month);
if (month < 10)
monthString = "0" + monthString;
ICalendar iCalendar = new ICalendar();
iCalendar.setExperimentalProperty("X-WR-CALNAME", "Kalendarz");
String url = "http://www.weeia.p.lodz.pl/pliki_strony_kontroler/kalendarz.php?rok=" + year + "&miesiac=" + monthString;
List<EventDay> eventDays = getCalendarFromWeeia(url);
for (EventDay eventDay : eventDays) {
VEvent vEvent = new VEvent();
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(year + "-" + monthString + "-" + eventDay.day);
vEvent.setDateStart(date);
vEvent.setDateEnd(date);
vEvent.setSummary(eventDay.description);
iCalendar.addEvent(vEvent);
}
File file = new File(FILE_NAME + "_" + year + "_" + monthString + ".ics");
Biweekly.write(iCalendar).go(file);
Path path = Paths.get(FILE_NAME + "_" + year + "_" + monthString + ".ics");
Resource resource = new UrlResource(path.toUri());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename())
.body(resource);
}
private List<EventDay> getCalendarFromWeeia(String urlWeeia) throws IOException {
URL url = new URL(urlWeeia);
URLConnection connection = url.openConnection();
StringBuilder fromWebsite = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
fromWebsite.append(line);
}
String htmlContent = fromWebsite.toString();
Document document = Jsoup.parse(htmlContent);
Elements activeElement = document.select("td.active");
Elements events = activeElement.select("div.InnerBox");
Elements days = activeElement.select("a.active");
List<EventDay> eventDayList = new ArrayList<>();
for (int i = 0; i < events.size(); i++) {
eventDayList.add(new EventDay(Integer.parseInt(days.get(i).text()), events.get(i).text()));
}
return eventDayList;
}
}
|
SnehaDoughnut/sonarqube
|
refs/heads/master
|
/Dockerfile
|
FROM sonarqube:7.1
ENV LDAP_PASSWD=""
ENV PATH $PATH:$SONARQUBE_HOME/bin
ENV LDAP_CONTAINER_NAME=""
#ENV LDAP_PORT=389
RUN apt-get update && apt-get install -y curl
RUN curl -L -O https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-6.2.4-amd64.deb
RUN dpkg -i filebeat-6.2.4-amd64.deb
RUN apt-get remove curl -y
WORKDIR /opt/sonarqube/extensions/plugins
RUN wget http://sonarsource.bintray.com/Distribution/sonar-ldap-plugin/sonar-ldap-plugin-2.2.0.608.jar
#RUN cp /opt/sonarqube/conf/sonar.properties /opt/sonarqube/conf/sonar.properties.orig
COPY ./sonar.properties /opt/sonarqube/conf/
COPY filebeat.yml /etc/filebeat/
RUN chmod go-w /etc/filebeat/filebeat.yml
WORKDIR $SONARQUBE_HOME
COPY entrpoint.sh ./bin/
COPY run.sh ./bin/
RUN chmod +x ./bin/*
ENTRYPOINT ["entrpoint.sh"]
|
SnehaDoughnut/sonarqube
|
refs/heads/master
|
/entrpoint.sh
|
#!/bin/bash
sed -i 's/ldap.bindPassword=/ldap.bindPassword='"$LDAP_PASSWD"'/' /opt/sonarqube/conf/sonar.properties
sed -i 's#ldap.url=ldap://#ldap.url=ldap://'"$LDAP_CONTAINER_NAME"':'"$LDAP_SERVICE_PORT"'#' /opt/sonarqube/conf/sonar.properties
#sed -i '/ldap.url=ldap:\/\//a '"$LDAP_CONTAINER_NAME"':'"$LDAP_PORT"'/' /opt/sonarqube/conf/sonar.properties
$SONARQUBE_HOME/bin/run.sh
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.