language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
C | UTF-8 | 614 | 2.734375 | 3 | [] | no_license | #include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
using ll=long long;
using ld=long double;
using P=pair<ll,ll>;
#define FOR(i,n,m) for(ll i=n; i<(ll)m;i++)
#define cinv(v,n,m) FOR(i,n,m) cin>>v.at(i)
#define coutv(v,n,m) FOR(i,n,m) cout<<v.at(i) <<" "
#define cout(n) cout<<fixed<<setprecision(n)
int main(){
string s;
cin>>s;
int flag=0;
if(s[0]=='A'){
FOR(i,2,(int)s.size()-1){
if(s[i]=='C') flag++;
}
}
FOR(i,0,(int)s.size()){
if(s[i]=='A'||s[i]=='C'||('a'<=s[i]&&s[i]<='z')){
}
else flag=2;
}
if(flag==1) cout<<"AC"<<endl;
else cout<<"WA"<<endl;
}
|
Java | UTF-8 | 1,181 | 2.421875 | 2 | [
"Apache-2.0"
] | permissive | package com.norwand.game.management.gamedata.environement.entities.monsters;
import com.badlogic.gdx.graphics.Pixmap;
import com.norwand.game.management.gamedata.GameData;
import com.norwand.game.management.gamedata.environement.Floor;
import com.norwand.game.management.gamedata.environement.entities.Monster;
import com.norwand.game.resources.ImagesHolder;
import com.norwand.game.utility.objects.DoubleRectangle;
public class Mimic extends Monster {
public Mimic(Floor roompointer, double x, double y) {
super(roompointer, x, y);
}
private int spritecounter = 25;
@Override
public void update() {
--spritecounter;
if (spritecounter < 0)
spritecounter = 50;
if(knockback())
GameData.get().player.info.health -= 0.25;
}
@Override
public Pixmap getCurrentSprite() {
return ImagesHolder.entityset.getTile((spritecounter < 25) ? 832 : 840);
}
@Override
public DoubleRectangle getHitbox(double posX, double posY) {
return new DoubleRectangle(posX - 0.3, posY - 0.3, 0.6, 0.6);
}
@Override
public void onhit(double damage) {
kill();
}
@Override
public void onAct() {
}// Does nothing
}
|
Python | UTF-8 | 5,466 | 3.0625 | 3 | [
"MIT"
] | permissive | #
# File: project1.py
#
## top-level submission file
'''
Note: Do not import any other modules here.
To import from another file xyz.py here, type
import project1_py.xyz
However, do not import any modules except numpy in those files.
It's ok to import modules only in files that are
not imported here (e.g. for your plotting code).
'''
import numpy as np
def optimize(f, g, x0, n, count, prob):
"""
Args:
f (function): Function to be optimized
g (function): Gradient function for `f`
x0 (np.array): Initial position to start from
n (int): Number of evaluations allowed. Remember `g` costs twice of `f`
count (function): takes no arguments are returns current count
prob (str): Name of the problem. So you can use a different strategy
for each problem. `prob` can be `simple1`,`simple2`,`simple3`,
`secret1` or `secret2`
Returns:
x_best (np.array): best selection of variables found
"""
_, x_best = optimize_history(f, g, x0, n, count, prob)
return x_best
class GradientDescent:
def __init__(self, problem, alpha=0.001):
self.alpha = alpha
def step(self, x, f_val = None, g_val = None):
return x - self.alpha*g_val/np.linalg.norm(g_val)
class Momentum():
def __init__(self, problem, beta = 0.9, alpha=0.001, threshold=1):
self.beta = beta
self.alpha = alpha
self.prev_v = 0
self.tau = threshold
def step(self, x, f_val=None, g_val=None):
g_val = clip_grad(g_val, self.tau)
self.prev_v = self.beta*self.prev_v - self.alpha*g_val
return x + self.prev_v
class Adagrad():
def __init__(self, problem, alpha=0.001, epsilon=1e-8, threshold=1):
self.alpha = alpha
self.epsilon = epsilon
self.tau = threshold
self.xdim = find_xdim(problem)
self.s = np.zeros(self.xdim)
def step(self, x, f_val=None, g_val=None):
g_val = clip_grad(g_val, self.tau)
new_x = np.copy(x)
self.s += g_val**2
new_x -= self.alpha/(self.epsilon + np.sqrt(self.s))*g_val
#for idx in range(np.size(x)):
# new_x[idx] -= self.alpha/(self.epsilon + np.sqrt(self.s[idx]))*g_val[idx]
return new_x
class Adam():
def __init__(self, problem, alpha=0.001, epsilon = 1e-8, gamma_v = 0.9, gamma_s = 0.999, threshold = 1):
self.alpha = alpha
self.epsilon = epsilon
self.gamma_v = gamma_v
self.gamma_s = gamma_s
self.tau = threshold
self.t = 0
self.xdim = find_xdim(problem)
self.v = np.zeros(self.xdim)
self.s = np.zeros(self.xdim)
def step(self, x, f_val=None, g_val=None):
self.t += 1
g_val = clip_grad(g_val, self.tau)
self.v = self.gamma_v*self.v + (1 - self.gamma_v)*g_val
self.s = self.gamma_s*self.s + (1 - self.gamma_s)*g_val**2
v_hat = self.v/(1 - self.gamma_v**self.t)
s_hat = self.s/(1 - self.gamma_s**self.t)
return x - self.alpha*v_hat / (self.epsilon + np.sqrt(s_hat))
def find_xdim(problem):
if problem == 'simple1':
xdim = 2
elif problem == 'simple2':
xdim = 2
elif problem == 'simple3':
xdim = 4
elif problem == 'secret1':
xdim = 50
elif problem == 'secret2':
xdim = 1
elif problem == 'test':
xdim = 2
else:
ValueError('Incorrect problem specified')
return xdim
def clip_grad(g_val, tau):
if np.linalg.norm(g_val) > tau:
g_val = tau * g_val/np.linalg.norm(g_val)
return g_val
def optimize_history(f, g, old_x, n, count, prob, debug=False):
x_hist = []
#optim = Momentum(prob, alpha = 0.001, beta=0.9 )
#optim = Adam(prob, alpha=0.2, gamma_v=0.9, gamma_s=0.99, threshold=1)
optim = Adam(prob, alpha=0.2, gamma_v=0.85, gamma_s=0.99, threshold=1)
if debug:
print('Solving problem ', prob)
print('Initial condition is', old_x)
print('Initial function evaluation', f(old_x))
print('Initial count ', count())
print('Number of counts allowed', n)
x_hist.append(old_x)
while count() < n:
g_eval = g(old_x)
new_x = optim.step(old_x, g_val = g_eval)
x_hist.append(new_x)
old_x = np.copy(new_x)
if debug:
if count() > 200:
break
if debug:
print('Final count number ', count())
print('Final function evaluation ', f(x_hist[-1]))
print('Final x is ', x_hist[-1])
if prob == 'simple1':
x_star = np.array([1, 1])
print('Optimal x is ', x_star)
print('Distance from optimal point is ', np.linalg.norm(x_star - new_x))
elif prob == 'simple2':
print('First optimal point is (3, 2)')
print('Second optimal point is (-2.8, 3.13)')
print('Third optimal point is (-3.77, -3.28)')
print('Fourth optimal point is (3.58, -1.84)')
elif prob == 'simple3':
print('The optimal point is (0, 0, 0, 0)')
elif prob == 'test':
x_star = np.array([0, 0])
print('Optimal x is ', x_star)
print('Distance from optimal point is ', np.linalg.norm(x_star - new_x))
else:
print('Optimal point not entered yet')
return x_hist, new_x
|
Markdown | UTF-8 | 2,437 | 2.96875 | 3 | [] | no_license | # Tugas-SI-Web-Sederhana
E41181245 Nurlaita Afia Tri Wahyuni
# CRUD
CRUD adalah singkatan dari Create, Read, Update dan Delete. CRUD maksudnya membuat input data ke database, menampilkan data dari database, mengedit mengupdate data serta menghapus data.
CRUD sangat penting untuk pengelolaan data pada database. Hal ini juga sangat diperlukan dalam pengolahan website yang melibatkan database.
# Cara Menampilkan Data Dari Database Dengan CodeIgniter
1. Konfigurasi database terlebih dahulu
2. Sesuaikan pengaturan database pada file config database.php di application/config/database.php dengan mengisi username(root) dan nama database
3. Buatlah sebuah controller baru dengan nama mesin.php(panggil atau buka model m_mesin, karena untuk operasi databasenya akan kita buat pada model m_mesin. kemudian function index menampilkan data dengan function tampil_data yg dibuat dalam m_mesin untuk mengambil data dari database kemudian mempersingnya ke data_mesin) dapat kalian lihat pada codenya
4. buatlah sebuah model dengan nama m_mesin
5. kemudian buat sebuah view dengan nama data_mesin
# Input Data ke Database
1. Setting base_url codeigniter dengan nama project pada application/config/config.php ($config['base_url'] = ....)
2. Tambahkan method function tambah() yang berisi perintah untuk menampilkan v_input. v_input sebagai form inputan, dimana data yang di input di sini akan masuk ke database (pada controller mesin.php)
3. Buatlah sebuah view dengan nama v_input.php
4. Buatlah sebuah function iput_data pada m_mesin.php
# Hapus Data
1. Pada view data_mesin telah berisi link edit dan hapus dan terdapat function hyperlink yang menuju pada method/function hapus di controller mesin.php
2. Pada controller tambahkan sebuah method hapus. pada parameter function hapus() saya memberikan variabel $id_mesin yg berguna untuk menangkap data id yang di kirim melalu url link hapus tadi
3. Buatlah function hapus pada model m_mesin.php
# Update Data
1. Buatlah sebuah method edit pada controller mesin
2. Kemudian buat juga method/function edit_data pada model m_mesin
3. Buatlah sebuah view dengan nama v_edit dimana view ini kita jadikan sebagai form yang menampilkan data yang akan di edit
4. Buatlah aksi untuk update pada controller mesin yaitu method update
5. Tangkap data dari form edit
6. Kemudian masukkan data yang akan di update ke dalam variabel data
7. Yang terakhir buatlah sebuah function lagi pada model denan nama update_data
|
Shell | UTF-8 | 6,504 | 3.875 | 4 | [] | no_license | #!/bin/bash
###############################################################################
# #
# #
###############################################################################
PH_MARIADB_INSTALL_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
PH_INSTALL_DIR="$( cd "${PH_MARIADB_INSTALL_DIR}" && cd ../../ && pwd )"
. ${PH_INSTALL_DIR}/bootstrap.sh
if ph_is_installed mysql ; then
echo "MySQL is already installed!"
ls -l `which mysql` | awk '{print $9 $10 $11}'
mysql --version
read -p "Do you wish to continue with the MariaDB installation? [y/n] " REPLY
[ $REPLY == "n" ] && { return 1 || exit 1; }
fi
read -p "Specify MariaDB version (e.g. 5.5.29): " MARIADB_VERSION_STRING
if [ "${PH_OS}" == "windows" ]; then
ph_mkdirs /usr/local/src
cd /usr/local/src
if [ "${PH_OS_FLAVOUR}" == "7 64bit" ]; then
MARIADB_INSTALLER_URI="http://ftp.osuosl.org/pub/mariadb/mariadb-${MARIADB_VERSION_STRING}/winx64-packages/mariadb-${MARIADB_VERSION_STRING}-winx64.msi"
MARIADB_INSTALLER_FILENAME="mariadb-${MARIADB_VERSION_STRING}-winx64.msi"
else
MARIADB_INSTALLER_URI="http://ftp.osuosl.org/pub/mariadb/mariadb-${MARIADB_VERSION_STRING}/win32-packages/mariadb-${MARIADB_VERSION_STRING}-win32.msi"
MARIADB_INSTALLER_FILENAME="mariadb-${MARIADB_VERSION_STRING}-win32.msi"
fi
if [ ! -f ${MARIADB_INSTALLER_FILENAME} ]; then
wget ${MARIADB_INSTALLER_URI}
if [ ! -f ${MARIADB_INSTALLER_FILENAME} ]; then
echo "MariaDB MSI installer download failed!"
return 1 || exit 1
fi
fi
echo "Running MSI installer..."
msiexec /i ${MARIADB_INSTALLER_FILENAME} SERVICENAME=MySQL /qn
else
ph_install_packages\
bison\
cmake\
gcc\
m4\
make\
ncurses\
openssl\
wget
read -p "Overwrite existing symlinks in /usr/local? (recommended) [y/n]: " REPLY
[ "$REPLY" == "y" ] && MARIADB_OVERWRITE_SYMLINKS=true || MARIADB_OVERWRITE_SYMLINKS=false
ph_mkdirs /usr/local/src
ph_creategroup mysql
ph_createuser mysql
ph_assigngroup mysql mysql
cd /usr/local/src
if [ ! -f mariadb-${MARIADB_VERSION_STRING}.tar.gz ]; then
wget http://ftp.osuosl.org/pub/mariadb/mariadb-${MARIADB_VERSION_STRING}/kvm-tarbake-jaunty-x86/mariadb-${MARIADB_VERSION_STRING}.tar.gz
if [ ! -f mariadb-${MARIADB_VERSION_STRING}.tar.gz ]; then
echo "mariadb source download failed!"
return 1 || exit 1
fi
fi
tar xzf mariadb-${MARIADB_VERSION_STRING}.tar.gz
cd mariadb-${MARIADB_VERSION_STRING}
[ -f CMakeCache.txt ] && rm CMakeCache.txt
make clean
cmake . \
-DCMAKE_INSTALL_PREFIX=/usr/local/mariadb-${MARIADB_VERSION_STRING} \
-DMYSQL_DATADIR=/usr/local/mariadb-${MARIADB_VERSION_STRING}/data \
&& { make -j ${PH_NUM_THREADS} && make install; } || \
{ echo "./configure failed! Check dependencies and re-run the installer."; exit 1; }
chown -R mysql:mysql /usr/local/mariadb-${MARIADB_VERSION_STRING}
chmod -R 0755 /usr/local/mariadb-${MARIADB_VERSION_STRING}/data
cd /usr/local/mariadb-${MARIADB_VERSION_STRING}
cp support-files/my-medium.cnf /etc/my.cnf
ph_search_and_replace "^skip-networking" "#skip-networking" /etc/my.cnf
ph_search_and_replace "^socket" "#socket" /etc/my.cnf
ph_search_and_replace "^#innodb" "innodb" /etc/my.cnf
scripts/mysql_install_db --user=mysql
ph_symlink /usr/local/mariadb-${MARIADB_VERSION_STRING} /usr/local/mysql ${MARIADB_OVERWRITE_SYMLINKS}
for i in `ls -1 /usr/local/mariadb-${MARIADB_VERSION_STRING}/bin`; do
ph_symlink /usr/local/mariadb-${MARIADB_VERSION_STRING}/bin/$i /usr/local/bin/$i ${MARIADB_OVERWRITE_SYMLINKS}
done
case "${PH_OS}" in \
"linux")
case "${PH_OS_FLAVOUR}" in \
"arch")
ph_symlink
/usr/local/mariadb-${MARIADB_VERSION_STRING}/support-files/mysql.server\
/etc/rc.d/mariadb-${MARIADB_VERSION_STRING}\
${MARIADB_OVERWRITE_SYMLINKS}
/etc/rc.d/mariadb-${MARIADB_VERSION_STRING} start
;;
"suse")
ph_symlink\
/usr/local/mariadb-${MARIADB_VERSION_STRING}/support-files/mysql.server\
/etc/init.d/mariadb-${MARIADB_VERSION_STRING}\
${MARIADB_OVERWRITE_SYMLINKS}
/etc/init.d/mariadb-${MARIADB_VERSION_STRING} start
chkconfig --level 3 mysql on
;;
"debian")
ph_symlink\
/usr/local/mariadb-${MARIADB_VERSION_STRING}/support-files/mysql.server\
/etc/init.d/mariadb-${MARIADB_VERSION_STRING}\
${MARIADB_OVERWRITE_SYMLINKS}
/etc/init.d/mariadb-${MARIADB_VERSION_STRING} start
update-rc.d mariadb-${MARIADB_VERSION_STRING} defaults
;;
*)
ph_symlink\
/usr/local/mariadb-${MARIADB_VERSION_STRING}/support-files/mysql.server\
/etc/init.d/mariadb-${MARIADB_VERSION_STRING}\
${MARIADB_OVERWRITE_SYMLINKS}
/etc/init.d/mariadb-${MARIADB_VERSION_STRING} start
esac
;;
"mac")
ph_mkdirs /Library/LaunchAgents
ph_cp_inject ${PH_INSTALL_DIR}/modules/mariadb/org.mysql.mysqld.plist /Library/LaunchAgents/org.mysql.mysqld.plist \
"##MARIADB_VERSION_STRING##" "${MARIADB_VERSION_STRING}"
chown root:wheel /Library/LaunchAgents/org.mysql.mysqld.plist
launchctl load -w /Library/LaunchAgents/org.mysql.mysqld.plist
;;
*)
echo "mariadb startup script not implemented for this OS... starting manually"
/usr/local/mariadb-${MARIADB_VERSION_STRING}/bin/mysqld_safe --user=mysql >/dev/null &
esac
/usr/local/mariadb-${MARIADB_VERSION_STRING}/bin/mysql_secure_installation
fi
# Cleanup
echo -n "Deleting source files... "
rm -rf /usr/local/src/mariadb-${MARIADB_VERSION_STRING} \
/usr/local/src/mariadb-${MARIADB_VERSION_STRING}.tar.gz
echo "Complete."
return 0 || exit 0
|
Markdown | UTF-8 | 6,634 | 3.03125 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: 跟我一起学Makefile 学习记录2
categories: Makefile
description: 工作中用到Makefile学习
keywords: Linux, Makefile
---
### 命令执行
```
#上一条命令的结果应用在下一条命令时,你应该使用分 号分隔这两条命令
exec:
cd /home/hchen
pwd
#cd没有作用,pwd会打印出当前的Makefile
exec:
cd /home/hchen; pwd
#忽略命令的出错,我们可以在Makefile的命令行前加一个减号“-”
clean:
-rm -f *.o
#还有一个全局的办法是,给make加上“-i”或是“--ignore-errors”参数,Makefile中所有命令都会忽略错误。
#make的参数的是“-k”或是“--keep-going”,这个参数的意思是,如果某规则中的命令出错了,那么就终目该规则的执行,但继续执行其它规则
--------------------------------------------------------------
```
### 嵌套执行make
```
#子目录叫subdir,这个目录下有个Makefile 文件,来指明了这个目录下文件的编译规则。
#这两个例子的意思都是先进入“subdir”目录,然后执行 make 命令。
#定义$(MAKE)宏变量的意思是,也许我们的 make 需要一些参数,所以定义成一个变量比较 利于维护。
subsystem:
cd subdir && $(MAKE)
#等价于:
subsystem:
$(MAKE) -C subdir
#这个Makefile叫做“总控 Makefile”,总控 Makefile的变量可以传递到下级的 Makefile 中(如果你显示的声明),但是不会覆盖下层的 Makefile中所定义的变量,除非指定了“-e”参数。
#如果你要传递变量到下级 Makefile中,那么你可以使用这样的声明:
export <variable ...>
#如果你不想让某些变量传递到下级 Makefile 中,那么你可以这样声明:
unexport <variable ...>
export variable = value
等价于:
variable = value
export variable
export variable += value
其等价于:
variable += value
export variable
如果你要传递所有的变量,那么,只要一个export就行了。后面什么也不用跟,表示传递 所有的变量。
需要注意的是,有两个变量,一个是 SHELL,一个是MAKEFLAGS这两个变量不管你是否 export,其总是要传递到下层 Makefile 中,特别是MAKEFILES变量,其中包含了 make 的参数信息,如果我们执行“总控 Makefile”时有 make参数或是在上层 Makefile 中定义了这个变量,那么MAKEFILES变量将会是这些参数,并会传递到下层Makefile中,这是一个系统级的环境变量。
#如果你不想往下层传递参数,可以这样来:
subsystem:
cd subdir && $(MAKE) MAKEFLAGS=
--------------------------------------------------------------
```
### 定义命令包
```
#如果 Makefile 中出现一些相同命令序列,那么我们可以为这些相同的命令序列定义一个变 量。以“define”开始,以“endef”结束
define run-yacc
yacc $(firstword $^)
mv y.tab.c $@
endef
这里,“run-yacc”是这个命令包的名字,其不要和 Makefile 中的变量重名。在“define” 和“endef”中的两行就是命令序列。
#这个命令包中的第一个命令是运行 Yacc 程序,因为 Yacc 程序总是生成“y.tab.c”的文件,所以第二行的命令就是把这个文件改改名字。
foo.c : foo.y
$(run-yacc)
--------------------------------------------------------------
```
### Makefile 使用变量
```
在 Makefile 中的定义的变量,就像是 C/C++语言中的宏一样,他代表了一个文本字串。其与 C/C++所不同的是,你可以在 Makefile 中改变其值。
变量可以使用在“目标”,“依赖目标”,“命令”或是 Makefile 的其它部分中。
变量的命名字可以包含字符、数字,下划线(可以是数字开头),但不应该含有“:”、“#”、 “=”或是空字符(空格、回车等)。变量是大小写敏感的,推荐使用大小写搭配的变量名,如:MakeFlags。这样可以避免和系统的变量冲突,而发生意外的事情。
变量在声明时需要给予初值,而在使用时,需要给在变量名前加上“$”符号,但最好用小括号“()”或是大括号“{}”把变量给包括起来。如果你要使用真实的“$”字符,那么你需要用“$$”来表示。
objects = program.o foo.o utils.o program : $(objects)
cc -o program $(objects)
$(objects) : defs.h
--------------------------------------------------------------
```
### 变量中的变量
```
在“=”左侧是变量,右侧是变量的值,右侧变量的值可以定义在文件的任何一处,也就是说,右侧中的变量不一定非要是已定义好的值, 其也可以使用后面定义的值。如:
foo = $(bar)
bar = $(ugh)
ugh = Huh?
all:
echo $(foo)
我们可以使用 make 中的另一种用变量来定义变量的方法。这种方法使用的是“:=”操作符.第一个例子中y的值是“bar”,而不是“foo bar”。
x := foo
y := $(x) bar
x := later
其等价于:
y := foo bar
x := later
ifeq (0,${MAKELEVEL})
cur-dir := $(shell pwd)
whoami := $(shell whoami)
host-type := $(shell arch)
MAKE := ${MAKE} host-type=${host-type} whoami=${whoami}
endif
#后面采用“#”注释符来表示变量定义的终止
nullstring :=
space := $(nullstring) # end of the line
dir := /foo/bar # directory to put the frobs in
FOO没有被定义过,那么变量 FOO 的值就是“bar”,如果 FOO 先前被定义过,那么这条语将什么也不做
FOO ?= bar
等价于:
ifeq ($(origin FOO), undefined)
FOO = bar
endif
--------------------------------------------------------------
```
### 变量高级用法
```
#变量值的替换
先定义了一个“$(foo)”变量,而第二行的意思是把“$(foo)”中所有 以“.o”字串“结尾”全部替换成“.c”,所以我们的“$(bar)”的值就是“a.c b.c c.c”。
foo := a.o b.o c.o
bar := $(foo:.o=.c)
#把变量的值再当成变量
$(x)的值是“y”,所以$($(x))就是$(y),于是$(a)的值就是“z”。(注 意,是“x=y”,而不是“x=$(y)”)
x = y
y = z
a := $($(x))
x = $(y)
y = z
z = Hello
a := $($(x))
这里的$($(x))被替换成了$($(y)),因为$(y)值是“z”,所以,最终结果是:a:=$(z), 也就是“Hello”。
--------------------------------------------------------------
```
### 追加变量值
```
#$(objects)值变成:“main.o foo.o bar.o utils.o another.o” (another.o 被追加进去了)
objects = main.o foo.o bar.o utils.o objects += another.o
#override 指示符
``` |
Python | UTF-8 | 9,917 | 2.625 | 3 | [] | no_license | import json
import os
import sys # sys нужен для передачи argv в QApplication
from PyQt5 import QtWidgets
from PyQt5.QtCore import QStringListModel
import saver
from messages.errors import ERRORS
from messages.status import STATUS
from py_windows.design import Ui_MainWindow
DATA = {} # Загружается из json-файла при инициализации класса ExampleApp
JSON_FILE = 'name_list.json'
INPUT_FIELD_TYPE = QtWidgets.QLineEdit
class ExampleApp(QtWidgets.QMainWindow):
def __init__(self):
# Это здесь нужно для доступа к переменным, методам
# и т.д. в файле design.py
super().__init__()
self.ui = Ui_MainWindow()
self.file = saver.DocFile()
# Это нужно для инициализации нашего дизайна
self.ui.setupUi(self)
# Кнопка вывода в консоль имен полей
self.ui.pushButton.clicked.connect(self.print_fields)
# Кнопка проверки введенных данных(+save +clear)
self.ui.pushButton_2.clicked.connect(self.get_data_from_fields)
# Кнопка очистки формы
self.ui.pushButton_3.clicked.connect(self.clear_fields)
# Инициализация выпадающего списка районов
self.load_name_list(JSON_FILE)
# Инициализация выпадающего списка файлов
self.load_files_list()
self.clear_fields()
# Загрузка данных о Пожарных частях в районах
def load_name_list(self, file_name):
global DATA
self.ui.box_area_1.addItem("-") # Добавление первого (пустого) значения в выпадающий список
if os.path.isfile(file_name):
with open(file_name, 'r', encoding='utf-8') as f:
DATA = json.loads(f.read())
self.ui.box_area_1.addItems(DATA.keys())
# Уставнока сигнала для поля выбора района
self.ui.box_area_1.currentIndexChanged.connect(self.get_point_list)
# Сохранение списка всех имеющихся Пожарных частей (points) в атрибуте
if not self.file.points_list:
for values in DATA.values():
self.file.points_list.extend(values)
# Заполенение текстового поля всеми имеющимися названиями Пожарных частей
# TODO: сделать проверку и выборку и вывод в текстовое поле только тех пожарных частей,
# даннные по которым "незаполнены".
# TODO: реализовать чтение заданной области из Excel-файла названий частей, которые "незаполнены".
# TODO*: добавить изменение цвета в текстовом поле вывода "незаполенных" частей (рекомендуется)
model = QStringListModel(self.file.points_list)
self.ui.listView.setModel(model)
else:
self.show_error_text(ERRORS["no_name_list"])
# Сборка выпадающего списка исходя из того, какой выбран район.
def get_point_list(self):
self.ui.box_point_1.clear()
self.ui.box_point_1.addItem("-")
selected_area = self.ui.box_area_1.currentText()
for area, point_list in DATA.items():
if selected_area == area:
self.ui.box_point_1.addItems(point_list)
# служебная функция для просмотра подключенных виджетов TODO: удалить после завершения
def print_fields(self):
for elem in self.ui.__dict__.items():
print(elem)
# Очистка всех полей формы и заполенение их нулями.
def clear_fields(self):
self.clear_message()
for field_name, field_type in self.ui.__dict__.items():
if isinstance(field_type, INPUT_FIELD_TYPE):
self.ui.__dict__[field_name].setText('0')
# Возвращает value преобразованное в число, либо "error" и выводит ошибку
def give_me_int(self, value: str) -> int or str:
try:
return int(value)
except ValueError:
self.show_error_text(ERRORS["not_number"])
return "error"
# Получение данных со всех полей ввода и приведение их к числам.
# В случае корректности, поля очищаются.
def get_data_from_fields(self) -> list or None:
self.ui.label_error.setText("")
data = []
for field_name, field_type in self.ui.__dict__.items():
if isinstance(field_type, INPUT_FIELD_TYPE):
field_text = self.ui.__dict__[field_name].text()
data.append(self.give_me_int(field_text))
if "error" in data:
return None
# Проверка, на то, что пользватель ввел только нули (пустая форма)
elif not any(data):
self.show_status_text(STATUS['is_empty'])
else:
err = self.save_input_data(data)
if err is None:
self.clear_fields()
self.show_status_text(STATUS['is_valid'])
else:
self.show_error_text(error=err)
# print(data)
# Функция нициализации выпадающего списка файлов и связывание с выпадающим списком листов в документе
def load_files_list(self):
files_list = self.file.get_files_list()
files_list.insert(0, "-")
# Составление выпадающего списка файлов
self.ui.box_file_1.addItems(files_list)
# Добавление сигнала в поле списка файлов. Через lambda реализована передача параметра с именем,
# которое выбирает пользователь с списке файлов в текущей директории
self.ui.box_file_1.currentTextChanged.connect(
lambda val=self.get_select_element("box_file_1"): self.load_sheets_list(val)
)
def load_sheets_list(self, file_name: str):
self.ui.box_sheet_1.clear()
sheets_list, error = self.file.get_sheets_list(file_name)
self.ui.box_sheet_1.addItem("-") # Закоммитить эту строчку. чтобы последняя вкладка выбиралась автоматически.
if error:
self.show_error_text(error)
elif len(sheets_list) == 0:
self.show_error_text(ERRORS['no_sheets'])
else:
sheets_list.sort(reverse=True) # Сортировка листов документа в обратном порядке.
self.ui.box_sheet_1.addItems(sheets_list)
# Добавление сигнала в поле списка файлов. Через lambda реализована передача параметра с именем,
# которое выбирает пользователь с списке листов в текущем файле.
self.ui.box_sheet_1.currentTextChanged.connect(
lambda val=self.get_select_element("box_sheet_1"): self.file.get_active_sheet(val)
)
print(f'{self.file.active_sheet=}\n'
f'{self.file.sheets_list=}\n')
def save_input_data(self, input_list: list):
data_key: str = self.ui.box_point_1.currentText()
ok, err = self.file.save_in_file(key=data_key, data=input_list)
if not ok:
return err
def get_select_element(self, tag_name):
return self.ui.__dict__[tag_name].currentText()
# Демонстрация текста ошибки в окне
def show_error_text(self, error):
self.clear_message()
# Выводим текст об ошибке и меняем его цвет
self.ui.label_error.setText(error["text"])
self.ui.label_error.adjustSize()
self.ui.label_error.setStyleSheet(f'color: {error["color"]};')
# TODO: так, в дальнейшем можно объеденить в одну функцию
# через передачу доп.параметра в self.ui.__dict__["param"] ...
def show_status_text(self, status):
self.clear_message()
self.ui.label_status.setText(status["text"])
self.ui.label_status.adjustSize()
self.ui.label_status.setStyleSheet(f'color: {status["color"]};')
def clear_message(self):
self.ui.label_status.setText("")
self.ui.label_error.setText("")
def main():
app = QtWidgets.QApplication(sys.argv) # Новый экземпляр QApplication
window = ExampleApp() # Создаём объект класса ExampleApp
window.show() # Показываем окно
app.exec_() # и запускаем приложение
if __name__ == '__main__': # Если мы запускаем файл напрямую, а не импортируем
try:
main() # то запускаем функцию main()
except KeyboardInterrupt:
print("Окно закрыто")
|
Python | ISO-8859-1 | 235 | 4.15625 | 4 | [] | no_license | ## 27
print("Este programa le ayudar a calcular si el nmero ingresado es par o impar")
num=int(input("Por favor ingrese un nmero "))
if num % 2 == 0:
print("El nmero", num, "es par")
else:
print("El nmero", num, "es impar") |
Java | UTF-8 | 4,493 | 2.015625 | 2 | [
"Apache-2.0",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-protobuf",
"CC-BY-3.0"
] | permissive | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hbase
operator|.
name|metrics
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|yetus
operator|.
name|audience
operator|.
name|InterfaceAudience
import|;
end_import
begin_comment
comment|/** * A statictical sample of histogram values. */
end_comment
begin_interface
annotation|@
name|InterfaceAudience
operator|.
name|Private
specifier|public
interface|interface
name|Snapshot
block|{
comment|/** * Return the values with the given quantiles. * @param quantiles the requested quantiles. * @return the value for the quantiles. */
name|long
index|[]
name|getQuantiles
parameter_list|(
name|double
index|[]
name|quantiles
parameter_list|)
function_decl|;
comment|/** * Return the values with the default quantiles. * @return the value for default the quantiles. */
name|long
index|[]
name|getQuantiles
parameter_list|()
function_decl|;
comment|/** * Returns the number of values in the snapshot. * * @return the number of values */
name|long
name|getCount
parameter_list|()
function_decl|;
comment|/** * Returns the total count below the given value * @param val the value * @return the total count below the given value */
name|long
name|getCountAtOrBelow
parameter_list|(
name|long
name|val
parameter_list|)
function_decl|;
comment|/** * Returns the value at the 25th percentile in the distribution. * * @return the value at the 25th percentile */
name|long
name|get25thPercentile
parameter_list|()
function_decl|;
comment|/** * Returns the value at the 75th percentile in the distribution. * * @return the value at the 75th percentile */
name|long
name|get75thPercentile
parameter_list|()
function_decl|;
comment|/** * Returns the value at the 90th percentile in the distribution. * * @return the value at the 90th percentile */
name|long
name|get90thPercentile
parameter_list|()
function_decl|;
comment|/** * Returns the value at the 95th percentile in the distribution. * * @return the value at the 95th percentile */
name|long
name|get95thPercentile
parameter_list|()
function_decl|;
comment|/** * Returns the value at the 98th percentile in the distribution. * * @return the value at the 98th percentile */
name|long
name|get98thPercentile
parameter_list|()
function_decl|;
comment|/** * Returns the value at the 99th percentile in the distribution. * * @return the value at the 99th percentile */
name|long
name|get99thPercentile
parameter_list|()
function_decl|;
comment|/** * Returns the value at the 99.9th percentile in the distribution. * * @return the value at the 99.9th percentile */
name|long
name|get999thPercentile
parameter_list|()
function_decl|;
comment|/** * Returns the median value in the distribution. * * @return the median value */
name|long
name|getMedian
parameter_list|()
function_decl|;
comment|/** * Returns the highest value in the snapshot. * * @return the highest value */
name|long
name|getMax
parameter_list|()
function_decl|;
comment|/** * Returns the arithmetic mean of the values in the snapshot. * * @return the arithmetic mean */
name|long
name|getMean
parameter_list|()
function_decl|;
comment|/** * Returns the lowest value in the snapshot. * * @return the lowest value */
name|long
name|getMin
parameter_list|()
function_decl|;
comment|// TODO: Dropwizard histograms also track stddev
block|}
end_interface
end_unit
|
PHP | UTF-8 | 790 | 2.796875 | 3 | [] | no_license | <?php
//var_dump(get_magic_quotes_gpc());
//http://www.satya-weblog.com/2010/11/php-and-mysql-sql-injection-example.html
mysql_connect('localhost', 'L1ttleJ0hnny', '') or die('DB Conn error');
mysql_select_db('J0hnnyDr0pTables');
echo $query = "select * from user where user = '$_POST[user]' AND password = '$_POST[pass]'";
echo '<br>';
$res = mysql_query($query) ;
if ($res AND mysql_num_rows($res) != 0) {
while($row = mysql_fetch_assoc($res)) {
print_r($row);
echo $row['Ename'] . '<br>' ;
}
}
else if (!$res) {
echo 'Error in query' . mysql_error();
}
else if (mysql_num_rows($res) == 0) {
echo 'No match.';
}
?>
<form method=post action="">
User: <input type=text name="user">
<br />
Password: <input type=text name="pass">
<input type="submit" name="sbumit1">
</form>
|
C++ | UTF-8 | 6,864 | 2.796875 | 3 | [
"BSD-3-Clause"
] | permissive | /* ToString.cpp - String Tools
*
* Author : Alexander J. Yee
* Date Created : 07/07/2013
* Last Modified : 08/24/2014
*
*/
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
#include <sstream>
#include <iomanip>
#include "PublicLibs/CompilerSettings.h"
#include "PublicLibs/ConsoleIO/Label.h"
#include "ToString.h"
namespace ymp{
namespace StringTools{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Helpers
YM_NO_INLINE std::string tostr_u_commas(uiL_t x){
// Prints out x with comma separators.
std::string str = std::to_string(x);
std::string out;
const char* ptr = str.c_str();
upL_t len = str.size();
upL_t commas = (len + 2) / 3 - 1;
upL_t shift = len - commas * 3;
while (1){
char ch = *ptr++;
if (ch == '\0')
break;
if (shift == 0){
out += ',';
shift = 3;
}
out += ch;
shift--;
}
return out;
}
YM_NO_INLINE std::string tostr_s_commas(siL_t x){
if (x < 0)
return std::string("-") + tostr_u_commas(-x);
else
return tostr_u_commas(x);
}
YM_NO_INLINE std::string tostr_u_bytes(uiL_t bytes){
// Prints out bytes in one of the following forms:
// 0.xx suffix
// x.xx suffix
// xx.x suffix
// xxx suffix
const char* BYTE_NAMES[] = {
" bytes",
" KiB",
" MiB",
" GiB",
" TiB",
" PiB",
" EiB",
};
std::string out;
if (bytes < 1000){
if (bytes < 10){
out += " ";
}
out += std::to_string(bytes);
out += BYTE_NAMES[0];
return out;
}
int suffix_index = 1;
while (bytes >= 1024000){
bytes >>= 10;
suffix_index++;
}
bytes *= 1000;
bytes >>= 10;
// .xxx or (1.00)
if (bytes < 1000){
bytes += 5;
bytes /= 10;
if (bytes == 100){
out += "1.00";
out += BYTE_NAMES[suffix_index];
return out;
}
out += "0.";
out += std::to_string(bytes);
out += BYTE_NAMES[suffix_index];
return out;
}
// x.xx or (10.0)
if (bytes < 10000){
bytes += 5;
bytes /= 10;
if (bytes == 1000){
out += "10.0";
out += BYTE_NAMES[suffix_index];
return out;
}
out += std::to_string(bytes / 100);
bytes %= 100;
out += ".";
if (bytes >= 10){
out += std::to_string(bytes);
}else{
out += "0";
out += std::to_string(bytes);
}
out += BYTE_NAMES[suffix_index];
return out;
}
// xx.x or (0.98)
if (bytes < 100000){
bytes += 50;
bytes /= 100;
if (bytes == 1000){
out += " 100";
out += BYTE_NAMES[suffix_index];
return out;
}
out += std::to_string(bytes / 10);
bytes %= 10;
out += ".";
out += std::to_string(bytes);
out += BYTE_NAMES[suffix_index];
return out;
}
// xxx or (1.00)
{
bytes += 500;
bytes /= 1000;
if (bytes == 1000){
out += "0.98";
out += BYTE_NAMES[suffix_index + 1];
return out;
}
out += " ";
out += std::to_string(bytes);
out += BYTE_NAMES[suffix_index];
return out;
}
}
YM_NO_INLINE std::string tostr_s_bytes(siL_t bytes){
if (bytes < 0){
return std::string("-") + tostr_u_bytes(-bytes);
}else{
return tostr_u_bytes(bytes);
}
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
YM_NO_INLINE std::string tostr(uiL_t x, NumberFormat format){
switch (format){
case COMMAS:
return tostr_u_commas(x);
case BYTES:
return tostr_u_bytes(x);
case BYTES_EXPANDED:{
auto out = tostr_u_commas(x);
out += " (";
out += tostr_u_bytes(x);
out += ")";
return out;
}
default:
return std::to_string(x);
}
}
YM_NO_INLINE std::string tostr(siL_t x, NumberFormat format){
switch (format){
case COMMAS:
return tostr_s_commas(x);
case BYTES:
return tostr_s_bytes(x);
case BYTES_EXPANDED:{
auto out = tostr_s_commas(x);
out += " (";
out += tostr_s_bytes(x);
out += ")";
return out;
}
default:
return std::to_string(x);
}
}
YM_NO_INLINE std::string tostrln(uiL_t x, NumberFormat format){
return tostr(x, format) += "\r\n";
}
YM_NO_INLINE std::string tostrln(siL_t x, NumberFormat format){
return tostr(x, format) += "\r\n";
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Float
YM_NO_INLINE std::string tostr_float(double x, int precision){
std::ostringstream out;
out << std::setprecision(precision);
out << x;
return out.str();
}
YM_NO_INLINE std::string tostrln_float(double x, int precision){
return tostr_float(x, precision) += "\r\n";
}
YM_NO_INLINE std::string tostr_fixed(double x, int precision){
std::ostringstream out;
out << std::setprecision(precision);
out << std::fixed;
out << x;
return out.str();
}
YM_NO_INLINE std::string tostrln_fixed(double x, int precision){
return tostr_fixed(x, precision) += "\r\n";
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
}
}
|
Java | UTF-8 | 1,707 | 2.484375 | 2 | [] | no_license | package celebration.Logpack;
import java.sql.*;
import application.Main;
import application.cdb;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
public class login{
Connection con;
@FXML Label check;
@FXML
private TextField username;
@FXML
private TextField password;
@FXML
public void login(){
logged();
}
public boolean logged(){
try (Connection con = cdb.sqlcon();
Statement stmt =con.createStatement();
ResultSet rs = stmt.executeQuery("select * from log where username= '"+username.getText()+"' and pass = '"+password.getText()+"'") ;
){
if(rs.next()){
try{
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass()
.getResource("/celebration/view/homepage.fxml"));
AnchorPane anchorpane = loader.load();
Scene scene = new Scene(anchorpane);
Main.shop.setScene(scene);
Main.shop.show();
return true;
}catch(Exception e){
e.printStackTrace();
}
}else{
check.setText("Notice: Sorry username or the password is incorrect. \n ^^ signup and try Again please!");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
@FXML
public void sign(){
try{
FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass()
.getResource("/celebration/view/addpage.fxml"));
AnchorPane anchorpane = loader.load();
Scene scene = new Scene(anchorpane);
Main.shop.setScene(scene);
Main.shop.show();
}catch(Exception e){
e.printStackTrace();
}
}
}
|
C# | UTF-8 | 1,244 | 2.703125 | 3 | [
"MIT"
] | permissive | using System.Collections.Generic;
using Rhino.Geometry;
namespace KangarooSolver.Goals
{
public class GaviVRForce : GoalObject
{
public Vector3d Force;
public GaviVRForce()
{
}
public GaviVRForce(int u, Vector3d v)
{
PIndex = new int[1] { -1 };
Move = new Vector3d[1];
Weighting = new double[1];
Force = v;
}
public GaviVRForce(Point3d P, Vector3d v)
{
PPos = new Point3d[1] { P };
Move = new Vector3d[1];
Weighting = new double[1];
Force = v;
}
public override void Calculate(List<Particle> p)
{
PI
Move[0] = Force;
Weighting[0] = 1.0;
}
public int SearchIndex(List<KangarooSolver.Particle> p)
{
int L = p.Length;
floa[] dist = new float[L];
for (int i = 0; i < L - 1; i++)
{
dist[i] = abs(InsPt.Position - p[i].Position);
}
//base Point as minimum distance from insertion Pt
PIndex = Array.IndexOf(dist, dist.Min());
}
}
}
|
Markdown | UTF-8 | 1,451 | 2.703125 | 3 | [] | no_license | Polymer CI Runner
=================
A quick 'n dirty Node app that pulls GitHub webhook events off of a
[Firebase](https://www.firebase.com/) queue and runs the appropriate set of
tests for them.
Configuring The Webhook
-----------------------
Through the joys of Firebase, you can have GitHub webhooks publish directly to
it. Create a new webhook:
`https://<your-firebase-app>.firebaseio.com/queue.json`
You will want to turn on pull request and push status.
Running Locally
---------------
`node .`
Spinning Up Your Own Workers
----------------------------
The CI runner is intended to be run as a persistent server. The worker is published as a [Docker image](https://registry.hub.docker.com/u/polymerlabs/ci-runner/)
that you can use; and we provide configuration to make that easy.
### Google Compute Engine
You can make use of the [`tools/gcloud/manage`](tools/gcloud/manage) script.
You will need to create a configuration file and place it somewhere handy:
```sh
# The Google Compute Engine project name.
GCLOUD_PROJECT=my-ci-project
# A GitHub OAuth token with repo:status permissions.
# See https://github.com/settings/applications
GITHUB_OAUTH_TOKEN=abcdef0123456789abcdef0123456789abcdef01
# Your Sauce Labs username.
SAUCE_USERNAME=username
# Your Sauce Labs access key.
SAUCE_ACCESS_KEY=abcdef01-abcd-abcd-abcd-abcdef012345
# The firebase app where webhook jobs should be stored.
FIREBASE_APP=my-firebase-app
```
### Heroku
TODO.
### EC2
TODO.
### Other Hosting Providers
TODO.
|
Markdown | UTF-8 | 1,358 | 3.265625 | 3 | [] | no_license | Evolution
=========
Readme for the final project for Programming Paradigms, Spring 2014. A multiplayer networked game using the Pygame and Twisted libraries.
This game is a twist on the classic "eat smaller fish to grow" theme: you must compete with an opponent who might be bigger than you!
Setup
=====
Evolution.py contains the game code and network.py contains all the necessary networking for the game. To set up the game the server needs to launched first. It is launched with the command "python network.py server <port>". <port> is the port the server will listen on. Then the client can be run on a different machine with the command "python network client <hostname> <port>". <hostname> is the name of the host the server is running on and <port> the the port the server is listening on.
Game Play
========
When a connection is made both client and server will jump into the game.
Objective
========
Eat the other player
Rules
====
To eat the other player you must be bigger than they are and then collide with them.
To get bigger you must eat other fish (red) that are smaller than you.
To eat smaller red fish all you have to do is catch them.
Controls
========
Arrow Keys - Move your fish
When a player wins the winner is displayed on the command line and the game restarts.
|
Rust | UTF-8 | 1,060 | 2.546875 | 3 | [] | no_license | use amethyst::{
core::{math::Vector3, Transform},
ecs::{Join, Read, ReadStorage, System, WriteStorage},
input::InputHandler,
};
use crate::components::*;
pub struct MovementSystem;
impl<'s> System<'s> for MovementSystem {
type SystemData = (
ReadStorage<'s, Player>,
WriteStorage<'s, Position>,
ReadStorage<'s, Speed>,
WriteStorage<'s, Transform>,
Read<'s, InputHandler<String, String>>,
);
fn run(&mut self, (players, mut positions, speeds, mut transforms, input): Self::SystemData) {
let x_move = input.axis_value("entity_x").unwrap();
let y_move = input.axis_value("entity_y").unwrap();
for (_, position, speed, transform) in
(&players, &mut positions, &speeds, &mut transforms).join()
{
let translation: Vector3<f32> = Vector3::new(
x_move as f32 * speed.speed,
y_move as f32 * speed.speed,
0.0,
);
transform.append_translation(translation);
}
}
}
|
Shell | UTF-8 | 2,326 | 4.03125 | 4 | [] | no_license | #!/bin/bash
START_POINT=1
END_POINT=""
APPLY_ONLY=""
SIGNED_OFF=""
while getopts 's:e:a' OPT; do
case $OPT in
s)
START_POINT="$OPTARG";;
e)
END_POINT="$OPTARG";;
a)
APPLY_ONLY="yes";;
?)
echo "Usage: `$SHELL_NAME $0` [options] [path]"
esac
done
shift $((OPTIND -1))
GIT_PATH=$1
USER_EMAIL=`git config --global user.email`
if [ "$APPLY_ONLY" = "yes" ]; then
if [ "$USER_EMAIL" = "" ]; then
echo "no git user.email detected, pleasee add global user firstly!"
exit
fi
fi
echo start:$START_POINT end:$END_POINT apply:$APPLY_ONLY path:$GIT_PATH
if [ "$APPLY_ONLY" = "yes" ]; then
if ! [ -d git-helper.success.patch ]; then
mkdir git-helper.success.patch
fi
if ! [ -d git-helper.failure.patch ]; then
mkdir git-helper.failure.patch
fi
if ! [ -d git-helper.ignore.patch ]; then
mkdir git-helper.ignore.patch
fi
for one_commit in `ls *.patch`
do
if [ -f $one_commit ]; then
grep $USER_EMAIL $one_commit
if [ $? -eq 0 ]; then
git am $one_commit
else
git am -s $one_commit
fi
if [ $? -eq 0 ]; then
printf "%s\n" "successed applying $one_commit"
mv $one_commit git-helper.success.patch
else
patch_title=`grep ^Subject $one_commit | awk -F: '{print $NF;exit}'`
git log --pretty=oneline | grep "$patch_title"
if [ $? -eq 0 ]; then
git am --abort
printf "%s\n" "patch $one_commit already has been applied! just ignore and keep going!"
mv $one_commit git-helper.ignore.patch
else
echo failed applying $one_commit and exit
git am --abort
mv $one_commit git-helper.failure.patch
exit
fi
fi
fi
done
exit
fi
if [ "$START_POINT"="1" ]; then
START_POINT=`git log --pretty=oneline $GIT_PATH | sed -n "1p" | awk '{print $1}'`
fi
ALL_COMMITS=`git log --pretty=oneline $GIT_PATH | sed -n "/$START_POINT/,/$END_POINT/ p" | awk '{print $1}' | tac `
count=1
patch_name=""
for one_commit in $ALL_COMMITS
do
echo format the ${count}th patch: $one_commit
prefix_count=`printf "%04d" $count`
patch_name=`git format-patch -n1 $one_commit`
mv $patch_name $prefix_count--$patch_name
count=$(($count+1))
done
function add_man_to_patch()
{
man=$1
file=$2
#multi lines could seperate by \n
sed -i "/^---$/i $man" $file
}
|
C++ | UTF-8 | 1,087 | 3.125 | 3 | [] | no_license | /**
* 本代码由九章算法编辑提供。没有版权欢迎转发。
* - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。
* - 现有的面试培训课程包括:九章算法班,系统设计班,九章强化班,Java入门与基础算法班
* - 更多详情请见官方网站:http://www.jiuzhang.com/
*/
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void invertBinaryTree(TreeNode *root) {
// write your code here
dfs(root);
}
private:
void dfs(TreeNode *node) {
TreeNode *left = node->left, *right = node->right;
node->left = right; node->right = left;
if (left!=NULL) dfs(left);
if (right!=NULL) dfs(right);
}
};
|
Python | UTF-8 | 847 | 3.265625 | 3 | [] | no_license | ##nr = 33100000
##nrs = []
##for i in range(1, nr):
## divisors = []
## for j in range(0, int(i/2)):
## if i % (j+1) == 0:
## divisors.append(j+1)
## divisors.append(i)
## if sum(divisors)*10 >= nr:
## print(i)
## break
import math
def GetDivisors(n):
small_divisors = [i for i in range(1, int(math.sqrt(n)) + 1) if n % i == 0]
large_divisors = [n / d for d in small_divisors if n != d * d]
return small_divisors + large_divisors
target = 33100000
part_one, part_two = None, None
i = 0
while not part_one or not part_two:
i += 1
divisors = GetDivisors(i)
if not part_one:
if sum(divisors) * 10 >= target:
part_one = i
if not part_two:
if sum(d for d in divisors if i / d <= 50) * 11 >= target:
part_two = i
print(part_one, part_two)
|
Markdown | UTF-8 | 11,225 | 3.109375 | 3 | [] | no_license | FastSwitch
==========
A Sublime Text 2/3 plugin. To switch between files
A file of a given syntax will switch to a file with the same base name but with a different user defined extension.
The file will be searched in a list of user defined directory. The first file found respecting the criteria will be the one Sublime Text 2/3 will switch to.
If the file is not found with this fast switch algorithm then the path is walked. If a walked path contains the substring of the user define directory it will
be searched for the file to switch to.
2017/06/08
----------
New features:
- If the file is not found in the provided path, a new algorithm will be used based on the work of gmatte11/sublime-text-switch-file on github
to walk through the path and search for a path containing as a substring the user defined directory.
This is slower but will be able to find more with out giving too many paths.
2015/03/21
----------
New features:
- It is now possible to switch to a file with a different prefix if a prefix is specified in the settings.<BR>
The prefix is stripped from the filename as for the extension and the prefix and extension
of the other line of the settings is added.<BR>
See examples 6 and 9 below.
- It is possible to cycle between more than 2 files, if the settings has more than 2 lines.>BR>
See examples 7 and 9 below
Here is an example of a setting:
```
// For the settings you define the syntax for which the extension and directory applies
// "syntax_X": [
// [["ext_A1, ext_A2"], ["directory_A1", directory_A2]],
// [["ext_B1", "ext_B2"], ["directory_B1", "directory_B2"]]
// ]
// N.B. The "syntax_X" must be the string found in the lower right corner if the SublimeText 2/3
// Example: "Plain Text", "C++". "Python", "Markdown"
//
// settings with the new feature:
// "syntax_Y": [
// [["ext_A1, ext_A2"], ["directory_A1", directory_A2], {"prefixes": ["prefix_A1_", "prefix_A2_"]}],
// [["ext_B1", "ext_B2"], ["directory_B1", "directory_B2"], {"prefixes": ["prefix_B_"]}],
// [["ext_C1"], ["directory_C1", ""]]
// ]
// N.B. The {"prefixes": ["prefix_A1", "prefix_A2"]} is optional and can be ommitted
//
//
// With the above settings when in syntax_X (Ex C++) and you are currently in the file:
// .../foo/bar/directory_A1/file.ext_A1
//
// using the fastswitch pluging then the pluging will try to open the file:
// foo/bar/directory_B1/file.ext_B1
// foo/bar/directory_B1/file.ext_B2
// foo/bar/directory_B2/file.ext_B1
// foo/bar/directory_B2/file.ext_B2
//
//
// With the above settings when in syntax_Y and you are currently in the file:
// .../foo/bar/directory_A1/prefix_A1_file.ext_A1
//
// using the fastswitch pluging then the pluging will try to open the file:
// foo/bar/directory_B1/prefix_B_file.ext_B1
// foo/bar/directory_B1/prefix_B_file.ext_B2
// foo/bar/directory_B1/prefix_B_file.ext_B1
// foo/bar/directory_B1/prefix_B_file.ext_B2
// foo/bar/directory_B1/prefix_B_file.ext_B2
// foo/bar/directory_C1/file.ext_C1
// foo/bar/file.ext_C1
//
//
// The first existing file will be openned so the order is important.
//
//
// N.B. The "." will be replaced by the current directory
// Ex: If you are currently in c:\foo\src\bar\file.cpp the "include\." correspond to "include\bar"
// The "@d" means to replace the tag by the corresponding directory in path of the current file.
// d must be a negative number
// Ex:
// If you are currently in c:\foo\bar\src\file.cpp the "@-1" correspond to the directory "bar"
//
// For the C++ syntax, I'm using the following
"C++": [
[ [".cpp"], ["src", "../src", "../../src/."] ],
[ ["h", "hpp"], [".", "include", "include/@-1", "../include/@-2/."] ]
],
"verbosity": 0
```
With the above settings when in C++
If you are currently in the file:
* .../foo/bar/src/file.cpp
using the FastSwitch pluging, the pluging will try to open the file:
* .../foo/bar/src/file.h # because of the "."
* .../foo/bar/src/file.hpp # because of the "."
* .../foo/bar/include/file.h
* .../foo/bar/include/file.hpp
If you are currently in the file:
* .../foo/bar/include/file.hpp
using the FastSwitch pluging, the pluging will try to open the file:
* .../foo/bar/src/file.cpp
The following examples are using the advance settings of the FastSwitch pluging to be able to switch between files
where the relation between the different directory tree is more complex.
For each example the setting is minimal to expose the current feature. All the settings can be combined to achieve
powerfull fast and versatile switch.
Example 1:
With the following setting :
```
"C++": [
[ [".cpp"], ["src"] ],
[ ["hpp"], ["."] ]
]
```
or
```
"C++": [
[ [".cpp"], ["."] ],
[ ["hpp"], ["."] ]
]
```
and with the following directory containing the given files:<BR>
ls ./foo/src => test1.cpp, test1.hpp<BR>
when in the following file: ./foo/src/test1.cpp, you should be able to switch to ./src/test1.hpp<BR>
when in the following file: ./foo/src/test1.hpp should switch to ./src/test1.cpp<BR>
Example 2:
With the following setting :
```
"C++": [
[ [".cpp"], ["src"] ],
[ [".h"], ["include"] ]
]
```
and with the following directories containing the given file:<BR>
ls ./foo/src => test2.cpp<BR>
ls ./foo/include => test2.h<BR>
using the FastSwitch pluging :<BR>
when in the following file: ./foo/src/test2.cpp it will switch to ./include/test2.h<BR>
when in the following file: ./foo/include/test2.hpp it will switch to ./src/test2.cpp<BR>
Example 3:
With the following setting :
```
"C++": [
[ [".cpp"], ["../src"] ],
[ [".h"], ["include/@-1"] ]
]
```
and with the following directories containing the given file:<BR>
ls ./foo/src => test3.cpp<BR>
ls ./foo/include/foo => test3.h<BR>
when in the following file: ./foo/src/test3.cpp it will switch to ./foo/include/foo/test3.hpp<BR>
when in the following file: ./foo/include/foo/test3.hpp it will switch to ./foo/src/test3.cpp<BR>
Example 4:
With the following setting :
```
"C++": [
[ [".cpp"], ["../../src/."] ],
[ [".h"], ["../include/@-2/."] ]
]
```
and with the following directories containing the given file:<BR>
ls ./foo/src/bar => test4.cpp<BR>
ls ./foo/include/foo/bar/ => test4.h<BR>
when in the following file: ./foo/src/bar/test4.cpp it will switch to ./foo/include/foo/bar/test4.hpp<BR>
when in the following file: ./foo/include/foo/bar/test4.hpp it will switch to ./foo/src/bar/test4.cpp<BR>
Example 5:
With the following setting:
```
"Javascript": [
[[".js"], ["public/js"]],
[["Spec.js"], ["../test"]]
]
```
and with the following directories containing the given file:<BR>
ls ./foo/public/js => test5.js<BR>
ls ./foo/test => test5Spec.js<BR>
when in the following file ./foo/public/js/test5.js it will switch to ./foo/test/test5Spec.js<BR>
when in the following file ./foo/test/test5Spec.js it will switch to ./foo/public/js/test5.js<BR>
Example 6:
With the following settings:
```
"C++":[
[[".py"], [".", "..", ""] ],
[['.py'], [".", "./test", "./tests"], {"prefixes": ["test_", "test"]}]
]
```
and with the following directories containing the given file:<BR>
ls ./Test6 => test6.cpp<BR>
ls ./Test6/test => test_test6.cpp<BR>
when in the following file ./Test6/test6.cpp it will switch to ./Test6/test/test_test6.cpp<BR>
when in the following file ./Test6/test/test_test6.cpp it will switch to ./Test6/test6.cpp<BR>
Example 7:
With the following settings:
```
"Javascript": [
[[".controller.js"], ["."]],
[[".template.html"], ["."]],
[[".service.js"], ["."]]
],
"HTML": [
[[".template.html"], ["."]],
[[".service.js"], ["."]],
[[".controller.js"], ["."]],
]
```
and with the following directory containing the given files:<BR>
ls ./Test7 => test7_A.controller.js test7_A.service.js test7_A.template.html test7_B.controller.js test7_B.service.js<BR>
when in the following file ./Test7/test7_A.controller.js it will switch to ./Test7/test7_A.template.html<BR>
when in the following file ./Test7/test7_A.template.html it will switch to ./Test7/test7_A.service.js<BR>
when in the following file ./Test7/test7_A.service.js it will switch to ./Test7/test7_A.controller.js<BR>
when in the following file ./Test7/test7_B.controller.js it will switch to ./Test7/test7_B.service.js<BR>
when in the following file ./Test7/test7_B.service.js it will switch to ./Test7/test7_B.controller.js<BR>
Example 8:
With the following settings:
```
"C++": [
[[".cpp"], ["../../src/."], {"prefixes":[""]}],
[[".h", ".hpp"], ["../include/@-2/@0"], {"prefixes":[""]}]
]
```
and with the following directories containing the given file:<BR>
ls ./Test_8/foo/src/bar => test8_A.cpp test8_B.cpp<BR>
ls ./Test_8/foo/include/foo/bar/ => test8_A.h test8_B.hpp<BR>
when in the following file: ./Test_8/foo/src/bar/test8_A.cpp it will switch to ./foo/include/foo/bar/test8_A.h<BR>
when in the following file: ./Test_8/foo/include/foo/bar/test8_A.h it will switch to ./foo/src/bar/test8_A.cpp<BR>
Example 9:
```
"C++": [
[[".cpp"], [".", ""]],
[[".h"], ["."]],
[[".cpp"], ["./unittest"], {"prefixes":["t_"]}]
]
```
and with the following directories containing the given file:<BR>
ls ./Test_9/ => test9_A.cpp test9_A.h test9_B.cpp test9_B.h<BR>
ls ./Test_9/unittest/t_test9_A.cpp<BR>
when in the following file: ./Test_9/test9_A.cpp it will switch to ./Test_9/test9_A.h<BR>
when in the following file: ./Test_9/test9_A.h it will switch to ./Test_9/unittest/t_test9.cpp<BR>
when in the following file: ./Test_9/unittest/test9_A.cpp it will switch to ./Test_9/test9_A.cpp<BR>
when in the following file: ./Test_9/test9_B.cpp it will switch to ./foo/src/bar/test9_B.h<BR>
when in the following file: ./Test_9/test9_B.h it will switch to ./foo/src/bar/test9_B.cpp<BR>
Installation
------------
1. The easiest way to install FastSwitch is via the excellent Package Control Plugin.
See http://wbond.net/sublime_packages/package_control#Installation
* Once package control has been installed, bring up the command palette (cmd+shift+P or ctrl+shift+P)
* Type Install and select "Package Control: Install Package"
* Select FastSwitch from the list. Package Control will keep it automatically updated for you
2. If you don't want to use package control, you can manually install it
* Go to your packages directory and type:
```git clone --recursive https://github.com/papaDoc/FastSwitch FastSwitch ```
* To update run the following command:
```git pull && git submodule foreach --recursive git pull origin master```
* Back in the editor, open up the command palette by pressing cmd+shift+P or ctrl+shift+P
Type FastSwitch and open up the settings file you want to modify
Use the unit test to validate your changes:
```
python lib/fastswitch.py
```
|
JavaScript | UTF-8 | 24,592 | 2.71875 | 3 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2010-2012 Research In Motion Limited.
*
* 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.
*/
/**
* @toc {User Interface} Dialog
* @featureID blackberry.ui.dialog
* @namespace The Dialog object contains functions for manipulating system dialog boxes.
* <p/>
* The functionality in this object allows you to integrate standard system dialog boxes into your BlackBerry WebWorks Application and control your application flow based on user responses.
*/
blackberry.ui.dialog ={
/**
* @deprecated This API is deprecated, please use {@link blackberry.ui.dialog.customAskAsync} instead.
* @param {String} message Message to be displayed in the dialog.
* @param {String[]} choices Array of string choices that will be presented to the user in the form of buttons.
* @param {Number} [defaultChoice = 0] Optional parameter that specifies what choice should be selected by default. This is a number value representing the index of the choice provided in the choices parameter.
* @param {Boolean} [globalStatus = false] If set to true it adds a screen to the queue of displayed global status screens. Global status screens appear on top of all other screens on the PlayBook, even if the current application is not in the foreground. If no other status screens are currently displayed, your provided screen appears immediately. <p> NOTE: If the app is in the background and globalStatus is set to true, the app WILL NOT be brought to the foreground.
* @description Creates a dialog to ask the user a question. The dialog uses the standard question mark bitmap. The function will block execution and when the user selects an option it will return the index of the choice selected by the user.
* @returns {Number} The index of the choice selected by the user.
* @BB50+
* @example
* <script type="text/javascript">
*
* function globalDialog() {
* var ss = ["Saab", "Volvo", "BMW", "Subaru"];
* var ret = blackberry.ui.dialog.customAsk("Select your favorite car", ss, 2, true);
*
* document.getElementById('carSelect').innerHTML = ss[ret]
* }
*
* </script>
*/
customAsk : function(message, choices,defaultChoice,globalStatus){},
/**
* @function
* @description Creates an asynchronous custom dialog to ask the user a question. <br/>
* Uses the custom dialog. The function is an asynchronous call and will not block execution. It will return the 0-based index of the user's choice. <br/>
* NOTE: function is only implemented for Ripple emulation on Playbook.
* @param {String} message Message to be displayed in the dialog.
* @param {String[]} buttons Array of string choices that will be presented to the user in the form of buttons.
* @callback {function} [onOptionSelected] Optional callback function that will be invoked when the user makes a selection. Expected signature: function onOptionSelected(selectedButtonIndex). <p> NOTE: onOptionSelected is required for BlackBerry OS5.0+.
* @callback {Number} [onOptionSelected.index] The index of the selection the user has made.
* @param {Object} [settings = null] Optional Object literal that allows the user to manipulate the size, location, title of the dialog, and whether this is a global dialog (your application cannot be minimized when a global dialog is active; by default when the 'global' flag is not passed, dialog will be modal only for your application). It is not required to provide all parameters, and these do not have to be specified in any particular order. <p> NOTE: The settings parameter applies only to PlayBook, Ripple, and BB10. On the other devices, it has no effect.
* @param {String} [settings.title] Desired title of the dialog.
* @param {String} [settings.size] Desired size of the dialog.
* @param {String} [settings.position] Desired position of the dialog.
* @param {Boolean} [settings.global] Specifies the global flag of the dialog window. (Your application cannot be minimized when the dialog global setting is set to true and when any dialog window is open). By default this parameter is false when not specified. <br/>
* NOTE: The parameters for 'size', 'position', and 'global' are NOT implemented for BB10.
* @BB50+
* @PB10+
* @BB10X
* @RIPPLE
* @example
* <script type="text/javascript">
*
* function dialogCallBack(index){
* alert(index);
* }
*
* function customDialog() {
* try {
* var buttons = ["Yes", "No", "Sometimes", "NA"];
* var ops = {title : "Choose the answer that describes you best", size : blackberry.ui.dialog.SIZE_TALL, position : blackberry.ui.dialog.CENTER};
* blackberry.ui.dialog.customAskAsync("Do you routinely work out?", buttons, dialogCallBack, ops);
* } catch(e) {
* alert("Exception in customDialog: " + e);
* }
* }
*
* </script>
*/
customAskAsync : function(message,buttons,onOptionSelected,settings){},
/**
* @deprecated This API is deprecated, please use {@link blackberry.ui.dialog.standardAskAsync} instead.
* @param {Number} specifies the type of standard dialog. Constants starting with D_*.
* @param {String} message Message to be displayed in the dialog.
* @param {Number} [defaultChoice = 0] Optional parameter that specifies what choice should be selected by default. For the standard dialogs, these options can be one of the constants starting with C_*.
* @param {Boolean} [globalStatus = false] If set to true it adds a screen to the queue of displayed global status screens. Global status screens appear on top of all other screens on the PlayBook, even if the current application is not in the foreground. If no other status screens are currently displayed, your provided screen appears immediately. <p> NOTE: If the app is in the background and globalStatus is set to true, the app WILL NOT be brought to the foreground.
* @description Creates a standard dialog to ask the user a question.
* @returns {Number} The index of the choice selected by the user.
* @BB50+
* @example
* <script type="text/javascript">
*
* function launchDialog() {
* setTimeout(globalDialog, 5000);
* return;
* }
*
* function globalDialog() {
* var ss = ["Saab", "Volvo", "BMW"];
* var ret = blackberry.ui.dialog.customAsk("Select your favorite car", ss, 2, true);
* blackberry.ui.dialog.standardAsk(blackberry.ui.dialog.D_OK, "You selected " + ss[ret], 0, true);
* }
*
* </script">
*/
standardAsk : function(type, message, defaultChoice, globalStatus){},
/**
* @description Creates an asynchronous standard dialog to ask the user a question. <br/>
* Uses the standard dialog. The function is an asynchronous call and will not block execution. It will return an object containing the selected button, and the input values.<br/>
* NOTE: function is only implemented for Ripple emulation on Playbook.
* @param {String} message Message to be displayed in the dialog.
* @param {Number} type Parameter that specifies the type of standard dialog. Constants starting with D_*.
* @callback {function} [onOptionSelected] Optional callback function that will be invoked when the user makes a selection. Expected signature: function onOptionSelected(selectedButtonObject).
* @callback {String} [onOptionSelected.return] The element for the selected button, returns a string based on users choice.
* @callback {String} [onOptionSelected.promptText] The element for entered text. Returns the user's entered string. If cancel is selected set to null. (This property is only used for select dialogs: D_PROMPT). <br/><br/>
* Example returns for each dialog type:
* <ol>
* <li>D_OK</li>
* <ul>
* <li>Ok selected: {return: "Ok"}</li>
* </ul>
* <li>D_SAVE</li>
* <ul>
* <li>Save selected: {return: "Save"}</li>
* <li>Discard selected: {return: "Discard"}</li>
* </ul>
* <li>D_DELETE</li>
* <ul>
* <li>Delete selected: {return: "Delete"}</li>
* <li>Cancel selected: {return: "Cancel"}</li>
* </ul>
* <li>D_YES_NO</li>
* <ul>
* <li>Yes selected: {return: "Yes"}</li>
* <li>No selected: {return: "No"}</li>
* </ul>
* <li>D_OK_CANCEL</li>
* <ul>
* <li>Ok selected: {return: "Ok"}</li>
* <li>Cancel selected: {return: "Cancel"}</li>
* </ul>
* <li>D_PROMPT</li>
* <ul>
* <li>Ok selected with input: {return: "Ok", promptText: "test input"}</li>
* <li>Ok selected with empty input: {return: "Ok", promptText: null}</li>
* <li>Cancel selected: {return: "Cancel", promptText: null}</li>
* </ul>
* </ol>
* @param {Object} [settings = null] Optional Object literal that allows the user to manipulate the title and optional buttons of the dialog. It is not required to provide all parameters, and these do not have to be specified in any particular order. <p> NOTE: The settings parameter applies only to PlayBook, Ripple, and BB10. On the other devices, it has no effect.
* @param {String} [settings.title] Desired title of the dialog.
* @BB10X
* @RIPPLE
* @example
* <script type="text/javascript">
*
* function dialogCallBack(selection){
* alert(selection.return);
* }
*
* function standardDialog() {
* try {
* blackberry.ui.dialog.standardAskAsync("Save?", blackberry.ui.dialog.D_SAVE, dialogCallBack, {title : "Save Dialog"});
* }catch (e) {
* alert("Exception in standardDialog: " + e);
* }
* }
*
* </script>
*/
standardAskAsync : function(message,type,onOptionSelected,settings){},
/**
* @name blackberry.ui.dialog.standardAskAsync^2
* @function
* @description Creates an asynchronous standard dialog to ask the user a question. <br/>
* Uses the standard dialog. The function is an asynchronous call and will not block execution. It will return the 0-based index of the user's choice. <br/>
* NOTE: function is only implemented for Ripple emulation on Playbook.
* @param {String} message Message to be displayed in the dialog.
* @param {Number} type Parameter that specifies the type of standard dialog. Constants starting with D_*.
* @callback {function} [onOptionSelected] Optional callback function that will be invoked when the user makes a selection. Expected signature: function onOptionSelected(selectedButtonIndex). <p> NOTE: onOptionSelected is required for BlackBerry OS5.0+.
* @callback {Number} [onOptionSelected.index] The index of the selection the user has made.
* @param {Object} [settings = null] Optional Object literal that allows the user to manipulate the size, location, title of the dialog, and whether this is a global dialog (your application cannot be minimized when a global dialog is active; by default when the 'global' flag is not passed, dialog will be modal only for your application). It is not required to provide all parameters, and these do not have to be specified in any particular order. <p> NOTE: The settings parameter applies only to PlayBook, Ripple, and BB10. On the other devices, it has no effect.
* @param {String} [settings.title] Desired title of the dialog.
* @param {String} [settings.size] Desired size of the dialog.
* @param {String} [settings.position] Desired position of the dialog.
* @param {Boolean} [settings.global] Specifies the global flag of the dialog window. (Your application cannot be minimized when the dialog global setting is set to true and when any dialog window is open). By default this parameter is false when not specified.
* @BB50+
* @PB10+
* @RIPPLE
* @example
* <script type="text/javascript">
*
* function dialogCallBack(index){
* alert(index);
* }
*
* function standardDialog() {
* try {
* blackberry.ui.dialog.standardAskAsync("Save?", blackberry.ui.dialog.D_SAVE, dialogCallBack, {title : "Save Dialog", size: blackberry.ui.dialog.SIZE_MEDIUM, position : blackberry.ui.dialog.BOTTOM});
* }catch (e) {
* alert("Exception in standardDialog: " + e);
* }
* }
*
* </script>
*/
standardAskAsync : function(message,type,onOptionSelected,settings){},
/**
* @description Creates an asynchronous dialog to allow user to select one or many items in a list.
* <p/>The function is an asynchronous call and will not block JavaScript execution. It will return array of indexes that user selected.
* @param {Boolean} allowMultiple If true, the dialog will allow multiple selection.
* @param {Object[]} options Array of objects representing the select items and their states.
* @param {String} options.label The value of an item in the dropdown list
* @param {Boolean} options.selected Flag that indicates whether an item should be rendered as currently selected
* @param {Boolean} options.enabled Flag that indicates whether an item should be enabled for selection
* @param {String} options.type Can be either "group" or "option" to indicate whether an item is a group header or an option
* @callback {function} onSelected A callback that will be invoked with the user's choices from the native UI.
* @callback {Number[]} onSelected.indices The indices of the user's selections.
* @BB50+
* @example
* <script type="text/javascript">
*
* function onSelected(indices) {
* var i;
* for(i = 0; i < indices.length; i++) {
* alert("Item selected: " + indices[i]);
* }
* }
*
* function selectAsync() {
* try {
* blackberry.ui.dialog.selectAsync(false,
* [ { label : "Animals", selected : false, enabled : false, type : "group"},
* { label : "cat", selected : true, enabled : true, type : "option"},
* { label : "dog", selected : false, enabled : true, type : "option"},
* { label : "mouse", selected : false, enabled : true, type : "option"},
* { label : "raccoon", selected : false, enabled : true, type : "option"}
* ],
* window.onSelected);
* }catch (e) {
* alert("Exception in selectAsync: " + e);
* }
* }
*
* </script>
*/
selectAsync : function(allowMultiple, options, onSelected){},
/**
* @description Creates an asynchronous dialog to allow user to select a date/time for an HTML 5 input of types: date, datetime, datetime-local, month, time
* <p/>The function is an asynchronous call and will not block execution. It will return the value selected by the user.
* @param {String} type One of: "date", "datetime", "datetime-local", "month", "time".
* @param {Object[]} options The current state of the input control.
* @param {String} options.value String representation of the current date/time displayed in the field
* @param {String} options.min String representation of the minimum date/time allowed in the field
* @param {String} options.max String representation of the maximum date/time allowed in the field
* @callback {function} onDateTimeSelected A callback that will be invoked with the user's choices from the native UI.
* @callback {String} onDateTimeSelected.datetime The date/time user has selected.
* @BB50+
* @example
* <script type="text/javascript">
*
* function onDateTimeSelected(datetime){
* alert(datetime);
* }
*
* //Input argument is a reference to an input control of type: date, datetime, datetime-local, month, time
* function dateTimeAsync(htmlDateTimeInput) {
* try {
* var opts = { "value" : htmlDateTimeInput.value,
* "min" : htmlDateTimeInput.min || "",
* "max" : htmlDateTimeInput.max || ""
* };
*
* blackberry.ui.dialog.dateTimeAsync("date", opts, window.onDateTimeSelected);
* }catch (e) {
* alert("Exception in dateTimeAsync: " + e);
* }
* }
*
* </script>
*/
dateTimeAsync : function(type, options, onSelected){},
/**
* @description Creates an asynchronous dialog to allow user to select a color.
* <p/>The function is an asynchronous call and will not block execution. It will return the value selected by the user.
* @param {String} initialColor Color that will first be selected when the color picker dialog appears in hexadecimal format.
* @callback {function} onColorSelected Callback function that will be invoked when the user makes a selection. It will be invoked with the user's choice from the native UI.
* @callback {String} onColorSelected.color The color user has selected in hexadecimal format.
* @BB50+
* @example
* <script type="text/javascript">
*
* function onColorSelected(color){
* alert(color);
* }
*
* function colorPicker() {
* try {
* blackberry.ui.dialog.colorPickerAsync("000000", onColorSelected);
* } catch (e) {
* alert("Exception in colorPickerAsync: " + e);
* }
* }
*
* </script>
*/
colorPickerAsync : function(){initialColor, onColorSelected},
/**
* @constant
* @type Number
* @description Standard OK dialog
* @default 0
* @BB50+
* @PB10+
* @BB10X
* @RIPPLE
*/
D_OK : 0,
/**
* @constant
* @type Number
* @description Standard Save dialog
* @default 1
* @BB50+
* @PB10+
* @BB10X
* @RIPPLE
*/
D_SAVE:1,
/**
* @constant
* @type Number
* @description Standard Delete confirmation dialog
* @default 2
* @BB50+
* @PB10+
* @BB10X
* @RIPPLE
*/
D_DELETE:2,
/**
* @constant
* @type Number
* @description Standard Yes/No dialog
* @default 3
* @BB50+
* @PB10+
* @BB10X
* @RIPPLE
*/
D_YES_NO:3,
/**
* @constant
* @type Number
* @description Standard OK/Cancel dialog
* @default 4
* @BB50+
* @PB10+
* @BB10X
* @RIPPLE
*/
D_OK_CANCEL:4,
/**
* @constant
* @type Number
* @description Standard OK/Cancel dialog
* @default 5
* @BB10X
* @RIPPLE
*/
D_PROMPT:5,
/**
* @constant
* @type Number
* @description Standard Prompt input dialog
* @default -1
* @BB50+
* @RIPPLE
*/
C_CANCEL:-1,
/**
* @constant
* @type Number
* @description OK choice for use in dialogs
* @default 0
* @BB50+
* @RIPPLE
*/
C_OK:0,
/**
* @constant
* @type Number
* @description SAVE choice for use in dialogs
* @default 1
* @BB50+
* @RIPPLE
*/
C_SAVE:1,
/**
* @constant
* @type Number
* @description DISCARD choice for use in dialogs
* @default 2
* @BB50+
* @RIPPLE
*/
C_DISCARD:2,
/**
* @constant
* @type Number
* @description DELETE choice for use in dialogs
* @default 3
* @BB50+
* @RIPPLE
*/
C_DELETE:3,
/**
* @constant
* @type Number
* @description YES choice for use in dialogs
* @default 4
* @BB50+
* @RIPPLE
*/
C_YES:4,
/**
* @constant
* @type Number
* @description NO choice for use in dialogs
* @default -1
* @BB50+
* @RIPPLE
*/
C_NO:-1,
/**
* @constant
* @type String
* @description Bottom located dialog
* @default "bottomCenter"
* @PB10+
* @RIPPLE
*/
BOTTOM : "bottomCenter",
/**
* @constant
* @type String
* @description Center located dialog
* @default "middleCenter"
* @PB10+
* @RIPPLE
*/
CENTER : "middleCenter",
/**
* @constant
* @type String
* @description Top located dialog
* @default "topCenter"
* @PB10+
* @RIPPLE
*/
TOP : "topCenter",
/**
* @constant
* @type String
* @description Full size dialog
* @default "full"
* @PB10+
* @RIPPLE
*/
SIZE_FULL : null,
/**
* @constant
* @type String
* @description Large size dialog
* @default "large"
* @PB10+
* @RIPPLE
*/
SIZE_LARGE : null,
/**
* @constant
* @type String
* @description Medium size dialog
* @default "medium"
* @PB10+
* @RIPPLE
*/
SIZE_MEDIUM : null,
/**
* @constant
* @description Small size dialog
* @default "small"
* @PB10+
* @RIPPLE
*/
SIZE_SMALL : null,
/**
* @constant
* @type String
* @description Tall size dialog
* @default "tall"
* @PB10+
* @RIPPLE
*/
SIZE_TALL : null
};
|
Python | UTF-8 | 1,987 | 2.78125 | 3 | [] | no_license | from turtle import*
from math import*
from random import*
speed(0)
hideturtle()
screen = getscreen()
screen.tracer(True)
#-------------------------------------------------------------
global xhome
global yhome
xhome = -300
zhome = -250
home = (xhome, zhome)
global xline
global yline
global zline
xline = 400
yline = 250
zline = 300
global zmax
zmax = maxinput
global ax
global ay
ax = i - 1 #Anzahl x Werte -1
ay = j - 1 #Anzahl y Werte -1
global xyangle
xyangle = 45 #degrees
#-------------------------------------------------------------
def zpoint(x, y, zk):
xstartup = (x/ax)*xline
yxstartup = (y/(i-1))*yline*cos(xyangle*(pi/180))
zstartup = (zk/zmax)*zline
yzstartup = (y/(j-1))*yline*sin(xyangle*(pi/180))
cor = (xstartup + yxstartup + xhome, zstartup + yzstartup + zhome )
print(zstartup + yzstartup + zhome)
return cor
#-------------------------------------------------------------
for a in range(0, i):
for b in range(0, j):
middle = zpoint(a, b, k[h][a][b])
pu()
goto(middle)
pd()
if a == ax:
pass
else:
c = zpoint(a + 1, b, k[h][a + 1][b])
goto(c)
goto(middle)
if b == ay:
pass
else:
d = zpoint(a, b + 1, k[h][a][b + 1])
goto(d)
goto(middle)
pu()
#-------------------------------------------------------------
pu()
goto(home)
pd()
fd(xline)
left(xyangle)
fd(yline)
left(90-xyangle)
fd(zline)
right(90-xyangle)
bk(yline)
left(90-xyangle)
bk(zline)
fd(zline)
right(90)
bk(xline)
left(90)
bk(zline)
fd(zline)
right(90-xyangle)
fd(yline)
left(90-xyangle)
bk(zline)
right(90-xyangle)
bk(yline)
fd(yline)
right(xyangle)
fd(xline)
left(90)
fd(zline)
right(90)
bk(xline)
#-------------------------------------------------------------
update()
hideturtle()
exitonclick()
|
C++ | UTF-8 | 2,155 | 2.75 | 3 | [] | no_license | inline ll hilbertOrder(ll x, ll y, ll pow, ll rotate)
{
if (pow == 0) {
return 0;
}
ll hpow = 1 << (pow-1);
ll seg = (x < hpow) ? (
(y < hpow) ? 0 : 3
) : (
(y < hpow) ? 1 : 2
);
seg = (seg + rotate) & 3;
const ll rotateDelta[4] = {3, 0, 0, 1};
ll nx = x & (x ^ hpow), ny = y & (y ^ hpow);
ll nrot = (rotate + rotateDelta[seg]) & 3;
ll subSquareSize = 1ll << (2*pow - 2);
ll ans = seg * subSquareSize;
ll add = hilbertOrder(nx, ny, pow-1, nrot);
ans += (seg == 1 || seg == 2) ? add : (subSquareSize - add - 1);
return ans;
}
struct Query
{
ll l, r,idx;
ll ord;
inline void calcOrder() {
ord = hilbertOrder(l, r, 21, 0);
}
};
inline bool operator<(const Query &a,const Query &b){
return a.ord<b.ord;
}
// Arpa's Mo sorting algorithm
// S = the max integer number which is less than sqrt(N);
bool cmp(Query A, Query B){
if (A.l / S != B.l / S) return A.l < B.l;
return A.l / S % 2 ? A.r > B.r : A.r < B.r;
}
// Code Example in main
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
vector<Query> q(n);
for(int i=0;i<n;i++){
q[i].l=dis[i+1];
q[i].r=dis[i+1]+sz[i+1]-1;
q[i].idx=i+1;
q[i].calcOrder();
}
sort(all(q));
int l=1,r=n;
map<ll,ll> mt;
for(int i=1;i<=n;i++){
mt[v[temp[i]]]++;
}
for(int i=0;i<n;i++){
while(l>q[i].l){
mt[v[temp[l-1]]]++;
l--;
}
while(r<q[i].r){
mt[v[temp[r+1]]]++;
r++;
}
while(l<q[i].l){
if(mt[v[temp[l]]]==1){
mt.erase(v[temp[l]]);
}
else{
mt[v[temp[l]]]--;
}
l++;
}
while(r>q[i].r){
if(mt[v[temp[r]]]==1){
mt.erase(v[temp[r]]);
}
else{
mt[v[temp[r]]]--;
}
r--;
}
ans[q[i].idx]=(int)mt.size();
}
}
|
C++ | UTF-8 | 628 | 2.75 | 3 | [] | no_license | #ifndef DESCRIPTOR_HPP
#define DESCRIPTOR_HPP
#include <memory>
namespace tcp {
class Descriptor {
private:
int fd_;
public:
Descriptor() noexcept;
explicit Descriptor(int fd) noexcept;
Descriptor(const Descriptor& other_fd) = delete;
Descriptor& operator=(const Descriptor& other_fd) = delete;
Descriptor(Descriptor&& other_fd) noexcept;
Descriptor& operator=(Descriptor&& other_fd) noexcept;
~Descriptor() noexcept;
void set_fd(int fd) noexcept;
int get_fd() noexcept;
void close() noexcept;
};
}
#endif
|
Java | UTF-8 | 311 | 2.296875 | 2 | [] | no_license | package webchat.dao.sql.query;
import java.util.List;
public class PredicateToken implements Token {
MySQLWhere w;
@Override
public void exec(TokenList tl) {
List<Token> tokens = w.tokenList.tokens;
for (Token t : tokens) {
t.exec(tl);
}
}
PredicateToken(MySQLWhere w) {
this.w = w;
}
}
|
Java | UTF-8 | 4,881 | 2.25 | 2 | [] | no_license | package com.lawu.eshop.mall.srv.bo;
import java.math.BigDecimal;
import java.util.Date;
import com.lawu.eshop.mall.constants.DiscountPackageStatusEnum;
/**
* 优惠套餐BO
*
* @author Sunny
* @date 2017年6月26日
*/
public class DiscountPackageBO {
/**
* 主键
*/
private Long id;
/**
* 商家id
*/
private Long merchantId;
/**
* 实体门店id
*/
private Long merchantStoreId;
/**
* 套餐名称
*/
private String name;
/**
* 封面图片
*/
private String coverImage;
/**
* 套餐价格
*/
private BigDecimal price;
/**
* 原价
*/
private BigDecimal originalPrice;
/**
* 其他说明
*/
private String otherInstructions;
/**
* 有效期-开始
*/
private Date validityPeriodBegin;
/**
* 有效期-结束
*/
private Date validityPeriodEnd;
/**
* 使用时间-周一到周日
*/
private String useTimeWeek;
/**
* 使用时间-开始
*/
private Date useTimeBegin;
/**
* 使用时间-结束
*/
private Date useTimeEnd;
/**
* 状态
*/
private DiscountPackageStatusEnum status;
/**
* 是否需要预约
*/
private Boolean isReservation;
/**
* 提前预约时间(xx小时|xx分钟|)
*/
private String advanceBookingTime;
/**
* 购买须知
*/
private String purchaseNotes;
/**
* 使用规则
*/
private String useRules;
/**
* 上架时间
*/
private Date gmtUp;
/**
* 创建时间
*/
private Date gmtCreate;
/**
* 更新时间
*/
private Date gmtModified;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getMerchantId() {
return merchantId;
}
public void setMerchantId(Long merchantId) {
this.merchantId = merchantId;
}
public Long getMerchantStoreId() {
return merchantStoreId;
}
public void setMerchantStoreId(Long merchantStoreId) {
this.merchantStoreId = merchantStoreId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCoverImage() {
return coverImage;
}
public void setCoverImage(String coverImage) {
this.coverImage = coverImage;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public BigDecimal getOriginalPrice() {
return originalPrice;
}
public void setOriginalPrice(BigDecimal originalPrice) {
this.originalPrice = originalPrice;
}
public String getOtherInstructions() {
return otherInstructions;
}
public void setOtherInstructions(String otherInstructions) {
this.otherInstructions = otherInstructions;
}
public Date getValidityPeriodBegin() {
return validityPeriodBegin;
}
public void setValidityPeriodBegin(Date validityPeriodBegin) {
this.validityPeriodBegin = validityPeriodBegin;
}
public Date getValidityPeriodEnd() {
return validityPeriodEnd;
}
public void setValidityPeriodEnd(Date validityPeriodEnd) {
this.validityPeriodEnd = validityPeriodEnd;
}
public String getUseTimeWeek() {
return useTimeWeek;
}
public void setUseTimeWeek(String useTimeWeek) {
this.useTimeWeek = useTimeWeek;
}
public Date getUseTimeBegin() {
return useTimeBegin;
}
public void setUseTimeBegin(Date useTimeBegin) {
this.useTimeBegin = useTimeBegin;
}
public Date getUseTimeEnd() {
return useTimeEnd;
}
public void setUseTimeEnd(Date useTimeEnd) {
this.useTimeEnd = useTimeEnd;
}
public DiscountPackageStatusEnum getStatus() {
return status;
}
public void setStatus(DiscountPackageStatusEnum status) {
this.status = status;
}
public Boolean getIsReservation() {
return isReservation;
}
public void setIsReservation(Boolean isReservation) {
this.isReservation = isReservation;
}
public String getAdvanceBookingTime() {
return advanceBookingTime;
}
public void setAdvanceBookingTime(String advanceBookingTime) {
this.advanceBookingTime = advanceBookingTime;
}
public String getPurchaseNotes() {
return purchaseNotes;
}
public void setPurchaseNotes(String purchaseNotes) {
this.purchaseNotes = purchaseNotes;
}
public String getUseRules() {
return useRules;
}
public void setUseRules(String useRules) {
this.useRules = useRules;
}
public Date getGmtUp() {
return gmtUp;
}
public void setGmtUp(Date gmtUp) {
this.gmtUp = gmtUp;
}
public Date getGmtCreate() {
return gmtCreate;
}
public void setGmtCreate(Date gmtCreate) {
this.gmtCreate = gmtCreate;
}
public Date getGmtModified() {
return gmtModified;
}
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
} |
Java | UTF-8 | 4,774 | 1.96875 | 2 | [] | no_license | package fr.esil.wificonnector.service;
import java.io.File;
import java.util.LinkedList;
import java.util.List;
import net.esil.wificonnector.object.Form;
import net.esil.wificonnector.object.Input;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import com.rabgs.http.browser.Browser;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.util.Log;
import fr.esil.wificonnector.EnvWifi;
import fr.esil.wificonnector.R;
import fr.esil.wificonnector.object.Wifi;
import fr.esil.wificonnector.parser.XmlParser;
import fr.esil.wificonnector.ui.HomeActivity;
import fr.esil.wificonnector.ui.ProfileActivity;
public class WifiService extends Service {
private String TAG = "WifiService";
private WifiManager mManWifi;
private WifiInfo mWifiInfo;
private Form mForm;
private Wifi mWifi;
@Override
public void onCreate() {
Log.i(TAG, "****** Service ON CREATE");
mManWifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
mWifiInfo = mManWifi.getConnectionInfo();
// On regarde si un profil existe pour ce ssid
if( isProfilExist()){
File xmlFile = new File(getFilesDir() + "/" + EnvWifi.PROFILE_DIR +"/"+ mWifiInfo.getSSID() + ".xml");
mWifi = XmlParser.read(xmlFile);
mForm=mWifi.getForm();
Log.i(TAG, "Profil deja existant -> post ");
//On emet la requete POST pour s'authentifier
Browser mBrowser = new Browser(true);
List<NameValuePair> postData = new LinkedList<NameValuePair>();
for (Input input : mForm.getInputList()) {
// beware value sent for checkbox
BasicNameValuePair data = new BasicNameValuePair(input.getName(), input.getValue());
postData.add(data);
System.out.println(data);
}
if(mWifi.getSSID().equals("UNIVMED")){
mBrowser.doHttpPost("https://securelogin.arubanetworks.com" +mForm.getAction(), postData);
Log.i(TAG, "https://securelogin.arubanetworks.com" +mForm.getAction());
}
mBrowser.doHttpPost(mForm.getAction(), postData);
Log.i(TAG, "https://securelogin.arubanetworks.com" +mForm.getAction());
wifiNotify2(mWifiInfo.getSSID());
}
else{ // pas de profil, on propose d'en creer un nouveau
// Creation et envoi de la notification :
wifiNotify1(mWifiInfo.getSSID());
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void wifiNotify1(String SSID){
Log.i(TAG, "****** NOTIFY");
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.cancel(R.string.app_name);
Notification notifWifi = new Notification(R.drawable.iconwc,"Wifi Connector :",System.currentTimeMillis());
Intent intent = new Intent( getApplicationContext(), HomeActivity.class);
PendingIntent clikintent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
String text = "Vous etes connecte au reseau :" + SSID;
notifWifi.setLatestEventInfo(getBaseContext(), "Wifi Connector",text, clikintent);
nm.notify(R.string.tag_notif, notifWifi);
}
public void wifiNotify2(String SSID){
Log.i(TAG, "****** NOTIFY2");
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.cancel(R.string.app_name);
Notification notifWifi = new Notification(R.drawable.iconwc,"Wifi Connector",System.currentTimeMillis());
Intent intent = new Intent( getApplicationContext(), ProfileActivity.class);
PendingIntent clikintent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
String text = "Vous etes connecte a Internet";
notifWifi.setLatestEventInfo(getBaseContext(), "Wifi Connector :",text, clikintent);
nm.notify(R.string.tag_notif, notifWifi);
}
private boolean isProfilExist () {
String profileDirPath = getFilesDir() + "/" + EnvWifi.PROFILE_DIR;
File profileDir = new File(profileDirPath);
if ( profileDir.isDirectory() ) {
String [] profiles = profileDir.list();
if (profiles != null) {
// FOR EACH PROFILE
for (int i=0; i<profiles.length; i++) {
String filename = profiles[i];
if(filename.equals(mWifiInfo.getSSID()+".xml")){
return true;
}
}
}
}
return false;
}
}
|
Markdown | UTF-8 | 3,646 | 2.515625 | 3 | [] | no_license | - [ ] ok [42008574](https://bj.5i5j.com/ershoufang/42008574.html)
#地铁站/大井 #地铁站/郭庄子 , #地铁线/14号线(西)
#单价/6-8 #总价/210-225 #面积/30-35 #区域/丰台/七里庄/小区-丰体时代 #在售 #所在楼层/低楼层 #总楼层/28层 #layout

# 简介
210万, 6.28万/m²
小区: 丰体时代
建筑类型: 塔楼
区域: 丰台 七里庄
看房时间: 提前预约
地铁: 距离地铁大井434米 地图
# 基本信息
房屋户型|1室1厅1卫
所在楼层|低楼层/28层
建筑面积|33.45平米
户型结构|平层
建筑类型|塔楼
房屋朝向|南
建筑结构|钢混
装修情况|简装
配备电梯|有
# 交易信息
发布时间|2020-11-24
建筑年代|2005年|建筑年代仅供参考,实际房龄以政府信息为准
产权性质|商品房
规划用途|普通住宅
上次交易|2019-01-01
购房年限|满两年不满五年
抵押情况|无
房本备件|已上传房本照片
# 交易特色
核心卖点|房子是商品房,格局方正,南向采光充足。
户型介绍|此房为南向1室1厅1卫,建筑面积为33.45平米,房子是业主用心装过的,装修挺好的,之前自主房屋保持挺干净。可免去重新装修的成本。
交通出行|距离地铁大井站直线距离434米,出小区门口,往东走400米(此距离来自百度地图)可到丰体南路上乘坐大井地铁站14号线,出小区往东600米(此距离来自百度地图)走可到西四环。
税费解析|此房税费合计:21000元;其中增值税及附加:0元;契税:21000元;个人所得税:0元;(以上税费仅为购房参考,不能作为最终购房依据,了解准确方案,请咨询经纪人)
贷款情况|业主接受:全款##商贷##公积金##组合贷##均可。业主接受各种贷款形式(贷款情况仅供参考,最终以实际情况为准)
周边配套|出了小区之后就是丰台体育馆,现在是人和的主场,等待周末可以陪家人去看一场足球。14号线大井站也在小区附近,步行即到。
小区信息|另外附近有一个比较大的物美超市,能够满足日常所需。希望能成为您的置业之选
权属抵押|房屋产权:房屋是商品房,符合正常交易条件,房本满两年,免营业税及其附加
# 带看
2021-08-05|最近带看 1|次|近30天带看 22|次|累计带看
# 小区 丰体时代
## 小区指数
距 14号线 大井地铁站-A口 425米|距 丰台体育中心南门站 212米|西五环内, 高峰时间平均时速为22km/h|查看更多周边信息
500米内 平价餐厅24家 ,1家4星餐厅
中档餐厅6家 ,2家4星餐厅
高档餐厅3家 ,2家4星餐厅|500米内 1家便利店
1000米内 4家综合超市
2000米内 19家商场|500米内 药店 3家
1000米内 银行 7家|查看更多周边信息
小区物业费1.2元/平米/月|2005年建成|物业公司为北京盛世开元物业管理公司|查看更多周边信息
2000米内二级医院 1家|距离 北京市红十字会和平骨科医院 1405米|查看更多周边信息
距离 郭庄子公园-五里店绿化公园 960米|1000米内 16家 健身房
距离最近健身房中隆马术网球训练基地 652米|查看更多周边信息
## 小区信息
小区均价|51384元/m²
建筑面积|338000m²
建筑年代|2005年|建筑年代仅供参考,实际房龄以政府信息为准
总户数|2438
绿化率|36%
容积率|3.5
所在商圈|七里庄
小区物业|北京盛世开元物业管理公司
小区在售房源22套
小区在租房源21套
|
C# | UTF-8 | 633 | 2.5625 | 3 | [] | no_license | namespace System.Runtime.InteropServices
{
using System;
[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Struct | AttributeTargets.Class, Inherited=false), ComVisible(true)]
public sealed class TypeLibTypeAttribute : Attribute
{
internal TypeLibTypeFlags _val;
public TypeLibTypeAttribute(short flags)
{
this._val = (TypeLibTypeFlags) flags;
}
public TypeLibTypeAttribute(TypeLibTypeFlags flags)
{
this._val = flags;
}
public TypeLibTypeFlags Value =>
this._val;
}
}
|
Java | UTF-8 | 868 | 1.789063 | 2 | [] | no_license |
package ee.tenman.investing.integration.yieldwatchnet.api;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import java.math.BigDecimal;
@Data
@SuppressWarnings("unused")
public class Currencies {
@JsonProperty("BTCB")
private BigDecimal btcb;
@JsonProperty("EUR")
private BigDecimal eur;
@JsonProperty("GBP")
private BigDecimal gbp;
@JsonProperty("JPY")
private BigDecimal jpy;
@JsonProperty("RMB")
private BigDecimal rmb;
@JsonProperty("WBNB")
private BigDecimal wbnb;
@JsonProperty("AUD")
private BigDecimal aud;
@JsonProperty("BRL")
private BigDecimal brl;
@JsonProperty("HKD")
private BigDecimal hkd;
@JsonProperty("KRW")
private BigDecimal krw;
@JsonProperty("RUB")
private BigDecimal rub;
@JsonProperty("SGD")
private BigDecimal sgd;
}
|
Python | UTF-8 | 28,841 | 2.6875 | 3 | [] | no_license | # Python 3.7
"""
File: parsing.py
Author: Shengyuan Wang
Date: Jun 1, 2019
Last update: May 26, 2020
Purpose: Collect and parse individual protein individual chains data, including protein description,
protein sequence with start/end position, associate nucleotide sequence with accession number and
start/end position, DSSP secondary structure.
Input files: PISCES id30 list, PISCES individual protein chain description and sequence, PDB files, DSSP files.
Output files: PISCES clean file, TBLASTN files, clean TBLASTN files, final protein individual chain files with
codon, amino acid, residue number, coordinates, DSSP.
Notices: 1. Proteins data are downloaded from PDB have the following limitations: Resolution <= 2.0, R-factor <=
0.25, sequence length between 100-1000, sequence identity <= 30%.
2. PDB protein sequence files need to be cleaned before use.
3. After obtain TBLASTN files, check organism, remove '-', check 3' -> 5' or 5' -> 3',
perform longest_common_sequence between PISCES protein sequence and TBLASTN nucleotide translated
sequence.
4. The longest_common_sequences in this case set to at least 30 residues.
"""
import os
import glob
import pandas as pd
from time import sleep
import shutil
import urllib.request as request
from contextlib import closing
from Bio.Blast import NCBIWWW
from Bio.Blast import NCBIXML
from Bio import Entrez
from Bio.Seq import Seq
from Bio.Alphabet import generic_dna
def prepare_pdb_file(input_dir, pdb_ori_id, pdb_ori_csv, output_dir, pdb_clean_file):
"""
Protein chains are downloaded from PDB website with a customized report: PDB ID, Chain ID, R Free,
Structure Title, Exp. Method, Resolution, Classification, Uniprot Acc, Source, EC No, Chain Length, Sequence and
Secondary Structure in csv file.
pdb_ori_id file contains protein id and chain number, pdb_ori_csv contains protein entries details. Both files
are downloaded from PDB website with limits as follow: Resolution <= 2.0, R-factor free <= 0.25, seq_len between
100 - 1000, chain sequence identity <= 30%.
"""
f_id = list(open(os.path.join(input_dir, pdb_ori_id), 'r'))
f_csv = pd.read_csv(os.path.join(input_dir, pdb_ori_csv))
g = open(os.path.join(output_dir, pdb_clean_file), 'a')
# Convert number to alphabet for protein chains.
num_to_alphabet = {'1': 'A', '2': 'B', '3': 'C', '4': 'D', '5': 'E', '6': 'F', '7': 'G', '8': 'H', '9': 'I',
'10': 'J', '11': 'K', '12': 'L', '13': 'M', '14': 'N', '15': 'O', '16': 'P', '17': 'Q',
'18': 'R', '19': 'S', '20': 'T', '21': 'U', '22': 'V', '23': 'W', '24': 'X', '25': 'Y',
'26': 'Z'}
pdbid_list = []
for i in range(len(f_id)):
pdbid_list.append(f_id[i][:4] + num_to_alphabet[f_id[i][5]])
f_csv_id = f_csv['PDB ID']
f_csv_chain = f_csv['Chain ID']
f_csv_rf = f_csv['R Free']
f_csv_title = f_csv['Structure Title']
f_csv_r = f_csv['Resolution']
f_csv_class = f_csv['Classification']
f_csv_uni = f_csv['Uniprot Acc']
f_csv_source = f_csv['Source']
f_csv_len = f_csv['Chain Length']
f_csv_ss = f_csv['Sequence and Secondary Structure']
for i in range(len(f_csv_id)):
if len(f_csv_id[i]) > 4:
pid = f_csv_id[i][0] + f_csv_id[i][4] + f_csv_id[i][-2:]
else:
pid = f_csv_id[i]
pdbid = str(pid + f_csv_chain[i])
if pdbid in pdbid_list:
loc = f_csv_ss[i].find('#')
seq = str(f_csv_ss[i][:loc])
ss = str(f_csv_ss[i][loc + 1:])
g.writelines('>' + pdbid + '\t' + str("%.3f" % float(f_csv_rf[i])) + '\t' + str(f_csv_title[i]) + '\t' +
str(f_csv_r[i]) + '\t' + str(f_csv_class[i]) + '\t' + str(f_csv_uni[i]) + '\t' +
str(f_csv_source[i]) + '\t' + str(f_csv_len[i]) + '\n')
g.writelines(seq + '\n')
g.writelines(ss + '\n' + '\n')
def tblastn(input_dir, pdb_clean_file, output_dir):
"""
Input protein file with description on the first line and FASTA sequence on the next line. Very time-consuming,
better to perform multi-thread.
"""
f = list(open(os.path.join(input_dir, pdb_clean_file), 'r'))
for i in range(len(f)):
if f[i][0] == '>':
file = str(f[i] + f[i + 1])
result_handle = NCBIWWW.qblast("tblastn", "nt", file)
blast_records = NCBIXML.parse(result_handle)
blast_record = next(blast_records)
g = open(os.path.join(output_dir, "%s_tblastn" % str(f[i][1:6])), 'a')
for alignment in blast_record.alignments:
for hsp in alignment.hsps:
if hsp.expect < 0.1:
g.writelines('>' + alignment.title + '\n')
g.writelines(str(hsp.align_length) + '\t' + str(hsp.identities) + '\t' + str(hsp.query_start) +
'\t' + str(hsp.query_end) + '\t' + str(hsp.query) + '\t' + str(hsp.sbjct_start) +
'\t' + str(hsp.sbjct_end) + '\t' + str(hsp.sbjct) + '\t' + str(hsp.match) + '\n')
g.close()
def find(str, ch):
for i, ltr in enumerate(str):
if ltr == ch:
yield i
def extract_correct_tblastn(input_dir, pdb_clean_file, tblastn_dir, output):
f = list(open(os.path.join(input_dir, pdb_clean_file), 'r'))
g = open(os.path.join(input_dir, output), 'a')
for i in range(len(f)):
if f[i][0] == '>':
pdb_id = f[i][1:6]
pdb_organism = [m.split('\t', 7)[6] for m in [f[i][:-1]]][0]
pdb_organism_short = pdb_organism.lower()
ss = f[i + 2][:-1]
if ' ' in pdb_organism:
pdb_organism_split = pdb_organism.split()
pdb_organism_short = pdb_organism_split[0].lower()
# Human immunodeficiency virus was written short in TBLASTN files.
if "Human immunodeficiency virus" in pdb_organism_short:
pdb_organism_short = 'hiv'
# Check if TBLASTN file exists in database.
if os.path.isfile(os.path.join(tblastn_dir, "%s_tblastn" % pdb_id)):
f_tblastn = list(open(os.path.join(tblastn_dir, "%s_tblastn" % pdb_id), 'r'))
for j in range(len(f_tblastn)):
if f_tblastn[j][0] == '>':
try:
end = int(list(find(f_tblastn[j], " "))[2])
except IndexError:
end = len(f_tblastn[j])
# Remove predicted and synthetic proteins.
if 'predicted' in f_tblastn[j][:end].lower() or 'synthetic' in f_tblastn[j][:end].lower():
pass
else:
acc_start = int(list(find(f_tblastn[j], "|"))[2]) + 1
acc_end = int(list(find(f_tblastn[j], "|"))[3])
acc = f_tblastn[j][acc_start:acc_end]
align_len = [m.split('\t', 1)[0] for m in [f_tblastn[j + 1][:-1]]][0]
identity = [m.split('\t', 2)[1] for m in [f_tblastn[j + 1][:-1]]][0]
query_start = [m.split('\t', 3)[2] for m in [f_tblastn[j + 1][:-1]]][0]
query_end = [m.split('\t', 4)[3] for m in [f_tblastn[j + 1][:-1]]][0]
query = [m.split('\t', 5)[4] for m in [f_tblastn[j + 1][:-1]]][0]
subject_1 = int([m.split('\t', 6)[5] for m in [f_tblastn[j + 1][:-1]]][0])
subject_2 = int([m.split('\t', 7)[6] for m in [f_tblastn[j + 1][:-1]]][0])
subject_start, subject_end = str(min(subject_1, subject_2)), str(max(subject_1, subject_2))
subject = [m.split('\t', 8)[7] for m in [f_tblastn[j + 1][:-1]]][0]
query_ss = ss[int(query_start) - 1:int(query_end)]
# Only extract TBLASTN results if organism same as PDB or (match identity >=0.96 and
# match length >= 100).
if pdb_organism_short in f_tblastn[j][:end].lower() or \
(int(align_len) >= 100 and int(identity) / int(align_len) >= 0.96):
g.writelines('>' + pdb_id + '\t' + acc + '\t' + align_len + '\t' + identity + '\t' +
query_start + '\t' + query_end + '\t' + subject_start + '\t' + subject_end
+ '\t' + pdb_organism + '\n')
g.writelines('$' + query + '\n')
g.writelines('%' + subject + '\n')
g.writelines('&' + query_ss + '\n')
break
def extract_nt_seq(input_dir, tblastn_file, output):
f = list(open(os.path.join(input_dir, tblastn_file), 'r'))
g = open(os.path.join(input_dir, output), 'a')
for i in range(len(f)):
if f[i][0] == '>':
acc = [m.split('\t', 2)[1] for m in [f[i]]][0]
start = int([m.split('\t', 7)[6] for m in [f[i]]][0])
end = int([m.split('\t', 8)[7] for m in [f[i]]][0])
Entrez.email = 'michaelwang1335@gmail.com'
handle = Entrez.efetch(db='nucleotide', id=acc, rettype='fasta', retmode='text', seq_start=start,
seq_stop=end, api_key='fb157a95528a202add3c042769fb44071807')
sequence = ''
handletext = (str(handle.read()))
splithandle = handletext.split("\n")
for line in splithandle:
if line.startswith('>'):
pass
else:
sequence += line.strip()
g.writelines(f[i:i + 4])
g.writelines('@' + sequence + '\n')
sleep(0.1)
g.close()
def correct_ntseq(path, tblastn_ntseq_file, output):
"""parsing tblastn files"""
f_ntseq = list(open(os.path.join(path, tblastn_ntseq_file), 'r'))
g_correct_ntseq = open(os.path.join(path, output), 'a')
for i in range(len(f_ntseq)):
if f_ntseq[i][0] == '>':
query = f_ntseq[i + 1][1:-1]
# Remove '-' in query.
if '-' in query:
query = query.replace("-", "")
subject = f_ntseq[i + 2][1:-1]
# Remove '-' in subject.
# Do not remove '*' in subject, will be removed when longest common sequence performed.
if '-' in subject:
subject = subject.replace("-", "")
ss = f_ntseq[i + 3][1:-1]
ntseq = f_ntseq[i + 4][1:-1]
# Replace special character in nucleotide sequences to the first choice, based on IUPAC codes.
IUPAC_dic = {'Y': 'C', 'R': 'A', 'W': 'A', 'S': 'G', 'K': 'T', 'M': 'C', 'D': 'A', 'V': 'A', 'H': 'A',
'B': 'C', 'X': 'A', 'N': 'A'}
ntseq = "".join([IUPAC_dic.get(m, m) for m in ntseq])
# If 'X's in subject, remove them and corresponding nucleotide sequence.
if 'X' in subject:
nt_copy = ntseq
nt_rev_copy = ntseq
Xpos = [pos for pos, char in enumerate(subject) if char == 'X']
Xpos_nt = []
Xpos_nt_rev = []
for j in range(len(Xpos)):
Xpos_nt.append(Xpos[j] * 3)
Xpos_nt.append(Xpos[j] * 3 + 1)
Xpos_nt.append(Xpos[j] * 3 + 2)
Xpos_nt_rev.append(len(nt_rev_copy) - Xpos[j] * 3 - 1)
Xpos_nt_rev.append(len(nt_rev_copy) - Xpos[j] * 3 - 2)
Xpos_nt_rev.append(len(nt_rev_copy) - Xpos[j] * 3 - 3)
subject = subject.replace("X", "")
nt_copy = ''.join([nt_copy[j] for j in range(len(nt_copy)) if j not in Xpos_nt])
nt_rev_copy = ''.join([nt_rev_copy[j] for j in range(len(nt_rev_copy)) if j not in Xpos_nt_rev])
nt_copy_seq = Seq(nt_copy, generic_dna)
nt_copy_t = nt_copy_seq.translate()
nt_rev_copy_seq = Seq(nt_rev_copy, generic_dna)
nt_rev_rev_copy_t = nt_rev_copy_seq.reverse_complement().translate()
if nt_copy_t == subject:
ntseq = str(nt_copy_seq)
elif nt_rev_rev_copy_t == subject:
ntseq = str(nt_rev_copy_seq)
else:
print('Error in: ', f_ntseq[i][1:6], ' after remove "X"')
ntseq_dna = Seq(ntseq, generic_dna)
ntseq_dna_rev = ntseq_dna.reverse_complement()
# If nt sequence read from 3 to 5, mark as '1' for next step use, else mark as '0'.
if ntseq_dna.translate() == subject:
g_correct_ntseq.writelines(f_ntseq[i][:-1] + '\t' + '0' + '\n')
g_correct_ntseq.writelines('$' + query + '\n')
g_correct_ntseq.writelines('%' + subject + '\n')
g_correct_ntseq.writelines('&' + ss + '\n')
g_correct_ntseq.writelines('@' + ntseq_dna + '\n')
elif ntseq_dna_rev.translate() == subject:
g_correct_ntseq.writelines(f_ntseq[i][:-1] + '\t' + '1' + '\n')
g_correct_ntseq.writelines('$' + query + '\n')
g_correct_ntseq.writelines('%' + subject + '\n')
g_correct_ntseq.writelines('&' + ss + '\n')
g_correct_ntseq.writelines('@' + ntseq_dna + '\n')
# Print error if translated nt sequence not equal to subject sequence.
else:
print('Error in: ', f_ntseq[i][1:6])
def longest_substring(s1, s2):
t = [[0] * (1 + len(s2)) for i in range(1 + len(s1))]
l, xl, yl = 0, 0, 0
for x in range(1, 1 + len(s1)):
for y in range(1, 1 + len(s2)):
if s1[x - 1] == s2[y - 1]:
t[x][y] = t[x - 1][y - 1] + 1
if t[x][y] > l:
l = t[x][y]
xl = x
yl = y
else:
t[x][y] = 0
# Return sequence length, query_start, query_end, query_common_seq, subject_start, subject_end, subject_common_seq.
return l, xl - l, xl, s1[xl - l: xl], yl - l, yl, s2[yl - l:yl]
def ntseq_longest_common_string(path, correct_ntseq_file, total_match_ntseq_file, min_len):
"""min_len is the minimum match sequence length."""
f = list(open(os.path.join(path, correct_ntseq_file), 'r'))
g = open(os.path.join(path, total_match_ntseq_file), 'a')
for i in range(len(f)):
if f[i][0] == '>':
pdb_id = f[i][1:6]
acc = [m.split('\t', 2)[1] for m in [f[i]]][0]
query_start = int([m.split('\t', 5)[4] for m in [f[i]]][0])
nt_start = int([m.split('\t', 7)[6] for m in [f[i]]][0])
nt_end = int([m.split('\t', 8)[7] for m in [f[i]]][0])
organism = [m.split('\t', 9)[8] for m in [f[i]]][0]
query = f[i + 1][1:-1]
subject = f[i + 2][1:-1]
ss = f[i + 3][1:-1]
ntseq = f[i + 4][1:-1]
rev_mark = f[i][-2]
match_len, match_query_start, match_query_end, match_query, match_subject_start, match_subject_end, \
match_subject = longest_substring(query, subject)
match_ss = ss[match_query_start:match_query_end]
if match_len > min_len:
# if ntseq read from 5 to 3, rev_mark = '0'.
if rev_mark == '0':
match_ntseq_start = match_subject_start * 3
match_ntseq_end = match_subject_start * 3 + match_len * 3
match_ntseq = ntseq[match_ntseq_start:match_ntseq_end]
g.writelines('>' + pdb_id + '\t' + acc + '\t' + str(match_len) + '\t' +
str(query_start + match_query_start) + '\t' +
str(query_start + match_query_start + match_len - 1) + '\t' +
str(nt_start + match_query_start * 3) + '\t' +
str(nt_start + match_query_start * 3 + match_len * 3 - 1) + '\t' + organism + '\t' +
'0' + '\n')
g.writelines('$' + match_query + '\n')
g.writelines('&' + match_ss + '\n')
g.writelines('@' + match_ntseq + '\n')
# if ntseq read from 3 to 5, rev_mark = '1'.
elif rev_mark == '1':
match_ntseq_end = len(ntseq) - match_subject_start * 3
match_ntseq_start = match_ntseq_end - match_len * 3
match_ntseq = Seq(ntseq[match_ntseq_start:match_ntseq_end], generic_dna)
match_ntSeq = match_ntseq.reverse_complement()
# Watch out: careful about the start and end position of nucleotide sequence.
g.writelines('>' + pdb_id + '\t' + acc + '\t' + str(match_len) + '\t' +
str(query_start + match_query_start) + '\t' +
str(query_start + match_query_start + match_len - 1) + '\t' +
str(nt_end - match_subject_start * 3 - match_len * 3 + 1) + '\t' +
str(nt_end - match_subject_start * 3) + '\t' + organism + '\t' + '1' + '\n')
g.writelines('$' + match_query + '\n')
g.writelines('&' + match_ss + '\n')
g.writelines('@' + match_ntSeq + '\n')
g.close()
def aaa_to_a(aaa):
"""Convert 3-digits amino acids to 1-digit."""
dic = {'ALA': 'A', 'CYS': 'C', 'ASP': 'D', 'GLU': 'E', 'PHE': 'F', 'GLY': 'G', 'HIS': 'H', 'ILE': 'I', 'LYS': 'K',
'LEU': 'L', 'MET': 'M', 'ASN': 'N', 'PRO': 'P', 'GLN': 'Q', 'ARG': 'R', 'SER': 'S', 'THR': 'T', 'VAL': 'V',
'TRP': 'W', 'TYR': 'Y'}
return dic[aaa]
def pdb_rewrite(pdb_match_dir, pdb_match_file, pdb_dir, output_dir):
"""
Need to download pdb files first.
Rewrite pdb file, only keep CA and remove alternative points.
"""
f_pdb_match = list(open(os.path.join(pdb_match_dir, pdb_match_file), 'r'))
for j in range(len(f_pdb_match)):
if f_pdb_match[j][0] == '>':
pdb_id = f_pdb_match[j][1:6]
f = list(open(os.path.join(pdb_dir, "%s.pdb" % pdb_id[:4]), 'r'))
g = open(os.path.join(output_dir, "%s_pdb_rewrite" % pdb_id), 'a')
for i in range(len(f)):
if f[i][0:4] == 'ATOM' and f[i][21] == pdb_id[4] and f[i][13:15] == 'CA':
aaa = f[i][17:20]
# SEC, UNK are not consider as amino acid in this research.
amino_acid = ['ALA', 'CYS', 'ASP', 'GLU', 'PHE', 'GLY', 'HIS', 'ILE', 'LYS', 'LEU', 'MET', 'ASN',
'PRO', 'GLN', 'ARG', 'SER', 'THR', 'VAL', 'TRP', 'TYR']
if aaa in amino_acid:
a = aaa_to_a(aaa)
else:
a = 'X'
# 1-digit amino acid + residue# + CA_coordinates.
g.writelines(a + '\t' + str(int(f[i][22:26])) + '\t' + str(float(f[i][30:38])) + '\t' +
str(float(f[i][38:46])) + '\t' + str(float(f[i][46:54])) + '\n')
g.close()
def nt_to_codon(nt):
"""Convert nucleotide codon to special marked amino acid."""
dic = {'GCT': 'A1', 'GCC': 'A2', 'GCA': 'A3', 'GCG': 'A4', 'TGT': 'C1', 'TGC': 'C2', 'GAT': 'D1', 'GAC': 'D2',
'GAA': 'E1', 'GAG': 'E2', 'TTT': 'F1', 'TTC': 'F2', 'GGT': 'G1', 'GGC': 'G2', 'GGA': 'G3', 'GGG': 'G4',
'CAT': 'H1', 'CAC': 'H2', 'ATT': 'I1', 'ATC': 'I2', 'ATA': 'I3', 'AAA': 'K1', 'AAG': 'K2', 'TTA': 'L1',
'TTG': 'L2', 'CTT': 'L3', 'CTC': 'L4', 'CTA': 'L5', 'CTG': 'L6', 'ATG': 'M1', 'AAT': 'N1', 'AAC': 'N2',
'CCT': 'P1', 'CCC': 'P2', 'CCA': 'P3', 'CCG': 'P4', 'CAA': 'Q1', 'CAG': 'Q2', 'CGT': 'R1', 'CGC': 'R2',
'CGA': 'R3', 'CGG': 'R4', 'AGA': 'R5', 'AGG': 'R6', 'TCT': 'S1', 'TCC': 'S2', 'TCA': 'S3', 'TCG': 'S4',
'AGT': 'S5', 'AGC': 'S6', 'ACT': 'T1', 'ACC': 'T2', 'ACA': 'T3', 'ACG': 'T4', 'GTT': 'V1', 'GTC': 'V2',
'GTA': 'V3', 'GTG': 'V4', 'TGG': 'W1', 'TAT': 'Y1', 'TAC': 'Y2'}
# Few ntseq has few special characters, replace to one of the choice.
special = ['U', 'R', 'Y', 'S', 'W', 'K', 'M', 'B', 'D', 'H', 'V', 'N', '.', ',']
if any(alphabet in nt for alphabet in special):
# Based on IUPAC nucleotide code, replace special character to their first Base choice.
nt = nt.replace('R', 'A').replace('Y', 'C').replace('S', 'G').replace('S', 'G').replace('W', 'A'). \
replace('K', 'G').replace('M', 'A').replace('B', 'C').replace('D', 'A').replace('H', 'A'). \
replace('V', 'A').replace('N', 'A')
return dic[nt]
def codon_to_pdb_dssp(pdb_rewrite_dir, pdb_rewrite_id, seq_dic, output_dir, bad_dir):
"""
Convert amino acids into codons in pdb files, add DSSP. seq_dic contains pdb_id and corresponding nt and ss
sequence.
"""
f = list(open(os.path.join(pdb_rewrite_dir, "%s_pdb_rewrite" % pdb_rewrite_id), 'r'))
pdb_seq = ''
res_num = 0
res_num_save_line = []
for i in range(len(f)):
res_num_next = [j.split('\t', 2)[1] for j in [f[i][:-1]]][0]
# Watch out: same position mat have more than one residue options: only save the previous one.
if res_num_next != res_num:
pdb_seq += f[i][0]
res_num = res_num_next
# Save those lines that used for sequence alignment.
res_num_save_line.append(i)
ntseq_aa_seq = ''
ntseq_nt_seq = ''
ss_seq = ''
if pdb_rewrite_id.upper() in seq_dic:
ntseq_aa_seq = seq_dic[pdb_rewrite_id.upper()][0]
ntseq_nt_seq = seq_dic[pdb_rewrite_id.upper()][2]
ss_seq = seq_dic[pdb_rewrite_id.upper()][1]
if ntseq_aa_seq is not '':
# Find longest common substring.
match_len, match_query_start, match_query_end, match_query, match_subject_start, match_subject_end, \
match_subject = longest_substring(pdb_seq, ntseq_aa_seq)
# Only write to codon_pdb_dssp file if match sequence length > 19.
if match_len > 19:
g = open(os.path.join(output_dir, "%s_pdb_codon_dssp" % pdb_rewrite_id), 'a')
for i in range(match_len):
nt = ntseq_nt_seq[int(match_subject_start * 3 + i * 3):int(match_subject_start * 3 + i * 3 + 3)]
ss = ss_seq[int(match_subject_start + i):int(match_subject_start + i + 1)]
# Convert nucleotide codon to special marked amino acid.
nt_codon = nt_to_codon(nt)
g.writelines(nt_codon + '\t' + f[res_num_save_line[match_query_start + i]][:-1] + '\t' + ss + '\n')
g.close()
else:
g_bad = open(os.path.join(bad_dir, 'bad_file'), 'a')
g_bad.writelines("Match sequence less than 20: " + pdb_rewrite_id + '\n')
else:
g_bad = open(os.path.join(bad_dir, 'bad_file'), 'a')
g_bad.writelines("No ntseq find for: " + pdb_rewrite_id + '\n')
def download_dssp(dssp_url, dssp_id, output_dir):
"""
If the secondary structure was downloaded from PDB website at the beginning, the alternative way is
downloading DSSP from ftp://ftp.cmbi.ru.nl/pub/molbio/data/dssp. The following function helps to download DSSP
and add it to corresponding pdb files. DSSP file contains CA coordinates, so no need to download pdb files.
"""
with closing(request.urlopen("%s/%s.dssp" % (dssp_url, dssp_id))) as r:
with open(output_dir, 'wb') as f:
shutil.copyfileobj(r, f)
def codon_to_pdb_dssp_v2(dssp_dir, seq_dic, output_dir, bad_dir):
"""Use dssp files instead of pdb file. Protein sequence, CA and coordinates may slightly different."""
for key, value in seq_dic.items():
f = list(open(os.path.join(dssp_dir, "%s_dssp" % key[:4].lower()), 'r'))
pdb_seq = ''
res_num_save_line = []
# Watch out: same position mat have more than one residue options: only save the previous one.
for i in range(len(f)):
if f[i][2] == '#' and f[i + 1][11] == key[4]:
res_num = int(float(f[i + 1][5:10]))
res_num_save_line.append(i + 1)
pdb_seq += f[i + 1][13]
for j in range(i + 2, len(f)):
if f[j][11] == key[4]:
res_num_next = int(float(f[j][5:10]))
if res_num_next != res_num:
pdb_seq += f[j][13]
res_num = res_num_next
# Save those lines that used for sequence alignment.
res_num_save_line.append(j)
break
ntseq_aa_seq = seq_dic[key][0]
ntseq_nt_seq = seq_dic[key][2]
ss_seq = seq_dic[key][1]
if ntseq_aa_seq is not '':
# Find longest common substring.
match_len, match_query_start, match_query_end, match_query, match_subject_start, match_subject_end, \
match_subject = longest_substring(pdb_seq, ntseq_aa_seq)
# Only write to codon_pdb_dssp file if match sequence length > 19.
if match_len > 19:
g = open(os.path.join(output_dir, "%s_pdb_codon_dssp_v2" % key), 'a')
for i in range(match_len):
nt = ntseq_nt_seq[int(match_subject_start * 3 + i * 3):int(match_subject_start * 3 + i * 3 + 3)]
ss = ss_seq[int(match_subject_start + i):int(match_subject_start + i + 1)]
# Convert nucleotide codon to special marked amino acid.
nt_codon = nt_to_codon(nt)
g.writelines(nt_codon + '\t' + f[res_num_save_line[match_query_start + i]][13] + '\t' +
str(int(float(f[res_num_save_line[match_query_start + i]][5:10]))) + '\t' +
str(float(f[res_num_save_line[match_query_start + i]][116:122])) + '\t' +
str(float(f[res_num_save_line[match_query_start + i]][123:129])) + '\t' +
str(float(f[res_num_save_line[match_query_start + i]][130:136])) + '\t' + ss + '\n')
g.close()
else:
g_bad = open(os.path.join(bad_dir, 'bad_file'), 'a')
g_bad.writelines("Match sequence less than 20: " + key + '\n')
else:
g_bad = open(os.path.join(bad_dir, 'bad_file'), 'a')
g_bad.writelines("No ntseq find for: " + key + '\n')
if __name__ == '__main__':
"""
First part: Correlate PDB original file to nucleotide sequence.
"""
ori_dir = 'INDIVIDUAL/PDB_ori'
tblastn_dir = 'INDIVIDUAL/TBLASTN'
pdb_ori_id = 'PDBID_pc30_R2.0_Rf0.25_100_1000.txt'
pdb_ori_csv = 'PDB_pc30_R2.0_Rf0.25_100_1000.csv'
prepare_pdb_file(ori_dir, pdb_ori_id, pdb_ori_csv, ori_dir, 'PDB_clean.txt')
tblastn(ori_dir, 'PDB_clean.txt', tblastn_dir)
extract_correct_tblastn(ori_dir, 'PDB_clean.txt', tblastn_dir, 'PDB_tblastn')
extract_nt_seq(ori_dir, 'PDB_tblastn', 'PDB_nt')
correct_ntseq(ori_dir, 'PDB_nt', 'PDB_correct_nt')
ntseq_longest_common_string(ori_dir, 'PDB_correct_nt', 'PDB_match.txt', 20)
"""
Second part: Add nucleotide sequence and dssp to pdb files.
"""
pdb_dir = 'INDIVIDUAL/PDB'
pdb_rewrite_dir = 'INDIVIDUAL/backup/PDB_rewrite'
pdb_codon_dssp_dir = 'INDIVIDUAL/PDB_codon_dssp'
pdb_rewrite(ori_dir, 'PDB_match.txt', pdb_dir, pdb_rewrite_dir)
ntseq_dic = {}
f_ntseq = list(open(os.path.join(ori_dir, 'PDB_match.txt'), 'r'))
for i in range(len(f_ntseq)):
if f_ntseq[i][0] == '>':
pdbid = f_ntseq[i][1:6]
ntseq_dic[pdbid] = []
ntseq_dic[pdbid].append(f_ntseq[i + 1][1:-1])
ntseq_dic[pdbid].append(f_ntseq[i + 2][1:-1])
ntseq_dic[pdbid].append(f_ntseq[i + 3][1:-1])
pdb_rewrite_list = []
for filename in glob.glob(os.path.join(pdb_rewrite_dir, "*_pdb_rewrite")):
pdb_rewrite_list.append(filename[-17:-12])
for i in range(len(pdb_rewrite_list)):
codon_to_pdb_dssp(pdb_rewrite_dir, pdb_rewrite_list[i], ntseq_dic, pdb_codon_dssp_dir, ori_dir) |
Java | UTF-8 | 6,709 | 2.015625 | 2 | [] | no_license | package page;
import static core.DriverFactory.getDriver;
import org.openqa.selenium.support.PageFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import core.Propriedades;
public class SitePage {
public SitePage() {
PageFactory.initElements(getDriver(), this);
}
public void queEstouNoSite() throws IOException {
getDriver().get(Propriedades.URL);
}
public void clicoMenuComprar() throws IOException {
WebDriverWait espera = new WebDriverWait(getDriver(), 20);
WebElement menuComprar = espera.until(ExpectedConditions.elementToBeClickable(By.xpath("//li[contains(text(),'Comprar')]")));
menuComprar.click();
}
public void verTodasMarcas() throws IOException {
List<String> abas = new ArrayList<String>(getDriver().getWindowHandles());
getDriver().switchTo().window(abas.get(1));
WebDriverWait espera = new WebDriverWait(getDriver(), 20);
WebElement opcaoVerMarcas = espera.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[contains(text(),'Ver todas as marcas')]")));
opcaoVerMarcas.click();
}
public void escolhoMarcaHonda() throws IOException {
List<String> abas = new ArrayList<String>(getDriver().getWindowHandles());
getDriver().switchTo().window(abas.get(1));
WebDriverWait espera = new WebDriverWait(getDriver(), 60);
WebElement campoMarca = espera.until(ExpectedConditions.elementToBeClickable(By.xpath("//small[contains(text(),'honda')]")));
campoMarca.click();
}
public void escolhoModeloCity() throws IOException {
List<String> abas = new ArrayList<String>(getDriver().getWindowHandles());
getDriver().switchTo().window(abas.get(1));
WebDriverWait espera = new WebDriverWait(getDriver(), 30);
WebElement opcaoModelo = espera.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[contains(@class,'Filters__line Filters__line--gray Filters__line--icon Filters__line--icon--right')]")));
opcaoModelo.click();
WebElement modeloCity = espera.until(ExpectedConditions.elementToBeClickable(By.linkText("CITY")));
modeloCity.click();
}
public void escolhoVersao() throws IOException {
List<String> abas = new ArrayList<String>(getDriver().getWindowHandles());
getDriver().switchTo().window(abas.get(1));
WebDriverWait espera = new WebDriverWait(getDriver(), 10);
WebElement opcaoVersao = espera.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[contains(@class,'Filters__line Filters__line--icon Filters__line--icon Filters__line--icon--right Filters__line--gray')]")));
opcaoVersao.click();
WebElement versao15 = espera.until(ExpectedConditions.elementToBeClickable(By.linkText("1.5 DX 16V FLEX 4P MANUAL")));
versao15.click();
}
public void clicoMenuCarrosNovosUsados() throws IOException {
WebDriverWait espera = new WebDriverWait(getDriver(), 30);
WebElement menuCarroNovosUsados = espera.until(ExpectedConditions.presenceOfElementLocated(By.linkText("Carros usados ou seminovos")));
menuCarroNovosUsados.click();
}
public void aceitoCookies() throws IOException {
WebDriverWait espera = new WebDriverWait(getDriver(), 30);
WebElement cookies = espera.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[@class='sc-htoDjs gtMZoW']")));
cookies.click();
}
public void visualizoPaginadeCarrosUsadosESemiNovos() throws IOException {
List<String> abas = new ArrayList<String>(getDriver().getWindowHandles());
getDriver().switchTo().window(abas.get(1));
String URL = getDriver().getCurrentUrl();
Assert.assertEquals(URL, "https://www.webmotors.com.br/carros-usados/estoque?inst=header:webmotors:header-deslogado::carros-usados-ou-seminovos" );
}
public void validaSeCarregouAMarcaHonda() throws IOException {
List<String> abas = new ArrayList<String>(getDriver().getWindowHandles());
getDriver().switchTo().window(abas.get(1));
String PaginaMarcaDesejada = "Honda Usados e Seminovos";
WebDriverWait espera = new WebDriverWait(getDriver(), 60);
WebElement PaginaMarcaCarregada = espera.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//h1[@class='title-search']")));
PaginaMarcaCarregada.getText();
Assert.assertEquals(PaginaMarcaDesejada, PaginaMarcaCarregada.getText());
}
public void validaSeCarregouAModeloCity() throws IOException {
List<String> abas = new ArrayList<String>(getDriver().getWindowHandles());
getDriver().switchTo().window(abas.get(1));
String PaginaModeloDesejada = "Honda City Usados e Seminovos";
WebDriverWait espera = new WebDriverWait(getDriver(), 80);
WebElement PaginaModeloCarregada = espera.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h1[contains(@class,'title-search')]")));
PaginaModeloCarregada.getText();
Assert.assertEquals(PaginaModeloDesejada, PaginaModeloCarregada.getText());
}
public void validaSeCarregouAVersao() throws IOException {
List<String> abas = new ArrayList<String>(getDriver().getWindowHandles());
getDriver().switchTo().window(abas.get(1));
String PaginaVersao = "Honda City 1.5 Dx 16v Flex 4p Manual Usados e Seminovos";
WebDriverWait espera = new WebDriverWait(getDriver(), 60);
WebElement PaginaVersaoCarregada = espera.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//h1[@class='title-search']")));
Assert.assertEquals(PaginaVersao, PaginaVersaoCarregada.getText());
}
public void validaSeEstounaPaginaNovoESeminovos() throws IOException {
List<String> abas = new ArrayList<String>(getDriver().getWindowHandles());
getDriver().switchTo().window(abas.get(1));
String PaginSeminoNovosDesejada = "Carros Usados e Seminovos em Todo o Brasil";
WebDriverWait espera = new WebDriverWait(getDriver(), 60);
WebElement PaginaSemiNovoCarregada= espera.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//h1[@class='title-search']")));
Assert.assertEquals(PaginSeminoNovosDesejada, PaginaSemiNovoCarregada.getText());
}
public void validaSeRetornouMarcaModeloVersao() throws IOException {
List<String> abas = new ArrayList<String>(getDriver().getWindowHandles());
getDriver().switchTo().window(abas.get(1));
String PaginaVersao = "Honda City 1.5 Dx 16v Flex 4p Manual Usados e Seminovos";
WebDriverWait espera = new WebDriverWait(getDriver(), 60);
WebElement PaginaVersaoCarregada = espera.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//h1[@class='title-search']")));
Assert.assertEquals(PaginaVersao, PaginaVersaoCarregada.getText());
}
}
|
Shell | UTF-8 | 2,535 | 4.09375 | 4 | [
"Apache-2.0"
] | permissive | #!/bin/sh
usage="Usage: $(basename $0) [-h][-a account][-c comment][-p path] token url
-h - help
-w - wait for page to be cloned before returning (defaults to don't wait)
-l - print long url for created bolt (defaults to short url)
-a account - bo.lt account to put bolt in (defaults to first account)
-c comment - comment to associate with the create bolt (defaults to none)
-p path - path to give bolt
token - bolt secret token, generate here: https://bo.lt/app/settings#api-app-form
url - url to bolt
Creates a bolt from 'url' in the account associated with 'token' on BO.LT, http://bo.lt/
"
if ! which curl >/dev/null; then
echo "Error: unable to find the command 'curl', please install before running this command" >&2
exit 1
fi
account=
comment=
wait=0
link_name=short_url
while [ $# -gt 0 ]; do
case "$1" in
-h|-\?)
echo "$usage"
exit 0
;;
-w)
wait=1
;;
-l)
link_name=default_url
;;
-a)
if [ -z "$2" ]; then
echo "Error: option $1 expected argument" >&2
echo "$usage" >&2
exit 1
fi
account="$2"
shift
;;
-c)
if [ -z "$2" ]; then
echo "Error: option $1 expected argument" >&2
echo "$usage" >&2
exit 1
fi
comment="$2"
shift
;;
-p)
if [ -z "$2" ]; then
echo "Error: option $1 expected argument" >&2
echo "$usage" >&2
exit 1
fi
path="$2"
shift
;;
*)
break
;;
esac
shift
done
if [ $# -ne 2 ]; then
echo "Error: expect exactly 1 token and 1 url argument" >&2
echo "$usage" >&2
exit 1
fi
token="$1"
url="$2"
if [ -z "$path" ]; then
timestamp="$(date +%Y-%m-%d_%H_%M_%S)"
path=$(echo "$url/$timestamp" | sed -e 's/http:\/\///' -e 's/[^A-Za-z0-9\/\-\.\_]/-/g' -e 's/^[\/\_]//' -e 's/\/$//')
fi
action='curl --silent --get "https://api.bo.lt/bolt/create.plain" --data-urlencode "access_token=$token" --data-urlencode "url=$url" --data-urlencode "path=$path"'
if [ ! -z "$comment" ]; then
action="$action --data-urlencode \"comment=\$comment\""
fi
if [ ! -z "$account" ]; then
action="$action --data-urlencode \"account_id=\$account\""
fi
if [ "$wait" -eq "1" ]; then
action="$action --data-urlencode \"async=false\""
fi
bolt="$(eval $action)"
if echo "$bolt" | grep "error" >/dev/null; then
echo "Error: $(echo "$bolt" | grep "error.message" | awk -F "\t" '{print $2}')" >&2
exit 1
fi
echo "$bolt" | grep "bolt.$link_name" | awk -F "\t" '{print $2}'
|
Python | UTF-8 | 411 | 3.03125 | 3 | [] | no_license |
def euclidean(a, b):
c = a % b
return b if c == 0 else euclidean(b, c)
def extendedEuclideanAlgorithm(a, b):
if a != 0:
gcd, x, y = extendedEuclideanAlgorithm(b % a, a)
return (gcd, y - (b // a) * x, x)
else:
return (b, 0, 1)
def modInverse(a, n):
gcd, x, _ = extendedEuclideanAlgorithm(a, n)
if gcd == 1:
return x % n
return None
gcd = euclidean
|
Python | UTF-8 | 2,174 | 2.828125 | 3 | [
"BSD-3-Clause"
] | permissive | """Base class for metadata wrapper classes."""
import os
# Local import
class _geospatial(object):
"""
Base class used as interface for providing file-level metadata from
geospatial and temporal metadata files.
"""
def __init__(self):
self.unimpl_base_class()
def _add_checksum(self, dct):
"""Adds `checksum` and `checksum_type` to file info dict if they are accessible."""
md5_cksum = None
@staticmethod
def get_filesystem(fpath):
"""Returns a dict containing filesystem information"""
filesystem = {
"filename": os.path.basename(fpath),
"path": fpath,
"size": os.stat(fpath).st_size,
"symlinks": _geospatial.get_symlinks(fpath)
}
return filesystem
@staticmethod
def get_symlinks(path):
"""
Return a list of all the levels of symlinks (if any).
:param path: A string containing the path to examine.
:returns pathlist: A list of file paths corresponding to symlinks.
"""
paths_seen = []
while os.path.islink(path) and path not in paths_seen:
paths_seen.append(path)
path = os.readlink(path)
return paths_seen
def get_geospatial(self):
"""Returns a dict containing geospatial information"""
self.unimpl_base_class()
def get_temporal(self):
"""Returns a dict containing temporal information"""
self.unimpl_base_class()
def get_parameters(self):
"""Returns a dict containing parameter information"""
self.unimpl_base_class()
def get_properties(self):
"""
Return a ceda_di.metadata.product.Properties object populated with the
file's metadata.
:returns: A ceda_di.metadata.product.Properties object
"""
self.unimpl_base_class()
@staticmethod
def unimpl_base_class():
"""Throws relevant NotImplementedError."""
exception = \
"\"_geospatial\" is an abstract base class and is intended" + \
"to be used as an interface ONLY."
raise NotImplementedError(exception) |
C++ | UTF-8 | 10,634 | 2.734375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-philippe-de-muyter"
] | permissive | /*
config_file.hh - This file is part of MUSIC -
a code to generate multi-scale initial conditions
for cosmological simulations
Copyright (C) 2010 Oliver Hahn
*/
#ifndef __CONFIG_FILE_HH
#define __CONFIG_FILE_HH
#include <string>
#include <sstream>
#include <map>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <stdexcept>
#include <typeinfo>
#include "log.hh"
/*!
* @class config_file
* @brief provides read/write access to configuration options
*
* This class provides access to the configuration file. The
* configuration is stored in hash-pairs and can be queried and
* validated by the responsible class/routine
*/
class config_file {
//! current line number
unsigned m_iLine;
//! hash table for key/value pairs, stored as strings
std::map<std::string, std::string> m_Items;
public:
//! removes all white space from string source
/*!
* @param source the string to be trimmed
* @param delims a string of delimiting characters
* @return trimmed string
*/
std::string trim(std::string const& source, char const* delims = " \t\r\n") const{
std::string result(source);
//... skip initial whitespace ...
std::string::size_type index = result.find_last_not_of(delims);
if(index != std::string::npos)
result.erase(++index);
//... find beginning of trailing whitespace ...
index = result.find_first_not_of(delims);
//... remove trailing whitespace ...
if(index != std::string::npos)
result.erase(0, index);
else
result.erase();
return result;
}
//! converts between different variable types
/*!
* The main purpose of this function is to parse and convert
* a string argument into numbers, booleans, etc...
* @param ival the input value (typically a std::string)
* @param oval the interpreted/converted value
*/
template <class in_value, class out_value>
void convert( const in_value & ival, out_value & oval) const
{
std::stringstream ss;
ss << ival; //.. insert value into stream
ss >> oval; //.. retrieve value from stream
if (! ss.eof()) {
//.. conversion error
std::cerr << "Error: conversion of \'" << ival << "\' failed." << std::endl;
throw ErrInvalidConversion(std::string("invalid conversion to ")+typeid(out_value).name()+'.');
}
}
//! constructor of class config_file
/*! @param FileName the path/name of the configuration file to be parsed
*/
config_file( std::string const& FileName )
: m_iLine(0), m_Items()
{
std::ifstream file(FileName.c_str());
if( !file.is_open() )
throw std::runtime_error(std::string("Error: Could not open config file \'")+FileName+std::string("\'"));
std::string line;
std::string name;
std::string value;
std::string inSection;
int posEqual;
m_iLine=0;
//.. walk through all lines ..
while (std::getline(file,line)) {
++m_iLine;
//.. encounterd EOL ?
if (! line.length()) continue;
//.. encountered comment ?
unsigned long idx;
if( (idx=line.find_first_of("#;%")) != std::string::npos )
line.erase(idx);
//.. encountered section tag ?
if (line[0] == '[') {
inSection=trim(line.substr(1,line.find(']')-1));
continue;
}
//.. seek end of entry name ..
posEqual=line.find('=');
name = trim(line.substr(0,posEqual));
value = trim(line.substr(posEqual+1));
if( (size_t)posEqual==std::string::npos && (name.size()!=0||value.size()!=0) )
{
LOGWARN("Ignoring non-assignment in %s:%d",FileName.c_str(),m_iLine);
continue;
}
if(name.length()==0&&value.size()!=0)
{
LOGWARN("Ignoring assignment missing entry name in %s:%d",FileName.c_str(),m_iLine);
continue;
}
if(value.length()==0&&name.size()!=0)
{
LOGWARN("Empty entry will be ignored in %s:%d",FileName.c_str(),m_iLine);
continue;
}
if( value.length()==0&&name.size()==0)
continue;
//.. add key/value pair to hash table ..
if( m_Items.find(inSection+'/'+name) != m_Items.end() )
LOGWARN("Redeclaration overwrites previous value in %s:%d",FileName.c_str(),m_iLine);
m_Items[inSection+'/'+name] = value;
}
}
//! inserts a key/value pair in the hash map
/*! @param key the key value, usually "section/key"
* @param value the value of the key, also a string
*/
void insertValue( std::string const& key, std::string const& value )
{
m_Items[key] = value;
}
//! inserts a key/value pair in the hash map
/*! @param section section name. values are stored under "section/key"
* @param key the key value usually "section/key"
* @param value the value of the key, also a string
*/
void insertValue( std::string const& section, std::string const& key, std::string const& value )
{
m_Items[section+'/'+key] = value;
}
//! checks if a key is part of the hash map
/*! @param section the section name of the key
* @param key the key name to be checked
* @return true if the key is present, false otherwise
*/
bool containsKey( std::string const& section, std::string const& key )
{
std::map<std::string,std::string>::const_iterator i = m_Items.find(section+'/'+key);
if ( i == m_Items.end() )
return false;
return true;
}
//! checks if a key is part of the hash map
/*! @param key the key name to be checked
* @return true if the key is present, false otherwise
*/
bool containsKey( std::string const& key )
{
std::map<std::string,std::string>::const_iterator i = m_Items.find(key);
if ( i == m_Items.end() )
return false;
return true;
}
//! return value of a key
/*! returns the value of a given key, throws a ErrItemNotFound
* exception if the key is not available in the hash map.
* @param key the key name
* @return the value of the key
* @sa ErrItemNotFound
*/
template<class T> T getValue( std::string const& key ) const{
return getValue<T>( "", key );
}
//! return value of a key
/*! returns the value of a given key, throws a ErrItemNotFound
* exception if the key is not available in the hash map.
* @param section the section name for the key
* @param key the key name
* @return the value of the key
* @sa ErrItemNotFound
*/
template<class T> T getValue( std::string const& section, std::string const& key ) const
{
T r;
std::map<std::string,std::string>::const_iterator i = m_Items.find(section + '/' + key);
if ( i == m_Items.end() )
throw ErrItemNotFound('\'' + section + '/' + key + std::string("\' not found."));
convert(i->second,r);
return r;
}
//! exception safe version of getValue
/*! returns the value of a given key, returns a default value rather
* than a ErrItemNotFound exception if the key is not found.
* @param section the section name for the key
* @param key the key name
* @param default_value the value that is returned if the key is not found
* @return the key value (if key found) otherwise default_value
*/
template<class T> T getValueSafe( std::string const& section, std::string const& key, T default_value ) const
{
T r;
try{
r = getValue<T>( section, key );
} catch( ErrItemNotFound ) {
r = default_value;
}
return r;
}
//! exception safe version of getValue
/*! returns the value of a given key, returns a default value rather
* than a ErrItemNotFound exception if the key is not found.
* @param key the key name
* @param default_value the value that is returned if the key is not found
* @return the key value (if key found) otherwise default_value
*/
template<class T> T getValueSafe( std::string const& key, T default_value ) const
{
return getValueSafe( "", key, default_value );
}
//! dumps all key-value pairs to a std::ostream
void dump( std::ostream& out )
{
std::map<std::string,std::string>::const_iterator i = m_Items.begin();
while( i!=m_Items.end() )
{
if( i->second.length() > 0 )
out << std::setw(24) << std::left << i->first << " = " << i->second << std::endl;
++i;
}
}
void log_dump( void )
{
LOGUSER("List of all configuration options:");
std::map<std::string,std::string>::const_iterator i = m_Items.begin();
while( i!=m_Items.end() )
{
if( i->second.length() > 0 )
LOGUSER(" %24s = %s",(i->first).c_str(),(i->second).c_str());//out << std::setw(24) << std::left << i->first << " = " << i->second << std::endl;
++i;
}
}
//--- EXCEPTIONS ---
//! runtime error that is thrown if key is not found in getValue
class ErrItemNotFound : public std::runtime_error{
public:
ErrItemNotFound( std::string itemname )
: std::runtime_error( itemname.c_str() )
{}
};
//! runtime error that is thrown if type conversion fails
class ErrInvalidConversion : public std::runtime_error{
public:
ErrInvalidConversion( std::string errmsg )
: std::runtime_error( errmsg )
{}
};
//! runtime error that is thrown if identifier is not found in keys
class ErrIllegalIdentifier : public std::runtime_error{
public:
ErrIllegalIdentifier( std::string errmsg )
: std::runtime_error( errmsg )
{}
};
};
//==== below are template specialisations =======================================//
//... Function: getValue( strSection, strEntry ) ...
//... Descript: specialization of getValue for type boolean to interpret strings ...
//... like "true" and "false" etc.
//... converts the string to type bool, returns type bool ...
template<>
inline bool config_file::getValue<bool>( std::string const& strSection, std::string const& strEntry ) const{
std::string r1 = getValue<std::string>( strSection, strEntry );
if( r1=="true" || r1=="yes" || r1=="on" || r1=="1" )
return true;
if( r1=="false" || r1=="no" || r1=="off" || r1=="0" )
return false;
throw ErrIllegalIdentifier(std::string("Illegal identifier \'")+r1+std::string("\' in \'")+strEntry+std::string("\'."));
//return false;
}
template<>
inline bool config_file::getValueSafe<bool>( std::string const& strSection, std::string const& strEntry, bool defaultValue ) const{
std::string r1;
try{
r1 = getValue<std::string>( strSection, strEntry );
if( r1=="true" || r1=="yes" || r1=="on" || r1=="1" )
return true;
if( r1=="false" || r1=="no" || r1=="off" || r1=="0" )
return false;
} catch( ErrItemNotFound ) {
return defaultValue;
}
return defaultValue;
}
template<>
inline void config_file::convert<std::string,std::string>( const std::string & ival, std::string & oval) const
{
oval = ival;
}
#endif //__CONFIG_FILE_HH
|
Java | UTF-8 | 344 | 2.140625 | 2 | [] | no_license | package com.movieflix.app.repository;
import java.util.List;
import com.movieflix.app.entity.Video;
public interface VideoRepository {
Video getVideo(String videoId);
List<Video> getAllVideos();
void delete(Video video);
Video create(Video video);
Video getVideoByTitleYear(String title, int year);
Video update(Video video);
}
|
C++ | UTF-8 | 1,813 | 3.203125 | 3 | [
"MIT"
] | permissive | /*
Copyright (c) 2018 by CanftIn <wwc7033@gmail.com>
contact me at https://weibo.com/5632002270/profile
or http://www.canftin.com
MIT licence
*/
#pragma once
#include "Math.h"
template <typename T>
class Vec2
{
public:
T x, y;
public:
Vec2() {}
Vec2(T x, T y) : x(x), y(y) {}
Vec2(const Vec2& vec) : Vec2(vec.x, vec.y) {}
~Vec2() {}
template <typename T2>
explicit operator Vec2<T2>() const
{
return { static_cast<T2>(x), static_cast<T2>(y) };
}
T LenSquare() const
{
return square(*this);
}
T Len() const
{
return sqrt(LenSq());
}
Vec2& Normalize()
{
const T length = Len();
x /= length;
y /= length;
return *this;
}
Vec2 GetNormalized() const
{
Vec2 norm = *this;
norm.Normalize();
return norm;
}
Vec2 operator-() const
{
return Vec2(-x, -y);
}
Vec2& operator=(const Vec2 &rhs)
{
x = rhs.x;
y = rhs.y;
return *this;
}
Vec2& operator+=(const Vec2 &rhs)
{
x += rhs.x;
y += rhs.y;
return *this;
}
Vec2& operator-=(const Vec2 &rhs)
{
x -= rhs.x;
y -= rhs.y;
return *this;
}
T operator*(const Vec2 &rhs) const
{
return x * rhs.x + y * rhs.y;
}
Vec2 operator+(const Vec2 &rhs) const
{
return Vec2(*this) += rhs;
}
Vec2 operator-(const Vec2 &rhs) const
{
return Vec2(*this) -= rhs;
}
Vec2& operator*=(const T &rhs)
{
x *= rhs;
y *= rhs;
return *this;
}
Vec2 operator*(const T &rhs) const
{
return Vec2(*this) *= rhs;
}
Vec2& operator/=(const T &rhs)
{
x /= rhs;
y /= rhs;
return *this;
}
Vec2 operator/(const T &rhs) const
{
return Vec2(*this) /= rhs;
}
bool operator==(const Vec2 &rhs) const
{
return x == rhs.x && y == rhs.y;
}
bool operator!=(const Vec2 &rhs) const
{
return !(*this == rhs);
}
};
using Vector2 = Vec2<float>;
using Vector2i = Vec2<int>;
using Vector2d = Vec2<double>;
|
C++ | UTF-8 | 1,248 | 3.640625 | 4 | [] | no_license | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
/*
解法1:排序+双指针,排序后,对于每个nums[i]进行一次双指针遍历搜索
时间复杂度: O(nlogn) + O(n^2) = O(n^2)
空间复杂度: O(logn) 排序使用空间
可优化空间:保证每次判断不取重复的元素,如果遇到重复的元素则跳过
*/
int threeSumClosest(vector<int>& nums, int target)
{
int minSum = nums[0]+nums[1]+nums[2];
if (nums.size() == 3) return minSum;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i++)
{
int start = i + 1;
int end = nums.size() - 1;
while (start < end)
{
int curSum = nums[i] + nums[start] + nums[end];
if (abs(curSum - target) < abs(minSum - target))
minSum = curSum;
if (curSum > target)
end--;
else if (curSum < target)
start++;
else if (curSum == target)
return curSum;
}
}
return minSum;
}
}; |
Shell | UTF-8 | 2,916 | 2.984375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | #!/bin/bash
#
# script to try to automate ocserv setup on a device
sudo apt-get -y install ocserv
sudo apt-get -y install gnutls-bin
HERE="`pwd`"
cd /etc/ocserv
# sudo vi ca.tmpl
echo "cn = \"VPN Test CA\"" | sudo tee ca.tmpl
echo "organization = \"TEST VPN SERVER\"" | sudo tee -a ca.tmpl
echo "serial = 1" | sudo tee -a ca.tmpl
echo "expiration_days = 3650" | sudo tee -a ca.tmpl
echo "ca" | sudo tee -a ca.tmpl
echo "signing_key" | sudo tee -a ca.tmpl
echo "cert_signing_key" | sudo tee -a ca.tmpl
echo "crl_signing_key" | sudo tee -a ca.tmpl
sudo certtool --generate-privkey --outfile ca-key.pem
sudo certtool --generate-self-signed --load-privkey ca-key.pem --template ca.tmpl --outfile ca-cert.pem
INET_ADDR_TEST="`sudo ifconfig | grep -m 1 'inet addr:' | cut -d':' -f2 | cut -d' ' -f1`"
echo "cn = \"192.168.1.13\"" | sudo tee server.tmpl
echo "organization = \"TEST VPN SERVER\"" | sudo tee -a server.tmpl
echo "expiration_days = 3650" | sudo tee -a server.tmpl
echo "signing_key" | sudo tee -a server.tmpl
echo "encryption_key" | sudo tee -a server.tmpl
echo "tls_www_server" | sudo tee -a server.tmpl
sudo certtool --generate-privkey --outfile server-key.pem
sudo certtool --generate-certificate --load-privkey server-key.pem --load-ca-certificate ca-cert.pem --load-ca-privkey ca-key.pem --template server.tmpl --outfile server-cert.pem
# sudo vim ocserv.conf
sudo sed -i "s|pam\[gid-min=1000\]|plain[/etc/ocserv/ocpasswd]|g" ocserv.conf
sudo sed -i "s|server-cert = /etc/ssl/certs/ssl-cert-snakeoil.pem|server-cert = /etc/ocserv/server-cert.pem|g" ocserv.conf
sudo sed -i "s|server-key = /etc/ssl/private/ssl-cert-snakeoil.key|server-key = /etc/ocserv/server-key.pem|g" ocserv.conf
sudo sed -i "s/try-mtu-discovery = false/try-mtu-discovery = true/g" ocserv.conf
sudo sed -i "s/dns = 192.168.1.2/dns = 8.8.8.8/g" ocserv.conf
sudo sed -i "s/tcp-port = 443/tcp-port = 1443/g" ocserv.conf
sudo sed -i "s|route = 10.0.0.0/8|#route = 10.0.0.0/8|g" ocserv.conf
sudo sed -i "s|route = 192.168.0.0/16/255.255.0.0|#route = 192.168.0.0/16|g" ocserv.conf
sudo sed -i "s|no-route = 192.168.5.0/255.255.255.0|#no-route = 192.168.5.0/255.255.255.0|g" ocserv.conf
echo "enter VPN password for user $USER"
sudo ocpasswd -c /etc/ocserv/ocpasswd $USER
# sudo vim /etc/sysctl.conf
sudo sed -i "s/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/g" /etc/sysctl.conf
sudo sysctl -p
sudo iptables -A INPUT -p tcp --dport 1443 -j ACCEPT
sudo iptables -A INPUT -p udp --dport 1443 -j ACCEPT
sudo iptables -t nat -A POSTROUTING -j MASQUERADE
# sudo dpkg-reconfigure iptables-persistent
#( to save iptables rules )
sudo systemctl stop ocserv.socket
#( stop the service)
sudo ocserv -c /etc/ocserv/ocserv.conf
#( start the service )
#EXTRA:
#expose certificate
# sudo iptables -A INPUT -p tcp –dport 80 -j ACCEPT
# sudo apt-get install apache2
# sudo cp /etc/ocserv/ca-cert.pem /var/www/html
cd $HERE
|
Markdown | UTF-8 | 1,042 | 2.9375 | 3 | [
"MIT"
] | permissive | # Recollection
Effective immutable collections for Dart.
[API docs](https://pub.dartlang.org/documentation/recollection/latest/)
## Examples
Create immutable views around list with `ListView`. Recreate lists with `ListBuilder`.
```dart
var list = [1, 2, 3];
var view = ListView.of(list);
list = ListBuilder.from(list)
.add(4)
.remove(2)
.build();
```
Same is possible with sets and maps.
## Justification
SDK immutable collection constructors, like `List.unmodifiable`,
copy whole collection using `Iterator`, which is slow and inefficient.
`built_collection` package contains immutable wrappers around SDK collections, however
there is no way to create immutable wrapper around existing collection without recreating
collection from scratch.
`recollection` package contains immutable collection wrappers that do not copy source collection by themselves.
Also there are builders that can be used to create a copy of existing SDK collection with some changes.
Those are valuable benefits for performance-sensitive scenarios.
|
Java | UTF-8 | 1,110 | 2.625 | 3 | [] | no_license | package l2n.game.instancemanager;
import l2n.commons.list.GArray;
import l2n.game.event.L2Event;
import l2n.game.model.actor.L2Player;
/**
* Менеджер для управления ивентами
*
* @author bloodshed <a href="http://l2nextgen.ru/">L2NextGen</a>
* @email rkx.bloodshed@gmail.com
* @date 07.10.2011
* @time 20:00:09
*/
public final class L2EventManager
{
public static L2EventManager getInstance()
{
return SingletonHolder._instance;
}
@SuppressWarnings("synthetic-access")
private static class SingletonHolder
{
private static final L2EventManager _instance = new L2EventManager();
}
private final GArray<L2Event> _events;
public L2EventManager()
{
_events = new GArray<L2Event>();
}
public final void registerEvent(final L2Event event)
{
_events.add(event);
}
/**
* @param player
* @param answer
*/
public void participateAnswer(final L2Player player, final int answer)
{
// FIXME передавать ивент с которого идёт запрос в L2Player
for(final L2Event event : _events)
event.participateAnswer(player, answer);
}
}
|
Python | UTF-8 | 346 | 3.5625 | 4 | [] | no_license | average=(90+85+70+75+80)/5
print(average)
if(average>90 and average<=100):
print("A+")
elif(average>80 and average<=90):
print("A")
elif(average>70 and average<=80):
print("B")
elif(average>60 and average<=70):
print("C")
elif(average>50 and average<=60):
print("D")
elif(average<=50):
print("F")
else:
print("Error")
|
JavaScript | UTF-8 | 528 | 3.296875 | 3 | [] | no_license | var canvas=document.getElementById("canvas1")
ctx=canvas.getContext("2d")
color="Blue"
canvas.addEventListener("mousedown",draw)
function draw(e){
color = document.getElementById("color").nodeValue;
console.log(color);
mouseX=e.clientX-canvas.offsetLeft;
mouseY=e.clientY-canvas.offsetTop;
console.log("X = " + mouse_x + " ,Y = " + mouse_y);
circle(mouse_x , mouse_y);
}
function circle(mouse_X,mouse_Y){
ctx.beginPath
ctx.strokeStyle = color;
ctx.lineWidth = 2;
ctx.arc(200, 200, 40 ,0 , 2 * Math.PI);
ctx.stroke();;
}
|
Python | UTF-8 | 3,776 | 3.828125 | 4 | [
"MIT"
] | permissive | def sequence_breaker(sequence):
'''Create a set of intersections, this will eliminate duplicates.
'''
sequence = sequence.split(',')
x_value = 0
y_value = 0
grid = set()
for path in sequence:
direction = path[0]
distance = int(path[1:])
if direction == 'R':
x_value = x_value + distance
grid.update(list(((x, y_value) for x in range(x_value - distance, x_value))))
elif direction == 'U':
y_value = y_value + distance
grid.update(list(((x_value, y) for y in range(y_value - distance, y_value))))
elif direction == 'L':
x_value = x_value - distance
grid.update(list(((x, y_value) for x in range(x_value + distance, x_value, -1))))
elif direction == 'D':
y_value = y_value - distance
grid.update(list(((x_value, y) for y in range(y_value + distance, y_value, -1))))
else:
print('ERR')
return grid
def sequence_yield(sequence):
'''Generator of steps.
'''
sequence = sequence.split(',')
x_value = 0
y_value = 0
for path in sequence:
direction = path[0]
distance = int(path[1:])
if direction == 'R':
x_value = x_value + distance
for x in range(x_value - distance, x_value):
yield (x, y_value)
elif direction == 'U':
y_value = y_value + distance
for y in range(y_value - distance, y_value):
yield (x_value, y)
elif direction == 'L':
x_value = x_value - distance
for x in range(x_value + distance, x_value, -1):
yield (x, y_value)
elif direction == 'D':
y_value = y_value - distance
for y in range(y_value + distance, y_value, -1):
yield (x_value, y)
else:
print('ERR')
return False
def closest_intersection():
with open('input301.txt', 'r') as sequence:
first = sequence.readline()
second = sequence.readline()
grid_1 = sequence_breaker(first)
grid_2 = sequence_breaker(second)
grid_intersection = grid_1.intersection(grid_2)
result = [abs(x[0]) + abs(x[1]) for x in grid_intersection]
result.sort()
return result[1]
def fewest_steps():
with open('input301.txt', 'r') as sequence:
first = sequence.readline()
second = sequence.readline()
grid_1 = sequence_breaker(first)
grid_2 = sequence_breaker(second)
not_here = []
intersections = []
option = None
option_2 = None
grid_intersection = grid_1.intersection(grid_2)
for seq in grid_intersection:
grid_y_1 = sequence_yield(first)
grid_y_2 = sequence_yield(second)
count_i = 0
while(True):
count_i = count_i + 1
try:
option_2 = next(grid_y_2)
except StopIteration:
break
if option_2 in grid_1 and option_2 not in not_here and count_i > 1:
break
count_j = 0
while(True):
count_j = count_j + 1
try:
option = next(grid_y_1)
except StopIteration:
break
if option == option_2:
intersections.append(count_j + count_i)
not_here.append(option)
break
return min(intersections) - 2
if __name__ == '__main__':
print(f'The Manhattan distance to the closest is {closest_intersection()}')
print(f'The fewest steps to an intersectin is {fewest_steps()}')
|
Java | UTF-8 | 406 | 2.828125 | 3 | [] | no_license | package com.bridgelabz.algorithmprogram;
import java.io.IOException;
import java.util.Arrays;
import com.bridgelabz.utility.Utility;
public class BubbleSort {
public static void main(String[] args) throws IOException {
String arr[]= Utility.readFile("WordFile.txt");
System.out.println("Enter the array");
arr=Utility.bubbleSort(arr);
System.out.println(Arrays.toString(arr));
}
}
|
Markdown | UTF-8 | 766 | 2.640625 | 3 | [] | no_license | # am023_floor_builder
In questo esempio, senza usare *trick* come quelli proposti nell'originale, per creare l'oggetto `TaskDao` ci prepriamo per primo una computazione asincrona
``` dart
Future<TaskDao> _getDao() async {
final database = await $FloorAppDatabase
.databaseBuilder('flutter_database.db')
.build();
return database.taskDao;
}
```
e quindi
``` dart
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Floor Demo',
theme: ThemeData(primarySwatch: Colors.red),
home: FutureBuilder(
future: _getDao(),
builder: (BuildContext context, AsyncSnapshot<TaskDao> snapshot) {
...
```
Per il `FutureBuiler` [qui](https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html). |
Java | UTF-8 | 924 | 2.25 | 2 | [] | no_license | package springbasic;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import springbasic.entities.Course;
import springbasic.repos.CourseJpaRepo;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:beans.xml")
public class TestCourseJpaRepo {
@Autowired
CourseJpaRepo repo;
// @Test
public void testRecordsInCourses() {
// repo.fetchCourseCount();
}
@Test
public void testCourseWithId() {
Course course = repo.fetchCourse(6);
System.out.println(course);
assertEquals(6, course.getId());
}
// @Test
public void testCourseAdd() {
Course course = new Course("framework from google", "Angular");
repo.addCourse(course);
}
}
|
Java | UTF-8 | 2,041 | 2.296875 | 2 | [] | no_license | package co.edu.poli.dao;
import co.edu.poli.util.Columna;
public final class item_evaluacion{
@Columna(ClavePrimaria=true,AutoNumerico=true, Requered = true,NameForeingKey = "")
private java.lang.Integer id_item_evaluacion;
@Columna(ClavePrimaria=false,AutoNumerico=false, Requered = true,NameForeingKey = "")
private java.lang.Integer id_evidencia;
@Columna(ClavePrimaria=false,AutoNumerico=false, Requered = true,NameForeingKey = "")
private java.lang.Integer id_criterio_evaluacion;
@Columna(ClavePrimaria=false,AutoNumerico=false, Requered = true,NameForeingKey = "")
private java.lang.Integer id_rubrica;
@Columna(ClavePrimaria=false,AutoNumerico=false, Requered = false,NameForeingKey = "")
private java.lang.String descripcion_item;
public java.lang.Integer getId_item_evaluacion(){
return this.id_item_evaluacion;
}
public java.lang.Integer getId_evidencia(){
return this.id_evidencia;
}
public java.lang.Integer getId_criterio_evaluacion(){
return this.id_criterio_evaluacion;
}
public java.lang.Integer getId_rubrica(){
return this.id_rubrica;
}
public java.lang.String getDescripcion_item(){
return this.descripcion_item;
}
public void setId_item_evaluacion(java.lang.Integer id_item_evaluacion){
this.id_item_evaluacion = id_item_evaluacion;
}
public void setId_evidencia(java.lang.Integer id_evidencia){
this.id_evidencia = id_evidencia;
}
public void setId_criterio_evaluacion(java.lang.Integer id_criterio_evaluacion){
this.id_criterio_evaluacion = id_criterio_evaluacion;
}
public void setId_rubrica(java.lang.Integer id_rubrica){
this.id_rubrica = id_rubrica;
}
public void setDescripcion_item(java.lang.String descripcion_item){
this.descripcion_item = descripcion_item;
}
public item_evaluacion(){
}
public static void main(String... args){
}
} |
Java | UTF-8 | 2,926 | 2.03125 | 2 | [] | no_license | package pavloweather.controller;
import java.util.Date;
import java.util.List;
import java.lang.Iterable;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pavloweather.model.onsite.location.CityRepository;
import pavloweather.model.onsite.state.ApiState;
import pavloweather.model.onsite.state.ApiUsage;
import pavloweather.model.onsite.state.ApiUsageRepository;
import pavloweather.model.onsite.location.City;
import pavloweather.model.onsite.weather.Forecast;
import pavloweather.model.onsite.weather.ForecastRepository;
import pavloweather.model.onsite.weather.ForecastWrapper;
import pavloweather.model.outsource.url.CityUrlHandler;
import pavloweather.model.date.DateParser;
import pavloweather.model.ApiDataRecorder;
import pavloweather.model.apilimit.RequestRestrictor;
import pavloweather.model.apilimit.RestrictionConfigurator;
//@TODO: replace test controller by unit tests
//(Which should encompass much wider scope)
@Controller
@RequestMapping("/demo")
public class TestController {
@Autowired
private DateParser dateParser;
@Autowired
private CityRepository cityRepository;
@Autowired
private ApiUsageRepository apiUsageRepository;
@Autowired
private ApiState apiState;
@Autowired
private ApiState apiMonitor;
@Autowired
private ForecastRepository dailyUnitRepository;
@Autowired
private RestrictionConfigurator restrictionConfigurator;
@RequestMapping("/cities")
public @ResponseBody Iterable<City> showDatabaseCities(){
return cityRepository.findAll();
}
@RequestMapping("/apistate")
public @ResponseBody Iterable<ApiUsage> showApiStateDbRecorder(){
return apiUsageRepository.findAll();
}
@RequestMapping("/weather")
public @ResponseBody Iterable<Forecast> showDailyWeatherDbRecords(){
return dailyUnitRepository.findAll();
}
@RequestMapping("/apistate/formatted")
public @ResponseBody String checkstate(){
Date start = apiState.getStartTime();
Date last = apiState.getLastTime();
int reqNumber = apiState.getRequestNumber();
return "start is : " + dateParser.format(start)
+ " end is : " + dateParser.format(last)
+ " count: " + reqNumber + " nex visit is " + restrictionConfigurator.calculateNextVisit()
+ " duration : " + dateParser.getSecondsRelativity(apiMonitor.getStartTime())
+ " duration (module) : " + dateParser.getSecondsRelativity(apiMonitor.getStartTime()) % 60;
}
@RequestMapping("/apistate/check")
public @ResponseBody String check(){
RequestRestrictor res = RequestRestrictor.allowApiUsage(restrictionConfigurator);
return "apiUsageState is: " + res.getPermission();
}
} |
Markdown | UTF-8 | 1,075 | 2.875 | 3 | [
"MIT"
] | permissive | # Neural Architecture Search and AutoML
## Neural Architecture Search
If you wish to dive more deeply into neural architecture search, feel free to check out these optional references. You won’t have to read these to complete this week’s practice quizzes.
+ [Neural Architecture Search](https://arxiv.org/pdf/1808.05377.pdf)
+ [Bayesian Optimization](https://distill.pub/2020/bayesian-optimization/)
+ [Neural Architecture Search with Reinforcement Learning](https://arxiv.org/pdf/1611.01578.pdf)
+ [Progressive Neural Architecture Search](https://arxiv.org/pdf/1712.00559.pdf)
+ [Network Morphism](https://arxiv.org/abs/1603.01670)
## AutoML
If you wish to dive more deeply into AutoMLs, feel free to check out these cloud-based tools. You won’t have to read these to complete this week’s practice quizzes.
+ [Amazon SageMaker Autopilot](https://aws.amazon.com/sagemaker/autopilot)
+ [Microsoft Azure Automated Machine Learning](https://azure.microsoft.com/en-in/services/machine-learning/automatedml/)
+ [Google Cloud AutoML](https://cloud.google.com/automl)
|
Java | UTF-8 | 440 | 1.929688 | 2 | [
"MIT"
] | permissive | package org.communiquons.android.comunic.client.data.enums;
/**
* Notifications visibility enums
*
* @author Pierre HUBERT
* Created by pierre on 4/9/18.
*/
public enum NotificationVisibility {
/**
* When the notification is targeting only one single user
*/
EVENT_PRIVATE,
/**
* When a notification is targeting several users
*/
EVENT_PUBLIC,
/**
* Unknown visibility
*/
UNKNOWN
}
|
Python | UTF-8 | 321 | 2.875 | 3 | [] | no_license | from datetime import datetime
class Greeting:
# todo change Solomon to be the user from the user data json file.
def __init__(self, name):
date = datetime.today().strftime('%m-%d-%Y')
self.message = "<emphasis level=\"strong\">Good morning" + name + "! Today is " + date + ".\n" + "</emphasis>"
|
Java | UTF-8 | 5,442 | 2.234375 | 2 | [] | no_license | package com.repair.zhoushan.entity;
import android.os.Parcel;
import android.os.Parcelable;
public class EventItem implements Parcelable {
public EventItem() {
ID = 0;
EventName = "";
EventCode = "";
EventState = "";
ReportStation = "";
DealStation = "";
ReporterName = "";
ReporterDepart = "";
ReportTime = "";
UpdateTime = "";
UpdateState = "";
Picture = "";
Radios = "";
XY = "";
BusinessType = "";
Summary = "";
SummaryDetail = "";
BizCode = "";
EventMainTable = "";
FieldGroup = "";
SummaryField = "";
IsCreate = "";
IsReport = "";
IsRelatedCase = 0;
IsStick = 0;
Distance = 0;
DistanceStr = "";
}
/**
* 事件ID
*/
public int ID;
/**
* 事件名称
*/
public String EventName;
/**
* 事件编号
*/
public String EventCode;
/**
* 事件状态
*/
public String EventState;
/**
* 上报站点
*/
public String ReportStation;
/**
* 处理站点
*/
public String DealStation;
/**
* 上报人名称
*/
public String ReporterName;
/**
* 上报人部门
*/
public String ReporterDepart;
/**
* 上报时间
*/
public String ReportTime;
/**
* 最后上报时间
*/
public String UpdateTime;
/**
* 更新状态
*/
public String UpdateState;
/**
* 现场图片
*/
public String Picture;
/**
* 现场录音
*/
public String Radios;
/**
* 坐标位置
*/
public String XY;
/**
* 业务类型
*/
public String BusinessType;
/**
* 事件摘要
*/
public String Summary;
/**
* 事件摘要详情,包括摘要字段和摘要字段值
*/
public String SummaryDetail;
/**
* 业务编码
*/
public String BizCode;
/**
* 事件主表
*/
public String EventMainTable;
/**
* 字段集
*/
public String FieldGroup;
/**
* 摘要字段
*/
public String SummaryField;
/**
* 是否发起
*/
public String IsCreate;
/**
* 是否上报
*/
public String IsReport;
/**
* 事件是否已经发起过流程 - 标识
*/
public int IsRelatedCase;
/**
* 事件是否置顶
*/
public int IsStick;
// 手机本地为列表显示额外添加的字段
/**
* 距离当前坐标的距离
*/
public double Distance;
/**
* 距离当前坐标的距离的用于显示的字符串
*/
public String DistanceStr;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(ID);
out.writeString(EventName);
out.writeString(EventCode);
out.writeString(EventState);
out.writeString(ReportStation);
out.writeString(DealStation);
out.writeString(ReporterName);
out.writeString(ReporterDepart);
out.writeString(ReportTime);
out.writeString(UpdateTime);
out.writeString(UpdateState);
out.writeString(Picture);
out.writeString(Radios);
out.writeString(XY);
out.writeString(BusinessType);
out.writeString(Summary);
out.writeString(SummaryDetail);
out.writeString(BizCode);
out.writeString(EventMainTable);
out.writeString(FieldGroup);
out.writeString(SummaryField);
out.writeString(IsCreate);
out.writeString(IsReport);
out.writeInt(IsRelatedCase);
out.writeInt(IsStick);
}
public static final Parcelable.Creator<EventItem> CREATOR = new Parcelable.Creator<EventItem>() {
@Override
public EventItem createFromParcel(Parcel in) {
return new EventItem(in);
}
@Override
public EventItem[] newArray(int size) {
return new EventItem[size];
}
};
private EventItem(Parcel in) {
ID = in.readInt();
EventName = in.readString();
EventCode = in.readString();
EventState = in.readString();
ReportStation = in.readString();
DealStation = in.readString();
ReporterName = in.readString();
ReporterDepart = in.readString();
ReportTime = in.readString();
UpdateTime = in.readString();
UpdateState = in.readString();
Picture = in.readString();
Radios = in.readString();
XY = in.readString();
BusinessType = in.readString();
Summary = in.readString();
SummaryDetail = in.readString();
BizCode = in.readString();
EventMainTable = in.readString();
FieldGroup = in.readString();
SummaryField = in.readString();
IsCreate = in.readString();
IsReport = in.readString();
IsRelatedCase = in.readInt();
IsStick = in.readInt();
}
} |
C# | UTF-8 | 1,317 | 2.734375 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using OrbitOne.SharePoint.Importer.Domain;
namespace OrbitOne.SharePoint.Importer.SharePoint
{
public class FlatListDuplicateNameResolver
{
private readonly IList<string> m_filenames;
public FlatListDuplicateNameResolver(): this(Enumerable.Empty<string>())
{}
public FlatListDuplicateNameResolver(IEnumerable<string> existingFiles)
{
m_filenames = existingFiles.ToList();
}
public String ResolveName(ImportFile file)
{
int i = 0;
var duplicates = m_filenames.Where(name => name.StartsWith(Path.GetFileNameWithoutExtension(file.Name),StringComparison.InvariantCultureIgnoreCase));
string uniqueName = file.Name;
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(file.Name);
string extension = Path.GetExtension(file.Name);
while (duplicates.Any(s => s.Equals(uniqueName, StringComparison.InvariantCultureIgnoreCase)))
{
i++;
uniqueName = String.Format("{0}_{1}{2}", filenameWithoutExtension, i, extension);
}
m_filenames.Add(uniqueName);
return uniqueName;
}
}
} |
Python | UTF-8 | 689 | 3.046875 | 3 | [
"MIT"
] | permissive | from utils.parser_helpers import split_standard_separators
def multiple_choice_parser(msg, question):
""" Takes text and a dictionary/set of words. Parses the text for the first
word in the supplied dictionary, and returns the corresponding dictionary entry."""
if msg is None: return None
# TODO: update when question choices changes to dict
words_dict = dict((i.lower(), i) for i in question["choices_text"])
msg = msg.lower()
if msg in words_dict:
return words_dict[msg]
msg_words = split_standard_separators(msg)
for word in msg_words:
if word in words_dict:
return words_dict[word]
return None |
C# | UTF-8 | 2,351 | 3.828125 | 4 | [] | no_license | using System;
using System.Collections.Generic;
using System.Text;
namespace IntroducaoCS
{
class Tipologia
{
public static void inteiro()
{
Console.WriteLine("\n INTEIRO");
Console.WriteLine("------------------------");
int idade = 31;
var ano = 2021;
Console.WriteLine($"idade = {idade}");
Console.WriteLine("ano = " + ano);
Console.WriteLine("Informe a sua idade:");
var input = Console.ReadLine();
int valorConvertido = Int32.Parse(input);
Console.WriteLine($"Sua idade é :{valorConvertido}");
}
public static void numeroDecimal()
{
Console.WriteLine("\n DECIMAL");
Console.WriteLine("------------------------");
float peso = 100.5f;
double altura = 1.80;
Console.WriteLine($"peso = {peso}");
Console.WriteLine("altura = " + altura);
Console.WriteLine("Informe o seu peso:");
var input = Console.ReadLine();
Double valorConvertido = Double.Parse(input);
Console.WriteLine($"Seu peso é :{valorConvertido}");
}
public static void caracter()
{
Console.WriteLine("\n CARACTER");
Console.WriteLine("------------------------");
char letra = 'a';
var inicial = 'r';
Console.WriteLine($"letra = {letra}");
Console.WriteLine("inicial = " + inicial);
Console.WriteLine("Informe a primeira letra do seu nome:");
var input = Console.ReadKey();
char valorConvertido = input.KeyChar;
Console.WriteLine($"\nA primeira letra do seu nome é:{valorConvertido}");
}
public static void texto()
{
Console.WriteLine("\n STRING");
Console.WriteLine("------------------------");
string nome = "Rubem Duarte Oliota";
var curso = "Fundamentos c#";
Console.WriteLine($"nome = {nome}");
Console.WriteLine("curso = " + curso);
Console.WriteLine("Informe seu nome completo:");
var input = Console.ReadLine();
Console.WriteLine($"Seu nome completo é:{input}");
}
}
}
|
Python | UTF-8 | 1,652 | 3.03125 | 3 | [
"BSD-2-Clause"
] | permissive | # Copyright (c) 2016, Matt Layman
'''Validate aspects of MarkWiki.'''
import os
from markwiki import app
from markwiki.exceptions import ValidationError
def is_valid_section(section_path):
'''Check if the section path is valid.'''
return os.path.isdir(os.path.join(app.config['WIKI_PATH'], section_path))
def validate_directories(directories):
'''Check that the directories are sane.'''
for directory in directories:
# Prevent any double, triple, or however many slashes in a row.
if directory == '':
raise ValidationError(
'It looks like there were multiple slashes in a row in your '
'wiki name.')
# No relative paths allowed.
if directory in ['..', '.']:
raise ValidationError(
'Wiki names can\'t include just \'..\' or \'.\' between '
'slashes.')
# None of the directory parts can end in '.md' because that would
# screw up the ability to make a wiki in the directory that has the
# same name.
if directory.endswith('.md'):
raise ValidationError(
"Wiki names can't end in '.md' in the parts before the last "
"slash. Sorry, this rule is weird. I know.")
def validate_page_path(page_path):
'''Check that the page path is valid.'''
# An empty page path is no good.
if page_path is None or page_path == '':
raise ValidationError('You need to supply some wiki name.')
# Do some directory checking.
page_parts = page_path.split('/')
if len(page_parts) > 1:
validate_directories(page_parts[:-1])
|
JavaScript | UTF-8 | 3,361 | 2.84375 | 3 | [] | no_license | var notificationTemplate = undefined;
var notificationContainerDOM = undefined;
var buttonUpdateTemplate = undefined;
var buttonDeleteTemplate = undefined;
var updateButtonNumberColumn = 7;
var deleteButtonNumberColumn = 8;
/**
* Add a notification.
* @param level a string in the set {"success","warning","danger"}
* @param message the string contained in the new notification. Can contain HTML text.
*/
var addNotification = function(level,message)
{
var newNotificationDOM = notificationTemplate.clone(true).removeClass("allsafe-modele");
if( level === undefined || typeof level !== "string")
{
level = "danger";
}
if( message === undefined || typeof message !== "string")
{
message = "Warning ! No message found.";
}
newNotificationDOM
.addClass("alert-" + level);
$(".allsafe-message",newNotificationDOM).html(message);
notificationContainerDOM.prepend(newNotificationDOM);
};
/**
* Update a line of data user table.
* @param lineToUpdateDOM The line to actualize.
* @param actionList a string array that may contain following values : "update", "delete".
*/
var actualizesActionButtons = function(lineToUpdateDOM,actionList)
{
var addUpdateButton = function(lineToUpdateDOM)
{
var buttonContainer = $("td:nth-child(" + updateButtonNumberColumn + ")",lineToUpdateDOM);
if( buttonContainer === undefined)
{
throw Error("addUpdateButton - " + updateButtonNumberColumn +"th child of line to update not found.");
} else
{
if( !buttonContainer.html().includes("<input"))
buttonContainer.append(buttonUpdateTemplate.clone(true).removeClass("allsafe-modele"));
}
};
var addDeleteButton = function(lineToUpdateDOM)
{
var buttonContainer = $("td:nth-child(" + deleteButtonNumberColumn + ")",lineToUpdateDOM);
if( buttonContainer === undefined)
{
throw Error("addUpdateButton - " + deleteButtonNumberColumn + "th child of line to update not found.");
} else
{
if( !buttonContainer.html().includes("<input"))
buttonContainer.append(buttonDeleteTemplate.clone(true).removeClass("allsafe-modele"));
}
};
var removeUpdateButton = function(lineToUpdateDOM)
{
$("td:nth-child(" + updateButtonNumberColumn + ")",lineToUpdateDOM).empty();
};
var removeDeleteButton = function(lineToUpdateDOM)
{
$("td:nth-child(" + deleteButtonNumberColumn + ")",lineToUpdateDOM).empty();
};
if(actionList.includes("update"))
{
addUpdateButton(lineToUpdateDOM);
} else
{
removeUpdateButton(lineToUpdateDOM)
}
if(actionList.includes("delete"))
{
addDeleteButton(lineToUpdateDOM);
} else
{
removeDeleteButton(lineToUpdateDOM);
}
};
$(document).ready(function()
{
notificationTemplate = $("#notificationTemplate");
buttonDeleteTemplate = $("#buttonDeleteTemplate");
buttonUpdateTemplate = $("#buttonUpdateTemplate");
$("#notificationTemplate button").click(
function() // delete notification
{
$(this).parent().remove();
}
);
notificationContainerDOM = $("#allsafe-notification-container");
console.log("Notifications.js downloaded.");
}); |
Java | UTF-8 | 4,411 | 2.203125 | 2 | [] | no_license | package hello;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import hello.com.mvc.api.entities.Student;
import hello.com.mvc.api.service.IStudentService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.web.FilterChainProxy;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.util.Base64Utils;
import org.springframework.web.context.WebApplicationContext;
import java.util.*;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ServerControllerTests {
@Autowired
private MockMvc mockMvc;
@Autowired
ObjectMapper objectMapper;
@Autowired
WebApplicationContext context;
@Autowired
FilterChainProxy springSecurityFilterChain;
@MockBean
IStudentService studentService;
@Before
public void setUp() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(context)
.addFilter(springSecurityFilterChain).build();
}
//test to save data
@Test
public void saveStudent() throws Exception {
Student oneS = new Student();
oneS.setMajor("dance4");
oneS.setName("kate");
Mockito.when(studentService.addStudent(oneS)).thenReturn(true);
MvcResult mvcResult2 = this.mockMvc.perform(post("/user/student")
.header("Authorization", "Bearer"+ getAccessToken("adr", "password"))
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(oneS)))
.andReturn();
System.out.println(mvcResult2.getResponse());
ArgumentCaptor<Student> argument = ArgumentCaptor.forClass(Student.class);
Mockito.verify(studentService).addStudent(argument.capture());
}
//test to get data
@Test
public void getStudents() throws Exception {
List<Student> list = new ArrayList<Student>();
Student oneS = new Student();
oneS.setMajor("dance4");
oneS.setName("kate");
Student twoS = new Student();
twoS.setMajor("art");
twoS.setName("john");
list.add(oneS);
list.add(twoS);
Mockito.when(studentService.getAllStudents()).thenReturn(list);
MvcResult mvcResult = this.mockMvc.perform(get("/user/all-students")
.header("Authorization", "Bearer"+ getAccessToken("adr", "password"))
.accept(MediaType.APPLICATION_JSON))
.andReturn();
System.out.println(mvcResult.getResponse());
Mockito.verify(studentService).getAllStudents();
}
private String getAccessToken(String username, String password) throws Exception {
MockHttpServletResponse response = this.mockMvc.perform(post("/oauth/token")
.header("Authorization", "Basic "
+ new String(Base64Utils.encode(("studentapp:secret")
.getBytes())))
.param("username", username)
.param("password", password)
.param("grant_type", "password"))
.andReturn().getResponse();
return new ObjectMapper()
.readValue(response.getContentAsByteArray(), OAuthToken.class)
.accessToken;
}
@JsonIgnoreProperties(ignoreUnknown = true)
private static class OAuthToken {
@JsonProperty("access_token")
public String accessToken;
}
}
|
C++ | UTF-8 | 2,497 | 3.0625 | 3 | [] | no_license | #include <cstdio>
#include <algorithm>
#include <chrono>
#include <vector>
#include <streambuf>
#include <clientversion.h>
#include <primitives/block.h>
inline int transform_hex_symbol(int c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
return -1;
}
std::vector<char> read_block_hex() {
FILE *fp = fopen("./blocks/623200.hex", "r");
if (!fp) {
perror("Failed open block data");
std::abort();
}
std::vector<char> data;
while (true) {
int sym = fgetc(fp);
if (transform_hex_symbol(sym) == -1) {
break;
}
data.push_back(sym);
}
fclose(fp);
return data;
}
std::vector<char> hex_to_bytes(std::vector<char>& data) {
std::vector<char> hex;
hex.resize(data.size(), 0);
for (int i = 0; i < data.size(); i += 2) {
hex.push_back(transform_hex_symbol(data[i]) * 16 + transform_hex_symbol(data[i + 1]));
}
return hex;
}
class MyStreamZ {
private:
size_t size;
char* buf;
size_t position;
public:
MyStreamZ(std::vector<char>& data) : position(0) {
size = data.size();
buf = &*data.begin();
}
int GetVersion() const { return CLIENT_VERSION; }
void read(char *pch, size_t nSize) {
if (position + nSize > size) {
throw std::ios_base::failure("Read attempted past buffer limit");
}
memcpy(pch, &buf[position], nSize);
position += nSize;
}
template<typename T>
MyStreamZ& operator>>(T&& obj) {
// Unserialize from this stream
::Unserialize(*this, obj);
return (*this);
}
};
int main() {
auto hex = read_block_hex();
constexpr int iters = 100;
int elapsed[iters];
for (int i = 0; i < iters; ++i) {
auto t1 = std::chrono::high_resolution_clock::now();
auto data = hex_to_bytes(hex);
MyStreamZ z(data);
CBlock block;
z >> block;
auto t2 = std::chrono::high_resolution_clock::now();
elapsed[i] = std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count();
}
long long int sum = 0;
for (int i = 0; i < iters; ++i) sum += elapsed[i];
std::sort(elapsed, elapsed + iters);
printf("Parse bytes (%d iterations):\n", iters);
printf("min: %.6fms\n", elapsed[0] * 1e-6);
printf("average: %.6fms\n", sum / iters * 1e-6);
printf("max: %.6fms\n", elapsed[iters - 1] * 1e-6);
return 0;
}
|
Java | UTF-8 | 265 | 1.867188 | 2 | [] | no_license | package com.octa.iot.hub.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.octa.iot.hub.model.Sensor;
public interface SensorRepository extends JpaRepository<Sensor, Long> {
public Sensor findByNome(String nomeSensor);
}
|
Markdown | UTF-8 | 2,160 | 2.75 | 3 | [] | no_license | API e FrontEnd para encontrar Universidades Brasileiras
=================================
### API e Frontend que procura por Universidades Brasileiras dado um parâmetro "name" inserido pelo usuário na página inicial.
FrontEnd chama CarlotaAPI que chama outra API de Universidades do mundo. Git para a API mencionada: https://github.com/Hipo/university-domains-list-api/
### Funcionalidades
A API irá procurar por universidades brasileiras com nome caso especificado na caixa de input da tela inicial e apertando o botão "Buscar".
Caso nenhum parâmetro seja específicado, a API retornará todas as Universidades do Brasil ao apertar o botão.
### Tecnologias
- API: C# e .NET Core MVC
- FrontEnd: C#, .NET Core MVC, Razor
- Virtualização: Docker
### Rode o projeto
- Clone o repositório `git clone https://github.com/cmsulzbeck/ApiUniversidades.git`
- Setar ambiente virtual usando Docker:
- Dentro dos diretórios "CarlotaApi" e "FrontEnd" existem arquivos Dockerfile para configuração de ambiente
- Construir imagem docker baseado no Dockerfile da API e do FrontEnd
- `docker image build -t carlotaapi:1.0 .` (-t significa nome e/ou tag opcionais na construção da imagem)
- `docker image build -t carlotafrontend:1.0 .`
- Rodar containers docker baseados nas imagens respectivas
- `docker run -i -t -d --name carlota_api -v $PWD:/root carlotaapi:1.0`<br /> (-i mantém STDIN aberto, -t aloca um pseudo-TTY, -d Sobrescreve a sequencia para desacoplar de um container)
- `docker run -i -t -d --name carlota_frontend -v $PWD:/root carlotafrontend:1.0`
- Executar containers docker
- `docker exec -i -t carlota_api /bin/bash` (-i mantém STDIN aberto mesmo se não acoplado, -t aloca um pseudo-TTY, bin/bash é o caminho padrão da imagem)
- `docker exec -i -t carlota_frontend /bin/bash`
- Criar novos terminais para API
- `docker start carlota_api`
- `docker exec -i -t carlota_api /bin/bash`
- Criar novos terminais para frontend
- `docker start carlota_frontend`
- `docker exec -i -t carlota_frontend /bin/bash`
- Rodar projeto usando `dotnet run` dentro do diretório do projeto
|
Java | UTF-8 | 175 | 2.828125 | 3 | [] | no_license | public class MyMath {
public static int add(int a, int b) {
//Thread.sleep(1000)
return a+b;}
public static int div(int a, int b){return a/b;}
}
|
Markdown | UTF-8 | 2,828 | 2.625 | 3 | [
"CC0-1.0"
] | permissive | ---
layout: post
title: "Plan to conserve borough's species and habitat"
permalink: /archives/2019/05/lbrut-conservation-plan.html
commentfile: 2019-05-11-lbrut-conservation-plan
category: news
image: "/assets/images/2019/lbrut-attenborough-thumb.jpg"
date: 2019-05-11 07:14:16
excerpt: |
A Plan to conserve the borough's richly diverse plant and wildlife for future generations was launched yesterday at the London Wetland Centre in Barnes.
Richmond Council Cabinet Member for Environment, Planning and Sustainability, Cllr Martin Elengorn joined Sir David Attenborough, members of the South West London Environment Network (SWLEN) and others to help launch the Richmond upon Thames' Biodiversity Action Plan on Thursday (9<sup>th</sup> May).
---
<a href="/assets/images/2019/lbrut-attenborough.jpg" title="Click for a larger image"><img src="/assets/images/2019/lbrut-attenborough-thumb.jpg" width="250" alt="Image - lbrut-attenborough" class="photo right"/></a>
A Plan to conserve the borough's richly diverse plant and wildlife for future generations was launched yesterday at the London Wetland Centre in Barnes.
Richmond Council Cabinet Member for Environment, Planning and Sustainability, Cllr Martin Elengorn joined Sir David Attenborough, members of the South West London Environment Network (SWLEN) and others to help launch the Richmond upon Thames' Biodiversity Action Plan on Thursday (9<sup>th</sup> May).
The Plan has been produced by the Richmond Biodiversity Partnership - a partnership of organisations and residents, working to protect the local biodiversity - in association with Richmond Council.
It outlines the species and habitats which should be prioritised, where they are located, what is being done to conserve them and what land owners, managers and residents can do to help protect and enhance local wildlife for future generations.
Speaking at the event, Cllr Elengorn said:
> "We owe it to our children and grandchildren to save the rich biodiversity that still exists and can continue to exist. Let's all continue to work hard and keep our courage up."
Colin Cooper, Chief Executive of SWLEN said:
> "What difference does a biodiversity action plan make? It means 1.5km of new hedgerows, restored and expanded reedbeds, over 1km of river restoration work, large scale stag beetle loggery and bird box installation, mistletoe regeneration, dozens of hedgehog sightings."
Sir David Attenborough said:
> "I am so heartened that an audience of this kind should turn out to consider local action plans of the most practical and most humble level.
> "This work is modest and unpretentious, but nonetheless crucial.
> "If we can't look after this environment, who can? The enthusiasm, insight and knowledge that is so evident, makes me feel very privileged to be living where I do."
<cite>— from a Richmond Council press release - 10 May 2019</cite>
|
PHP | UTF-8 | 439 | 2.546875 | 3 | [] | no_license | <?php
try{
$db = new \PDO("mysql:host={$config["db_host"]};
dbname={$config["db_name"]};
port={$config["db_port"]};
charset=utf8mb4",
$config["db_user"],
$config["db_password"],
[\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION]);
}catch(\PDOException $e){
echo "erreur lors de la connexion à la base de données";
} |
JavaScript | UTF-8 | 2,322 | 3.375 | 3 | [] | no_license | const livros = {
1: {
"titulo": "Javascript Eloquente",
"quemEscreveu": "Marijn Haverbeke",
"link": "https://github.com/braziljs/eloquente-javascript"
},
2: {
"titulo": "Você não sabe JS",
"quemEscreveu": "Kyle Simpson",
"link": "https://github.com/cezaraugusto/You-Dont-Know-JS"
},
3: {
"titulo": "Calibã e a Bruxa: mulheres, corpo e acumulação primitiva",
"quemEscreveu": "Silvia Federici",
"link": "http://coletivosycorax.org/wp-content/uploads/2019/09/CALIBA_E_A_BRUXA_WEB-1.pdf"
}
}
const ul = document.getElementById("lista-do-catalogo")
for (let propriedade in livros){ // para cada propriedade em meu objeto:
const li = document.createElement("li") // cria elemento <li>
ul.appendChild(li) // linka filho na mãe
li.classList.add("livro") // adiciona classe
const tituloLivro = document.createElement("h2") // cria elemento <h2>
li.appendChild(tituloLivro) // linka o filho na mãe
tituloLivro.textContent = livros[propriedade]["titulo"] //cria conteudo, chamando o objeto
tituloLivro.classList.add("livro__titulo") // adiciona classe (e se repete nos passos abaixo)
const nomeAutor = document.createElement("p")
li.appendChild(nomeAutor)
nomeAutor.textContent = livros[propriedade]["quemEscreveu"]
nomeAutor.classList.add("livro__autoria")
const linkLivro = document.createElement("a")
li.appendChild(linkLivro)
linkLivro.setAttribute("href", livros[propriedade]["link"])
linkLivro.setAttribute("target", "_blank")
linkLivro.textContent = "Leia aqui"
linkLivro.classList.add("livro__link")
const botao = document.createElement("button")
li.appendChild(botao)
botao.setAttribute("type", "submit")
botao.textContent = "Já li"
botao.classList.add("botao-lido")
// TOGGLE
botao.addEventListener("click", function(){
if (tituloLivro.classList.contains("livro__titulo--lido")){
tituloLivro.classList.remove("livro__titulo--lido")
botao.classList.remove("botao-nao-lido")
botao.textContent = "Já li"
} else {
tituloLivro.classList.add("livro__titulo--lido")
botao.classList.add("botao-nao-lido")
botao.textContent = "Desfazer"
}
})
}
|
C++ | UTF-8 | 295 | 2.546875 | 3 | [] | no_license | #include<stdio.h>
int main()
{
int a,b,c;
int kase=0;
while(scanf("%d%d%d",&a,&b,&c)==3)
{
kase++;
int i;
for(i=10;i<100;i++)
{
if(i%3==a&&i%5==b&&i%7==c)
break;
}
if(i!=100)
printf("Case %d: %d\n",kase,i);
else
printf("Case %d: No answer\n",kase);
}
return 0;
}
|
Python | UTF-8 | 1,007 | 3.765625 | 4 | [] | no_license | parrot = "Norwegian Blue"
print(parrot)
print(parrot[3])
print(parrot[4])
print(parrot[9])
print(parrot[3])
print(parrot[6])
print(parrot[0])
print()
print(parrot[3 - 14])
print(parrot[4 - 14])
print(parrot[9 - 14])
print(parrot[3 - 14])
print(parrot[6 - 14])
print(parrot[0 - 14])
print(parrot[0:6])
print(parrot[3:5])
print(parrot[-14:-8])
print(parrot[-11:-9])
print()
print(parrot[0:9])
print(parrot[:9])
print(parrot[-14:-5])
print(parrot[:-5])
print()
print(parrot[10:14])
print(parrot[10:])
print(parrot[-4:-1])
print(parrot[-4:])
print()
print(parrot[:6])
print(parrot[6:])
print(parrot[:6] + parrot[6:])
print(parrot[:])
print(parrot[-4:-2])
print(parrot[-4:12])
print()
print(parrot[0:6:2]) #step of two is what the last line means
print(parrot[0:6:3])
number = "9,223;372:036 854,775;807"
seperators = number[1::4]
print(seperators)
values = "".join(char if char not in seperators else " " for char in number).split() #this won't make sense yet
print([int(val) for val in values]) |
C# | UTF-8 | 2,522 | 2.96875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.IO;
namespace updateDataSources
{
class Program
{
static void Main(string[] args)
{
string xmlPath = args[0];
string filePath = args[1];
string fileName = filePath.Substring(filePath.LastIndexOf('\\')+1, (filePath.Length - filePath.LastIndexOf('\\'))-1);
string mnemonic = args[2];
bool failed = false;
string line = string.Empty;
XmlDocument transactionTemplate = new XmlDocument();
try
{
transactionTemplate.Load(xmlPath);
}
catch
{
CustomLogger.Trace("Error - XML does not exist");
Console.WriteLine("Make sure you have the correct path for DataSources.xml");
return;
}
XmlNode dataSource;
StreamReader file = null;
try
{
file = new StreamReader(filePath);
}
catch
{
CustomLogger.Trace("Error - File does not exist");
Console.WriteLine("Make sure you have given the correct path for the file");
return;
}
file.ReadLine();
file.ReadLine();
while ((line = file.ReadLine()) != null)
{
string txtCode = line.Substring(0, line.IndexOf('\t'));
dataSource = transactionTemplate.SelectSingleNode("/transactionTemplate/dataSources/dataSource[@mnemonic='" + mnemonic + "']/entry/property[@name='Value'][text()='"+txtCode+"']");
if (dataSource==null)
{
CustomLogger.Trace(string.Format("Could not find entry with properties: \"{0}\" in DataSources.xml", line));
failed = true;
}
file.ReadLine();
}
file.Close();
if (failed)
{
Console.WriteLine("\nCould not find all entries in DataSources.xml.\nLook at logs to see which entries are missing");
}
else
{
CustomLogger.Trace("Success all entries are in DataSources.xml from " + fileName);
Console.WriteLine("\nSuccess all entries are in DataSources.xml from " + fileName);
}
}
}
}
|
Java | UTF-8 | 204 | 1.789063 | 2 | [] | no_license | package kotaro1116;
import java.util.Scanner;
public class Never_lose {
public static void main(String[] args) {
int a = 0;
Scanner s = new Scanner(System.in);
String op = s.nextLine();
}
}
|
Python | UTF-8 | 2,414 | 3.09375 | 3 | [] | no_license | # 17:50 start
# 19:31 pass
# 1시간 41분 소요,, 쉬운 문젠데 너무 오래 걸렸다.
# 시뮬레이션은 몇일만 쉬어도 금방 감 떨어진다.. 쉼없이 계속 코딩하자
# 특별한 알고리즘은 없다. 주어진 대로 그대로 구현하면 됨!
from sys import stdin
input = stdin.readline
# 8방향
dr = (0, 0, -1, -1, -1, 0, 1, 1, 1)
dc = (0, -1, -1, 0, 1, 1, 1, 0, -1)
# 1. 모든 구름이 d방향으로 s칸 이동한다.
# 2. 각 구름에서 비가 내려 구름이 있는 칸의 바구니에 저장된 물의 양이 1 증가한다.
def moveClouds(d, s):
newClouds = set()
for r, c in clouds:
nr = (r + dr[d] * s) % N
nc = (c + dc[d] * s) % N
A[nr][nc] += 1
newClouds.add((nr, nc))
return newClouds
# 4. 2에서 물이 증가한 칸 (r, c)에 물복사버그 마법을 시전한다.
def rainFall():
for r, c in newClouds:
waterCnt = 0
for d in range(2, 9, 2): # 대각선 방향(2, 4, 6, 8)
nr = r + dr[d]
nc = c + dc[d]
if not (0 <= nr < N and 0 <= nc < N):
continue
if A[nr][nc]: # 바구니에 물 있는 곳이면
waterCnt += 1
A[r][c] += waterCnt # 4방향 중 물이 있는 곳의 갯수만큼 더함
# 5. 바구니에 저장된 물의 양이 2 이상인 모든 칸에 구름이 생기고, 물의 양이 2 줄어든다.
def makeNewClouds():
clouds = set() # 3. 구름이 모두 사라진다. 초기화 후 재활용
for r in range(N):
for c in range(N):
if (r, c) in newClouds: # 구름이 있던 곳이면 넘어감
continue
if A[r][c] >= 2: # 물의 양 2 이상인 모든 칸에 물이 생기고
clouds.add((r, c)) # 구름의 새 위치 추가
A[r][c] -= 2 # 물의 양 2 줄어듦
return clouds
# main
N, M = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(N)]
clouds = {(N-2, 0), (N-2, 1), (N-1, 0), (N-1, 1)}
# 비바라기 M번 시전
for m in range(M):
d, s = map(int, input().split())
newClouds = moveClouds(d, s) # 구름 이동 후 새 위치 리턴
rainFall()
clouds = makeNewClouds() # 구름의 새 위치 리턴
# 출력
result = 0
for row in range(N):
for col in range(N):
result += A[row][col]
print(result) |
Python | UTF-8 | 2,252 | 3.71875 | 4 | [] | no_license | import time
class Call(object):
def __init__(self, unique_id, name, number, call_time, reason):
self.unique_id = unique_id
self.name = name
self.number = number
try:
time.strptime(call_time.replace(":", " "), "%I %M %p")
self.call_time = call_time
except ValueError:
print "Time of call #{} formatted incorrectly. Times should be formatted like so: 8:05 PM.\nCall moved to end of queue automatically.".format(unique_id)
self.call_time = "11:59 PM"
self.reason = reason
self.formatted_time = time.strptime(self.call_time.replace(":", " "), "%I %M %p")
def displayCall(self):
print "Unique ID: {}\nCaller Name: {}\nCaller Phone Number: {}\nTime of Call: {}\nReason for Call: {}\n".format(self.unique_id, self.name, self.number, self.call_time, self.reason)
return self
class CallCenter(object):
def __init__(self):
self.calls = []
self.queue_size = len(self.calls)
def set_queue(self):
self.queue_size = len(self.calls)
def add(self, *args):
#Hacker Level
for i in args:
if len(self.calls) >= 1:
idx = 0
for k in range(0, len(self.calls)):
if i.formatted_time > self.calls[k].formatted_time:
idx = k + 1
self.calls.insert(idx, i)
else:
self.calls.append(i)
self.set_queue()
return self
def remove(self):
del self.calls[0]
return self
def info(self):
self.set_queue()
print "\nCalls in Queue: {}\n".format(self.queue_size)
for i in self.calls:
print "Call Details:\n--------------"
i.displayCall()
return self
#Ninja Level
def dropCall(self, call_to_drop):
for i in self.calls:
if call_to_drop == i.number:
self.calls.remove(i)
self.set_queue()
return self
call1 = Call("12345", "Bob Smith", "555 555 5555", "8:07 PM", "test")
call2 = Call("87643", "Lauren Ipsum", "555 123 3421", "7:08 PM", "foobar")
call3 = Call('95673', "Larry Dairy", "555 345 9876", "10:05 AM", "moo")
call4 = Call("99999", "Val U. Error", "555 987 3214", "this is wrong", "can't give time in correct format")
call5 = Call('23456', "Baller Caller", '444 321 9876', "1:34 PM", "Wish I was taller")
verizon = CallCenter()
verizon.add(call1)
verizon.add(call2)
verizon.add(call3)
verizon.add(call4)
verizon.add(call5)
verizon.info()
verizon.dropCall('555 345 9876')
verizon.info() |
Python | UTF-8 | 1,178 | 3.5 | 4 | [] | no_license | #PROBLEM 19b
def leapYear(year):
if year%4 == 0:
return True
else:
return False
def generate():
lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
leaplengths = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
a = []
for bob in range(1901,2001):
if leapYear(bob):
a += leaplengths
else:
a += lengths
return a
def solution(dayChosen):
days = "Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split()
months = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split()
a = generate()
initial = 1
count = 0
position = 0
day = days.index(dayChosen)
print("Day Chosen: " + dayChosen)
for blob in a:
initial += blob
position += 1
b = initial%7
if b == day:
count += 1
c = position / 12
d = (position % 12)
print(months[d] + " " + str(int(c)+1901), end = ', ')
return [count, days[day]]
print("Choose a day: ")
dayChosen = input()
e = solution(dayChosen)
print("Number of " + str(e[1]) + "s: " + str(e[0]))
#answer = 171
|
JavaScript | UTF-8 | 933 | 2.734375 | 3 | [] | no_license | //array of maps to display on timer
var map_array = ["BWheat_1949-min.png", "BWheat_1954-min.png", "BWheat_1959-min.png", "BWheat_1964-min.png", "BWheat_1969-min.png", "BWheat_1974-min.png", "BWheat_1978-min.png", "BWheat_1982-min.png", "BWheat_1987-min.png", "BWheat_1992-min.png", "BWheat_1997-min.png", "BWheat_2002-min.png", "BWheat_2007-min.png", "BWheat_2012-min.png"];
$("#play1").on("click", function() { //Play Fast button is pressed
$("#play1").prop("disabled", true);//disable button so cannot restart and mess up photo order
var c = 0;
interval = setInterval(function() { //setTimeout() does once
if (c>12) { //once all the maps in the array have been displayed
clearInterval(interval);//stop interval program
$("#play1").prop("disabled", false);
}
switch_func(c);
c++;
}, 1000);
function switch_func(c) {
$("#map").attr("src", "/images/maps/"+map_array[c]); //switch to the next map
}
});
|
PHP | UTF-8 | 562 | 2.625 | 3 | [] | no_license | <?php
declare(strict_types=1);
namespace TMV\OpenIdClient\Token;
use TMV\OpenIdClient\Client\ClientInterface;
use TMV\OpenIdClient\Session\AuthSessionInterface;
interface TokenSetVerifierInterface
{
/**
* @return IdTokenVerifierInterface
*/
public function getIdTokenVerifier(): IdTokenVerifierInterface;
public function validate(
TokenSetInterface $tokenSet,
ClientInterface $client,
?AuthSessionInterface $authSession = null,
bool $fromAuthorization = true,
?int $maxAge = null
): void;
}
|
Java | UTF-8 | 281 | 1.765625 | 2 | [] | no_license | package irepdata.dao;
import irepdata.model.Content;
/**
* Created by Gvozd on 27.11.2016.
*/
public interface ContentDao {
public Content getContent(Long id);
public void createContent(Content content);
public boolean updateContent(Long ideaId, String content);
}
|
PHP | UTF-8 | 703 | 3.09375 | 3 | [] | no_license | <?php
define('SECRET_IV', pack('a16', 'c0nt0s')); // senha pode ser alterada
define('SECRET', pack('a16', 'f@d@s')); // senha pode ser alterada
$data = [
"nome"=>"1234567890123456"
];
$openssl = openssl_encrypt(
json_encode($data),
'AES-128-CBC', // metodo de cryptografia
SECRET, // primeira chave
0, // pode manter 0
SECRET_IV // segunda chave
);
echo $openssl;
$string = openssl_decrypt($openssl, 'AES-128-CBC', SECRET, 0, SECRET_IV);
echo "<br><br>";
var_dump(json_decode($string, true));
echo "<br><br>";
echo base64_encode(base64_encode($openssl));
// Uma senha com até 16 caracters ciyptografada via openssl dessa forma com 2 base64_encode gera uma string de até 80 caracters
?> |
JavaScript | UTF-8 | 1,043 | 2.625 | 3 | [] | no_license | /* anime_scroll_relative_content_davy */
function anime_scroll_relative_content_davy(block_anime_scroll_relative_content_davy, scroll_relative_content) {
var block_anime_scroll_relative_content = document.getElementsByClassName(block_anime_scroll_relative_content_davy);
var scroll_relative_content_davy = (window.pageYOffset - block_anime_scroll_relative_content[0].offsetTop) / (block_anime_scroll_relative_content[0].offsetHeight);
if ((scroll_relative_content_davy >= 0) && (scroll_relative_content_davy <= 1)) {
document.body.style.setProperty(scroll_relative_content, scroll_relative_content_davy);
}
if (scroll_relative_content_davy < 0) {
document.body.style.setProperty(scroll_relative_content, 0);
}
if (scroll_relative_content_davy > 1) {
document.body.style.setProperty(scroll_relative_content, 1);
}
}
window.addEventListener("scroll", () => {
anime_scroll_relative_content_davy("block_anime_scroll_relative_content_1_davy", "--scroll_relative_content_1");
}, false);
|
Go | UTF-8 | 2,995 | 2.796875 | 3 | [] | no_license | package handlers
import (
"net/http"
"revelbus/cmd/web/utils"
"revelbus/cmd/web/view"
"revelbus/internal/platform/domain"
"revelbus/internal/platform/domain/models"
"revelbus/internal/platform/flash"
"strconv"
"github.com/gorilla/mux"
)
func FaqForm(w http.ResponseWriter, r *http.Request) {
id := r.FormValue("id")
if id == "" {
view.Render(w, r, "faq-admin", &view.View{
Form: new(models.FAQForm),
Title: "New FAQ",
})
return
}
faq := &models.FAQ{
ID: utils.ToInt(id),
}
err := faq.Fetch()
if err != nil {
if err == domain.ErrNotFound {
view.NotFound(w, r)
return
}
view.ServerError(w, r, err)
return
}
f := &models.FAQForm{
ID: strconv.Itoa(faq.ID),
Question: faq.Question.String,
Answer: faq.Answer.String,
Category: faq.Category.String,
Order: strconv.FormatInt(faq.Order.Int64, 10),
Active: faq.Active,
}
view.Render(w, r, "faq-admin", &view.View{
Title: "FAQ",
Form: f,
})
}
func PostFAQ(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
view.ClientError(w, r, http.StatusBadRequest)
return
}
f := &models.FAQForm{
ID: r.PostForm.Get("id"),
Question: r.PostForm.Get("question"),
Category: r.PostForm.Get("category"),
Answer: r.PostForm.Get("answer"),
Order: r.PostForm.Get("order"),
Active: (len(r.Form["active"]) == 1),
}
if !f.Valid() {
v := &view.View{
Form: f,
Title: "FAQ",
}
if f.ID == "" {
v.Title = "New FAQ"
}
view.Render(w, r, "faq-admin", v)
}
var msg string
faq := models.FAQ{
ID: utils.ToInt(f.ID),
Question: utils.NewNullStr(f.Question),
Answer: utils.NewNullStr(f.Answer),
Category: utils.NewNullStr(f.Category),
Order: utils.NewNullInt(utils.ToInt(f.Order)),
Active: f.Active,
}
if faq.ID != 0 {
err := faq.Update()
if err != nil {
if err == domain.ErrNotFound {
view.NotFound(w, r)
return
}
view.ServerError(w, r, err)
return
}
msg = utils.MsgSuccessfullyUpdated
} else {
err := faq.Create()
if err != nil {
view.ServerError(w, r, err)
return
}
msg = utils.MsgSuccessfullyCreated
}
err = flash.Add(w, r, msg, "success")
if err != nil {
view.ServerError(w, r, err)
return
}
id := strconv.Itoa(faq.ID)
http.Redirect(w, r, "/admin/faq?id="+id, http.StatusSeeOther)
}
func ListFAQs(w http.ResponseWriter, r *http.Request) {
faqs, err := models.FetchFAQs()
if err != nil {
view.ServerError(w, r, err)
return
}
view.Render(w, r, "faqs-admin", &view.View{
Title: "FAQs",
FAQs: faqs,
})
}
func RemoveFAQ(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
id := vars["id"]
faq := models.FAQ{
ID: utils.ToInt(id),
}
err := faq.Delete()
if err != nil {
view.ServerError(w, r, err)
return
}
err = flash.Add(w, r, utils.MsgSuccessfullyRemoved, "success")
if err != nil {
view.ServerError(w, r, err)
return
}
http.Redirect(w, r, "/admin/faqs", http.StatusSeeOther)
}
|
Python | UTF-8 | 9,158 | 2.671875 | 3 | [] | no_license | """
Name : run_mvo.py
Author : Yinsen Miao
Contact : yinsenm@gmail.com
Time : 7/1/2021
Desc : run mean-variance optimization
"""
from util import get_mean_variance_space, plot_efficient_frontiers, get_frontier_limits
import pandas as pd
import numpy as np
import pickle
import os
from tqdm import tqdm
import argparse
DEBUG = 0
# define global variables
target_volatilities_array = np.arange(2, 16) / 100. # target volatility level from 2% to 16%
obj_function_list = ['minVariance', 'maxSharpe']
cov_function_list = ["HC", "SM", "GS1"] # list of covariance function
# portfolio setting
cash_start = 100000.
risk_free_rate = 0.
gs_threshold = 0.9 # threshold for gerber statistics
lookback_win_in_year = 2
lookback_win_size = 12 * lookback_win_in_year
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Parse parameter for Bloomberg 9")
parser.add_argument("-s", "--gs_threshold", type=float, default=0.5)
parser.add_argument("-o", "--optimization_cost", type=float, default=10)
parser.add_argument("-t", "--transaction_cost", type=float, default=10)
args = parser.parse_args()
gs_threshold = args.gs_threshold # threshold for gerber statistics
optimization_cost = args.optimization_cost # penalty for excessive transaction
transaction_cost = args.transaction_cost # actual transaction fee in trading simulation
savepath = "../results/%dyr_c%02dbps_t%02dbps/gs_threshold%.2f" % \
(lookback_win_in_year, optimization_cost, transaction_cost, gs_threshold)
prcs = pd.read_csv("../data/prcs.csv", parse_dates=['Date']).\
set_index(['Date'])
rets = prcs.pct_change().dropna(axis=0)
prcs = prcs.iloc[1:] # drop first row
nT, p = prcs.shape
symbols = prcs.columns.to_list()
# create folder to save results
os.makedirs("%s" % savepath, exist_ok=True)
os.makedirs("%s/plots" % savepath, exist_ok=True)
port_names = obj_function_list + ['%02dpct' % int(tgt * 100) for tgt in target_volatilities_array]
"""
initialize the portfolio below:
- equalWeighting
- minVariance
- maxReturn
- maxSharpe
- maxSortino
- riskParity
- meanVariance with risk constraints 3pct, 6pct, 9pct, 12pct, 15pct
"""
account_dict = {}
for cov_function in cov_function_list:
account_dict[cov_function] = {}
for port_name in port_names:
account_dict[cov_function][port_name] = []
account_dict[cov_function][port_name].append(
{
"date": prcs.index[lookback_win_size - 1].strftime("%Y-%m-%d"),
"weights": np.array([0] * p), # portfolio weight for each asset
"shares": np.array([0] * p), # portfolio shares for each asset
"values": np.array([0] * p), # portfolio dollar value for each asset
"portReturn": 0,
"transCost": 0,
"weightDelta": 0, # compute portfolio turnover for current rebalancing period
"portValue": cash_start,
}
)
# # save the trajectory of efficient frontier
# efficient_frontiers = {}
# for cov_function in cov_function_list:
# efficient_frontiers[cov_function] = []
t = lookback_win_size
# keep track of previous optimal weights to penalize extensive turnover
prev_port_weights_dict = {key: None for key in cov_function_list}
for t in tqdm(range(lookback_win_size, nT)):
bgn_date = rets.index[t - lookback_win_size]
end_date = rets.index[t - 1]
end_date_p1 = rets.index[t]
bgn_date_str = bgn_date.strftime("%Y-%m-%d")
end_date_str = end_date.strftime("%Y-%m-%d")
end_date_p1_str = end_date_p1.strftime("%Y-%m-%d")
# subset the data accordingly
sub_rets = rets.iloc[t - lookback_win_size: t]
_nT, _ = sub_rets.shape
prcs_t = prcs.iloc[t-1: t].values[0] # price at time t
prcs_tp1 = prcs.iloc[t: t + 1].values[0] # price at time t + 1
rets_tp1 = rets.iloc[t: t + 1].values[0] # return at time t + 1
if DEBUG:
print("MVO optimimize from [%s, %s] (n=%d) and applied to rets at %s" % \
(bgn_date_str, end_date_str, _nT, end_date_p1_str))
# get portfolio weight for a given cov_function
opt_ports_dict = {}
for cov_function in cov_function_list:
if DEBUG:
print("Processing %s ..." % cov_function)
opt_ports_dict[cov_function] = get_mean_variance_space(sub_rets,
target_volatilities_array,
obj_function_list, cov_function,
prev_port_weights=prev_port_weights_dict[cov_function],
gs_threshold=gs_threshold,
cost=optimization_cost)
prev_port_weights_dict[cov_function] = opt_ports_dict[cov_function]["port_opt"]
for port_name in port_names:
port_tm1 = account_dict[cov_function][port_name][-1]
# updated portfolio
port_t = {
"date": end_date_p1_str,
"weights": opt_ports_dict[cov_function]['port_opt'][port_name]['weights'],
"shares": None,
"values": None,
"portReturn": None,
"transCost": None,
"weightDelta": None, # compute portfolio turnover for current rebalancing period
"portValue": None
}
# calculate shares given new weight
port_t["shares"] = port_tm1['portValue'] * port_t["weights"] / prcs_t
port_t["portReturn"] = (port_t["weights"] * rets_tp1).sum()
port_t['values'] = port_t['weights'] * port_tm1['portValue']
# compute transaction by trading volume
# redistribute money according to the new weight
volume_buy = np.maximum(port_t["values"] - port_tm1["values"], 0)
volume_sell = np.maximum(port_tm1["values"] - port_t["values"], 0)
port_t["transCost"] = (volume_buy + volume_sell).sum() * transaction_cost / 10000 # pay 10bps transaction cost
# calculate portfolio turnover for this period
port_t["weightDelta"] = np.sum(np.abs(port_t["weights"] - port_tm1["weights"]))
# calculate updated portfolio at time t
port_t["portValue"] = (port_tm1['portValue'] - port_t["transCost"]) * (1 + port_t['portReturn'])
account_dict[cov_function][port_name].append(port_t)
# # save efficient frontier for both ex-ante and ex-post
# efficient_frontier = {
# "date": end_date_p1_str,
# "rets": [round(ret, 3) for ret in opt_ports_dict[cov_function]["mvo"]["rets"]], # ex-ante annual return
# "stds": [round(std, 3) for std in opt_ports_dict[cov_function]["mvo"]["stds"]], # ex-ante annual risk (std)
# "post_rets": [(wgt * rets_tp1).sum() for wgt in opt_ports_dict[cov_function]["mvo"]["weights"]] # ex-post monthly return
# }
# efficient_frontiers[cov_function].append(efficient_frontier)
# plot efficient frontiers among HC, GS1, and GS2
plot_efficient_frontiers(opt_ports_dict, prefix="%s/plots" % savepath)
# save the port result as a pickle file
with open("%s/result.pickle" % savepath, "wb") as f:
pickle.dump(account_dict, f)
# # load saved pickle file
# with open("%s/result.pickle" % savepath, "rb") as f:
# account_dict = pickle.load(f)
for cov_func in cov_function_list:
portAccountDF = pd.DataFrame.from_dict({
(port_name, account['date']): {
"value": account['portValue'],
"return": account['portReturn'],
"trans": account['transCost'],
"turnover": account['weightDelta']
}
for port_name in account_dict[cov_func].keys()
for account in account_dict[cov_func][port_name]
}, orient='index')
portAccountDF.reset_index(inplace=True)
portAccountDF.columns = ['port', 'date', 'value', 'return', 'trans', 'turnover']
portAccountDF.pivot(index="date", columns='port', values='value'). \
to_csv("%s/%s_value.csv" % (savepath, cov_func))
portAccountDF.pivot(index="date", columns='port', values='return'). \
to_csv("%s/%s_return.csv" % (savepath, cov_func))
portAccountDF.pivot(index="date", columns='port', values='trans'). \
to_csv("%s/%s_trans.csv" % (savepath, cov_func))
portAccountDF.pivot(index="date", columns='port', values='turnover'). \
to_csv("%s/%s_turnover.csv" % (savepath, cov_func)) |
PHP | UTF-8 | 1,911 | 3.09375 | 3 | [] | no_license | <?php
namespace App\Lib;
use PDO;
/**
* <b>CLASS</b>
*
* Objeto responsável pelas configurações de acesso a base de dados.
*
* @package App\Lib
* @author Original Manoel Louro <manoel.louro@redetelecom.com.br>
* @date 17/06/2021
*/
class ConexaoBD {
/**
* Conexão padrao do sistema (CRUD INTERNO).
*
* @var PDO
*/
private static $CONEXAO_DEFAULT;
/**
* <b>CONSTRUTOR</b>
* <br>Construtor da classe bloqueado
*
* @author Manoel Louro <manoel.louro@redetelecom.com.br>
* @date 10/05/2019
*/
private function __construct() {
//BLOQUEADO
}
/**
* <b>FUNÇÃO CORE</b>
* <br>Retorna instancia de conexão com a base de dados padrão do sistema.
*
* @return PDO Conexão configurada
* @author Manoel Louro <manoel.louro@redetelecom.com.br>
* @date 10/05/2019
*/
static function getConnection() {
//CONFIGURACAO
$DB_DRIVER = 'mysql';
$DB_HOST = 'localhost';
$DB_NAME = 'pinguins_dev';
$DB_USER = 'root';
$DB_PASS = 'A.)NoZMZp3dR';
$pdoConfig = $DB_DRIVER . ":" . "host=" . $DB_HOST . ";";
$pdoConfig .= "dbname=" . $DB_NAME . ";";
try {
if (!isset(self::$CONEXAO_DEFAULT)) {
self::$CONEXAO_DEFAULT = new PDO($pdoConfig, $DB_USER, $DB_PASS);
self::$CONEXAO_DEFAULT->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$CONEXAO_DEFAULT;
} catch (\PDOException $erro) {
error_log($erro->getMessage());
exit();
}
}
/**
* <b>CORE</b>
* <br>Caso haja alguma conexão DEFAULT a mesma é fechada.
*
* @author Manoel Louro <manoel.louro@redetelecom.com.br>
* @date 24/09/2019
*/
static function setConnectionClose() {
if (isset(self::$CONEXAO_DEFAULT)) {
self::$CONEXAO_DEFAULT = null;
}
}
}
|
Markdown | UTF-8 | 2,064 | 2.859375 | 3 | [
"MulanPSL-2.0",
"LicenseRef-scancode-mulanpsl-2.0-en",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ---
---
---
title: 对于《新潮》一部分的意见[17]
---
孟真[18]先生:
来信收到了。现在对于《新潮》[19]没有别的意见:倘以后想到什么,极愿意随时通知。
《新潮》每本里面有一二篇纯粹科学文,也是好的。但我的意见,以为不要太多;而且最好是无论如何总要对于中国的老病刺他几针,譬如说天文忽然骂阴历,讲生理终于打医生之类。现在的老先生听人说“地球椭圆”,“元素七十七种”,是不反对的了。《新潮》里装满了这些文章,他们或者还暗地里高兴。(他们有许多很鼓吹少年专讲科学,不要议论,《新潮》三期通信内有史志元先生的信[20],似乎也上了他们的当。)现在偏要发议论,而且讲科学,讲科学而仍发议论,庶几乎他们依然不得安稳,我们也可告无罪于天下了。总而言之,从三皇五帝时代的眼光看来,讲科学和发议论都是蛇,无非前者是青梢蛇,后者是蝮蛇罢了;一朝有了棍子,就都要打死的。既然如此,自然还是毒重的好。——但蛇自己不肯被打,也自然不消说得。
《新潮》里的诗写景叙事的多,抒情的少,所以有点单调。此后能多有几样作风很不同的诗就好了。翻译外国的诗歌也是一种要事,可惜这事很不容易。
《狂人日记》很幼稚,而且太逼促,照艺术上说,是不应该的。来信说好,大约是夜间飞禽都归巢睡觉,所以单见蝙蝠能干了。我自己知道实在不是作家,现在的乱嚷,是想闹出几个新的创作家来,——我想中国总该有天才,被社会挤倒在底下,——破破中国的寂寞。
《新潮》里的《雪夜》,《这也是一个人》,《是爱情还是苦痛》[21](起首有点小毛病),都是好的。上海的小说家梦里也没有想到过。这样下去,创作很有点希望。《扇误》[22]译的很好。《推霞》[23]实在不敢恭维。
鲁迅 四月十六日 |
Java | UTF-8 | 7,773 | 1.84375 | 2 | [] | no_license | package org.zzy.driver.mvp.ui.activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.linchaolong.android.imagepicker.ImagePicker;
import com.linchaolong.android.imagepicker.cropper.CropImage;
import com.linchaolong.android.imagepicker.cropper.CropImageView;
import com.zzy.quick.image.ImageFactory;
import com.zzy.quick.mvp.ui.BaseActivity;
import com.zzy.quick.router.Router;
import com.zzy.quick.utils.FileUtils;
import com.zzy.quick.utils.SPUtils;
import com.zzy.quick.utils.ToastUtils;
import org.zzy.driver.R;
import org.zzy.driver.common.AppConfig;
import org.zzy.driver.common.CommonValue;
import org.zzy.driver.common.UserAuthTypeEnunm;
import org.zzy.driver.mvp.model.bean.response.ResponseUserInfo;
import org.zzy.driver.mvp.model.bean.response.ResponseVehicle;
import org.zzy.driver.mvp.presenter.PersonCenterPresenter;
import org.zzy.driver.mvp.presenter.PersonInfoPresenter;
import org.zzy.driver.utils.UserInfoUtils;
import org.zzy.driver.utils.VehicleInfoUtils;
import java.io.File;
import butterknife.BindView;
import butterknife.OnClick;
/**
* Created by zhou on 2018/5/11.
*/
public class PersonInfoActivity extends BaseActivity<PersonInfoPresenter> {
@BindView(R.id.iv_icon)
ImageView ivIcon;
@BindView(R.id.ll_head)
LinearLayout llHead;
@BindView(R.id.tv_userName)
TextView tvUserName;
@BindView(R.id.tv_phone)
TextView tvPhone;
@BindView(R.id.ll_contact)
LinearLayout llContact;
@BindView(R.id.tv_baseName)
TextView tvBaseName;
@BindView(R.id.layout_region)
LinearLayout layoutRegion;
@BindView(R.id.tv_vehicleCode)
TextView tvVehicleCode;
@BindView(R.id.tv_userType)
TextView tvUserType;
@BindView(R.id.tv_company)
TextView tvCompany;
@BindView(R.id.ll_resetpassword)
LinearLayout llResetpassword;
@BindView(R.id.ll_exit)
LinearLayout llExit;
private ImagePicker imagePicker = new ImagePicker();
private ResponseUserInfo userInfo;
@Override
public PersonInfoPresenter newPresenter() {
return new PersonInfoPresenter();
}
@Override
public int getLayoutId() {
return R.layout.activity_personinfo;
}
@Override
public void initView() {
super.initView();
getTopbar().setTitle("个人信息");
getTopbar().setLeftImageListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
}
@Override
public void initData() {
//设置裁剪图片
imagePicker.setCropImage(true);
userInfo = UserInfoUtils.getUserInfo();
//先注释,以后有用
//ResponseVehicle vehicleInfo = VehicleInfoUtils.getVehicleInfo();
tvUserName.setText(userInfo.getReal_name());
tvPhone.setText(userInfo.getPhone());
tvBaseName.setText(userInfo.getRegion_name());
tvUserType.setText(UserAuthTypeEnunm.getName(userInfo.getAuth_type()));
tvCompany.setText(userInfo.getOrganization_name());
//tvVehicleCode.setText(vehicleInfo.getCode());
showAvatar();
}
/**
* 显示头像
* */
public void showAvatar(){
ImageFactory.getImageLoader()
.loadCircleImage(AppConfig.IMAGE_URL + userInfo.getIcon(),ivIcon,R.drawable.img_default_avatar);
}
@Override
public void showError(String msg) {
}
/**
* @function 修改头像
* */
@OnClick(R.id.ll_head)
public void clickUpdateHead(){
startCameraOrGallery();
}
/**
* @function 修改手机号
* */
public void clickUpdatePhone(){
}
/**
* @function 修改驻地
* */
public void clickUpdateBaseName(){
}
/**
* @function 修改登录密码
* */
public void clickUpdatePassword(){
}
/**
* @function 点击退出,清除SP中用户数据
* */
@OnClick(R.id.ll_exit)
public void clickExit(){
SPUtils.getInstance().remove(CommonValue.USERINFO);
SPUtils.getInstance().remove(CommonValue.VEHICLEINFO);
SPUtils.getInstance().remove(CommonValue.USERID);
SPUtils.getInstance().remove(CommonValue.TOKENCODE);
Router.newIntent(this).to(LoginActivity.class).launch();
finish();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
imagePicker.onActivityResult(this,requestCode,resultCode,data);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
imagePicker.onRequestPermissionsResult(this,requestCode,permissions,grantResults);
}
/**
* 弹出对话框,选择相册或者启动摄像头拍照
* */
private void startCameraOrGallery() {
new AlertDialog.Builder(this).setTitle("设置头像")
.setItems(new String[] { "从相册中选取图片", "拍照" }, new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
// 回调
ImagePicker.Callback callback = new ImagePicker.Callback() {
@Override public void onPickImage(Uri imageUri) {
}
@Override public void onCropImage(Uri imageUri) {
File file=FileUtils.uri2File(imageUri);
if(file!=null) {
getPresenter().setUserHead(file);
}else{
ToastUtils.showShort("图片地址错误!");
}
}
@Override
public void cropConfig(CropImage.ActivityBuilder builder) {
super.cropConfig(builder);
builder
// 是否启动多点触摸
.setMultiTouchEnabled(false)
// 设置网格显示模式
.setGuidelines(CropImageView.Guidelines.OFF)
// 圆形/矩形
.setCropShape(CropImageView.CropShape.OVAL)
// 调整裁剪后的图片最终大小
.setRequestedSize(960, 540)
// 宽高比
.setAspectRatio(9, 9);
}
};
if (which == 0) {
// 从相册中选取图片
imagePicker.startGallery(PersonInfoActivity.this, callback);
} else {
// 拍照
imagePicker.startCamera(PersonInfoActivity.this, callback);
}
}
})
.show()
.getWindow()
.setGravity(Gravity.BOTTOM);
}
}
|
Swift | UTF-8 | 3,586 | 2.9375 | 3 | [] | no_license | //
// ImageViewerView.swift
// MyCamera
//
// Created by Aung Ko Min on 9/3/21.
//
import SwiftUI
import AVKit
struct ImageViewerView: View {
let photo: Photo
@Environment(\.presentationMode) var presentationMode
@State private var isFavourite = false
init(photo: Photo) {
self.photo = photo
self.isFavourite = photo.isFavourite
}
var body: some View {
NavigationView{
VStack {
Spacer()
if photo.isVideo, let url = photo.mediaUrl {
VideoPlayer(player: AVPlayer(url: url))
}else {
if let image = photo.originalImage {
Image(uiImage: image)
.resizable()
.scaledToFit()
.pinchToZoom()
}
}
Spacer()
if Utils.isPotrait() {
bottomBar()
}
}
.navigationBarTitleDisplayMode(.inline)
.navigationBarItems(leading: Button("Cancel") {
presentationMode.wrappedValue.dismiss()
}
, trailing: Text(Int(photo.fileSize).byteSize).font(.footnote))
.navigationTitle("\(photo.date ?? Date(), formatter: relativeDateFormat)")
.onAppear{
isFavourite = photo.isFavourite
}
}
}
private func bottomBar() -> some View {
return HStack {
Button {
if let url = photo.mediaUrl {
share(items: [url])
}
} label: {
Image(systemName: "square.and.arrow.up")
}
Spacer()
Button {
SoundManager.vibrate(vibration: .selection)
photo.isFavourite.toggle()
isFavourite = photo.isFavourite
} label: {
Image(systemName: isFavourite ? "heart.fill" : "heart")
}
Spacer()
Button {
let action = {
Photo.delete(photo: photo)
presentationMode.wrappedValue.dismiss()
}
let actionPair = ActionPair("Confirm Delete", action, .destructive)
AlertPresenter.presentActionSheet(title: "Delete this item?", actions: [actionPair])
} label: {
Image(systemName: "trash")
}
}.padding()
}
private func share(items: [Any]) {
let ac = UIActivityViewController(activityItems: items, applicationActivities: nil)
UIApplication.getTopViewController()?.present(ac, animated: true)
}
}
// Our custom view modifier to track rotation and
// call our action
struct DeviceRotationViewModifier: ViewModifier {
let action: (UIDeviceOrientation) -> Void
func body(content: Content) -> some View {
content
.onAppear()
.onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)) { _ in
action(UIDevice.current.orientation)
}
}
}
// A View wrapper to make the modifier easier to use
extension View {
func onRotate(perform action: @escaping (UIDeviceOrientation) -> Void) -> some View {
self.modifier(DeviceRotationViewModifier(action: action))
}
}
|
Python | UTF-8 | 1,308 | 2.609375 | 3 | [] | no_license | from django.conf import settings
from django.shortcuts import get_object_or_404
from stock.models import Item
from decimal import Decimal
def cart_contents(request):
''' Creates the cart contents context to be used
throughout the site not just in the cart app '''
cart_items = []
total = 0
item_count = 0
cart = request.session.get("cart", {})
for item_id, quantity in cart.items():
item = get_object_or_404(Item, pk=item_id)
total += quantity * item.price
item_count += quantity
cart_items.append({
"item_id": item_id,
"quantity": quantity,
"item": item,
})
delivery_cost = total * Decimal(settings.DELIVERY_COST_PERCENTAGE/100)
if delivery_cost < settings.STANDARD_HOME_DELIVERY_COST_MIN:
home_delivery = settings.STANDARD_HOME_DELIVERY_COST_MIN
elif delivery_cost > settings.STANDARD_HOME_DELIVERY_COST_MAX:
home_delivery = settings.STANDARD_HOME_DELIVERY_COST_MAX
else:
home_delivery = delivery_cost
grand_total = home_delivery + total
context = {
"cart_items": cart_items,
"total": total,
"item_count": item_count,
"home_delivery": home_delivery,
"grand_total": grand_total,
}
return context
|
Python | UTF-8 | 114 | 3.65625 | 4 | [] | no_license | for i in range(1, 31, 1):
if (i % 5 == 0) :
print("*\n",end="")
else :
print("* ",end="") |
Java | UTF-8 | 6,865 | 2.109375 | 2 | [
"MIT"
] | permissive |
package com.fetchsky.RNTextDetector;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.util.Log;
import androidx.annotation.NonNull;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.text.FirebaseVisionText;
import com.google.firebase.ml.vision.text.FirebaseVisionTextRecognizer;
import java.io.IOException;
import java.net.URL;
public class RNTextDetectorModule extends ReactContextBaseJavaModule {
private final ReactApplicationContext reactContext;
private FirebaseVisionTextRecognizer detector;
private FirebaseVisionImage image;
public RNTextDetectorModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
try {
detector = FirebaseVision.getInstance().getOnDeviceTextRecognizer();
}
catch (IllegalStateException e) {
e.printStackTrace();
}
}
@ReactMethod
public void detectFromFile(String uri, final Promise promise) {
try {
image = FirebaseVisionImage.fromFilePath(this.reactContext, android.net.Uri.parse(uri));
Task<FirebaseVisionText> result =
detector.processImage(image)
.addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
@Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
promise.resolve(getDataAsArray(firebaseVisionText));
}
})
.addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
e.printStackTrace();
promise.reject(e);
}
});;
} catch (IOException e) {
promise.reject(e);
e.printStackTrace();
}
}
@ReactMethod
public void detectFromUri(String uri, final Promise promise) {
try {
URL url = new URL(uri);
image = FirebaseVisionImage.fromBitmap(BitmapFactory.decodeStream(url.openConnection().getInputStream()));
Task<FirebaseVisionText> result =
detector.processImage(image)
.addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
@Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
promise.resolve(getDataAsArray(firebaseVisionText));
}
})
.addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
e.printStackTrace();
promise.reject(e);
}
});;
} catch (IOException e) {
promise.reject(e);
e.printStackTrace();
}
}
/**
* Converts firebaseVisionText into a map
*
* @param firebaseVisionText
* @return
*/
private WritableArray getDataAsArray(FirebaseVisionText firebaseVisionText) {
WritableArray data = Arguments.createArray();
for (FirebaseVisionText.TextBlock block: firebaseVisionText.getTextBlocks()) {
WritableArray blockElements = Arguments.createArray();
for (FirebaseVisionText.Line line: block.getLines()) {
WritableArray lineElements = Arguments.createArray();
for (FirebaseVisionText.Element element: line.getElements()) {
WritableMap e = Arguments.createMap();
WritableMap eCoordinates = Arguments.createMap();
eCoordinates.putInt("top", element.getBoundingBox().top);
eCoordinates.putInt("left", element.getBoundingBox().left);
eCoordinates.putInt("width", element.getBoundingBox().width());
eCoordinates.putInt("height", element.getBoundingBox().height());
e.putString("text", element.getText());
// e.putDouble("confidence", element.getConfidence());
e.putMap("bounding", eCoordinates);
lineElements.pushMap(e);
}
WritableMap l = Arguments.createMap();
WritableMap lCoordinates = Arguments.createMap();
lCoordinates.putInt("top", line.getBoundingBox().top);
lCoordinates.putInt("left", line.getBoundingBox().left);
lCoordinates.putInt("width", line.getBoundingBox().width());
lCoordinates.putInt("height", line.getBoundingBox().height());
l.putString("text", line.getText());
// l.putDouble("confidence", line.getConfidence());
l.putMap("bounding", lCoordinates);
l.putArray("elements", lineElements);
blockElements.pushMap(l);
}
WritableMap info = Arguments.createMap();
WritableMap coordinates = Arguments.createMap();
coordinates.putInt("top", block.getBoundingBox().top);
coordinates.putInt("left", block.getBoundingBox().left);
coordinates.putInt("width", block.getBoundingBox().width());
coordinates.putInt("height", block.getBoundingBox().height());
info.putMap("bounding", coordinates);
info.putString("text", block.getText());
info.putArray("lines", blockElements);
// info.putDouble("confidence", block.getConfidence());
data.pushMap(info);
}
return data;
}
@Override
public String getName() {
return "RNTextDetector";
}
}
|
Python | UTF-8 | 1,799 | 2.96875 | 3 | [] | no_license |
import numpy as np
from sklearn.cluster import KMeans
from HMSM.util.linalg import normalize_rows, normalized_laplacian
def spectral(P, k, eig=None, return_eig=False):
"""
Cluster the data into k clusters using the spectral clustering algorithm.
:param P: A transition probability matrix
:param k: The number of desired clusters.
:return: clustering an np.ndarray such that clustering[i] is the assignment of the i'th vertex
"""
# Sometimes we may call this function many times on the same X, so we want to be able to
# calculate the eigenvectors once in advance, because that may be the heaviest part computationally
if eig is not None:
e_vals, e_vecs = eig
else:
L = normalized_laplacian(P)
e_vals, e_vecs = np.linalg.eig(L) # gen the eigenvectors
if return_eig:
eig = e_vals, e_vecs
e_vals = np.real(e_vals)
e_vecs = np.real(e_vecs)
k_smallest = np.argpartition(e_vals, min(k, len(e_vals)-1))[:k]
projection = e_vecs[:,k_smallest]
projection = normalize_rows(projection, norm=2)
clusters = KMeans(n_clusters=k).fit_predict(projection)
if return_eig:
return clusters, eig
return clusters
def get_size_or_timescale_split_condition(max_size=2048, max_timescale=64):
"""Get a function which checks if a vertices size or timescale are larger than some constant,
provided as arguments to this function.
"""
return size_or_timescale_split_condition(max_timescale, max_size)
class size_or_timescale_split_condition:
def __init__(self, max_timescale, max_size):
self.max_timescale = max_timescale
self.max_size = max_size
def __call__(self, vertex):
return vertex.timescale/vertex.tau > self.max_timescale or vertex.n > self.max_size
|
C | UTF-8 | 307 | 3.078125 | 3 | [] | no_license | #include <stdio.h>
#include <errno.h>
#include <string.h>
int main()
{
FILE *f_ptr;
int i;
f_ptr = fopen("nosuch.file", "r");
if (f_ptr != NULL)
{
printf("File opened\n");
}
else
{
perror("Error");
}
for (i = 0; i < 48; i++)
{
printf("Error %d : %s\n", i, strerror(i));
}
return 0;
} |
Java | UTF-8 | 1,846 | 2.34375 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package inventorymanagement.Controllers;
import java.net.URL;
import java.util.ResourceBundle;
//import javafx.collections.FXCollections;
//import javafx.collections.ObservableList;
import javafx.fxml.Initializable;
//import javafx.scene.control.ComboBox;
/**
* FXML Controller class
*
* @author User
*/
public class NISaleController implements Initializable {
/**
* Initializes the controller class.
*/
// private ComboBox comboBox;
//
// private ComboBox comboBox;
//
// @FXML
// private Button addbtn;
//
// private void Add(ActionEvent event) {
//
//
//
// Stage primaryStage = (Stage)addbtn.getScene().getWindow();
//
// Alert.AlertType type = Alert.AlertType.CONFIRMATION;
//
// Alert alert = new Alert(type, "");
//
// alert.initModality(Modality.APPLICATION_MODAL);
// alert.initOwner(primaryStage);
//
// alert.getDialogPane().setContentText("Successful !");
// alert.getDialogPane().setHeaderText(" Reply ");
//
// Optional<ButtonType> result = alert.showAndWait();
// if(result.get() == ButtonType.OK)
// {
// System.out.println("Ok button pressed");
// }
// else if(result.get() == ButtonType.CANCEL){
// System.out.println("Cancel Button pressed");
// }
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
// ObservableList<String> list = FXCollections.observableArrayList("Beauty","Books","Car","Clothing");
// comboBox.setItems(list);
}
}
|
Ruby | UTF-8 | 171 | 3.0625 | 3 | [] | no_license | def compute(string1,string2)
num_of_false = 0
string1.length.times do |n|
num_of_false += 1 if string1[n] != string2[n]
end
return num_of_false
end |
Markdown | UTF-8 | 407 | 2.5625 | 3 | [] | no_license | # PASS Summit 2017
Demos used in my "Dapper: the ORM that will change your life" session @ PASS Summit 2017
Each demo shows how to use one of the feature offered by the Micro ORM "Dapper"
https://github.com/StackExchange/Dapper
a simple yet extremely powerful and fast MicroORM.
Slides are available on SlideShare:
https://www.slideshare.net/davidemauri/dapper-the-microorm-that-will-change-your-life |
Rust | UTF-8 | 589 | 3.25 | 3 | [] | no_license | use std::io::Read;
use std::io;
const PARSE_ERROR: &str = "Parsing error. Please, use the follwing input format:
(0-9)+, (0-9)+
(N|W|E|S)
(F|L|R)+
";
fn main() {
let mut buffer = String::new();
io::stdin().read_to_string(&mut buffer).unwrap();
let mut data = match htt::parse_input(&buffer) {
Some(d) => d,
None => {
println!("{}", PARSE_ERROR);
return ();
}
};
match htt::solve(&mut data) {
Ok(p) => println!("No collision detected. Current position: {:?}", p),
Err(p) =>println!("Would collide at {:?}", p)
}
}
|
Shell | UTF-8 | 492 | 2.890625 | 3 | [] | no_license | #!/bin/bash
DATE=$(date -R)
GIT_RV=$(git rev-list HEAD | wc -l)
INEX_VERSION=$(grep "Version=" src/i-nex/.project | cut -d "=" -f 2)
DATE_Y_M_D=$(date +%Y%m%d)
echo "i-nex ($INEX_VERSION-0~git$GIT_RV~$DATE_Y_M_D) unstable; urgency=low
* next unstable
-- eloaders <eloaders@yahoo.com> $DATE
" >debian/changelog1
cp debian/changelog debian/changelog_bak
cat debian/changelog >> debian/changelog1
mv debian/changelog1 >> debian/changelog
dpkg-buildpackage
mv debian/changelog_bak debian/changelog |
Markdown | UTF-8 | 354 | 2.703125 | 3 | [] | no_license | Advanced Imputation Techniques
Finally, go beyond simple imputation techniques and make the most of your dataset by using advanced imputation techniques that rely on machine learning models, to be able to accurately impute and evaluate your missing data. You will be using methods such as KNN and MICE in order to get the most out of your missing data!
|
TypeScript | UTF-8 | 3,562 | 3.015625 | 3 | [] | no_license | import { operatorsAndPriority } from './static/calcOperators'
export default class Modifyre {
operationsStack: string[]
outputStr: string[]
constructor() {
;(this.operationsStack = []), (this.outputStr = [])
}
getPostfixExample(): string[] {
return this.outputStr
}
closingBracketOperator(): void {
let flagStopPoint = true
while (flagStopPoint) {
// while not find '(' or empty stack
const OperationStacklength: number = this.operationsStack.length
if (this.operationsStack[OperationStacklength - 1] === '(') {
flagStopPoint = false
this.operationsStack.pop()
} else {
// for prevention infinite cycle
if (OperationStacklength > 0) {
this.outputStr.push(this.operationsStack.pop() as string)
} else {
flagStopPoint = false
}
}
}
}
defaultMathOperators(mathOperator: string): void {
const operationsStackLastElement: number = this.operationsStack.length - 1
//check operator priority in operationsStack
if (
operatorsAndPriority[
this.operationsStack[operationsStackLastElement]
] >= operatorsAndPriority[mathOperator]
) {
const operatorFromStack: string = this.operationsStack.pop() as string
this.operationsStack.push(mathOperator)
this.outputStr.push(operatorFromStack)
} else {
this.operationsStack.push(mathOperator)
}
}
conversionFromInfix(inputExample: string): void {
this.outputStr = []
// =========== add whitespace and replace ','===========
inputExample = inputExample.replace(/(\,)/g, '.')
inputExample = inputExample.replace(/(\()/g, '( ')
inputExample = inputExample.replace(/(\))/g, ' )')
const splitInputExample: string[] = inputExample.split(' ')
// ========== delete all whitespace
const splitAndClearInputExample: string[] = splitInputExample.filter(
(el: string) => {
if (el !== '' && el !== ' ') {
return el
}
}
)
splitAndClearInputExample.forEach((element: string, index: number) => {
const elNumber: number = +element
// ========== negative number ============
if( (index === 0 && element === '-') || (this.operationsStack[this.operationsStack.length - 1] === '(') && element === '-'){
this.operationsStack.push(element)
this.outputStr.push('0')
return 0
}
// ========== element number or '(' ============
if (!isNaN(elNumber) || element === '(') {
element === '('
? this.operationsStack.push(element)
: this.outputStr.push(element)
return 0
}
if (element === ')') {
this.closingBracketOperator()
return 0
}
// ========== /,*,+,-,% ============
if (operatorsAndPriority.hasOwnProperty(element)) {
this.defaultMathOperators(element)
}
})
//clear from wrong '(', ')'
this.operationsStack = this.operationsStack.filter((el: string) => {
if (el !== '(' && el !== ')') {
return el
}
})
//push the remaining operation in outputStr
for (const index = 0; index < this.operationsStack.length; ) {
this.outputStr.push(this.operationsStack.pop() as string)
}
this.operationsStack = []
}
}
|
Python | UTF-8 | 9,039 | 3.984375 | 4 | [] | no_license | # Francisco Ariel Arenas Enciso
# A01369122
# Desarrollo de Misión 9 (listas)
'''Declaración de lista global'''
listaGlobal = [1,2,3,2,4,60,5,8,3,22,44,55] #Esta lista se usará en todas las funciones
'''Función que recibe una lista y mediante un cliclo 'for' regresa una NUEVA lista
con solamente los valores pares'''
def extraerPares(listaGlobal):
listaNueva = [] #Se crea una lista vacía
for valor in listaGlobal: #Ciclo 'for' que recorre a la lista
if valor % 2 == 0: #Condición que pregunta respecto a si un número es par o impar
listaNueva.append(valor) #La condición se cumple (es par) por lo tanto se añaden los valores a lista
return(listaNueva) #Se regresa el resultado
'''Función que recibe una lista y mediante un ciclo 'for' se coloca en una nueva lista, solamente
los datos mayores respecto al anterior de la lista original'''
def extraerMayorPrevio(listaGlobal):
listaNueva = [] #Se crea la lista vacía
numeroValoresLista = len(listaGlobal) #Se obtiene la longitud de la lista original
ultimoValor = numeroValoresLista - 1 #Se obtiene el último término de la lista
for valor in range (0, ultimoValor): #Se recorre cada uno de los elementos de la lista
if listaGlobal[valor] < listaGlobal[valor+1]: #Se evalua la condición sobre si el número posterior es mayor
listaNueva.append(listaGlobal[valor+1]) #Se añade a la nueva lista el valor mayor respecto al anterior
return (listaNueva) #Se regresa el resultado
'''Función que reibe una lista la cual es analizada mediante varios condicionales 'if' y un ciclo 'for' con
el fin de regresar en una lista nueva un intercambio de las parejas presentes en la original'''
def intercambiarParejas(listaGlobal):
listaNueva = [] #Se crea una nueva lista
largoLista = len(listaGlobal) #Se obtiene el largo de la lista original
if largoLista == 0: #Condición que evalúa que sucede cuando no hay elementos
return listaNueva #Regresa una lista vacía
if largoLista == 1: #Condición que evalúa que pasa cuando hay un solo valor
listaNueva.append(listaGlobal[0]) #Se le añade a la lista nueva el valor en cuestión
return listaNueva #Regresa una lista nueva con el mismo índice que la orginal
for valor in range(1, largoLista, 2): #Ciclo 'for' que recorre los elementos de dos en dos (pares)
listaNueva.append(listaGlobal[valor]) #Sucede el cambio de lugares
listaNueva.append(listaGlobal[valor-1]) #Sucede elcambio de lugares
if largoLista % 2 != 0: #Condición que evalúa al últimoelemento de la lista (debe ser par)
listaNueva.append(listaGlobal[-1]) #Si no lo es... no cambia
return listaNueva #Devuelve el resultado
'''Función que recibe una lista y ésta es modificada para regresar una lista con la posiión del
valor máximo y mínimo invertida'''
def intercambiarMM(listaGlobal):
if len(listaGlobal) < 2: #Condición que establece que para hacer algún cambio, la lista debe
listaGlobal = [] #de contar con más de un elemento
else:
valorMenor = min(listaGlobal) #Se obtiene el valor mínimo de los índices de la lista
valorMayor = max(listaGlobal) #Se obtiene el valor máximo de los índices de la lista
menor = listaGlobal.index(valorMenor) #Se busca la posición del elemento menor en la lista
mayor = listaGlobal.index(valorMayor) #Se busca la posición del elemento mayor en la lista
listaGlobal[menor] = valorMayor #Se modifica la posición del menor por el mayor
listaGlobal[mayor] = valorMenor #Se modifica la posición del mayor por el menor
return (listaGlobal) #Regresa el resultado
'''Función que recibe una lista, ésta es copiada con copy() con el fin de poder obtener el promedio
del valor de sus índices'''
def promediarCentro(listaGlobal):
listaNueva = listaGlobal.copy() #Se crea la copia de la lista
if len(listaNueva) <= 2: #Condición que establece que debe de haber al menos más de 2 elementos
return (0) #Al no tener más de dos valores, regresa 0
else:
valorMaximo = max(listaNueva) #Se obtiene el valor máximo de la copia de la lista
valorMMinimo = min(listaNueva) #Se obtiene el valor mínimo de la copia de la lista
listaNueva.remove(valorMaximo) #Se elimina el valor máximo de la copia de la lista
listaNueva.remove(valorMMinimo) #Se elimina el valor mínimo de la copia de la lista
suma = sum(listaNueva) #Se suman los elementos no elimandos
promedio = suma // len(listaNueva) #Se obtiene el promedio entero
return(promedio) #Regresa el resultado
'''Función que recibe una lista y mediante varias condiciones, un ciclo 'for', regresa una dupla con
el valor de la desviación estándar de los valores de los ínidies de la lista original'''
def calcularEstadistica(listaGlobal):
largoLista = len(listaGlobal) #Se obtiene el largo de la lista
duplaInicial = (0, 0) #Se crea una variable global (para la función) de la dupla
suma = sum(listaGlobal) #Se guarda en una variable la suma de los elementos de la lista
if largoLista == 0: #Si la lista no tiene elementos...
return duplaInicial #...regresará la dupla creada
if largoLista != 0: #Si sí hay valores dentro de la lista...
mean = suma / largoLista #...se calcula la media
if largoLista > 1: #Si el largo de la lista resulta mayor a uno
xi = 0 #Acumulador x de la fórmula
for numero in listaGlobal: #Se recorre a la lista
xi += (numero - mean) ** 2 #El acumulador toma el valor de los parametros menos la media al cuadrado
desviacion = ((xi) / (len(listaGlobal) - 1)) ** 0.5 #Se calcula la desviación de acuerdo con la fórmula
else:
desviacion = 0 #En caso de ingresar un valor individual su desviación siempre será 0
return (mean, desviacion) #Regresa el resultado
'''Función que recibe una lista y esta regresa la suma de los valores que no se encuentras a lado del
número 13'''
def calcularSuma(listaGlobal):
largoLista = len(listaGlobal) # Se obtiene el largo de la lista
listaNueva = listaGlobal.copy() # Se crea una copia de la lista orginal para obtener los valores de índices
listaDatos = [] # Se crea una lista en donde se guardarán los datos
valorSuma = 0 # Se asume que el resultado de la suma es de 0
if listaNueva == []: # Si no hay parametros que sumar...
return valorSuma # ...se regresa 0
listaNueva.insert(0, 0) # Se le coloca el valor de 0 a la posición incial
listaNueva.append(0) # Se agrega 0 a la lista
largoNuevaLista = len(listaNueva) # Se obtiene el largo de la lista actualizada
if listaNueva[0] != 13:
listaDatos.append(listaNueva[0]) # Se le pasa a la lista 'datos' el índice 0 de la lista actualizada
if listaNueva[-1] != 13:
listaDatos.append(listaNueva[-1]) # Se agrega el último índice de la lista actualizada
ultimoValorActualizado = largoNuevaLista - 1 # Se crea la variable que almacena el valor del último índice
for valor in range(1, ultimoValorActualizado):
if listaNueva[valor] != 13 and listaNueva[valor + 1] != 13 and listaNueva[valor - 1] != 13:
listaDatos.append(listaNueva[valor])
listaDatos.remove(listaDatos[0]) #Se remueve el primer término de la lista actualizada
listaDatos.remove(listaDatos[0]) #Se vuelve a eliminar el primer término
suma = len(listaDatos) #Se obtiene el largo de la nueva lista
for resultado in range(0, suma):
valorSuma += listaDatos[resultado] #Se eactuliza el resultado de la suma
return valorSuma #Regresa el resultado
|
Python | UTF-8 | 3,779 | 4.125 | 4 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 12 13:03:32 2018
@author:Mandy
Assignment 10 - Benchmarking Sorting Algorithms
(1) Create a class with functions for three sorting algorithms - bubble sort, selection sort and insertion sort.
(2) Write a program that determines the amount of time taken to sort lists of random numbers of the following lenghs: n=[10000,20000,30000,40000,50000]
(3) Output of the program:
Bubble sort algorithm:
n time
10000 2.23
20000 4.67
30000 7.88
40000 11.34
50000 14.44
Insertion sort algorithm:
n time
10000 2.23
20000 14.67
30000 117.88
40000 211.34
50000 11214.44
Selection Sort algorithm:
n time
10000 1.4
20000 4.5
30000 10.4
40000 29.3
50000 100.2
(4) Have Python graph the results using pyplot / matplotlib
"""
import random
import time
class sorting():
def bubbleSort(self):
n = len(list)
# Push the largest num to the end.
for i in range (0,n-1): # (n-1) is the biggest num of times to sort.
for j in range (0,n-1-i): # (n-1-i) is the largest num of times that you need to swap in each i.
if list[j] > list[j+1]:
list[j], list[j+1] = list[j+1], list[j]
return(list) # from the small num to the large num.
#del n
def selectionSort(self):
for fillslot in range(len(list)-1,0,-1):
positionOfMax=0
for location in range(1,fillslot+1):
if list[location] > list[positionOfMax]:
positionOfMax = location
temp = list[fillslot]
list[fillslot] = list[positionOfMax]
list[positionOfMax] = temp
return(list)
def insertionSort(self):
for index in range(1,len(list)):
currentvalue = list[index]
position = index
while position>0 and list[position-1]>currentvalue:
list[position]=list[position-1]
position = position-1
list[position]=currentvalue
return(list)
############################
a = sorting()
a1times = []
a2times = []
a3times = []
n=[10000,20000,30000,40000,50000]
k = [1000,2000,3000,4000,5000]
for z in range(0, len(n)): # pick k (size) from n (range)
for num in n:
list = random.sample(range(num), k[z])
t0 = time.time()
a.bubbleSort()
t1 = time.time()
total = t1-t0 # timing the speed of each function
tA = time.time()
a.selectionSort()
tB = time.time()
totalC = tB-tA # timing the speed of each function
ti = time.time()
a.insertionSort()
tii = time.time()
totaliii = tii-ti # timing the speed of each function
a1times.append(total) # record the time used in each test
a2times.append(totalC)
a3times.append(totaliii)
# print forms
print("Bubble Sort Algorithm")
print("n"," ","time")
for i in range (0,5):
print(n[i]," ",a1times[i])
print(" ")
print("Selection Sort Algorithm")
print("n"," ","time")
for i in range (0,5):
print(n[i]," ",a2times[i])
print(" ")
print("Insertion Sort algorithm")
for i in range (0,5):
print(n[i]," ",a3times[i])
##########################
import matplotlib.pyplot as plt
#draw diagrams
plt.plot(n,a1times,color='red') # Bubble sort algorithm
plt.plot(n,a2times,color='blue') # Selection sort algorithm
plt.plot(n,a3times,color='green') # Insertion sort algorithm
plt.title('Benchmarking Sorting Algorithms') # title ofthe graph
plt.ylabel('Time') # y label for the graph
plt.xlabel('n Value') # x label for the graph
plt.show()
|
Java | UTF-8 | 1,245 | 1.84375 | 2 | [] | no_license | package kulaga.michail.demolocalizations.screenshots;
import android.support.test.rule.ActivityTestRule;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import kulaga.michail.demolocalizations.MainActivity;
import kulaga.michail.demolocalizations.R;
import tools.fastlane.screengrab.Screengrab;
import tools.fastlane.screengrab.locale.LocaleTestRule;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
@RunWith(JUnit4.class)
public class ScreengrabScreenshots {
@ClassRule
public static final LocaleTestRule localeTestRule = new LocaleTestRule();
@Rule
public ActivityTestRule<MainActivity> activityRule = new ActivityTestRule<>(MainActivity.class);
@Test
public void testTakeScreenshot() {
Screengrab.screenshot("before_button_click");
onView(withId(R.id.fab)).perform(click());
Screengrab.screenshot("after_button_click");
}
@Test
public void testOpenActivity() {
onView(withId(R.id.btn_show_scrollview)).perform(click());
Screengrab.screenshot("scrollview");
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.