branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int h,n;
int count = 0;
cin>>n>>h;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int i=0;i<n;i++){
if(arr[i] > h){
count = count + 2;
}
if(arr[i] <= h){
count++;
}
}
cout<<count;
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
ll num;
cin>>num;
if (num % 4 == 0 || num % 7 == 0 || num % 44 == 0 || num % 47 == 0 || num % 74 == 0 || num % 77 == 0 || num % 444 == 0 || num % 447 == 0 || num % 474 == 0 || num % 477 == 0 || num % 744 == 0 || num % 747 == 0 || num % 774 == 0 || num % 777 == 0) {
cout<<"YES";
}
else
{
cout<<"NO";
}
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("Output.txt","w",stdout);
#endif
int t;
cin>>t;
while(t--){
ll n,k,b,ans;
cin>>n>>k;
if(k>n){
cout<<k-n<<endl;
}
else if(n%2 != k%2){
cout<<1<<endl;
}
else{
cout<<0<<endl;
}
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int t;
cin>>t;
while(t--){
int n,k,i,j;
cin>>n>>k;
int a[n],b[n];
int sum=0,sum1=0;
for(int i=0;i<n;i++){
cin>>a[i];
//sum += a[i];
}
for(int i=0;i<n;i++){
cin>>b[i];
//sum1+=b[j];
}
sort(a,a+n);
sort(b,b+n,greater<int>());
int ans =0 ;
for(int i=0;i<n;i++){
if(i<k){
ans += max(a[i],b[i]);
}
else{
ans += a[i];
}
}
cout<<ans<<" ";
}
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int x1,x2,x3;
int low,mid,hi;
cin>>x1>>x2>>x3;
if(x1>x2) {
mid=x1;
low=x2;
}
else{
mid=x2;
low=x1;
}
if(mid>x3){
hi=mid;
if(low>x3){
mid=low;
low=x3;
}else {
mid=x3;
}
}else hi=x3;
//cout<<low<<" "<<mid<<" "<<hi<<" ";
int dist1 = abs(mid-low);
int dist2 = abs(hi-mid);
int total = dist1 + dist2;
cout<<total<<" ";
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("Output.txt","w",stdout);
#endif
ll t;
cin>>t;
while(t--){
ll x,y,n;
cin>>x>>y>>n;
if(n-n%x+y <= n){
cout<<(n-n % x+y)<<endl;
}
else{
cout<<(n-n % x-(x-y))<<endl;
}
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
string s;
cin>>s;
s[0] = toupper(s[0]);
cout<<s<<"\n";
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n;
cin>>n;
int count = 0;
vector<ll>h(n),a(n);
for(int i=0;i<n;i++){
cin>>h[i]>>a[i];
}
for(int i=0;i<n;i++){
for(int j=0;j<i;j++){
if(h[i] == a[j]){
count++;
//cout<<h[i]<<" ";
}
if(a[i] == h[j]){
count++;
//cout<<a[i] << " ";
}
}
}
cout<<count<<"\n";
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
string n,m,a;
cin>>n>>m;
for(int i=0;i<n.length();i++){
if(n[i]==m[i]){
n[i] = '0';
}
else{
n[i] = '1';
}
}
cout<<n<<endl;
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
char s[100];
cin>>s;
int l = strlen(s);
for(int i=0;i<l;i+=2){
for(int j=0;j<l-i-2;j+=2){
if(s[j]>s[j+2]){
swap(s[j],s[j+2]);
}
}
}
cout<<s<<"\n";
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
double n,m,a;
cin>>n>>m>>a;
long long int tot = (long long)ceil(n/a) * (long long)ceil(m/a);
cout<<tot<<"\n";
return 0;
}
/*---------------------Problem Set------------------------*/
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,m;
cin>>n>>m;
n=min(n,m);
if(n%2==0){
cout<<"Malvika"<<endl;
}
else{
cout<<"Akshat"<<endl;
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n;
int count = 0;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int i=0;i<n;i++){
if(arr[i] > 0){
count = 1;
}
}
if(count == 1){
cout<<"HARD";
}
else
{
cout<<"EASY";
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
string p;
int count =0;
cin>>p;
for(int i=0;i<p.length();i++){
if(p[i] == 'H' || p[i] == 'Q' || p[i] == '9'){
count++;
//cout<<count<<endl;
}
}
if(count > 0){
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
return 0;
}<file_sep># My Solutions
My Solved Solutions of CODEFORCES.
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int t;
cin>>t;
while(t--){
int a,b;
cin>>a>>b;
if(a%b==0){
cout<<0<<endl;
}
else
{
cout<< b- a%b <<endl;
}
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int arr[5],count=0;
for(int i=0;i<5;i++){
cin>>arr[i];
}
sort(arr,arr+5);
for(int i=0;i<5;i++){
if(arr[i]==arr[i+1]){
count++;
}
}
cout<<count<<endl;
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,m,ans;
cin>>n>>m;
ans = floor(n*m*0.5);
cout<<ans;
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("Output.txt","w",stdout);
#endif
int n,m;
cin>>n>>m;
char arr[n][m];
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
cin>>arr[i][j];
}
}
bool rang = false;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(arr[i][j] == 'C' || arr[i][j] == 'Y' || arr[i][j] == 'M'){
rang = true;
break;
}
}
}
if(rang == true){
cout<<"#Color"<<endl;
}
else{
cout<<"#Black&White"<<endl;
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,m,c,misk=0,chris=0;
cin>>n;
for(int i=0;i<n;i++){
cin>>m>>c;
if(m>c){
misk++;
}
else if(c>m){
chris++;
}
}
if(misk>chris){
cout<<"Mishka"<<endl;
}
else if(chris>misk){
cout<<"Chris"<<endl;
}
else{
cout<<"Friendship is magic!^^"<<endl;
}
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
ll n,ans;
cin>>n;
if(n%2==0){
n=n/2;
cout<<n<<endl;
}
else if(n%2==1){
n++;
ans = n/2*(-1);
cout<<ans<<endl;
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("Output.txt","w",stdout);
#endif
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
sort(arr,arr+n);
int res = arr[n-1] - arr[0];
for(int i=0;i<n-1;i++){
res = min(arr[i+1]-arr[i],res);
//cout<<res<<"\n";
}
cout<<res<<"\n";
}
return 0;
}
<file_sep>#include<bits/stdc++.h>
#include<string.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
string str;
int i,j,count =0;
cin>>str;
sort(str.begin(),str.end());
for(i =0;i<str.length();i++){
if(str[i]!=str[i-1]){
count++;
}
}
if(count%2==0){
cout<<"CHAT WITH HER!"<<endl;
}
else
{
cout<<"IGNORE HIM!"<<endl;
}
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
ll n,k;
cin>>n>>k;
if(k<=(n+1)/2){
cout<<(k*2)-1<<endl;
}
else
{
cout<<(k - ((n+1)/2))*2<<endl;
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int arr[100];
int n,i,p,q;
cin>>n;
cin>>p;
int count=0;
for(i=0;i<p;i++){
cin>>arr[i];
}
cin>>q;
for(int i=p;i<p+q;i++){
cin>>arr[i];
}
sort(arr,arr+(p+q));
for(int i=0;i<p+q;i++){
if(arr[i] != arr[i+1]){
count++;
}
}
//cout<<count<<"\n";
if(n==(count)){
cout<<"I become the guy."<<"\n";
}
else{
cout<<"Oh, my keyboard!"<<"\n";
}
return 0;
}<file_sep>#include <iostream>
#include<cmath>
using namespace std;
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n;
int maxvalue=0;
int minvalue=101;
int maxindex=0;
int minindex=0;
cin>>n;
for(int i=0;i<n;i++){
int x;
cin>>x;
if(x>maxvalue){
maxindex=i;
maxvalue=x;
}
if(x<=minvalue){
minindex=i;
minvalue=x;
}
}
if(maxindex>minindex){
cout<<(maxindex-1)+(n-minindex)-1;
}
else{
cout<<(maxindex-1)+(n-minindex);
}
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
ll t,X=0,i;
cin>>t;
for(i=0;i<t;i++){
string n;
cin>>n;
if(n[0]=='+'){
++X;
}
if(n[0]=='-'){
--X;
}
if(n[2]=='+'){
X++;
}
if(n[2]=='-'){
X--;
}
}
cout<<X<<endl;
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n;
cin>>n;
float arr[n],sum=0;
double ans;
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int i=0;i<n;i++){
sum = sum + arr[i];
}
ans = sum/n;
cout<<ans<<setprecision(12);
//printf("%.12f",ans);
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
string x;
int flag =1;
cin>>x;
for(int i=0;i<x.length();i++){
if(x[i] == 'W' && x[i+1] == 'U' && x[i+2] == 'B'){
i+=2;
if(!flag){
cout<<" ";
}
continue;
}
else{
flag =0;
cout<<x[i];
}
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,x,y;
cin>>n;
int arr[n];
for(int i=1;i<=n;i++){
cin>>arr[i];
}
int count=0,count1=0;
for(int i=1;i<=n;i++){
if(arr[i]%2 == 1){
count++;
x=i;
}
else if(arr[i]%2 == 0){
count1++;
y=i;
}
}
//cout<<count<<" "<<count1<<endl;
if(count == 1){
cout<<x<<"\n";
}
else if(count1==1)
{
cout<<y<<"\n";
}
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL)
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
fastio;
int a,b,c,ans;
cin>>a>>b>>c;
ans = a+b+c;
ans = max(ans,a+b*c);
ans = max(ans,a*(b+c));
ans = max(ans,a*b*c);
ans = max(ans,(a+b)*c);
ans = max(ans,(a*b)+c);
cout<<ans<<endl;
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
#define endl "\n"
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,k;
cin>>n>>k;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
sort(arr,arr+n);
int count=0;
for(int i=0;i<n;i++){
if(5 - arr[i] >= k){
count++;
}
}
cout<<(count/3)<<endl;
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int w;
cin>>w;
ll count =0;
while(w--){
ll p,s,t;
cin>>p>>s>>t;
if(p+s+t >= 2){
count++;
}
}
cout<<count<<endl;
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,m,a,b;
cin>>n>>m>>a>>b;
if(m*a > b){
int rem = (n%m)*a;
if(rem > b){
cout<<(n/m * b) + b;
}
else
{
cout<<(n/m * b) + rem;
}
}
else
cout<<(n*a);
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
ll n;
cin>>n;
ll arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
ll sum = 0,count=0;
for(int i=0;i<n;i++){
if(arr[i]>0){
sum+=arr[i];
}
else if(sum > 0){
sum--;
}
else
{
count++;
}
}
cout<<count;
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
ll n,i;
cin>>n;
ll a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
ll sum = 0,ans;
int max = a[0];
for(int i=0;i<n;i++){
if(a[i]>max){
max = a[i];
}
}
for(int i=0;i<n;i++){
sum += ans = max - a[i];
}
cout<<sum;
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int t;
cin>>t;
while(t--){
int n;
cin>>n;
int sum1 = pow(2,n),sum2 = 0;
for(int i=1;i<n/2;i++){
sum1 += pow(2,i);
}
for(int i=n/2;i<n;i++){
sum2 += pow(2,i);
}
cout<<abs(sum1 - sum2)<<endl;
}
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
ll n;
cin>>n;
ll a,b,ans;
for(int i=0;i<n;i++){
cin>>a>>b;
ans = min(pow(max(2*b,a),2),pow(max(2*a,b),2));
cout<<ans<<"\n";
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,a[1000],b[1000],max=0,ans,k,i;
cin>>n;
for(i = 0;i<n;i++){
cin>>a[i]>>b[i];
}
k = a[0];
for(i = 0;i<n;i++){
ans = b[i]-a[i]+k;
k=ans;
if(ans>max){
max=ans;
}
}
cout<<max<<"\n";
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("Output.txt","w",stdout);
#endif
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
int half = 0;
for(int i=0;i<n;i++){
half = half + arr[i];
}
half = half/2;
//cout<<half<<endl;
sort(arr,arr+n,greater<int>());
int res=0,curr_sum=0;
for(int i=0;i<n;i++){
curr_sum+=arr[i];
res++;
if(curr_sum>half){
break;
// cout<<res;
}
}
cout<<res<<endl;
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("Output.txt","w",stdout);
#endif
int t;
cin>>t;
while(t--){
int n,m;
cin>>n>>m;
//ll blocks = n*m;
int ans = ((n*m)+1)/2;
cout<<ans<<"\n";
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int i,n,count=0;
char s[105];
cin>>n>>s;
for(i=0;i<n;i++){
if(s[i] >= 65 && s[i] <= 90){
s[i] = 97+s[i] - 65;
}
}
sort(s,s+n);
for(i=0;i<n;i++){
if(s[i]!=s[i+1]){
count++;
}
//cout<<s[i];
}
//cout<<count<<endl;
if(count == 26){
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
return 0;
}<file_sep>#include<bits/stdc++.h>
#include<algorithm>
#include<string>
#define endl "\n"
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
string s1,s2;
cin>>s1>>s2;
for(int i=0;i<s1.size();i++){
s1[i]= tolower(s1[i]);
s2[i]= tolower(s2[i]);
}
//cout<<s1<<"\n"<<s2;
if(s1==s2){
cout<<"0"<<"\n";
}
else if(s1<s2){
cout<<"-1"<<endl;
}
else{
cout<<"1"<<endl;
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,k,w,mul,sum=0,sub=0;
cin>>k>>n>>w;
for(int i=1;i<=w;i++){
mul = i*k;
sum=sum+mul;
sub = sum - n;
}
if(sub > 0){
cout<<sub<<"\n";
}
else
{
cout<<"0"<<endl;
}
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
ll n;
cin>>n;
int a[100000];
for(int i = 0;i<n;i++){
cin>>a[i];
}
int icount=0;
for(int i=0;i<n;i++){
if(a[i] != a[i+1]){
icount++;
}
}
cout<<icount<<endl;
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("Output.txt","w",stdout);
#endif
int t;
cin>>t;
while(t--){
int n;
cin>>n;
if(n%2 == 0){
n=n/2;
}
else{
n = (n/2)+1;
}
cout<<n<<endl;
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int i,n;
cin>>n;
for(i=0;i<n;i++){
if(i%2==0){
cout<<"I hate ";
}
else
{
cout<<"I love ";
}
if(i!=n-1){
cout<<"that ";
}
else
{
cout<<"it ";
}
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,anton=0,danik=0;
cin>>n;
char str[n];;
cin>>str;
for(int i=0;i<n;i++){
if(str[i] == 'A'){
anton++;
}
else if(str[i] == 'D'){
danik++;
}
}
//cout<<anton<<" "<<danik<<endl;
if(anton < danik){
cout<<"Danik"<<endl;
}
else if(anton > danik){
cout<<"Anton"<<endl;
}
else
{
cout<<"Friendship"<<endl;
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
string s,t;
int sum=0;
cin>>s>>t;
int n = s.length();
for(int i=0;i<n/2;i++){
swap(s[i],s[n-i-1]);
}
if(s == t){
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int t;
cin>>t;
while(t--){
ll n;
cin>>n;
if(n<=2){
cout<<0<<endl;
}
else if(n%2==1){
cout<<n/2<<endl;
}
else{
cout<<((n/2)-1)<<endl;
}
}
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("Output.txt","w",stdout);
#endif
int t;
cin>>t;
while(t--){
int n,m;
cin>>n>>m;
ll ans = min(2,n-1)*m;
cout<<ans<<endl;
}
return 0;
}<file_sep>#include<bits/stdc++.h>
#include<algorithm>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
ll n,m;
cin>>n>>m;
ll arr[m];
for(int i=0;i<m;i++){
cin>>arr[i];
}
sort(arr,arr+m);
ll ans = arr[n-1] -arr[0];
for(int i=1;i<=m-n ;i++){
if(arr[i+n-1] - arr[i] < ans){
ans = arr[i+n-1] -arr[i];
}
}
cout<<ans<<endl;
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int i,j,min;
int arr[6][6];
for(int i=1;i<6;i++){
for(int j=1;j<6;j++){
cin>>arr[i][j];
}
}
int y;
for(int i=1;i<6;i++){
for(int j=1;j<6;j++){
if(arr[i][j]==1){
y = (abs(3-i)+abs(3-j));
cout<<y;
}
}
}
return 0;
}<file_sep>#include<bits/stdc++.h>
#include <cstring>
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
string ch;
cin>>ch;
int upper =0,lower=0;
for(int i = 0;i<ch.size();i++){
if(isupper(ch[i])){
upper++;
}else{
lower++;}}
if(upper>lower){
char s;
for(int i=0;i<ch.size();i++){
s=toupper(ch[i]);
cout<<s;}
}else{
char s;
for(int i=0;i<ch.size();i++){
s=tolower(ch[i]);
cout<<s;}}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n=5;
long long int arr[5];
for(int i=0;i<n;i++){
cin>>arr[i];
}
sort(arr,arr+n);
cout<<arr[3] - arr[0]<<" "<<arr[3] - arr[1]<<" "<<arr[3] - arr[2];
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
#define endl "\n"
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
ll t;
cin>>t;
while(t--){
ll n;
cin>>n;
vector<ll>ans;
ll power = 1;
while(n > 0){
if(n%10>0){
ans.push_back((n%10)*power);
}
n = n/10;
power *= 10;
}
cout<<ans.size()<<endl;
for(auto number : ans) cout<<number<<" ";
cout<<endl;
}
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
long long int n,l,m,i,maxdist = 0;;
double x,y,z,ans;
cin>>n>>l;
long long int a[n];
for(i=0;i<n;i++){
cin>>a[i];
}
sort(a,a+n);
for(i=0;i<n-1;i++){
//a[i] = abs(a[i]-a[i+1]);
if(a[i+1]-a[i] > maxdist){
maxdist = a[i+1]-a[i];
}
}
//cout<<maxdist<<" ";
x = maxdist/2.0;
//cout<<x<<"\n";
y = a[0] - 0.0;
//cout<<y<<"\n";
z = l-a[n-1];
//cout<<z<<"\n";
ans = max(y,z);
//cout<<ans<<"\n";
ans = max(ans,x);
printf("%.10f\n",ans);
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
#define endl "\n"
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
ll n,i;
ll k=0,count=0;
cin>>n>>k;
ll arr[n];
for(i =0;i<n;i++){
cin>>arr[i];
}
for(i=0;i<n;i++){
if(arr[i]>=arr[k-1] && arr[i] > 0){
count++;
}
}
cout<<count<<endl;
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int a,b,count=0;
cin>>a>>b;
for(int i=0;i<10;i++){
if(a<=b){
a = a*3;
b = b*2;
count++;
}
}
cout<<count<<endl;
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int y;
cin>>y;
while(y!=0){
y+=1;
int a = y/1000;
int b = y/100%10;
int c = y/10%10;
int d = y%10;
if(a != b && a != c && a != d && b != c && b != d && c != d){
break;
}
}
cout<<y<<endl;
return 0;
}<file_sep>#include <iostream>
#include <string>
using namespace std;
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
string s,s2;
cin>>s;
int len=s.length();
for(int i=0;i<len;i++){
if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'||s[i]=='y'||s[i]=='A'||s[i]=='E'||s[i]=='O'||s[i]=='I'||s[i]=='U'||s[i]=='Y')
continue;
else
{
s2+='.';
s2+=tolower(s[i]);
}
}
cout<<s2;
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
#define endl "\n"
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int a,b,ans;
cin>>a>>b;
if(a>b){
swap(a,b);
}
b = (b-a)/2;
cout<<a<<" "<<b;
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int x;
cin>>x;
int count=0;
while(x){
x &= (x-1);
count++;
}
cout<<count;
return 0;
}<file_sep>#include<iostream>
#include<string.h>
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
string word="hello";
string t;
cin>>t;
int l=t.length();
int a=0,count=0;
for(int i=0;i<l;i++)
{
if(t[i]==word[a])
{
a++;
count++;
}
}
if(count==5)
{
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int t,a;
int sum1=0,sum2=0,sum3=0;
cin>>t;
while(t--){
int x,y,z;
cin>>x>>y>>z;
sum1+=x;
sum2+=y;
sum3+=z;
}
if(sum1 == 0 && sum2 == 0 && sum3 == 0){
cout<<"YES";
}
else
{
cout<<"NO";
}
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("Output.txt","w",stdout);
#endif
int t;
cin>>t;
while(t--){
string str;
cin>>str;
int n = str.length();
cout<<str[0];
for(int i=1;i<n-1;i++){
if(i%2 != 0){
cout<<str[i];
}
}
cout<<str[n-1]<<endl;
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,p[100],q[100],i;
cin>>n;
int count =0;
for(int i=0;i<n;i++){
cin>>p[i]>>q[i];
}
for(int i=0;i<n;i++){
if(q[i] - p[i] >=2){
count++;
}
}
cout<<count<<endl;
return 0;
}<file_sep>#include<bits/stdc++.h>
#include<string.h>
#define endl "\n"
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
long long int t;
cin>>t;
while(t--){
string str;
int i;
cin>>str;
if(str.length()>10){
cout<<str[0] << str.length()-2<<str[str.length()-1]<<endl;
}
else
{
cout<<str<<endl;
}
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n;
cin>>n;
char arr[n];
for(int i =0;i<n;i++){
cin>>arr[i];
}
int count =0;
for(int i =0;i<n-1;i++){
if(arr[i]==arr[i+1]){
count++;
//cout<<count<<endl;
}
}
cout<<count<<endl;
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
ll n;
cin>>n;
int count =0;
while(n!=0){
if(n%10 == 4 || n%10 == 7){
count+=1;
}
n=n/10;
}
if(count == 4 || count == 7){
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
string s,a,b,c;
cin>>a>>b>>c;
s = a+b;
sort(s.begin(), s.end());
sort(c.begin(), c.end());
if(s==c){
cout<<"YES"<<endl;
}
else{
cout<<"NO"<<endl;
}
return 0;
}<file_sep>#include <bits/stdc++.h>
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
char ch[106];
int i,j,ck=1;
std::cin>>ch;
for(i=1;ch[i]!='\0';i++)
{
if(ch[i]>=97&&ch[i]<=122)
{
ck=0;
break;
}
}
if(ck==1)
{
if(ch[0]>=65&&ch[0]<=90)
ch[0]=ch[0]+32;
else
ch[0]=ch[0]-32;
for(j=1;ch[j]!='\0';j++)
{
ch[j]=ch[j]+32;
}
}
std::cout<<ch;
return 0;
}
<file_sep>#include<bits/stdc++.h>
#define endl "\n"
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
string s;
cin>>s;
int count =0;
for(int i=0;i<s.length();i++)
{
if(s[i]==s[i-1]){
count++;
if(count>=7){
cout<<"YES"<<endl;
return 0;
}
}
else
{
count = 1;
}
}
cout<<"NO"<<endl;
return 0;
}
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n,m;
cin>>n>>m;
//int arr[100];
for(int i=1;i<=n;i++){
if(i%4 == 2){
for(int j=1;j<m;j++){
cout<<".";
}
cout<<"#\n";
}
else if(i%4 == 0){
printf("#");
for(int j=1;j<m;j++){
cout<<".";
}
cout<<"\n";
}
else
{
for(int j=1;j<=m;j++){
cout<<"#";
}
cout<<"\n";
}
}
return 0;
}<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
ll n,k;
cin>>n>>k;
for(int i = 0;i<k;i++){
if(n%10!=0){
n=n-1;
}
else
{
n=n/10;
}
}
cout<<n<<"\n";
return 0;
}<file_sep>#include <bits/stdc++.h>
#define ll long long int
using namespace std;
int main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("Output.txt","w",stdout);
#endif
int t;
cin >> t;
for (int tt = 0; tt < t; tt++)
{
int x1, x2, y1, y2, z1, z2;
cin >> x1 >> y1 >> z1;
cin>> x2 >> y2 >> z2;
ll sum = 0;
int res = min(z1, y2);
sum = sum + 2 * res;
z1 = z1 - res;
y2 = y2 - res;
if (z1 > 0)
{
res = min(z1, z2);
z1 = z1 - res;
z2 = z2 - res;
}
if (z2 > 0)
{
res = min(z2, x1);
x1 = x1 - res;
z2 = z2 - res;
}
if (z2 > 0)
{
res = min(z2, y1);
sum = sum - 2 * res;
y1 = y1 - res;
z2 = z2 - res;
}
cout << sum << endl;
}
return 0;
}<file_sep>#include <bits/stdc++.h>
using namespace std;
int a[100];
int main() {
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
//int a[110];
int n;
cin>>n;
int x[n];
for (int i = 1; i <= n; ++i) {
cin>>x[i];
}
for (int i = 1; i <= n; ++i) {
a[x[i]]=i;
}
for (int i = 1; i <= n; ++i) {
cout<<a[i]<<" ";
}
return 0;
}<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int n;
cin>>n;
if((n%2==0) && n>2){
cout<<"YES"<<"\n";
}
else
{
cout<<"NO"<<"\n";
}
return 0;
}
/*-------------------------------------4A.WaterMelon.cpp---------------------------*/
<file_sep>#include<bits/stdc++.h>
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int x,div;
cin>>x;
long long int count =0;
if(x%5!=0){
div = x/5;
div++;
}
else {
div = x/5;
}
cout<<div<<endl;
return 0;
}<file_sep>#include <iostream>
using namespace std;
int main() {
// your code goes here
long long int t,n;
cin>>t;
while(t--){
cin>>n;
int c=0;
while(n){
c++;
n=n&(n-1);
}
cout<<c-1<<"\n";
}
return 0;
}
<file_sep>#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin>>t;
while(t--){
ll n,x;
cin>>n;
for(int k=2;k<35;k++){
ll dino = pow(2,k)-1;
if(n%dino){
continue;
}
x = n/dino;
break;
}
cout<<x<<"\n";
}
return 0;
} | c1b20b52514a88c4924df2ae7c3ae9378f79b43a | [
"Markdown",
"C++"
] | 81 | C++ | Shreyash41/CodeForces | 66f9ecabf1ea90868bc0412f9a864a259610700a | 9d8ae67577a30f284d31af448673ff0823b53fa9 |
refs/heads/master | <file_sep>FROM java
ADD /service-A-1.0-SNAPSHOT.jar /
ENTRYPOINT ["java", "-jar", "service-A-1.0-SNAPSHOT.jar"]<file_sep>FROM java
ADD /zipkin-server-1.0-SNAPSHOT.jar /
ENTRYPOINT ["java", "-jar", "zipkin-server-1.0-SNAPSHOT.jar"]
<file_sep>FROM java
ADD /zuul-server-1.0-SNAPSHOT.jar /
ENTRYPOINT ["java", "-jar", "zuul-server-1.0-SNAPSHOT.jar"]
<file_sep>package com.tembin.cloud.service_c;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
/**
* @author Tlsy1
* @since 2018-10-30 18:12
**/
@EnableHystrix
@SpringBootApplication
@EnableDiscoveryClient
@EnableEurekaClient
public class CServiceApplication {
public static void main(String[] args) {
SpringApplication.run(CServiceApplication.class, args);
}
}
<file_sep>FROM java
ADD /config-server-1.0-SNAPSHOT.jar /
ENTRYPOINT ["java", "-jar", "config-server-1.0-SNAPSHOT.jar"]
<file_sep>package com.tembin.cloud.auth.utils;
import com.nimbusds.jose.EncryptionMethod;
import com.nimbusds.jose.JWEAlgorithm;
import org.pac4j.jwt.config.encryption.SecretEncryptionConfiguration;
import org.pac4j.jwt.config.signature.SecretSignatureConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.util.HashMap;
import java.util.Map;
import static com.nimbusds.jose.JWSAlgorithm.HS512;
/**
* @author Tlsy1
* @since 2018-11-08 17:59
**/
@EnableScheduling
@Configuration
public class JwtGenerator {
private static final Logger logger = LoggerFactory.getLogger(JwtGenerator.class);
private String jwtToken;
@Value("${spring.application.name}")
private String serviceId;
@Value("${jwt.signingSecret}")
private String signingSecret;
@Value("${jwt.encryptionSecret}")
private String encryptionSecret;
@Value("${jwt.header}")
private String header;
@Scheduled(cron = "0 0/10 * * * ?")
public void refreshJwtToken() {
logger.info("refresh jwt token.....");
org.pac4j.jwt.profile.JwtGenerator generator = new org.pac4j.jwt.profile.JwtGenerator();
generator.setSignatureConfiguration(new SecretSignatureConfiguration(signingSecret, HS512));
generator.setEncryptionConfiguration(new SecretEncryptionConfiguration(encryptionSecret,
JWEAlgorithm.DIR, EncryptionMethod.A128CBC_HS256));
Map<String,Object> claims = new HashMap<>();
claims.put("serverId", serviceId);
this.jwtToken = generator.generate(claims);
}
public String getHeader() {
return header;
}
public String getJwtToken() {
if (this.jwtToken == null) {
this.refreshJwtToken();
}
return jwtToken;
}
}
<file_sep>FROM java
ADD /admin-server-1.0-SNAPSHOT.jar /
ENTRYPOINT ["java", "-jar", "admin-server-1.0-SNAPSHOT.jar"]
<file_sep>package com.tembin.cloud.auth.utils;
import com.nimbusds.jose.*;
import com.nimbusds.jwt.*;
import org.pac4j.core.exception.CredentialsException;
import org.pac4j.core.util.CommonHelper;
import org.pac4j.jwt.config.encryption.EncryptionConfiguration;
import org.pac4j.jwt.config.signature.SignatureConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Tlsy1
* @since 2018-11-08 18:47
**/
public class JwtAuthenticator {
private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticator.class);
private List<EncryptionConfiguration> encryptionConfigurations = new ArrayList<>();
private List<SignatureConfiguration> signatureConfigurations = new ArrayList<>();
public void validate(String token) throws CredentialsException {
try {
// Parse the token
JWT jwt = JWTParser.parse(token);
if (jwt instanceof PlainJWT) {
if (signatureConfigurations.isEmpty()) {
logger.debug("JWT is not signed and no signature configurations -> verified");
} else {
throw new CredentialsException("A non-signed JWT cannot be accepted as signature configurations have been defined");
}
} else {
SignedJWT signedJWT = null;
if (jwt instanceof SignedJWT) {
signedJWT = (SignedJWT) jwt;
}
// encrypted?
if (jwt instanceof EncryptedJWT) {
logger.debug("JWT is encrypted");
final EncryptedJWT encryptedJWT = (EncryptedJWT) jwt;
boolean found = false;
final JWEHeader header = encryptedJWT.getHeader();
final JWEAlgorithm algorithm = header.getAlgorithm();
final EncryptionMethod method = header.getEncryptionMethod();
for (final EncryptionConfiguration config : encryptionConfigurations) {
if (config.supports(algorithm, method)) {
logger.debug("Using encryption configuration: {}", config);
try {
config.decrypt(encryptedJWT);
signedJWT = encryptedJWT.getPayload().toSignedJWT();
if (signedJWT != null) {
jwt = signedJWT;
}
found = true;
break;
} catch (final JOSEException e) {
logger.debug("Decryption fails with encryption configuration: {}, passing to the next one", config);
}
}
}
if (!found) {
throw new CredentialsException("No encryption algorithm found for JWT: " + token);
}
}
// signed?
if (signedJWT != null) {
logger.debug("JWT is signed");
boolean verified = false;
boolean found = false;
final JWSAlgorithm algorithm = signedJWT.getHeader().getAlgorithm();
for (final SignatureConfiguration config : signatureConfigurations) {
if (config.supports(algorithm)) {
logger.debug("Using signature configuration: {}", config);
try {
verified = config.verify(signedJWT);
found = true;
if (verified) {
break;
}
} catch (final JOSEException e) {
logger.debug("Verification fails with signature configuration: {}, passing to the next one", config);
}
}
}
if (!found) {
throw new CredentialsException("No signature algorithm found for JWT: " + token);
}
if (!verified) {
throw new CredentialsException("JWT verification failed: " + token);
}
}
}
} catch (final ParseException e) {
throw new CredentialsException("Cannot decrypt / verify JWT", e);
}
}
public void addSignatureConfiguration(final SignatureConfiguration signatureConfiguration) {
CommonHelper.assertNotNull("signatureConfiguration", signatureConfiguration);
signatureConfigurations.add(signatureConfiguration);
}
public void addEncryptionConfiguration(final EncryptionConfiguration encryptionConfiguration) {
CommonHelper.assertNotNull("encryptionConfiguration", encryptionConfiguration);
encryptionConfigurations.add(encryptionConfiguration);
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<groupId>com.tembin</groupId>
<artifactId>cloud-server</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>eureka-server</module>
<module>config-server</module>
<module>admin-server</module>
<module>zuul-server</module>
<module>zipkin-server</module>
<module>service-a</module>
<module>service-b</module>
<module>service-c</module>
<module>service-a-client</module>
<module>service-b-client</module>
<module>service-c-client</module>
<module>auth-core</module>
</modules>
<properties>
<springCloudVersion>2.0.2</springCloudVersion>
<springBootMyBatisVersion>1.3.0</springBootMyBatisVersion>
<springBootpagehelperVersion>1.1.3</springBootpagehelperVersion>
<springBootAdminVersion>1.5.3</springBootAdminVersion>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<!-- Docker maven plugin -->
<plugin>
<groupId>com.spotify</groupId>
<artifactId>docker-maven-plugin</artifactId>
<version>1.2.0</version>
<configuration>
<dockerHost>http://test.tembin.com:2375</dockerHost>
<imageName>registry.colossus.vip/${project.artifactId}</imageName>
<dockerDirectory>${project.build.outputDirectory}/docker</dockerDirectory>
<resources>
<resource>
<targetPath>/</targetPath>
<directory>${project.build.directory}</directory>
<include>${project.build.finalName}.jar</include>
</resource>
</resources>
</configuration>
</plugin>
<!-- Docker maven plugin -->
</plugins>
</build>
</project><file_sep>package com.tembin.cloud.service_a.api;
import com.tembin.cloud.service_a.api.hystrix.AServiceHystrix;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
/**
* @author Tlsy1
* @since 2018-10-30 17:32
**/
@FeignClient(value = "service-A",fallback = AServiceHystrix.class)
public interface AService {
@GetMapping("message")
String message();
@GetMapping("trace-message")
String traceMessage();
@GetMapping("log-test")
void logTest();
}
<file_sep>FROM java
ADD /eureka-server-1.0-SNAPSHOT.jar /
ENTRYPOINT ["java", "-jar", "eureka-server-1.0-SNAPSHOT.jar"]
<file_sep>package com.tembin.cloud.auth.interceptor;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
public class JwtTokenInterceptor implements RequestInterceptor {
private Logger logger = LoggerFactory.getLogger(JwtTokenInterceptor.class);
@Autowired
private com.tembin.cloud.auth.utils.JwtGenerator jwtGenerator;
@Override
public void apply(RequestTemplate requestTemplate) {
try {
requestTemplate.header(jwtGenerator.getHeader(),jwtGenerator.getJwtToken() );
} catch (Exception e) {
logger.error("{}", e);
}
}
}
<file_sep>package com.tembin.cloud.auth.config;
import com.tembin.cloud.auth.interceptor.JwtTokenInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Tlsy1
* @since 2018-11-08 18:22
**/
@Configuration
public class FeignClientConfig {
@Bean
public JwtTokenInterceptor jwtTokenInterceptor(){
return new JwtTokenInterceptor();
}
}
<file_sep>package com.tembin.cloud.service_c.api;
import com.tembin.cloud.service_c.api.hystrix.CServiceHystrix;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
/**
* @author Tlsy1
* @since 2018-10-30 20:39
**/
@FeignClient(value = "service-C",fallback = CServiceHystrix.class)
public interface CService {
@GetMapping("message")
String message();
}
<file_sep>package com.tembin.cloud.auth.config;
import com.nimbusds.jose.EncryptionMethod;
import com.nimbusds.jose.JWEAlgorithm;
import com.nimbusds.jose.JWSAlgorithm;
import com.tembin.cloud.auth.utils.JwtAuthenticator;
import org.pac4j.jwt.config.encryption.SecretEncryptionConfiguration;
import org.pac4j.jwt.config.signature.SecretSignatureConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author Tlsy1
* @since 2018-11-08 18:57
**/
@Configuration
public class JwtConfig {
@Value("${jwt.signingSecret}")
private String signingSecret;
@Value("${jwt.encryptionSecret}")
private String encryptionSecret;
@Bean
public JwtAuthenticator jwtAuthenticator(){
JwtAuthenticator jwtAuthenticator = new JwtAuthenticator();
jwtAuthenticator.addSignatureConfiguration(new SecretSignatureConfiguration(signingSecret, JWSAlgorithm.HS512));
jwtAuthenticator.addEncryptionConfiguration(new SecretEncryptionConfiguration(encryptionSecret, JWEAlgorithm.DIR, EncryptionMethod.A128CBC_HS256));
return jwtAuthenticator;
}
}
<file_sep>package com.tembin.cloud.config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@EnableConfigServer
//@EnableDiscoveryClient //todo 不使用这个注解,也可以关联到admin-server中,为啥呢
@EnableEurekaClient //todo 如何把config-server弄到eureka中呢
@EnableAutoConfiguration
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
<file_sep>FROM java
ADD /service-B-1.0-SNAPSHOT.jar /
ENTRYPOINT ["java", "-jar", "service-B-1.0-SNAPSHOT.jar"]
<file_sep>FROM java
ADD /service-C-1.0-SNAPSHOT.jar /
ENTRYPOINT ["java", "-jar", "service-C-1.0-SNAPSHOT.jar"]
<file_sep>package com.tembin.cloud.auth.filter;
import com.tembin.cloud.auth.utils.JwtAuthenticator;
import com.tembin.cloud.auth.utils.JwtGenerator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
/**
* @author Tlsy1
* @since 2018-11-08 17:25
**/
public class ServiceAuthFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(ServiceAuthFilter.class);
private JwtGenerator jwtGenerator;
private JwtAuthenticator jwtAuthenticator;
public ServiceAuthFilter(JwtGenerator jwtGenerator,JwtAuthenticator jwtAuthenticator) {
this.jwtGenerator = jwtGenerator;
this.jwtAuthenticator = jwtAuthenticator;
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
if( httpServletRequest.getRequestURI().startsWith("/actuator/")){
logger.info("健康检查放行remoteAddr:{}, url:{}", httpServletRequest.getRemoteAddr(),
httpServletRequest.getRequestURL());
chain.doFilter(request, response);
return;
}
String jwt = httpServletRequest.getHeader(jwtGenerator.getHeader());
try {
// jwtAuthenticator.validate(jwt);
chain.doFilter(request, response);
chain.doFilter(request, response);
}catch (Exception e){
logger.error("checkToken false remoteAddr:{}, url:{}", httpServletRequest.getRemoteAddr(),
httpServletRequest.getRequestURL());
HttpServletResponse resp = (HttpServletResponse) response;
resp.setContentType("application/json;charset=utf-8");
PrintWriter pw = resp.getWriter();
pw.write("{\n" +
" \"data\": null,\n" +
" \"code\": 401,\n" +
" \"pagination\": null,\n" +
" \"message\": \"非法请求\",\n" +
" \"successful\": false\n" +
"}");
pw.flush();
pw.close();
}
}
@Override
public void destroy() {
}
}
| 5182376567ad3ab7f071656279ba2c15d2f1da16 | [
"Java",
"Maven POM",
"Dockerfile"
] | 19 | Dockerfile | lkx1993/spring-cloud-test | 97c25effc7e44adf53633f5f7a91c3dee05a7ee8 | 6282991497d5383294362f30651ec23910ce8517 |
refs/heads/master | <repo_name>iravivarma/Algorithms<file_sep>/multiple_occurances.py
def count_occurances(arr, search_num):
numCount=0
for num in arr:
if arr[num]==search_num:
numCount += 1
return numCount
A = [1, 2, 2]
print(count_occurances(A,3))
<file_sep>/col_sum.py
A=[[1,2,3,4],
[5,6,7,8],
[9,2,3,4]]
def solve(A):
rows_len=len(A)
col_len=len(A[0])
print(col_len)
res=[]
for row in range(0, rows_len):
mat_sum=0
for column in range(0, col_len):
mat_sum=mat_sum+A[row][column]
res.append(mat_sum)
return res
print(solve(A))<file_sep>/range_sum_query.py
def pf_range_sum(A,B):
pf_sum=[]
pf_range_sum=[]
for i in range(0,len(A)):
if i == 0:
pf_sum.append(A[0])
else:
pf_sum.append(pf_sum[i-1]+A[i])
for i in range(0,len(B)):
start=B[i][0]-1
end=B[i][1]-1
if i == 0:
pf_range_sum.append(pf_sum[end])
else:
pf_range_sum.append(pf_sum[end] - pf_sum[start - 1])
return pf_range_sum
A = [2, 2, 2]
B = [[1, 1], [2, 3]]
print(pf_range_sum(A,B))<file_sep>/poer_modulo.py
A = 9
B = 0
C = 7
def power_modulo(A,B,C):
if A==0 or B==0 or C==0:
return -1
i=1
ans=1
while i<=B:
ans=(ans%C * A%C)%C
i +=1
return ans%B
print(power_modulo(A,B,C))<file_sep>/decimal_to_anybase.py
A=4
B=3
ans=0
power=0
while A>0:
rem=A%B
ans = ans + rem * (10 ** power)
power = power + 1
print(A//=B)
A//=B
print(ans) <file_sep>/divisiblity_by_3.py
A = [1,2,3]
if sum(A) % 3 == 0:
print(1)
else: print(0)<file_sep>/noble_elements.py
def noble_element(A):
A.sort()
for i in len(A):
if A[i] != A[i-1]:
if A[i]==len(A)-1-i:
return 1
if A[len(A)-1]==0:
return 1
return -1
<file_sep>/good_pair.py
def solve(A, B):
for i in range(len(A)):
print(A[i])
for j in range(i+1, len(A)):
# print(j)
if A[i] + A[j] == B:
return 1
return 0
A=[1,2,3,4]
B=9
print(solve(A,B))<file_sep>/binary_search.py
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 2 05:37:21 2020
@author: <NAME>
"""
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
return mid
return -1
arr = [1,2,3,4,5,6,7,8]
searching = binary_search(arr, 9)
print(searching)<file_sep>/elements_removal.py
price_list=[3,5,1,-3]
price_list.sort(reverse=True)
print(price_list)
min_cost=0
for price in range(len(price_list)):
min_cost += (price+1) * price_list[price]
print(min_cost)<file_sep>/valid_paranthesis.py
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 4 06:26:08 2020
@author: <NAME>
"""
def valid_paranthesis(char):
brackets = []
for brac in char:
if brac in ["(","{","["]:
brackets.append(brac)
else:
if brac in [")","}","]"]:
#return False
####storing in a temporary variable####
current_char = brackets.pop()
if current_char == '(':
if brac != ")":
return False
if current_char == '[':
if brac != ']':
return False
if current_char == '{':
if brac != "}":
return False
if brackets:
return False
return True
char = '{(lfjhbdg)}'#"{()}["
k = valid_paranthesis(char)
if k:
print("True")
else:
print("False")
<file_sep>/remove_duplicate.py
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 6 05:54:07 2020
@author: <NAME>
"""
def remove_duplicates(num):
index = 1
while index < len(num):
if num[index] == num[index - 1]:
num.pop(index)
else:
index = index + 1
return len(num)
num = [0,0,1,1,1,2,2,3,3,4]
print(remove_duplicates((num)))<file_sep>/range_sum_query-2.py
A = [2, 2, 2]
B = [[1, 1], [2, 3]]
sum_list=[]
for num in B:
sum_arr=A[num[0]-1:num[1]]
sum_range=sum(sum_arr)
sum_list.append(sum_range)
print(sum_list) <file_sep>/two_sum.py
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 2 06:41:27 2020
@author: <NAME>
"""
def two_sum(arr, x):
for i in range(len(arr)):
left = i + 1
right = len(arr) - 1
temp = x - arr[i]
while left <= right:
mid = left + (right -left) // 2
if arr[mid] == temp:
return[left, mid + 1]
elif arr[mid] < temp:
left = mid + 1
else:
right = mid - 1
return -1
arr = [2,7,11,15]
x = 10
print(two_sum(arr, x))<file_sep>/elements>itself.py
A=[24,5,6,10,28,32]
# print(max(A))
# max_num=max(A)
# count=0
# for num in A:
# if num == max_num:
# count=count+1
# print(count)
# print (len(A)-count)
max=A[0]
count=1
for num in range(1,len(A)):
if A[num] > max:
max=A[num]
elif A[num]==max:
count = count + 1
print(count)
out=len(A)-count
print(out)
<file_sep>/mod_array.py
A=[ 8, 2, 5, 6, 7, 6, 2, 6, 2 ]
B=10
pow = 1
ans=0
for i in range(len(A)-1,-1,-1):
print(i)
ans=ans+(A[i]*pow)%B
pow=(pow*10)%B
print(ans%B)<file_sep>/main_diagonal_sum.py
A=[[1,2,3],
[5,6,7],
[9,2,3]]
row=len(A)
col=len(A[0])
diagonal_sum=0
for i in range(row):
print(A[i][i])
diagonal_sum = diagonal_sum + A[i][i]
print(diagonal_sum)<file_sep>/last_word.py
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 7 05:55:23 2020
@author: <NAME>
"""
def last_word(word):
words = word.split()
if len(words) == 0:
return 0
return len((words[-1]))
word = "<NAME>"
print(last_word(word))<file_sep>/sum_max_min_arr.py
import sys
def sum_max_min_array(arr):
max_num=-sys.maxsize-1
min_num=sys.maxsize
for num in range(0,len(arr)):
if arr[num] > max_num:
max_num = arr[num]
if arr[num] < min_num:
min_num = arr[num]
return (max_num + min_num)
arr=[1,5,2,6,9]
print(solve(arr))<file_sep>/reverser_num.py
def reverse_num(num):
rev = 0
while num > 0:
rem = num % 10
rev = rev * 10 + rem
num = num//10
return rev
kn = reverse_num(23456987)
print(kn)
<file_sep>/square_root.py
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 2 06:17:33 2020
@author: <NAME>
"""
import math
def square_root(x):
sqr = math.sqrt(x)
return int(sqr)
print(square_root(8))<file_sep>/linked_lists.py
###Initializing the nodes#######
from xxlimited import new
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
class Linked_List:
#######this will add the head to the nodes#########
def __init__(self):
self.head = None
######Insertion of a Linked List#######
def insertionatEnd(self, insertingNum):
newNode=Node(insertingNum)
##check head is there or not.If not make current node as the head.
if self.head is None:
self.head=newNode
return
last = self.head
while(last.next):
last= last.next
last.next=newNode
#########Insertion at begining of the Node
def atBegining(self, newnum):
new_node=Node(newnum)
new_node.next=self.head
self.head=new_node
#############Traversing the linked list
def traverse_linkedList(self):
currentHead=self.head
while (currentHead):
print(currentHead.data)
currentHead=currentHead.next
nodes = Linked_List()
nodes.head=Node(4)
node1=Node(5)
node2=Node(6)
nodes.head.next=node1;
node1.next=node2;
nodes.atBegining(28)
nodes.atBegining(30)
nodes.insertionatEnd(25)
nodes.insertionatEnd(26)
nodes.insertionatEnd(27)
nodes.traverse_linkedList()
<file_sep>/pallindrome.py
def is_pallindrome(num):
temp = num
reverse = 0
while num > 0:
rem = num % 10
reverse = reverse * 10 + rem
num = num // 10
if reverse == temp:
print("Hey, Its a Palindrome Number")
k = is_pallindrome(91019)
<file_sep>/minor_diagonal_sum.py
A = [[1, -2, -3],
[-4, 5, -6],
[-7, -8, 9]]
len_rows=len(A)
diag_sum=0
for row in range(len_rows):
diag_sum = diag_sum + A[row][len_rows-row - 1]
print(diag_sum) | 9be870d531136d3d190f055ea33e4b1a2391301d | [
"Python"
] | 24 | Python | iravivarma/Algorithms | 2ffdd40c26bef2f6b3418bc395de3ee92d7a4ee3 | afdbf101054c2297ef2deb045b5c48897c91ccd4 |
refs/heads/main | <file_sep>"""empty message
Revision ID: f93a58ed3b7d
Revises: <PASSWORD>
Create Date: 2021-06-22 16:02:23.840009
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f93a5<PASSWORD>'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('work',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(length=300), nullable=True),
sa.Column('studentfirstname', sa.String(length=50), nullable=True),
sa.Column('studentsurname', sa.String(length=50), nullable=True),
sa.Column('projectname', sa.String(length=100), nullable=True),
sa.Column('date', sa.Date(), nullable=True),
sa.Column('coursename', sa.String(length=100), nullable=True),
sa.Column('grade', sa.String(length=100), nullable=True),
sa.Column('feedback', sa.String(length=1000), nullable=True),
sa.Column('filename', sa.String(length=300), nullable=True),
sa.Column('file', sa.LargeBinary(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users2.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('work')
# ### end Alembic commands ###
<file_sep>"""Adding conetent table
Revision ID: 9802f18c14af
Revises: 50b4ce1e4826
Create Date: 2021-06-17 16:56:40.388722
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '9802f18c14af'
down_revision = '50b4ce1e4826'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('content',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=300), nullable=True),
sa.Column('file', sa.LargeBinary(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('content')
# ### end Alembic commands ###
<file_sep>from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField, HiddenField,TextField,FileField,DateField,TimeField,TextAreaField
from wtforms.validators import ValidationError, DataRequired, Email, EqualTo,Length
from wtforms import HiddenField
from app.models import User2
from flask_login import current_user
from flask_wtf import Form
from datetime import date
from wtforms.widgets import TextArea
class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired(message='Enter your username'),Length(min=2,max=20,message='Username must be between 2 and 20 characters.')])
password = PasswordField('<PASSWORD>', validators=[DataRequired(message='Enter your password'),Length(min=8,max=20,message='Password must be between 8 and 20 characters.')])
remember_me = BooleanField('Remember Me')
submit = SubmitField('Sign In')
class studentsignup1(FlaskForm):
firstname = StringField('First name', validators=[DataRequired(message='Enter your first name'),Length(min=2,max=20,message='First name must be between 2 and 20 characters.')])
surname = StringField('Surname', validators=[DataRequired(message='Enter your surname'),Length(min=2,max=20,message='Surname must be between 2 and 20 characters.')])
email = StringField('Email address', validators=[DataRequired(message='Enter your email address'), Email(),Length(min=2,max=50,message='Email address must be between 2 and 50 characters.')])
username = StringField('Username', validators=[DataRequired(message='Enter your username'),Length(min=2,max=20,message='Username must be between 2 and 20 characters.')])
password = PasswordField('<PASSWORD>', validators=[DataRequired(message='Enter your password'),Length(min=8,max=20,message='Password must be between 8 and 20 characters.')])
password2 = PasswordField(
'Confirm Password', validators=[DataRequired(message='Enter your password again'), EqualTo('password',message='Password\'s aren\'t the same'),Length(min=8,max=20,message='Password must be between 8 and 20 characters.')])
type = HiddenField('type')
submit = SubmitField('Sign up')
def validate_username(self, username):
user = User2.query.filter_by(username=username.data).first()
if user is not None:
raise ValidationError('Please use a different username.')
def validate_email(self, email):
user = User2.query.filter_by(email=email.data).first()
if user is not None:
raise ValidationError('Please use a different email address.')
class tutorsignup1(FlaskForm):
firstname = StringField('First name', validators=[DataRequired(message='Enter your first name'),Length(min=2,max=20,message='First name must be between 2 and 20 characters.')])
surname = StringField('Surname', validators=[DataRequired(message='Enter your surname'),Length(min=2,max=20,message='Surname must be between 2 and 20 characters.')])
email = StringField('Email address', validators=[DataRequired(message='Enter your email address'), Email(),Length(min=2,max=50,message='Email address must be between 2 and 50 characters.')])
username = StringField('Username', validators=[DataRequired(message='Enter your username'),Length(min=2,max=20,message='Username must be between 2 and 20 characters.')])
password = PasswordField('Password', validators=[DataRequired(message='Enter your password'),Length(min=8,max=20,message='Password must be between 8 and 20 characters.')])
password2 = PasswordField(
'Confirm Password', validators=[DataRequired(message='Enter your password again'), EqualTo('password',message='Password\'s aren\'t the same'),Length(min=8,max=20,message='Password must be between 8 and 20 characters.')])
type = 'tutor'
submit = SubmitField('Sign up')
def validate_username(self, username):
user = User2.query.filter_by(username=username.data).first()
if user is not None:
raise ValidationError('Please use a different username.')
def validate_email(self, email):
user = User2.query.filter_by(email=email.data).first()
if user is not None:
raise ValidationError('Please use a different email address.')
class accountdetails1(FlaskForm):
firstname = StringField('First name', validators=[DataRequired(message='Enter your first name'),Length(min=2,max=20,message='First name must be between 2 and 20 characters.' )])
surname = StringField('Surname', validators=[DataRequired(message='Enter your surname'),Length(min=2,max=20,message='Surname must be between 2 and 20 characters.')])
email = StringField('Email address', validators=[DataRequired(message='Enter your email address'), Email(),Length(min=2,max=50,message='Email address must be between 2 and 50 characters.')])
username = StringField('Username', validators=[DataRequired(message='Enter your username'),Length(min=2,max=20,message='Username must be between 2 and 20 characters.')])
password = PasswordField('<PASSWORD>', validators=[DataRequired(message='Enter your password'),Length(min=8,max=20,message='Password must be between 8 and 20 characters.')])
address = StringField('Address', validators=[Length(min=2,max=50,message='Address must be between 2 and 50 characters.')])
town = StringField('Town', validators=[Length(min=2,max=20,message='Town must be between 2 and 20 characters.')])
city = StringField('City', validators=[Length(min=2,max=20,message='City must be between 2 and 20 characters.')])
postcode = StringField('Postcode', validators=[Length(min=6,max=20,message='Postcode must be between 6 and 20 characters.')])
phone = StringField('Phone number', validators=[Length(min=11,max=11,message='Phone number must be 11 digits.')])
workexperience = TextAreaField('Work experience', validators=[Length(min=2,max=50,message='Work experience must be between 2 and 50 characters.')])
submit = SubmitField('Save details')
def validate_username(self, username):
if User2.query.filter_by(username=username.data).first() and username.data != current_user.username:
raise ValidationError('Please use a different username.')
def validate_email(self, email):
if User2.query.filter_by(email=email.data).first() and email.data != current_user.email:
raise ValidationError('Please use a different email address.')
class settingsform1(FlaskForm):
password = PasswordField('New password', validators=[DataRequired(message='Enter your password'),Length(min=8,max=20,message='Password must be between 8 and 20 characters.')])
password2 = PasswordField(
'<PASSWORD> password', validators=[DataRequired(message='Confirm your password '), EqualTo('password',message='Password\'s aren\'t the same'),Length(min=8,max=20,message='Password must be between 8 and 20 characters.')])
email = StringField('New email address', validators=[DataRequired(message='Enter your email address'), Email(),Length(min=2,max=50,message='Email address must be between 2 and 50 characters.')])
email2 = StringField('Confirm email address', validators=[DataRequired(message='Confirm your email address '), EqualTo('email',message='Email addresses aren\'t the same'), Email(),Length(min=2,max=50,message='Email address must be between 2 and 50 characters.')])
submit = SubmitField('Save details')
def validate_email(self, email):
if User2.query.filter_by(email=email.data).first() and email.data != current_user.email:
raise ValidationError('Please use a different email address.')
class deleteform(Form):
delete = SubmitField('Delete account')
class addcourse1(FlaskForm):
name = StringField('Name', validators=[DataRequired(message='Enter the course name'),Length(min=2,max=50,message='Course name must be between 2 and 50 characters.' )])
description = TextAreaField('Description', validators=[DataRequired(message='Enter the course description'),Length(min=2,max=200,message='Course description must be between 2 and 200 characters.' )])
chapters = StringField('Chapters', validators=[DataRequired(message='Enter the course chapters'),Length(min=1,max=200,message='Course chapters must be between 1 and 200 characters.' )])
user_id = current_user
submit = SubmitField('Add course')
class addproject1(FlaskForm):
name = StringField('Name', validators=[DataRequired(message='Enter the project name'),Length(min=2,max=50,message='Course name must be between 2 and 50 characters.' )])
description = TextAreaField('Description', validators=[DataRequired(message='Enter the project description'),Length(min=2,max=200,message='Course description must be between 2 and 200 characters.' )])
chapters = StringField('Chapters', validators=[DataRequired(message='Enter the project chapters'),Length(min=1,max=200,message='Course chapters must be between 1 and 200 characters.' )])
user_id = current_user
submit = SubmitField('Add project')
class joincourseform(Form):
joincourse = SubmitField('Join course')
class Uploadform(Form):
file = FileField()
submit = SubmitField('Upload files')
class helpform1(FlaskForm):
sendername = StringField('Name', validators=[DataRequired(message='Enter your name'),Length(min=1,max=200,message='Your name must be between 1 and 100 characters.' )])
email = StringField('Email address', validators=[DataRequired(message='Enter your email address'), Email(),Length(min=2,max=50,message='Email address must be between 2 and 50 characters.')])
phone = StringField('Phone number', validators=[Length(min=11,max=11,message='Phone number must be 11 digits.')])
ticketname = StringField('Ticket name', validators=[DataRequired(message='Enter the subject'),Length(min=2,max=50,message='Subject must be between 2 and 50 characters.' )])
message = TextAreaField('Message', validators=[DataRequired(message='Enter your message'),Length(min=2,max=1000,message='Message must be between 2 and 1000 characters.' )])
response = ''
progress = 'Sent'
assignedto = 'Tom'
user_id = current_user
date = date.today
submit = SubmitField('Send message')
class helpform2(FlaskForm):
response = TextAreaField('Response:', validators=[DataRequired(message='Enter your response'),Length(min=2,max=1000,message='Response must be between 2 and 1000 characters.')])
submit = SubmitField('Send')
class booksession1(FlaskForm):
sessionname = StringField('Session name', validators=[DataRequired(message='Enter the session name'),Length(min=2,max=200,message='The session name must be between 2 and 200 characters.')])
date = DateField('Date', validators=[DataRequired(message='Enter the date of the session')])
time = TimeField('Time', validators=[DataRequired(message='Enter the time of the session')])
duration = StringField('Duration', validators=[DataRequired(message='Enter the duration of the session'),Length(min=2, max=100,message='Duration must be between 2 and 100 characters')])
coursename = StringField('Course name', validators=[DataRequired(message='Enter the course name'),Length(min=2,max=200,message='Course name must be between 2 and 200 characters')])
submit = SubmitField('Book session')
class paymentform(FlaskForm):
firstname = StringField('First name', validators=[DataRequired(message='Enter your first name'),Length(min=2,max=50,message='Your first name should be between 2 and 50 characters')])
surname = StringField('Surname', validators=[DataRequired(message='Enter your surname'),Length(min=2,max=50,message='Your surname should be between 2 and 50 characters')])
address = StringField('Address', validators=[DataRequired(message='Enter your address'),Length(min=2,max=50,message='Address must be between 2 and 50 characters.')])
town = StringField('Town', validators=[DataRequired(message='Enter your town'),Length(min=2,max=20,message='Town must be between 2 and 20 characters.')])
city = StringField('City', validators=[DataRequired(message='Enter your city'),Length(min=2,max=20,message='City must be between 2 and 20 characters.')])
postcode = StringField('Postcode', validators=[DataRequired(message='Enter your postcode'),Length(min=6,max=20,message='Postcode must be between 6 and 20 characters.')])
phone = StringField('Phone number', validators=[DataRequired(message='Enter your phone'),Length(min=11,max=11,message='Phone number must be 11 digits.')])
email = StringField('Email address', validators=[DataRequired(message='Enter your email address'), Email(),Length(min=2,max=50,message='Email address must be between 2 and 50 characters.')])
service = StringField('Service', validators=[DataRequired(message='Enter the service you are paying for'), Length(min=2,max=200,message='Service must be between 2 and 200 characters.')])
amount = StringField('Amount',validators=[DataRequired(message='Enter the amount you are paying'), Length(min=1,max=200,message='Amount must be between 1 and 200 characters.')])
cardno = StringField('Card number',validators=[DataRequired(message='Enter your card number'), Length(min=1,max=16,message='Card number must be between 1 and 16 characters.')])
expirydate = StringField('Expiry date',validators=[DataRequired(message='Enter the expiry date on your card'), Length(min=1,max=5,message='Amount must be between 1 and 5 characters.')])
securitycode = StringField('Security code',validators=[DataRequired(message='Enter the security code on your card'), Length(min=1,max=3,message='Amount must be between 1 and 3 characters.')])
date = DateField('Date', validators=[DataRequired(message='Enter the date of the payment')])
submit = SubmitField('Make payment')<file_sep>alembic==1.6.5
appdirs==1.4.4
appnope==0.1.0
backcall==0.2.0
blinker==1.4
certifi==2021.5.30
chardet==4.0.0
click==8.0.1
decorator==4.4.2
distlib==0.3.2
dnspython==2.1.0
docopt==0.6.2
email-validator==1.1.3
filelock==3.0.12
Flask==2.0.1
Flask-Login==0.5.0
Flask-Mail==0.9.1
Flask-Migrate==3.0.1
Flask-SQLAlchemy==2.5.1
Flask-WTF==0.15.1
greenlet==1.1.0
gunicorn==20.1.0
idna==2.10
ipykernel==5.3.4
ipython==7.18.1
ipython-genutils==0.2.0
itsdangerous==2.0.1
jedi==0.17.2
Jinja2==3.0.1
jupyter-client==6.1.7
jupyter-core==4.6.3
Mako==1.1.4
MarkupSafe==2.0.1
parso==0.7.1
pexpect==4.8.0
pickleshare==0.7.5
pipenv==2021.5.29
pipreqs==0.4.10
prompt-toolkit==3.0.7
ptyprocess==0.6.0
py-email-validation==1.0.0.3
Pygments==2.7.1
python-dateutil==2.8.1
python-dotenv==0.18.0
python-editor==1.0.4
pyzmq==19.0.2
requests==2.25.1
six==1.15.0
SQLAlchemy==1.4.19
tornado==6.0.4
traitlets==5.0.4
urllib3==1.26.6
virtualenv==20.4.7
virtualenv-clone==0.5.4
wcwidth==0.2.5
Werkzeug==2.0.1
WTForms==2.3.3
yarg==0.1.9
<file_sep>FLASK_APP=iptutorial.py
<file_sep>
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{{ url_for('static', filename='css/addcourse.css') }}">
<link href="https://fonts.googleapis.com/css2?family=Comfortaa&family=Open+Sans&display=swap" rel="stylesheet">
<title> IP tutorials </title>
</head>
<body >
<div id="nav" >
<p><img src=' 'width="30" height="30">IP tutorials</p>
<ul>
<li style="text-align:right;"> <a href="{{ url_for('tutordashboard') }}"> Home </a></li>
<div class="dropdown">
<button class="dropbtn">Work
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
<a href="{{ url_for('tutorcourses') }}">Courses</a>
<a href="{{url_for('tutorprojects')}}">Projects</a>
<a href="{{ url_for('sessions') }}">Sessions</a>
<a href="{{ url_for('content') }}">Content</a>
<a href="{{ url_for('meeting') }}">Meeting</a>
</div></div>
<div class="dropdown">
<button class="dropbtn">Other
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
<a href="{{ url_for('supportpage') }}">Support</a>
<a href="{{ url_for('messages') }}">Messages</a>
<a href="{{ url_for('payment') }}">Payments</a>
</div></div>
<div class="dropdown">
<button class="dropbtn">Account
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
<a href="{{ url_for('studentprofile') }}">Profile</a>
<a href="{{ url_for('studentaccount') }}">Account details</a>
<a href="{{ url_for('studentsettings') }}">Settings</a>
<a href="{{ url_for('logout') }}">Log out</a>
</div></div>
</ul>
</div>
<!-- <div id="background"> -->
<section>
<div id="header" style="margin-bottom: 10%;">
<div id="headertext">Add project</div>
</div>
</section >
<div style="margin-left:5%;margin-bottom: 10%;">
<table>
<form action="" method="post" >
<div class="container">
{{ form.hidden_tag() }}
<tr> <p>
<td> <h3> {{ form.name.label }}</h3></td><br>
<td> {{ form.name(size=50) }}</td><br>
{% for error in form.name.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p></tr>
<tr>
<p>
<td> <h3>{{ form.description.label }}</h3></td> <br>
<td><textarea style="
padding: 12px 20px;
margin: 8px 0;
margin-top: 20px;
margin-bottom: 20px;
border: 1px solid #ccc;
box-sizing: border-box;font-family: 'Comfortaa', cursive;
"name="description" cols="44" rows="10" id="description"></textarea></td> <br>
{% for error in form.description.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p></tr>
<tr>
<p>
<td> <h3>{{ form.chapters.label }}</h3></td><br>
<td> {{ form.chapters(size=120) }}</td><br>
{% for error in form.chapters.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p></tr>
<tr><td> <p>{{ form.submit() }}</p></td></tr>
</div>
</form>
</table>
{% with messages = get_flashed_messages() %}
{% if messages %}
<ul>
{% for message in messages %}
<li>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
{% block content %}{% endblock %}
</div>
<div style="background-color: #d4d4d4;">
<footer style="background-color: #d4d4d4;">
<div style="position:relative;background-color:#d4d4d4" class="footer" id="footer">
<div class="logo">
<p style="font-size: 10pt;"><img src=' ' width="30" height="30" align="left" style="display: inline-block;">IP tutorials</p>
</div>
<div class="column">
<h3>Pages</h3>
<p>Link</p>
<p>Link</p>
<p>Link</p>
<p>Link</p>
</div>
<div class="column">
<h3>Pages</h3>
<p>Link</p>
<p>Link</p>
<p>Link</p>
<p>Link</p>
</div>
<div class="column">
<h3>Pages</h3>
<p>Link</p>
<p>Link</p>
<p>Link</p>
<p>Link</p>
</div>
</div>
</footer>
</div>
</body>
</html><file_sep>"""Adding projects table
Revision ID: 50b4ce1e4826
Revises: <PASSWORD>
Create Date: 2021-06-17 14:27:49.161944
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '50b4ce1e4826'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('projects',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=50), nullable=True),
sa.Column('description', sa.String(length=200), nullable=True),
sa.Column('chapters', sa.String(length=200), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('projects')
# ### end Alembic commands ###
<file_sep>from flask import Flask
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_mail import Mail
from random import *
app = Flask(__name__)
app.config.from_object(Config)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
login = LoginManager(app)
mail = Mail(app)
app.config["MAIL_SERVER"]='smtp.gmail.com'
app.config["MAIL_PORT"] = 465
app.config["MAIL_USERNAME"] = '<EMAIL>'
app.config['MAIL_PASSWORD'] = '*************'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail = Mail(app)
app.static_folder = 'static'
login.login_view = 'login'
from app import routes, models<file_sep>"""courses table
Revision ID: 724e4f97f8c4
Revises:
Create Date: 2021-06-16 16:38:26.559325
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7<PASSWORD>'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('firstname', sa.String(length=50), nullable=True),
sa.Column('surname', sa.String(length=50), nullable=True),
sa.Column('username', sa.String(length=64), nullable=True),
sa.Column('email', sa.String(length=120), nullable=True),
sa.Column('password_hash', sa.String(length=128), nullable=True),
sa.Column('address', sa.String(length=100), nullable=True),
sa.Column('town', sa.String(length=100), nullable=True),
sa.Column('city', sa.String(length=100), nullable=True),
sa.Column('postcode', sa.String(length=7), nullable=True),
sa.Column('phone', sa.String(length=11), nullable=True),
sa.Column('workexperience', sa.String(length=100), nullable=True),
sa.Column('type', sa.String(length=20), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True)
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
op.create_table('courses',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=50), nullable=True),
sa.Column('description', sa.String(length=200), nullable=True),
sa.Column('chapters', sa.String(length=200), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('courses')
op.drop_index(op.f('ix_users_username'), table_name='users')
op.drop_index(op.f('ix_users_email'), table_name='users')
op.drop_table('users')
# ### end Alembic commands ###
<file_sep>import re
from flask import render_template, flash, redirect, url_for, send_file
from app import app
from app import db
from app.forms import LoginForm, studentsignup1, tutorsignup1, accountdetails1, settingsform1, deleteform, addcourse1, \
joincourseform, addproject1, Uploadform, helpform1, helpform2, booksession1, paymentform
from app.models import User2, Courses, Project2, Content2, Supporttickets3, Sessions2, Payments, Work
from flask_login import current_user, login_user
from flask_login import logout_user
from flask_login import login_required
from flask import request
from werkzeug.urls import url_parse
from io import BytesIO
from datetime import date
from flask_mail import Message
from flask_mail import Mail
from random import *
from datetime import datetime
@app.route('/')
@app.route('/index')
def index():
return render_template('index.html', title='Home')
@app.route('/studentdashboard')
@login_required
def studentdashboard():
course = Courses.query.filter_by(id='1')
project = Project2.query.filter_by(id='1')
return render_template('studentdashboard.html', course=course, project=project)
@app.route('/aboutus')
def aboutus():
return render_template('aboutus.html')
@app.route('/courses')
def courses():
return render_template('courses.html')
@app.route('/projects')
def projects():
return render_template('projects.html')
@app.route('/contactus')
def contactus():
return render_template('contactus.html')
@app.route('/studentsignup', methods=['GET', 'POST'])
def studentsignup():
if current_user.is_authenticated:
return redirect(url_for('studentdashboard'))
form = studentsignup1()
if form.validate_on_submit():
user = User2(username=form.username.data, email=form.email.data, firstname=form.firstname.data,
surname=form.surname.data, type='student', password=form.password.data)
user.set_password(form.password.data)
db.session.add(user)
db.session.commit()
flash('You are now a registered user!')
return redirect(url_for('login'))
return render_template('studentsignup.html', title='Student sign up', form=form)
@app.route('/tutorsignup', methods=['GET', 'POST'])
def tutorsignup():
if current_user.is_authenticated:
return redirect(url_for('tutordashboard'))
form = tutorsignup1()
if form.validate_on_submit():
user = User2(username=form.username.data, email=form.email.data, firstname=form.firstname.data,
surname=form.surname.data, type='tutor', password=<PASSWORD>)
user.set_password(<PASSWORD>.data)
db.session.add(user)
db.session.commit()
flash('You are now a registered user!')
return redirect(url_for('login'))
return render_template('tutorsignup.html', title='Tutor sign up', form=form)
@app.route('/courseprogress')
@login_required
def courseprogress():
data = Courses.query.filter_by(id='1')
return render_template('courseprogress.html', data=data)
@app.route('/projectprogress')
@login_required
def projectprogress():
data = Project2.query.filter_by(id='1')
work = Work.query.filter_by(id='3')
return render_template('projectprogress.html', data=data, work=work)
@app.route('/certificates')
@login_required
def certificates():
certificate = Content2.query.filter_by(id=2)
return render_template('certificates.html', certificate=certificate)
@app.route('/supportpage')
@login_required
def supportpage():
return render_template('supportpage.html')
@app.route('/messages')
@login_required
def messages():
return render_template('messages.html')
@app.route('/studentprofile')
@login_required
def studentprofile():
projects = Project2.query.filter_by(id='1')
courses = Courses.query.filter_by(id='1')
return render_template('studentprofile.html', projects=projects, courses=courses)
@app.route('/studentaccount', methods=['GET', 'POST'])
@login_required
def studentaccount():
form = accountdetails1(request.form, obj=current_user)
if request.method == 'POST':
if form.validate_on_submit():
current_user.username = form.username.data
current_user.firstname = form.firstname.data
current_user.surname = form.surname.data
current_user.password = <PASSWORD>
current_user.email = form.email.data
current_user.address = form.address.data
current_user.town = form.town.data
current_user.city = form.city.data
current_user.postcode = form.postcode.data
current_user.phone = form.phone.data
current_user.workexperience = form.workexperience.data
current_user.set_password(<PASSWORD>)
# #Ignore form fields not in data model
# form_data = {i: form.data[i] for i in form.data if i not in ["csrf_token", "submit"]}
# #Remove empty fields
# new_data = {k: v for k, v in form_data.items() if v is not None}
# #Unpack into Company model
# current_user.update(**new_data)
db.session.commit()
flash('Your details have been changed.')
return redirect(url_for('studentaccount'))
elif request.method == 'GET':
form.username.data = current_user.username
form.firstname.data = current_user.firstname
form.surname.data = current_user.surname
form.password.data = <PASSWORD>_hash
form.email.data = current_user.email
form.address.data = current_user.address
form.town.data = current_user.town
form.city.data = current_user.city
form.postcode.data = current_user.postcode
form.phone.data = current_user.phone
form.workexperience.data = current_user.workexperience
return render_template('studentaccount.html', title='Student account',
form=form)
@app.route('/studentsettings', methods=['GET', 'POST'])
@login_required
def studentsettings():
form = settingsform1(request.form, obj=current_user)
if request.method == 'POST':
if "savedetails" in request.form and form.validate_on_submit():
current_user.password = <PASSWORD>
current_user.email = form.email.data
current_user.set_password(form.password.data)
db.session.commit()
flash('Your details have been changed.')
return redirect(url_for('studentsettings'))
elif request.method == 'GET':
form.password.data = <PASSWORD>_<PASSWORD>
form.email.data = current_user.email
return render_template('studentsettings.html', title='Student settings',
form=form, obj=current_user)
@app.route('/delete', methods=['GET', 'POST'])
@login_required
def delete():
id = 1
user = User2.query.filter(id == id).first()
db.session.delete(user)
db.session.commit()
flash('Your account has been successfully deleted. ', 'success')
return redirect(url_for('login'))
return render_template('login.html', form=form, id=id, user=user)
@app.route('/coursedetails', methods=['GET', 'POST'])
def coursedetails():
course = Courses.query.filter_by(id='1')
return render_template('coursedetails.html', course=course)
@app.route('/projectdetails2', methods=['GET', 'POST'])
def projectdetails2():
project = Project2.query.filter_by(id='1')
return render_template('projectdetails2.html', project=project)
@app.route('/joincourse', methods=['GET', 'POST'])
@login_required
def joincourse():
course = Courses(name='Intellectual property', description='copyright laws', chapters='20', status='confirmed',
user_id=current_user.id)
db.session.add(course)
db.session.commit()
flash('Joined course')
return redirect(url_for('coursedetails'))
return render_template('coursedetails.html', title='Course details', form=form)
@app.route('/confirmcourse', methods=['GET', 'POST'])
def confirmcourse():
course = Courses(name='Intellectual property', description='copyright laws', chapters='20', status='confirmed',
user_id=current_user.id)
db.session.add(course)
db.session.commit()
flash('Confirmed course')
return redirect(url_for('courserequests'))
return render_template('courserequests.html', title='Course requests', form=form)
@app.route('/joinproject', methods=['GET', 'POST'])
@login_required
def joinproject():
project = Project2(name='Trademarks', description='trademark laws', chapters='22', user_id=current_user.id)
db.session.add(project)
db.session.commit()
flash('Joined project')
return redirect(url_for('projectdetails2'))
return render_template('projectdetails2.html', title='Project details', form=form)
@app.route('/helpform', methods=['GET', 'POST'])
def helpform():
form = helpform1()
if form.validate_on_submit():
ticket = Supporttickets3(sendername=form.sendername.data, email=form.email.data, phone=form.phone.data,
ticketname=form.ticketname.data, message=form.message.data, user_id=current_user.id,
date=date.today(), assignedto='Tom', progress='sent')
db.session.add(ticket)
db.session.commit()
flash('Help form submitted')
return redirect(url_for('helpform'))
return render_template('helpform.html', title='Help form', form=form)
@app.route('/supporttickets')
@login_required
def supporttickets():
supportticket = Supporttickets3.query.filter_by(id='2')
return render_template('supporttickets.html', supportticket=supportticket)
return render_template('supporttickets.html')
@app.route('/submitwork', methods=["GET", "POST"])
@login_required
def submitwork():
if request.method == 'POST':
file = request.files['inputFile']
firstname = request.form['firstname']
surname = request.form['surname']
projectname = request.form['projectname']
coursename = request.form['coursename']
titleofwork = request.form['titleofwork']
newFile = Work(filename=file.filename, file=file.read(), title=titleofwork, studentfirstname=firstname,
studentsurname=surname, projectname=projectname, coursename=coursename, date=date.today(),
user_id=current_user.id)
db.session.add(newFile)
db.session.commit()
flash('Work submitted')
return redirect(url_for('submitwork'))
return render_template('submitwork.html')
@app.route('/tutordashboard')
@login_required
def tutordashboard():
work = Work.query.filter_by(id='5')
return render_template('tutordashboard.html', work=work)
@app.route('/markwork', methods=["GET", "POST"])
@login_required
def markwork():
work = Work.query.filter_by(id='5')
if request.method == 'POST':
grade = request.form['grade']
feedback = request.form['feedback']
newFile = Work(filename='Report (1).docx', title='Assignment 1', studentfirstname='Lucy',
studentsurname='Abbott', projectname='Trade secrets', coursename='Intellectual property',
date=date.today(), user_id=current_user.id, grade=grade, feedback=feedback)
db.session.add(newFile)
db.session.commit()
flash('The work has been marked')
return redirect(url_for('markwork'))
return render_template('markwork.html', work=work)
@app.route('/content')
@login_required
def content():
content = Content2.query.filter_by(id='1')
return render_template('content.html', content=content)
@app.route('/meeting')
@login_required
def meeting():
return render_template('meeting.html')
@app.route('/payment')
@login_required
def payment():
payment = Payments.query.filter_by(id='1')
return render_template('payment.html', payment=payment)
@app.route('/sessions')
@login_required
def sessions():
session = Sessions2.query.filter_by(id='1')
return render_template('sessions.html', session=session)
@app.route('/tutorcourses')
@login_required
def tutorcourses():
course = Courses.query.filter_by(id='1')
user = User2.query.filter_by(id='3')
return render_template('tutorcourses.html', course=course, user=user)
@app.route('/booksession', methods=['GET', 'POST'])
@login_required
def booksession():
form = booksession1()
if form.validate_on_submit():
session = Sessions2(sessionname=form.sessionname.data, date=form.date.data, time=form.time.data,
duration=form.duration.data, coursename=form.coursename.data, user_id=current_user.id)
db.session.add(session)
db.session.commit()
flash('Session booked')
return redirect(url_for('sessions'))
return render_template('booksession.html', title='Book session', form=form)
@app.route('/newmeeting')
@login_required
def newmeeting():
return render_template('newmeeting.html')
@app.route('/meetingcode')
@login_required
def meetingcode():
return render_template('meetingcode.html')
@app.route('/invoice')
@login_required
def invoice():
return render_template('invoice.html')
@app.route('/admindashboard')
@login_required
def admindashboard():
course = Courses.query.filter_by(id='1')
ticket = Supporttickets3.query.filter_by(id='2')
return render_template('admindashboard.html', course=course, ticket=ticket)
@app.route('/adminsupportpage', methods=['GET', 'POST'])
@login_required
def adminsupportpage():
form = helpform2(request.form, obj=current_user)
supportticket = Supporttickets3.query.filter_by(id='2')
if request.method == 'POST':
if form.validate_on_submit():
ticket = Supporttickets3(sendername='<NAME>', email='<EMAIL>', phone='07656787678',
ticketname='Cancel membership', message='How do I cancel my membership?',
user_id='5', date=date.today(), assignedto='Tom', progress='recieved',
response=form.response.data)
db.session.add(ticket)
db.session.commit()
flash('Response submitted')
return render_template('adminsupportpage.html', supportticket=supportticket, form=form)
return render_template('adminsupportpage.html')
@app.route('/courserequests')
@login_required
def courserequests():
course = Courses.query.filter_by(id='1')
return render_template('courserequests.html', course=course)
@app.route('/projectdetails')
@login_required
def projectdetails():
project = Project2.query.filter_by(id='1')
work = Work.query.filter_by(id='3')
user = User2.query.filter_by(id='2')
return render_template('projectdetails.html', project=project, work=work, user=user)
@app.route('/studentdetails')
@login_required
def studentdetails():
user = User2.query.filter_by(id='2')
course = Courses.query.filter_by(id='1')
work = Work.query.filter_by(id='3')
project = Project2.query.filter_by(id='1')
return render_template('studentdetails.html', user=user, course=course, project=project, work=work)
@app.route('/tutordetails')
@login_required
def tutordetails():
tutor = User2.query.filter_by(id='2')
student = User2.query.filter_by(id='3')
course = Courses.query.filter_by(id='1')
project = Project2.query.filter_by(id='1')
return render_template('tutordetails.html', tutor=tutor, student=student, course=course, project=project)
@app.route('/index2')
def index2():
return render_template('index2.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if current_user.is_authenticated:
if current_user.type == 'student':
return redirect(url_for('studentdashboard'))
elif current_user.type == 'tutor':
return redirect(url_for('tutordashboard'))
elif current_user.type == 'admin':
return redirect(url_for('admindashboard'))
form = LoginForm()
if form.validate_on_submit():
user = User2.query.filter_by(username=form.username.data).first()
if user is None or not user.check_password(form.password.data):
flash('Invalid username or password')
return redirect(url_for('login'))
login_user(user, remember=form.remember_me.data)
next_page = request.args.get('next')
if not next_page or url_parse(next_page).netloc != '':
if user.type == 'student': next_page = url_for('studentdashboard')
if user.type == 'tutor': next_page = url_for('tutordashboard')
if user.type == 'admin': next_page = url_for('admindashboard')
return redirect(next_page)
return redirect(url_for('studentdashboard'))
return render_template('login.html', title='Sign In', form=form)
@app.route('/logout')
def logout():
logout_user()
return redirect(url_for('index'))
@app.route('/addcourse', methods=['GET', 'POST'])
def addcourse():
form = addcourse1()
if form.validate_on_submit():
course = Courses(name=form.name.data, description=form.description.data, chapters=form.chapters.data,
status='unconfirmed', user_id=current_user.id)
db.session.add(course)
db.session.commit()
flash('Course added')
return redirect(url_for('addcourse'))
return render_template('addcourse.html', title='Add course', form=form)
@app.route('/tutorprojects')
@login_required
def tutorprojects():
project = Project2.query.filter_by(id='1')
student = User2.query.filter_by(id='3')
return render_template('tutorprojects.html', project=project, student=student)
@app.route('/addproject', methods=['GET', 'POST'])
def addproject():
form = addproject1()
if form.validate_on_submit():
project = Project2(name=form.name.data, description=form.description.data, chapters=form.chapters.data,
user_id=current_user.id)
db.session.add(project)
db.session.commit()
flash('Project added')
return redirect(url_for('addproject'))
return render_template('addproject.html', title='Add project', form=form)
@app.route('/upload', methods=["GET", "POST"])
def upload():
file = request.files['inputFile']
newFile = Content2(name=file.filename, file=file.read())
db.session.add(newFile)
db.session.commit()
flash('File added')
return redirect(url_for('content'))
return render_template('content.html')
@app.route('/download', methods=["POST"])
def download():
file_data = Content2.query.filter_by(id=1).first()
return send_file(BytesIO(file_data.file), attachment_filename='flask.pdf', as_attachment='True')
@app.route('/download2', methods=["POST"])
def download2():
file_data = Content2.query.filter_by(id=2).first()
return send_file(BytesIO(file_data.file), attachment_filename='degree certificate.pdf', as_attachment='True')
@app.route('/download3', methods=["POST"])
def download3():
file_data = Work.query.filter_by(id=2).first()
return send_file(BytesIO(file_data.file), attachment_filename='lastReport.docx', as_attachment='True')
@app.route('/verify', methods=["POST"])
def verify():
code = randint(000000, 999999)
mail = Mail(app)
email = request.form["email"]
msg = Message('code', sender='<EMAIL>', recipients=[email])
msg.body = str(code)
mail.send(msg)
return render_template('emailverification.html')
@app.route('/validate', methods=["POST"])
def validate():
user_code = request.form['code']
if code == int(user_code):
user = User2(username='lucy', email='<EMAIL>', firstname='Lucy', surname='Abbott', type='student',
password='<PASSWORD>', confirmed='1', timestamp=datetime.now())
user.set_password('<PASSWORD>')
db.session.add(user)
db.session.commit()
flash('You are now a registered user!')
if __name__ == '__main__':
app.run(debug=True)
@app.route('/makepayment', methods=['GET', 'POST'])
def makepayment():
form = paymentform()
if form.validate_on_submit():
payment = Payments(firstname=form.firstname.data, surname=form.surname.data, address=form.address.data,
town=form.town.data, city=form.city.data, postcode=form.postcode.data, phone=form.phone.data,
service=form.service.data, amount=form.amount.data, email=form.email.data,
cardno=form.cardno.data, expirydate=form.expirydate.data,
securitycode=form.securitycode.data, date=form.date.data, user_id=current_user.id)
db.session.add(payment)
db.session.commit()
flash('Payment made')
return redirect(url_for('payment'))
return render_template('makepayment.html', title='Make payment', form=form)
<file_sep>"""empty message
Revision ID: dbbf62da1adc
Revises: <KEY>
Create Date: 2021-06-22 14:11:19.952520
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('courses',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=50), nullable=True),
sa.Column('description', sa.String(length=200), nullable=True),
sa.Column('chapters', sa.String(length=200), nullable=True),
sa.Column('status', sa.String(length=50), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users2.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.drop_table('courses2')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('courses2',
sa.Column('id', sa.INTEGER(), nullable=False),
sa.Column('name', sa.VARCHAR(length=50), nullable=True),
sa.Column('description', sa.VARCHAR(length=200), nullable=True),
sa.Column('chapters', sa.VARCHAR(length=200), nullable=True),
sa.Column('user_id', sa.INTEGER(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users2.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.drop_table('courses')
# ### end Alembic commands ###
<file_sep>"""sessions
Revision ID: <KEY>
Revises: e0ae844dfe41
Create Date: 2021-06-21 13:27:25.216412
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = 'e0ae844dfe41'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('sessions',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('sessionname', sa.String(length=100), nullable=True),
sa.Column('date', sa.Date(), nullable=True),
sa.Column('time', sa.Time(), nullable=True),
sa.Column('duration', sa.String(length=100), nullable=True),
sa.Column('coursename', sa.String(length=200), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('sessions')
# ### end Alembic commands ###
<file_sep>"""support tickets2
Revision ID: e0ae844dfe41
Revises: 06108259096c
Create Date: 2021-06-18 15:15:40.986231
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e0ae844dfe41'
down_revision = '06108259096c'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('supporttickets2',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('ticketname', sa.String(length=100), nullable=True),
sa.Column('date', sa.Date(), nullable=True),
sa.Column('message', sa.String(length=1000), nullable=True),
sa.Column('sendername', sa.String(length=100), nullable=True),
sa.Column('email', sa.String(length=120), nullable=True),
sa.Column('phone', sa.String(length=11), nullable=True),
sa.Column('response', sa.String(length=1000), nullable=True),
sa.Column('progress', sa.String(length=50), nullable=True),
sa.Column('assignedto', sa.String(length=100), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.drop_table('supporttickets')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('supporttickets',
sa.Column('id', sa.INTEGER(), nullable=False),
sa.Column('ticketname', sa.VARCHAR(length=100), nullable=True),
sa.Column('date', sa.DATE(), nullable=True),
sa.Column('message', sa.VARCHAR(length=1000), nullable=True),
sa.Column('sendername', sa.VARCHAR(length=100), nullable=True),
sa.Column('email', sa.VARCHAR(length=120), nullable=True),
sa.Column('phone', sa.VARCHAR(length=11), nullable=True),
sa.Column('response', sa.VARCHAR(length=1000), nullable=True),
sa.Column('progress', sa.VARCHAR(length=50), nullable=True),
sa.Column('assignedto', sa.VARCHAR(length=100), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.drop_table('supporttickets2')
# ### end Alembic commands ###
<file_sep>"""tables
Revision ID: f<PASSWORD>fac7
Revises: <KEY>
Create Date: 2021-06-21 16:30:15.715944
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'f2f28b21fac7'
down_revision = '<KEY>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('users2',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('firstname', sa.String(length=50), nullable=True),
sa.Column('surname', sa.String(length=50), nullable=True),
sa.Column('username', sa.String(length=64), nullable=True),
sa.Column('email', sa.String(length=120), nullable=True),
sa.Column('password_hash', sa.String(length=128), nullable=True),
sa.Column('address', sa.String(length=100), nullable=True),
sa.Column('town', sa.String(length=100), nullable=True),
sa.Column('city', sa.String(length=100), nullable=True),
sa.Column('postcode', sa.String(length=7), nullable=True),
sa.Column('phone', sa.String(length=11), nullable=True),
sa.Column('workexperience', sa.String(length=100), nullable=True),
sa.Column('type', sa.String(length=20), nullable=True),
sa.Column('confirmed', sa.Boolean(), nullable=True),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_users2_email'), 'users2', ['email'], unique=True)
op.create_index(op.f('ix_users2_username'), 'users2', ['username'], unique=True)
op.create_table('content2',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=300), nullable=True),
sa.Column('file', sa.LargeBinary(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users2.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('courses2',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=50), nullable=True),
sa.Column('description', sa.String(length=200), nullable=True),
sa.Column('chapters', sa.String(length=200), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users2.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('projects2',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=50), nullable=True),
sa.Column('description', sa.String(length=200), nullable=True),
sa.Column('chapters', sa.String(length=200), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users2.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('sessions2',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('sessionname', sa.String(length=100), nullable=True),
sa.Column('date', sa.Date(), nullable=True),
sa.Column('time', sa.Time(), nullable=True),
sa.Column('duration', sa.String(length=100), nullable=True),
sa.Column('coursename', sa.String(length=200), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users2.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('supporttickets3',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('ticketname', sa.String(length=100), nullable=True),
sa.Column('date', sa.Date(), nullable=True),
sa.Column('message', sa.String(length=1000), nullable=True),
sa.Column('sendername', sa.String(length=100), nullable=True),
sa.Column('email', sa.String(length=120), nullable=True),
sa.Column('phone', sa.String(length=11), nullable=True),
sa.Column('response', sa.String(length=1000), nullable=True),
sa.Column('progress', sa.String(length=50), nullable=True),
sa.Column('assignedto', sa.String(length=100), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users2.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.drop_table('supporttickets2')
op.drop_table('projects')
op.drop_table('sessions')
op.drop_table('content')
op.drop_table('courses')
op.drop_index('ix_users_email', table_name='users')
op.drop_index('ix_users_username', table_name='users')
op.drop_table('users')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('users',
sa.Column('id', sa.INTEGER(), nullable=False),
sa.Column('firstname', sa.VARCHAR(length=50), nullable=True),
sa.Column('surname', sa.VARCHAR(length=50), nullable=True),
sa.Column('username', sa.VARCHAR(length=64), nullable=True),
sa.Column('email', sa.VARCHAR(length=120), nullable=True),
sa.Column('password_hash', sa.VARCHAR(length=128), nullable=True),
sa.Column('address', sa.VARCHAR(length=100), nullable=True),
sa.Column('town', sa.VARCHAR(length=100), nullable=True),
sa.Column('city', sa.VARCHAR(length=100), nullable=True),
sa.Column('postcode', sa.VARCHAR(length=7), nullable=True),
sa.Column('phone', sa.VARCHAR(length=11), nullable=True),
sa.Column('workexperience', sa.VARCHAR(length=100), nullable=True),
sa.Column('type', sa.VARCHAR(length=20), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index('ix_users_username', 'users', ['username'], unique=False)
op.create_index('ix_users_email', 'users', ['email'], unique=False)
op.create_table('courses',
sa.Column('id', sa.INTEGER(), nullable=False),
sa.Column('name', sa.VARCHAR(length=50), nullable=True),
sa.Column('description', sa.VARCHAR(length=200), nullable=True),
sa.Column('chapters', sa.VARCHAR(length=200), nullable=True),
sa.Column('user_id', sa.INTEGER(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('content',
sa.Column('id', sa.INTEGER(), nullable=False),
sa.Column('name', sa.VARCHAR(length=300), nullable=True),
sa.Column('file', sa.BLOB(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('sessions',
sa.Column('id', sa.INTEGER(), nullable=False),
sa.Column('sessionname', sa.VARCHAR(length=100), nullable=True),
sa.Column('date', sa.DATE(), nullable=True),
sa.Column('time', sa.TIME(), nullable=True),
sa.Column('duration', sa.VARCHAR(length=100), nullable=True),
sa.Column('coursename', sa.VARCHAR(length=200), nullable=True),
sa.Column('user_id', sa.INTEGER(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('projects',
sa.Column('id', sa.INTEGER(), nullable=False),
sa.Column('name', sa.VARCHAR(length=50), nullable=True),
sa.Column('description', sa.VARCHAR(length=200), nullable=True),
sa.Column('chapters', sa.VARCHAR(length=200), nullable=True),
sa.Column('user_id', sa.INTEGER(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('supporttickets2',
sa.Column('id', sa.INTEGER(), nullable=False),
sa.Column('ticketname', sa.VARCHAR(length=100), nullable=True),
sa.Column('date', sa.DATE(), nullable=True),
sa.Column('message', sa.VARCHAR(length=1000), nullable=True),
sa.Column('sendername', sa.VARCHAR(length=100), nullable=True),
sa.Column('email', sa.VARCHAR(length=120), nullable=True),
sa.Column('phone', sa.VARCHAR(length=11), nullable=True),
sa.Column('response', sa.VARCHAR(length=1000), nullable=True),
sa.Column('progress', sa.VARCHAR(length=50), nullable=True),
sa.Column('assignedto', sa.VARCHAR(length=100), nullable=True),
sa.Column('user_id', sa.INTEGER(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.drop_table('supporttickets3')
op.drop_table('sessions2')
op.drop_table('projects2')
op.drop_table('courses2')
op.drop_table('content2')
op.drop_index(op.f('ix_users2_username'), table_name='users2')
op.drop_index(op.f('ix_users2_email'), table_name='users2')
op.drop_table('users2')
# ### end Alembic commands ###
<file_sep>from flask import render_template, flash, redirect, url_for
from app import app
from app import db
# from app.forms import LoginForm, RegistrationForm
from app.models import User2
from flask_login import current_user, login_user
from flask_login import logout_user
from flask_login import login_required
from flask import request
from werkzeug.urls import url_parse
# def not_logged_in():
# return render_to_template('index.html')
def view_fn():
if not current_user:
# Anonymous user
return redirect(url_for('not_logged_in'))
elif 'admin' in current_user.type:
# admin page
return redirect(url_for('admindashboard'))
elif 'student' in current_user.type:
# student page
return redirect(url_for('studentdashboard'))
elif 'tutor' in current_user.type:
# tutor page
return redirect(url_for('tutordashboard'))
<file_sep>"""support tickets
Revision ID: 06108259096c
Revises: 9802f18c14af
Create Date: 2021-06-18 15:07:31.895128
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '06108259096c'
down_revision = '9802f18c14af'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('supporttickets',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('ticketname', sa.String(length=100), nullable=True),
sa.Column('date', sa.Date(), nullable=True),
sa.Column('message', sa.String(length=1000), nullable=True),
sa.Column('sendername', sa.String(length=100), nullable=True),
sa.Column('email', sa.String(length=120), nullable=True),
sa.Column('phone', sa.String(length=11), nullable=True),
sa.Column('response', sa.String(length=1000), nullable=True),
sa.Column('progress', sa.String(length=50), nullable=True),
sa.Column('assignedto', sa.String(length=100), nullable=True),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('supporttickets')
# ### end Alembic commands ###
<file_sep>from app import db
from app import login
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin
class User2(UserMixin,db.Model):
__tablename__ = 'users2'
id = db.Column(db.Integer, primary_key=True)
firstname = db.Column(db.String(50))
surname = db.Column(db.String(50))
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
address = db.Column(db.String(100))
town = db.Column(db.String(100))
city = db.Column(db.String(100))
postcode = db.Column(db.String(7))
phone = db.Column(db.String(11))
workexperience = db.Column(db.String(100))
type = db.Column(db.String(20),default="student")
confirmed = db.Column(db.Boolean(1),default = '0')
timestamp = db.Column(db.DateTime())
def __init__(self, firstname, surname, username, email, password, address=None,town=None,city=None,postcode=None,phone=None,workexperience=None,type=None,confirmed=0,timestamp=None):
self.firstname = firstname
self.surname = surname
self.username = username
self.email = email
self.password_hash = <PASSWORD>_password_hash(password)
self.address = address
self.town = town
self.city = city
self.postcode = postcode
self.phone = phone
self.workexperience = workexperience
self.type = type
self.confirmed = confirmed
self.timestamp = timestamp
def __repr__(self):
return '<User2 {}>'.format(self.username)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
@login.user_loader
def load_user(id):
return User2.query.get(int(id))
class Courses(db.Model):
__tablename__ = 'courses'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
description = db.Column(db.String(200))
chapters = db.Column(db.String(200))
status = db.Column(db.String(50),default='unconfirmed')
user_id = db.Column(db.Integer, db.ForeignKey('users2.id'))
users = db.relationship(User2)
def __init__(self, name, description, chapters,status,user_id):
self.name = name
self.description = description
self.chapters = chapters
self.status = status
self.user_id = user_id
def __repr__(self):
return '<Courses {}>'.format(self.name)
class Project2(db.Model):
__tablename__ = 'projects2'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
description = db.Column(db.String(200))
chapters = db.Column(db.String(200))
user_id = db.Column(db.Integer, db.ForeignKey('users2.id'))
users = db.relationship(User2)
def __init__(self, name, description, chapters,user_id):
self.name = name
self.description = description
self.chapters = chapters
self.user_id = user_id
def __repr__(self):
return '<Project2 {}>'.format(self.name)
class Content2(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(300))
file = db.Column(db.LargeBinary)
user_id = db.Column(db.Integer, db.ForeignKey('users2.id'))
users = db.relationship(User2)
def __init__(self, name=None, file=None, user_id=None):
self.name = name
self.file = file
self.user_id = user_id
def __repr__(self):
return '<Content2 {}>'.format(self.name)
class Supporttickets3(db.Model):
id = db.Column(db.Integer, primary_key=True)
ticketname = db.Column(db.String(100))
date = db.Column(db.Date())
message = db.Column(db.String(1000))
sendername = db.Column(db.String(100))
email = db.Column(db.String(120))
phone = db.Column(db.String(11))
response = db.Column(db.String(1000))
progress = db.Column(db.String(50))
assignedto = db.Column(db.String(100))
user_id = db.Column(db.Integer, db.ForeignKey('users2.id'))
users = db.relationship(User2)
def __init__(self, ticketname=None, date=None, message=None, sendername=None, email=None, phone=None, response=None, progress=None, assignedto=None, user_id=None):
self.ticketname = ticketname
self.date = date
self.message = message
self.sendername = sendername
self.email = email
self.phone = phone
self.response = response
self.progress = progress
self.assignedto = assignedto
self.user_id = user_id
def __repr__(self):
return '<Supporttickets3 {}>'.format(self.name)
class Sessions2(db.Model):
id = db.Column(db.Integer, primary_key=True)
sessionname = db.Column(db.String(100))
date = db.Column(db.Date())
time = db.Column(db.Time())
duration = db.Column(db.String(100))
coursename = db.Column(db.String(200))
user_id = db.Column(db.Integer, db.ForeignKey('users2.id'))
users = db.relationship(User2)
def __init__(self, sessionname=None, date=None, time=None, duration=None, coursename=None, user_id=None):
self.sessionname = sessionname
self.date = date
self.time = time
self.duration = duration
self.coursename = coursename
self.user_id = user_id
def __repr__(self):
return '<Session2 {}>'.format(self.name)
class Payments(db.Model):
id = db.Column(db.Integer, primary_key=True)
firstname = db.Column(db.String(50))
surname = db.Column(db.String(50))
address = db.Column(db.String(100))
town = db.Column(db.String(100))
city = db.Column(db.String(100))
postcode = db.Column(db.String(7))
phone = db.Column(db.String(11))
service = db.Column(db.String(200))
amount = db.Column(db.Numeric(10,2))
email = db.Column(db.String(120))
cardno = db.Column(db.String(16))
expirydate = db.Column(db.String(5))
securitycode = db.Column(db.String(3))
date = db.Column(db.Date())
user_id = db.Column(db.Integer, db.ForeignKey('users2.id'))
users = db.relationship(User2)
def __init__(self, firstname=None, surname=None, address=None, town=None, city=None,postcode=None,phone=None,service=None,amount=None,email=None,cardno=None,expirydate=None,securitycode=None,date=None, user_id=None):
self.firstname = firstname
self.surname = surname
self.address = address
self.town = town
self.city = city
self.postcode = postcode
self.phone = phone
self.service = service
self.amount = amount
self.email = email
self.cardno = cardno
self.expirydate = expirydate
self.securitycode = securitycode
self.date = date
self.user_id = user_id
def __repr__(self):
return '<Payments {}>'.format(self.name)
class Work(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(300))
studentfirstname = db.Column(db.String(50))
studentsurname = db.Column(db.String(50))
projectname = db.Column(db.String(100))
date = db.Column(db.Date())
coursename = db.Column(db.String(100))
grade = db.Column(db.String(100))
feedback = db.Column(db.String(1000))
filename = db.Column(db.String(300))
file = db.Column(db.LargeBinary)
user_id = db.Column(db.Integer, db.ForeignKey('users2.id'))
users = db.relationship(User2)
def __init__(self, title=None,studentfirstname=None,studentsurname=None,projectname=None,date=None,coursename=None,grade=None,feedback=None,filename=None, file=None, user_id=None):
self.title = title
self.studentfirstname = studentfirstname
self.studentsurname = studentsurname
self.projectname = projectname
self.date = date
self.coursename = coursename
self.grade = grade
self.feedback = feedback
self.filename = filename
self.file = file
self.user_id = user_id
def __repr__(self):
return '<Work {}>'.format(self.name)
<file_sep>from app import app, db
from app.models import User2
@app.shell_context_processor
def make_shell_context():
return {'db': db, 'User': User2}<file_sep>"""payments
Revision ID: <KEY>
Revises: <PASSWORD>
Create Date: 2021-06-22 11:51:20.715768
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '<PASSWORD>'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('payments',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('firstname', sa.String(length=50), nullable=True),
sa.Column('surname', sa.String(length=50), nullable=True),
sa.Column('address', sa.String(length=100), nullable=True),
sa.Column('town', sa.String(length=100), nullable=True),
sa.Column('city', sa.String(length=100), nullable=True),
sa.Column('postcode', sa.String(length=7), nullable=True),
sa.Column('phone', sa.String(length=11), nullable=True),
sa.Column('service', sa.String(length=200), nullable=True),
sa.Column('amount', sa.Numeric(precision=10, scale=2), nullable=True),
sa.Column('email', sa.String(length=120), nullable=True),
sa.Column('cardno', sa.String(length=16), nullable=True),
sa.Column('expirydate', sa.String(length=5), nullable=True),
sa.Column('securitycode', sa.String(length=3), nullable=True),
sa.Column('date', sa.Date(), nullable=True),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users2.id'], ),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('payments')
# ### end Alembic commands ###
<file_sep>
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{{ url_for('static', filename='css/signup.css') }}">
<link href="https://fonts.googleapis.com/css2?family=Comfortaa&family=Open+Sans&display=swap" rel="stylesheet">
<title> IP tutorials </title>
</head>
<body >
<div id="nav" >
<p><img src=' 'width="30" height="30">IP tutorials</p>
<ul>
<li style="text-align:right;"> <a href="{{ url_for('index') }}"> Home </a></li>
<li style="text-align:right;"> <a href="{{ url_for('courses') }}"> Courses </a></li>
<li style="text-align:right;"> <a href="{{ url_for('projects') }}"> Projects </a></li>
<li style="text-align:right;"> <a href="{{ url_for('login') }}"> Log in </a></li>
<li style="text-align:right;"> <a href="{{ url_for('aboutus') }}"> About us </a></li>
<li style="text-align:right;"> <a href="{{ url_for('contactus') }}"> Contact us </a></li>
</ul>
</div>
<!-- <div id="background"> -->
<section>
<div id="header" style="margin-bottom: 10%;">
<div id="headertext">Tutor sign up</div>
</div>
</section >
<div style="margin-bottom: 10%;">
<form action="" method="post" >
<div class="container">
{{ form.hidden_tag() }}
<p>
{{ form.firstname.label }}<br>
{{ form.firstname(size=50) }}<br>
{% for error in form.firstname.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>
{{ form.surname.label }}<br>
{{ form.surname(size=50) }}<br>
{% for error in form.surname.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>
{{ form.email.label }}<br>
{{ form.email(size=120) }}<br>
{% for error in form.email.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>
{{ form.username.label }}<br>
{{ form.username(size=64) }}<br>
{% for error in form.username.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>
{{ form.password.label }}<br>
{{ form.password(size=128) }}<br>
{% for error in form.password.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<p>
{{ form.password2.label }}<br>
{{ form.password2(size=128) }}<br>
{% for error in form.password2.errors %}
<span style="color: red;">[{{ error }}]</span>
{% endfor %}
</p>
<input type="hidden" name="type" value="tutor">
<p>{{ form.submit() }}</p>
<label>
<p >Already got an account? <a href="{{ url_for('login') }}">Login here</a></p>
</label>
</div>
</form>
<div class="right"id="box" ></div>
</div>
<div style="background-color: #d4d4d4;">
<footer style="background-color: #d4d4d4;">
<div style="position:relative;background-color:#d4d4d4" class="footer" id="footer">
<div class="logo">
<p style="font-size: 10pt;"><img src=' ' width="30" height="30" align="left" style="display: inline-block;">IP tutorials</p>
</div>
<div class="column">
<h3>Pages</h3>
<p>Link</p>
<p>Link</p>
<p>Link</p>
<p>Link</p>
</div>
<div class="column">
<h3>Pages</h3>
<p>Link</p>
<p>Link</p>
<p>Link</p>
<p>Link</p>
</div>
<div class="column">
<h3>Pages</h3>
<p>Link</p>
<p>Link</p>
<p>Link</p>
<p>Link</p>
</div>
</div>
</footer>
</div>
</body>
</html><file_sep>import code
from flask import *
from flask_mail import *
from random import *
from datetime import datetime
app = Flask(__name__)
mail = Mail(app)
app.config["MAIL_SERVER"] = 'smtp.gmail.com'
app.config["MAIL_PORT"] = 465
app.config["MAIL_USERNAME"] = '<EMAIL>'
app.config['MAIL_PASSWORD'] = '*************'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail = Mail(app)
otp = randint(000000, 999999)
@app.route('/')
def index():
return render_template("index.html")
@app.route('/verify', methods=["POST"])
def verify():
email = request.form["email"]
msg = Message('code', sender='<EMAIL>', recipients=[email])
msg.body = str(code)
mail.send(msg)
return render_template('emailverification.html')
@app.route('/validate', methods=["POST"])
def validate():
user_code = request.form['code']
if code == int(user_code):
return "<h3> Email verification is successful </h3>"
user = User2(username='lucy', email='<EMAIL>', firstname='Lucy', surname='Abbott', type='student',
password='<PASSWORD>', confirmed='1', timestamp=datetime.now())
user.set_password('<PASSWORD>')
db.session.add(user)
db.session.commit()
flash('You are now a registered user!')
return redirect(url_for('login'))
return "<h3>failure, verification code does not match</h3>"
if __name__ == '__main__':
app.run(debug=True)
| e81a7ec5dfdbb19fb08090311f829b5ff6bcc639 | [
"Python",
"Text",
"HTML",
"Shell"
] | 21 | Python | Megh05/iptutorial | 6421b7f401feb0e7d18dd18f0764426db8e81961 | cc884f9fa21534de67045003e00363497da50c99 |
refs/heads/master | <file_sep><?php
/**
* Created by PhpStorm.
* User: bbphuc
* Date: 4/18/2017
* Time: 12:37 PM
*/
require_once 'config.php';
require_once 'lib/AutoLoader.php';
$loader = new \Lib\Psr4AutoloaderClass();
$loader->register();
$loader->addNamespace('\Controllers', './controllers/');
$loader->addNamespace('\Models', './models/');
$loader->addNamespace('\Views', './views/');
$loader->addNamespace('\Lib', './lib/');
//$ctrl = new \Controllers\MyController();
//$ctrl->home();
class App
{
protected $controller = 'home';
protected $method = 'index';
protected $param = [];
function __construct()
{
print_r( $this->parseUrl());
}
public function parseUrl()
{
if (isset($_GET['url'])){
$url = explode('/', filter_var(rtrim($_GET['url'], '/'), FILTER_SANITIZE_URL));
return 'Blala';
}
return 'B;a';
}
}
$app = new App();
if (isset($_GET['controller']) && isset($_GET['action'])){
$controller = $_GET['controller'];
$action = $_GET['action'];
} else {
$controller = "pages";
$action = "home";
}
require_once 'views/layout.php';
<file_sep><?php
/**
* Created by PhpStorm.
* User: bbphuc
* Date: 4/19/2017
* Time: 11:03 PM
*/
namespace Lib;
class View
{
private $name;
private $attributes;
function __construct($name)
{
$this->name = $name;
}
/**
* Get an attribute for a given key
* @return mixed
*/
public function getAttribute($key)
{
return $this->attributes[$key];
}
/**
* Set some attribute or add new attribute for this view
* @param mixed $attribute
*/
public function setAttribute($key, $value)
{
$this->attributes[$key] = $value;
}
public function render()
{
extract($this->attributes);
require('./views/'.$this->name.'.php');
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: bbphuc
* Date: 4/19/2017
* Time: 10:55 PM
*/
namespace Controllers;
use Lib\View;
class MyController
{
public function __construct()
{
}
public function home()
{
$username = "Pjic";
$view = new View("home");
$view->setAttribute("username", $username);
$view->render();
}
}<file_sep><h2>This is hoem page. Hello <?php echo $username ?> </h2><file_sep><?php
/**
* Created by PhpStorm.
* User: bbphuc
* Date: 4/20/2017
* Time: 2:50 PM
*/
namespace models;
/**
* Class User
* @package models
*/
class User
{
private $username;
private $email;
private $password;
private $first_name;
private $last_name;
function __construct()
{
}
/**
* @return mixed
*/
public function getUsername()
{
return $this->username;
}
/**
* @param mixed $username
*/
public function setUsername($username)
{
$this->username = $username;
}
/**
* @return mixed
*/
public function getEmail()
{
return $this->email;
}
/**
* @param mixed $email
*/
public function setEmail($email)
{
$this->email = $email;
}
/**
* @return mixed
*/
public function getPassword()
{
return $this->password;
}
/**
* @param mixed $password
*/
public function setPassword($password)
{
$this->password = $<PASSWORD>;
}
/**
* @return mixed
*/
public function getFirstName()
{
return $this->first_name;
}
/**
* @param mixed $first_name
*/
public function setFirstName($first_name)
{
$this->first_name = $first_name;
}
/**
* @return mixed
*/
public function getLastName()
{
return $this->last_name;
}
/**
* @param mixed $last_name
*/
public function setLastName($last_name)
{
$this->last_name = $last_name;
}
/**
* Check user already exist in database
* @param $username
* @return bool
*/
public static function check_user_exist($username){
$conn = \DBConnection::getInstance();
// TODO: Check user exist
return true;
}
public static function register_user()
{
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: bbphuc
* Date: 4/18/2017
* Time: 1:05 PM
*/
class PagesController
{
public function home() {
$first_name = "Phuc";
$last_name = "Bui";
require_once 'views/pages/home.php';
}
public function error(){
require_once 'views/pages/error.php';
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: bbphuc
* Date: 4/18/2017
* Time: 1:24 PM
*/
include_once 'models/Post.php';
class PostController{
public function index(){
$posts = Post::all();
require_once 'views/posts/index.php';
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: bbphuc
* Date: 4/18/2017
* Time: 12:35 PM
*/
class DBConnection {
private $conn;
private static $instance;
function __construct(){}
/**
* Establishing database connection
* @return mysqli database connection handler
*/
function connect() : mysqli {
include_once './config.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check for database connection error
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL :". mysqli_connect_error();
}
return $this->conn;
}
/**
* Skeleton pattern
* @return mysqli database connection
*/
public static function getInstance() {
if (self::$instance != null){
return self::$instance->conn;
} else {
self::$instance = new DBConnection();
return self::$instance->connect();
}
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: bbphuc
* Date: 4/18/2017
* Time: 12:32 PM
*/
define("DB_NAME", "test_db");
define("DB_HOST", "localhost");
define("DB_PORT", "3306");
define("DB_USERNAME", "test1");
define("DB_PASSWORD", "123");
?>
<file_sep><?php
/**
* Created by PhpStorm.
* User: bbphuc
* Date: 4/18/2017
* Time: 1:13 PM
*/
include_once 'DBConnection.php';
class Post
{
public $id;
public $author;
public $content;
public function __construct($id, $author, $content)
{
$this->id = $id;
$this->author = $author;
$this->content = $content;
}
public static function all(){
$conn = DBConnection::getInstance();
$list = [];
$query = $conn->query('SELECT * FROM test_db.post');
while($row = $query->fetch_assoc()){
$list[] = new Post($row['id'], $row['author'], $row['content']);
}
return $list;
}
} | 6ab17d7d158b4695639f736050198ff54dd29e17 | [
"PHP"
] | 10 | PHP | PhyTeam/AssignmentWeb | 14e17014db9f3848d9ad58a56a03a9c415e99642 | 8e5798b0c40ecb59e77bbfd04b68fdf6410905bb |
refs/heads/master | <file_sep># Guitar
##
### GUI for Tar
A simple, open-source, graphical utility written in C# to create **ODIN** compatible tarball archives optionally supporting multiple files per operation.

Since this is [on GitHub](https://github.com/vaibhavpandeyvpz/guitar), let me know if you forked and got some improvements ready to merge.
### Credits:
* [SharpZipLib](http://icsharpcode.github.io/SharpZipLib/) for Tar abstraction
* [Aha Soft](http://www.aha-soft.com/) for Icon
<file_sep>using ICSharpCode.SharpZipLib.Tar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
namespace Guitar
{
public partial class Guitar : Form
{
private string Destination;
private List<string> Sources = new List<string>();
public class Writer : TextWriter
{
RichTextBox Box = null;
public Writer(RichTextBox output)
{
Box = output;
}
public override void Write(char value)
{
base.Write(value);
if (value != '\r')
{
Box.AppendText(value.ToString());
}
}
public override Encoding Encoding
{
get { return Encoding.UTF8; }
}
}
public Guitar()
{
InitializeComponent();
}
private void OnClearClick(object sender, EventArgs e)
{
Sources.Clear();
Files.Items.Clear();
}
private void OnChooseClick(object sender, EventArgs e)
{
if (Chooser.ShowDialog() == DialogResult.OK)
{
foreach (var f in Chooser.FileNames)
{
if (!Sources.Contains(f))
{
Files.Items.Add(new ListViewItem(new string[] { Path.GetFileName(f), f }));
Sources.Add(f);
Console.WriteLine("Selected {0}", f);
}
}
}
}
private void OnGuitarClosing(object sender, FormClosingEventArgs e)
{
if (Worker.IsBusy)
{
var result = MessageBox.Show("Cancel current archive?", "In Progress", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes)
{
Worker.CancelAsync();
}
else
{
e.Cancel = true;
}
}
}
private void OnGuitarLoad(object sender, EventArgs e)
{
Console.SetOut(new Writer(OutputBox));
OutputBox.TextChanged += (a, b) =>
{
OutputBox.SelectionStart = OutputBox.Text.Length;
OutputBox.ScrollToCaret();
};
Profile.MouseEnter += (a, b) =>
{
Profile.Cursor = Cursors.Hand;
Profile.ForeColor = Color.MidnightBlue;
};
Profile.MouseLeave += (a, b) =>
{
Profile.Cursor = Cursors.Default;
Profile.ForeColor = Color.RoyalBlue;
};
Website.MouseEnter += (a, b) =>
{
Website.Cursor = Cursors.Hand;
Website.ForeColor = Color.MidnightBlue;
};
Website.MouseLeave += (a, b) =>
{
Website.Cursor = Cursors.Default;
Website.ForeColor = Color.RoyalBlue;
};
}
private void OnMakeClick(object sender, EventArgs e)
{
if (Sources.Count >= 1)
{
if (Saver.ShowDialog() == DialogResult.OK)
{
if (!Worker.IsBusy)
{
Destination = Saver.FileName;
Make.Enabled = false;
Progress.Style = ProgressBarStyle.Continuous;
Worker.RunWorkerAsync();
}
}
}
else
{
Console.WriteLine("Please choose files to add to *.tar");
}
}
private void OnProfileClick(object sender, EventArgs e)
{
Process.Start("http://forum.xda-developers.com/member.php?u=5490832");
}
private void OnWebsiteClick(object sender, EventArgs e)
{
Process.Start("http://www.vaibhavpandey.com");
}
private void OnWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Console.WriteLine(new String('-', 48));
Make.Enabled = true;
Progress.Style = ProgressBarStyle.Blocks;
Progress.Value = 0;
}
private void OnWorkerDo(object sender, DoWorkEventArgs e)
{
try
{
var file = Destination;
var sources = Sources;
using (Stream output = File.Create(file))
{
Worker.ReportProgress(5, string.Format("Creating {0}", file));
using (TarArchive archive = TarArchive.CreateOutputTarArchive(output, TarBuffer.DefaultBlockFactor))
{
archive.ProgressMessageEvent += (a, b, c) =>
{
if (!string.IsNullOrWhiteSpace(c))
{
Console.Write("{0}; {1}", b.Name, c);
}
};
archive.SetKeepOldFiles(false);
archive.SetUserInfo(1, Environment.UserName, 1, null);
int factor = (int)75 / sources.Count;
int progress = 10;
foreach (string s in sources)
{
progress += factor;
Worker.ReportProgress(progress, string.Format("Adding {0}", s));
TarEntry entry = TarEntry.CreateEntryFromFile(s);
archive.WriteEntry(entry, true);
}
archive.Close();
Worker.ReportProgress(85, string.Format("Finished creating {0}", file));
if (Checksum.Checked)
{
Worker.ReportProgress(95, "Calculating MD5 checksum of created archive");
string checksum;
using (var md5 = MD5.Create())
{
using (var stream = new BufferedStream(File.OpenRead(file), 1024 * 1024))
{
byte[] bytes = md5.ComputeHash(stream);
checksum = string.Concat(bytes.Select(b => b.ToString("X2")).ToArray());
}
}
Worker.ReportProgress(98, string.Format("Checksum is {0}", checksum));
using (var stream = new FileStream(file, FileMode.Append))
{
var bytes = Encoding.UTF8.GetBytes(string.Format("{0} {1}\n", checksum, Path.GetFileName(file)));
stream.Write(bytes, 0, bytes.Length);
}
var renamed = file + ".md5";
if (File.Exists(renamed))
{
File.Delete(renamed);
}
File.Move(file, (file = renamed));
Worker.ReportProgress(99, string.Format("Renamed archive to {0}", file));
}
Worker.ReportProgress(100, "Package is ready to be flashed via ODIN");
}
}
}
catch (Exception ex)
{
Worker.ReportProgress(99, "Error occurred while creating archive");
Worker.ReportProgress(100, ex.Message);
}
}
private void OnWorkerProgress(object sender, ProgressChangedEventArgs e)
{
Progress.Value = e.ProgressPercentage;
Console.WriteLine(e.UserState.ToString());
}
}
}
| f92438f1fbc628a58e1c0aa32e1133865ef96880 | [
"Markdown",
"C#"
] | 2 | Markdown | modoj/guitar | a872fdbec606cd1502e396527067f6cf5f0933c6 | 4eb4141052349ee41e13271cdb5035a72bacd728 |
refs/heads/master | <repo_name>netas-ankara/rabbitmq_tutorial<file_sep>/rabbitmq_client/src/main/java/tr/com/cenk/spring/cluster/OrderType.java
package tr.com.cenk.spring.cluster;
/**
* Created by calp on 22.06.2018.
*/
public enum OrderType {
ACTIVATE, MODIFY, DELETE;
}
<file_sep>/README.md
# rabbitmq_tutorial
RabbitMQ Tutorial
<file_sep>/rabbitmq_cluster_server/README.md
#RabbitMQ Server
To run the rabbitmq server run
`docker-compose up`
| 38e0bbe7fb731c9c5a93dad2803056984769eb6e | [
"Markdown",
"Java"
] | 3 | Java | netas-ankara/rabbitmq_tutorial | a5825938211776e5ddf69983e09d02fc8ab14313 | 742b6b99816a2ed6708a71cb1e1c731551d76122 |
refs/heads/master | <repo_name>ZippoRays/pythonscraperForClass<file_sep>/raper.py
from lxml import html
import requests
page = requests.get('http://www.blic.rs/forum/premijer-o-sluaju-gvantanamo-jesmo-li-deo-sveta-il,2,2823015,0,czytaj-najnowsze.html')
tmpsrv = html.fromstring(page.content)
retard = tmpsrv.xpath('//span[@class="k_author"]/text()')
retardova_misao = tmpsrv.xpath('//span[@class="k_noteLead"]/text()')
print 'Retard:', retard
print 'Retardov komentar', retardova_misao
| 24b475c5f4b1f0491e7dc997111ca1d82a6473db | [
"Python"
] | 1 | Python | ZippoRays/pythonscraperForClass | fb1ef6ae7355dc7c88b1a61a09c9b1dd4cc8d6e0 | 7b2649504360eacc1817fd18bf8586cfabe9f65b |
refs/heads/main | <file_sep>game contains instance of
-board
CLASSES
-Player
-@color
-@display
-initialize(color, display)
-Display (phase 2)
-@board: Board
-@cursor: Cursor
-initialize(board)
-Board
-@rows
-@null_piece
-lots of methods // refer to UML
-Piece (contains instances of)
-all pieces under inherit from
-create files from filetree UML guide
<file_sep>module Slideable
HORIZONTAL_AND_VERTICAL_DIRS = [
[0,1], #right
[0,-1], #left
[1,0], #down
[-1,0] #up
].freeze
DIAGONAL_DIRS = [
[-1,1], #upright
[-1,-1], #upleft
[1,1], #downright
[1,-1] #downleft
].freeze
#getters
def horizontal_and_vertical_dirs
HORIZONTAL_AND_VERTICAL_DIRS
end
def diagonal_dirs
DIAGONAL_DIRS
end
#make emtpy [] shovel all poss moves when we found => return [moves pos]
def moves
moves = []
move_dirs.each do |poss_move|
dx, dy = poss_move
moves += grow_unblocked_moves_in_dir(dx, dy)
end
moves
end
private
def move_dirs
# overwritten by subclass
raise NeedToAddMovesForPiece
end
def grow_unblocked_moves_in_dir(dx, dy)
# till out of the board
# have enemy pices on the way
# have my owne pice on the
cur_x, cur_y = pos
possible_moves = []
moves_left = true
while moves_left
cur_x, cur_y = cur_x + dx, cur_y + dy
pos = [cur_x, cur_y]
if !board.valid_pos?(pos)
# if position not valid
moves_left = false
elsif board[pos].empty?
# if runs into null piece / empty spot
possible_moves << pos
else
# can take an opponent's piece
possible_moves << pos if board[pos].color != color
# once we attack (above) the move will be over
# break out of the loop
# can't move past blocking piece
moves_left = false
end
end
possible_moves
end
end<file_sep>require 'singleton'
require_relative "piece"
require "byebug"
class NullPiece < Piece
include Singleton
def initialize
# self.instance
# debugger
@color = :none
end
def empty?
true
end
def symbol
"_"
end
def moves
[]
end
end<file_sep>module Stepable
def moves
possible_moves = []
move_diffs.each do |dx, dy|
# ^destructuring possible moves
cur_x, cur_y = pos
# looking at current pos
future_pos = [cur_x + dx, cur_y + dy]
# adds dx dy from possible moves to find new possible positions
if board.valid_pos?(future_pos)
# make sure the move is valid
if board[future_pos].empty?
# if nullpiece then can step there
possible_moves << future_pos
elsif board[future_pos].color != color
# if space has other players color, can attack
possible_moves << pos
end
end
end
possible_moves
end
def move_diff
#overwritten by subclass
raise NotImplementedError
end
end<file_sep>require_relative 'pieces'
require 'byebug'
class Board
attr_accessor :board
def initialize
@board = Array.new(8) {Array.new(8, NullPiece.instance)}
populate
# fill_board
end
# def fill_board
# board.each_with_index do |row, i|
# row.each_with_index do |el, j|
# set_back_row(i, :yellow) if i == 0
# set_pawns(i, :yellow) if i == 1
# @board[i][j] = null_piece if (2..5).to_a.include?(i)
# set_pawns(i, :blue) if i == 6
# set_back_row(i, :blue) if i == 7
# end
# end
# end
# def set_back_row(row,color)
# (0..7).each do |j|
# if [0,7].include?(j)
# @board[row][j] = Rook.new(color, self, [row,j])
# elsif [1,6].include?(j)
# @board[row][j] = Knight.new(color, self, [row,j])
# elsif [2,5].include?(j)
# @board[row][j] = Bishop.new(color, self, [row,j])
# elsif j == 3
# @board[row][j] = Queen.new(color, self, [row,j])
# elsif j == 4
# @board[row][j] = King.new(color, self, [row,j])
# end
# end
# end
# def set_pawns(row,color)
# (0..7).each do |j|
# @board[row][j] = Pawn.new(color, self, [row,j])
# end
# end
def populate
back_rows = [Rook, Knight, Bishop, Queen, King, Bishop, Knight, Rook]
back_rows.each_with_index do |back_row_piece, idx|
@board[0][idx] = back_row_piece.new(:yellow, self, [0,idx])
@board[7][idx] = back_row_piece.new(:blue, self, [7,idx])
end
8.times { |col| @board[1][col] = Pawn.new(:yellow, self, [1, col]) }
8.times { |col| @board[6][col] = Pawn.new(:blue, self, [6, col]) }
end
def [](pos)
row, col = pos
@board[row][col]
end
def []=(pos,val)
row, col = pos
@board[row][col] = val
end
def move_piece(color, start_pos, end_pos)
raise 'no piece to move at start position' if self[start_pos].class == NullPiece
raise 'position is not valid' if !valid_pos?(end_pos)
raise 'cannot move other players piece' if self[start_pos].color != color
raise 'cannot move on your own piece' if self[end_pos].color == color
# maybe check color for valid move
#update
self[start_pos].pos = end_pos #reassigning the position of the instance
self[end_pos] = self[start_pos] #moving the position on the board
self[start_pos] = NullPiece.instance #creating nullpiece instance in new empty space
end
def valid_pos?(pos)
# row,col = pos
# row.between?(0,7) && col.between?(0,7)
# row, col = pos
# (0..7).include?(row) && (0..7).include?(col)
# debugger
pos.all? { |coord| coord.between?(0, 7) }
end
def add_piece(piece, pos)
end
def checkmate?(color)
end
def in_check?(color)
end
def find_king(color)
end
def pieces
end
def dup
end
def move_piece!(color, start_pos, end_pos)
end
end<file_sep>require_relative "piece"
require_relative "modules/stepable"
class King < Piece
include Stepable
def symbol
"♚".colorize(color)
end
def move_diffs
[
[1,0], #right
[1,1], #right down
[1,-1], #right up
[-1,1], #left down
[-1,0], #left
[-1,-1], #left up
[0,1], #down
[0,-1] #up
]
end
end | af76756558d1411abde22f4e2db8ec29641637ff | [
"Ruby"
] | 6 | Ruby | juliajykim/Chess | 5ce026606cd478b65853ccdc82877132f546f63a | bfc273f159928500724883c2fa0ad5c69103615f |
refs/heads/master | <repo_name>iamsania0895/Sania_bootstrap-project<file_sep>/js/custom.js
/* =================================
LOADER
=================================== */
/* =================================
=== FULL SCREEN HEADER ====
=================================== */
function alturaMaxima() {
var altura = $(window).height();
$(".full-screen").css('min-height',altura);
}
$(document).ready(function() {
alturaMaxima();
$(window).bind('resize', alturaMaxima);
});
/* =================================
=== SMOOTH SCROLL ====
=================================== */
var scrollAnimationTime = 1200,
scrollAnimation = 'easeInOutExpo';
$('a.scrollto').bind('click.smoothscroll', function (event) {
event.preventDefault();
var target = this.hash;
$('html, body').stop().animate({
'scrollTop': $(target).offset().top
}, scrollAnimationTime, scrollAnimation, function () {
window.location.hash = target;
});
});
/* =================================
=== WOW ANIMATION ====
=================================== */
wow = new WOW(
{
mobile: false
});
wow.init();
/* =================================
=== EXPAND COLLAPSE ====
=================================== */
//$('.expand-form').simpleexpand({
// 'defaultTarget': '.expanded-contact-form'
//});
/* =================================
=== STELLAR ====
=================================== */
$(window).stellar({
horizontalScrolling: false
});
/* =================================
=== Bootstrap Internet Explorer 10 in Windows 8 and Windows Phone 8 FIX
=================================== */
if (navigator.userAgent.match(/IEMobile\/10\.0/)) {
var msViewportStyle = document.createElement('style')
msViewportStyle.appendChild(
document.createTextNode(
'@-ms-viewport{width:auto!important}'
)
)
document.querySelector('head').appendChild(msViewportStyle)
} | 8b5e4c080cc8846d4084706569c46a359bf98b95 | [
"JavaScript"
] | 1 | JavaScript | iamsania0895/Sania_bootstrap-project | 52b96216e5f517f764ded159cd4f50a7b08a7f41 | cc4a58846849e7aa8dbc83e9e5c4d44ca84b62e1 |
refs/heads/master | <repo_name>AlirezaShahabi/CPP-word-count-program<file_sep>/README.md
# CPP-word-count-program
This cpp program reads a text file and report how many times each word is repeated. It excludes certain words such as 'the', 'or', 'an', .. and punctuations from the counting process. The result is written to another text file.
<file_sep>/main.cpp
// c++11
// In this program, we read a text file and report how many times each word is
// repeated. We exclude certain words from the counting process. We use a std::map
// to store the words and their repetition and a std::set to store the exclusion words.
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <set>
// declaring the readText(), countWord() and display() functions
void read_text(std::ifstream&, std::map<std::string,int>&, const std::set<std::string>&);
void count_word(const std::string&, std::map<std::string,int>&, const std::set<std::string>&);
void display(const std::map<std::string,int>&, std::ofstream&);
int main (){
std::ifstream rFile("1-string-stream.txt");
std::map<std::string,int> word_count;
std::set<std::string> exclude_word = {"a","an","the","The","or","of","on","On"};
read_text(rFile, word_count, exclude_word);
std::ofstream wFile("output.txt");
display(word_count, wFile);
return 0;
}
// this function reads text from file, devide it into lines, and then passes each line
// into countWord() function
void read_text(std::ifstream& rf, std::map<std::string,int>& w_c, const std::set<std::string>& e_w){
std::string line;
// call CountWord for each line
while (std::getline(rf,line)) {count_word(line, w_c, e_w);}
}
// this function recieves lines of string, check each word in the line, add the word
// to a map if it does not exist in the exclusion set
void count_word(const std::string& line, std::map<std::string,int>& w_c, const std::set<std::string>& e_w){
std::istringstream iss(line);
std::string word;
std::vector<char> punc_v{'.' , ',' , ':' , ';' , '?'};
while (iss >> word) {
// remove the punctuations at the end of words (if any)
char c = *(word.end()-1);
if (std::find(punc_v.begin(),punc_v.end(),c) != punc_v.end()) {word.erase(word.end()-1);}
// add the word to the map if it is not a member of the excluded words
if (e_w.find(word) == e_w.end()) {++w_c[word];}
}
}
// this function displays the content of word_count
void display(const std::map<std::string,int>& w_c, std::ofstream& wf){
for (const auto& element : w_c){
std::string s = element.second>1 ? " times":" time";
wf << element.first << " is repeated " << element.second << s << std::endl;
}
}
| aa570f50adbbb479ae47f342615a1773f78523c5 | [
"Markdown",
"C++"
] | 2 | Markdown | AlirezaShahabi/CPP-word-count-program | 29dea35c995ea8159a859c1817856ab693651593 | 761f8a68941757989398785dd401985d67b1b5aa |
refs/heads/master | <file_sep><?php
$dbhost = "localhost";
$dbuser = "root";
$dbpassword = "<PASSWORD>";
$dbname = "checkDB";
$tablename = "AutoRun";<file_sep><?php
include_once './config.php';
$conn = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
if ($conn->connect_error) {
echo "{\"code\":302}";
}else{
$result_out = array("code"=>200,"list"=>array());
$sql = "select activity as script,date_format(time,'%Y-%m-%d') as date from AutoRun group by activity,date_format(time,'%Y-%m-%d') order by activity,time asc";
$result = $conn->query($sql);
if($result->num_rows>0){
while($row = $result->fetch_assoc()) {
array_push($result_out["list"],array("script"=>$row["script"],"date"=>$row["date"]));
}
echo json_encode($result_out);
}else{
echo "{\"code\":404}";
echo $sql;
}
$conn->close();
}
?><file_sep><?php
include_once './config.php';
$conn = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
if ($conn->connect_error) {
echo "{\"code\":302}";
}else{
$start="";
$end="";
$name="";
if(isset($_POST["start"])){
$start = "time>'".$_POST["start"]."'";
}
if(isset($_POST["end"])){
$end = "time<'".$_POST["end"]."'";
}
if(isset($_POST["name"])){
$name = "activity='".$_POST["name"]."'";
}
if(isset($_GET["start"])){
$start = "time>'".$_GET["start"]."'";
}
if(isset($_GET["end"])){
$end = "time<'".$_GET["end"]."'";
}
if(isset($_GET["name"])){
$name = "activity='".$_GET["name"]."'";
}
$result_out = array("code"=>200,"list"=>array());
$sql = "select * from ".$tablename." where ".($name=="" && $start=="" && $end==""?"time>date(now())":($name.($name=="" || $start==""?"":" and ").$start.(($start==""||$end=="")&&($name==""||$end=="")?"":" and ").$end))." order by time asc";
$result = $conn->query($sql);
if($result->num_rows>0){
while($row = $result->fetch_assoc()) {
array_push($result_out["list"],array("time"=>$row["time"],"name"=>$row["activity"],"message"=>$row["log"]));
// if($_light){
// echo "{".$row["time"]."</td><td>".$row["activity"]."</td><td>".$row["log"]."</td></tr>";
// $_light = false;
// }else{
// echo "<tr class=\"light\"><td class=\"nowrap\">".$row["time"]."</td><td>".$row["activity"]."</td><td>".$row["log"]."</td></tr>";
// $_light = true;
// }
}
echo json_encode($result_out);
}else{
echo "{\"code\":404}";
echo $sql;
}
$conn->close();
}
?> | 72f2de90c67158b04d6e0a030d5f88e6b3d79546 | [
"PHP"
] | 3 | PHP | GuokeNo1/Dailycheckin-Log-Web | 89fe72f62a4bfb357f93557feea40b127ceec656 | db2cbd872a59f7bcc1783d2d195879b873204729 |
refs/heads/master | <file_sep>import VueResource from 'vue-resource'
import Vue from 'vue'
import App from './App'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue(App)
Vue.use(VueResource)
app.$mount()
export default {
// 这个字段走 app.json
config: {
// 页面前带有 ^ 符号的,会被编译成首页,其他页面可以选填,我们会自动把 webpack entry 里面的入口页面加进去
pages: ['pages/logs/main', '^pages/index/main'],
window: {
backgroundTextStyle: 'light',
navigationBarBackgroundColor: 'pink',
navigationBarTitleText: '醉心民谣',
navigationBarTextStyle: 'black'
}
}
}
| 57e4cfd5f046ea601d32486e0eda405557e95123 | [
"JavaScript"
] | 1 | JavaScript | VyaWave/music-scientist | f4e48c52674cfd5ac1b7042595ca43ac90388b57 | 98cbc20a36e3e722a628620c138f1d9daf24483e |
refs/heads/master | <file_sep>package me.staartvin.plugins.netherwater;
import org.bukkit.plugin.java.JavaPlugin;
public class NetherWater extends JavaPlugin
{
private ConfigManager configManager;
private CommandManager commandManager = new CommandManager(this);
public void onEnable() {
// Enable config.
setConfigManager(new ConfigManager(this));
// Enable listener to check when water is placed.
this.getServer().getPluginManager().registerEvents(new WaterPlaceListener(this), this);
// Enable command manager.
this.getCommand("netherwater").setExecutor(commandManager);
this.getCommand("netherwater").setTabCompleter(commandManager);
}
public void onDisable() {
this.saveConfig();
}
public ConfigManager getConfigManager() {
return configManager;
}
public void setConfigManager(ConfigManager configManager) {
this.configManager = configManager;
}
}
<file_sep>package me.staartvin.plugins.netherwater;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
public class WaterPlaceListener implements Listener {
NetherWater plugin;
public WaterPlaceListener(final NetherWater plugin) {
this.plugin = plugin;
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onPlayerInteract(final PlayerInteractEvent event) {
if (event.getAction() != Action.RIGHT_CLICK_BLOCK) {
return;
}
if (event.getItem() == null) {
return;
}
if (event.getClickedBlock() == null) {
return;
}
final World world = event.getClickedBlock().getWorld();
if (!plugin.getConfigManager().isWorldEnabled(world.getName())) return;
if (world.getEnvironment() != World.Environment.NETHER) return;
if (event.getItem().getType() != Material.WATER_BUCKET) return;
// Cancel the event.
event.setCancelled(true);
// Set clicked block to water.
event.getClickedBlock().getRelative(event.getBlockFace()).setType(Material.WATER);
// Set item (from filled bucket to empty bucket).
event.getItem().setType(Material.BUCKET);
}
}
<file_sep># NetherWater
A Bukkit/Spigot plugin to enable or disable placing water buckets in Nether worlds.
#Installation
Put the jar in your plugins folder and run the server! You can use the config file to adjust what worlds can be used to place water buckets.
You can also toggle the setting per world.
<file_sep>package me.staartvin.plugins.netherwater;
import java.io.File;
import java.util.List;
public class ConfigManager {
private NetherWater plugin;
public ConfigManager(NetherWater instance) {
this.plugin = instance;
loadConfig();
}
private void loadConfig() {
if (!plugin.getDataFolder().exists()) {
plugin.getDataFolder().mkdir();
}
if (!new File(plugin.getDataFolder(), "config.yml").exists()) {
plugin.saveDefaultConfig();
} else {
plugin.reloadConfig();
}
}
/**
* Toggle whether water can be placed in a world. The boolean that returns indicates whether placing on this
* world is now enabled or disabled.
* @param worldName Name of the world to toggle
* @return true if the world has been toggled to true, otherwise false.
*/
public boolean toggleWorld(String worldName) {
boolean enabled = this.isWorldEnabled(worldName);
setWorldEnabled(worldName, !enabled);
return !enabled;
}
/**
* Check whether placing water is enabled on the given world.
* @param worldName Name of the world to check.
* @return true if water may be placed on this world, false otherwise.
*/
public boolean isWorldEnabled(String worldName) {
return plugin.getConfig().getStringList("allowed worlds").contains(worldName);
}
/**
* Set whether a player can place water on the given world.
* @param worldName Name of the world
* @param enabled Whether water can be placed on this world.
*/
public void setWorldEnabled(String worldName, boolean enabled) {
List<String> enabledWorlds = plugin.getConfig().getStringList("allowed worlds");
if (enabled) {
// Only add to the list if it isn't already in there. We don't like duplicates.
if (!enabledWorlds.contains(worldName)) {
enabledWorlds.add(worldName);
}
} else {
enabledWorlds.remove(worldName);
}
plugin.getConfig().set("allowed worlds", enabledWorlds);
plugin.saveConfig();
}
}
| be07ae430713a54f47f2f286140d2aaf6f3ca47a | [
"Markdown",
"Java"
] | 4 | Java | Staartvin/NetherWater | 77beb4b4a7d602ad0b2e5069166a00879907e190 | 4fe099a162f73ec745de820a4096a21f4a392b84 |
refs/heads/master | <file_sep>package com.example.hamzajerbi.vipertemplate.Main
import android.content.Context
import com.example.hamzajerbi.vipertemplate.Main.Adapter.MainAdapterModel
interface MainPresenterToViewInterface {
val contxt: Context
var presenter: MainViewToPresenterInterface?
fun showMain(argument: ArrayList<MainAdapterModel>)
}
interface MainInteractorToPresenterInterface {
fun mainFetched(argument: MainEntities)
}
interface MainPresentorToInteractorInterface {
var presenter: MainInteractorToPresenterInterface?
fun fetchMain(context: Context)
}
interface MainViewToPresenterInterface {
var view: MainPresenterToViewInterface?
var interector: MainPresentorToInteractorInterface?
var router: MainPresenterToRouterInterface?
fun requestMain()
}
interface MainPresenterToRouterInterface {
companion object {
fun configure(activity: MainActivity) {}
}
}<file_sep>package com.example.hamzajerbi.vipertemplate.Main
import com.example.hamzajerbi.vipertemplate.Main.Adapter.MainAdapterModel
import java.util.ArrayList
data class MainEntities( val list: ArrayList<MainAdapterModel>)
<file_sep>package com.example.hamzajerbi.vipertemplate.Main.Adapter
data class MainAdapterModel(val title: String)<file_sep>package com.example.hamzajerbi.vipertemplate.Main
class MainRouter: MainPresenterToRouterInterface {
companion object {
fun configure(activity: MainActivity) {
val view = activity
val presenter = MainPresenter()
val interactor = MainInteractor()
val router = MainRouter()
view.presenter = presenter
presenter.view = view
presenter.router = router
presenter.interector = interactor
interactor.presenter = presenter
}
}
}<file_sep>package com.example.hamzajerbi.vipertemplate.Main
class MainPresenter : MainViewToPresenterInterface, MainInteractorToPresenterInterface {
override var view: MainPresenterToViewInterface? = null
override var interector: MainPresentorToInteractorInterface? = null
override var router: MainPresenterToRouterInterface? = null
override fun requestMain() {
val view = view ?: return
interector?.fetchMain(view.contxt)
}
override fun mainFetched(argument: MainEntities) {
view?.showMain(argument.list)
}
}
<file_sep>package com.example.hamzajerbi.vipertemplate.Main
import android.content.Context
import com.example.hamzajerbi.vipertemplate.Main.Adapter.MainAdapterModel
class MainInteractor : MainPresentorToInteractorInterface {
override fun fetchMain(context: Context) {
val service = ArrayList<MainAdapterModel>()
service.add(MainAdapterModel("Text"))
service.add(MainAdapterModel("Text"))
service.add(MainAdapterModel("Text"))
service.add(MainAdapterModel("Text"))
service.add(MainAdapterModel("Text"))
service.add(MainAdapterModel("Text"))
val entity = MainEntities(list = service)
presenter?.mainFetched(entity)
}
override var presenter: MainInteractorToPresenterInterface? = null
}<file_sep>package com.example.hamzajerbi.vipertemplate.Main.Adapter
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.example.hamzajerbi.vipertemplate.R
class MainAdapter(val newsList: ArrayList<MainAdapterModel>) : RecyclerView.Adapter<MainAdapter.ViewHolder>() {
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ViewHolder {
val v = LayoutInflater.from(p0?.context).inflate(R.layout.main_item_list, p0, false)
return ViewHolder(v);
}
override fun getItemCount(): Int {
return newsList.count()
}
override fun onBindViewHolder(p0: ViewHolder, p1: Int) {
p0?.txtName?.text = newsList[p1].title
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val txtName = itemView.findViewById<TextView>(R.id.txt)
}
}<file_sep>package com.example.hamzajerbi.vipertemplate.Main
import android.content.Context
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import com.example.hamzajerbi.vipertemplate.Main.Adapter.MainAdapter
import com.example.hamzajerbi.vipertemplate.Main.Adapter.MainAdapterModel
import com.example.hamzajerbi.vipertemplate.R
class MainActivity : AppCompatActivity(),MainPresenterToViewInterface {
override var presenter: MainViewToPresenterInterface? = null
override val contxt: Context = this
private var recycleView: RecyclerView? = null
override fun onCreate(savedInstanceState: Bundle?) {
MainRouter.configure(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recycleView = findViewById(R.id.recyclerView)
recycleView?.layoutManager = LinearLayoutManager(this)
presenter?.requestMain()
}
override fun showMain(argument: ArrayList<MainAdapterModel>) {
recycleView?.adapter = MainAdapter(argument)
}
}
| 9e13fa8f2dcf84185f61fa62234a3495b3edcd82 | [
"Kotlin"
] | 8 | Kotlin | hamzon55/viperTemplate | 179021ef5ab559ab0901fcaf9cb51b5912cf952d | 32e486b641d062ccc049e5c66db8d3788d47f749 |
refs/heads/master | <file_sep>package com.samhaus.mylibrary.network;
import android.content.Context;
import com.samhaus.mylibrary.BuildConfig;
import com.samhaus.mylibrary.base.BaseActivity;
import com.samhaus.mylibrary.bean.CommonRequestBean;
import com.samhaus.mylibrary.util.LogUtil;
import com.samhaus.mylibrary.util.NetUtil;
import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.functions.Predicate;
import io.reactivex.schedulers.Schedulers;
/**
* Retrofit帮助类 返回参数滤错
*/
public class RxTransformerHelper {
/**
* 服务器返回错误码 0为成功
*/
public static final String RESULTOK = "200"; //请求后台成功
public static final int RESULTFAIL = 1; //请求失败
// public static final int REQUESTFLAG1 = 1011; //请先登录
//
// public static final int REQUESTFLAG2 = 1012; //登录超时
//
// public static final int REQUESTFLAG3 = 1013; //登录验证失败
//
public static final int NET_ERROR = -1; //网络错误
/**
* 业务错误过滤器(自定义)
*/
private static <T> Predicate<T> verifyBusiness(ErrorVerify errorVerify) {
return response -> {
if (response instanceof CommonRequestBean) {
CommonRequestBean baseResponse = (CommonRequestBean) response;
String responseCode = baseResponse.getError_code();
boolean isSuccess = responseCode.equals(RESULTOK);
if (!isSuccess) {
if (errorVerify != null) {
errorVerify.call(Integer.valueOf(baseResponse.getError_code()), baseResponse.getReason());
}
}
return isSuccess;
} else {
return false;
}
};
}
/**
* 非空过滤器(自定义)
*/
private static <T> Predicate<T> verifyNotEmpty() {
return response -> response != null;
}
/**
* 错误提醒处理
*
* @param context
* @param errorVerify
* @param <T>
* @return
*/
private static <T> Function<Throwable, T> doError(final Context context, ErrorVerify errorVerify) {
return throwable -> {
throwable.printStackTrace();
if (errorVerify != null) {
if (!NetUtil.isConnected(context)) {
errorVerify.call(NET_ERROR, "暂无网络");
} else {
if (BuildConfig.DEBUG) {
errorVerify.call(0, throwable.toString());
} else {
errorVerify.call(0, "系统异常");
}
}
}
return null;
};
}
/**
* sessionId 过期的过滤器
*/
private static <T> Predicate<T> verifyResultCode(Context context) {
return response -> {
if (response instanceof CommonRequestBean) {
CommonRequestBean baseResponse = (CommonRequestBean) response;
String state = baseResponse.getError_code();
if (!state.equals(RESULTOK)) {
return false;
}
return true;
} else {
return false;
}
};
}
/**
* 优先使用这个,可以继续使用操作符
*/
public static <T> ObservableTransformer<T, T> applySchedulers() {
return observable -> observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}
/**
* 聚合了session过滤器,业务过滤器及合并操作 自定义错误回调
*/
public static <T> ObservableTransformer<T, T>
applySchedulersAndAllFilter(Context context, ErrorVerify errorVerify) {
return observable -> observable
.compose(applySchedulers())
.filter(verifyNotEmpty())
.filter(verifyBusiness(errorVerify))
.onErrorReturn(doError(context, errorVerify))
.doFinally(() -> {
if (context instanceof BaseActivity)
((BaseActivity) context).hideWaitDialog();
});
}
// /**
// * 聚合了session过滤器,简单业务过滤器及合并操作及自定义的错误返回
// */
// public static <T> ObservableTransformer<BaseModel<T>, T>
// applySchedulersResult(Context context, ErrorVerify errorVerify) {
// return observable -> observable
// .compose(applySchedulersAndAllFilter(context, errorVerify))
// .map(BaseModel::getData);
// }
//
// /**
// * 聚合了session过滤器,简单业务过滤器及合并操作
// * 结果直接返回包含BaseModelNew<T>里定义的 T 对象
// */
// public static <T> ObservableTransformer<BaseModel<T>, T> applySchedulerResult(Context context) {
// return applySchedulersResult(context, new SimpleErrorVerify(context));
// }
/**
* 聚合了session过滤器,简单业务过滤器及合并操作
* 结果返回包含BaseModelNew的对象
*/
public static <T> ObservableTransformer<T, T> applySchedulerAndAllFilter(Context context) {
return applySchedulersAndAllFilter(context, new SimpleErrorVerify(context));
}
}
<file_sep>package com.samhaus.mylibrary.service;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.StrictMode;
import com.github.moduth.blockcanary.BlockCanary;
import com.samhaus.mylibrary.BuildConfig;
import com.samhaus.mylibrary.application.AppBlockCanaryContext;
import com.samhaus.mylibrary.application.AppCrashHandler;
import com.samhaus.mylibrary.base.AppContext;
import com.squareup.leakcanary.LeakCanary;
public class InitializeService extends IntentService {
public static final String ACTION_INIT_LIBRARY = "service.action.initThirdLibrary";
public InitializeService() {
super("InitializeService");
}
public static void start(Context context) {
Intent intent = new Intent(context, InitializeService.class);
intent.setPackage(context.getPackageName());
intent.setAction(ACTION_INIT_LIBRARY);
context.startService(intent);
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
final String action = intent.getAction();
if (ACTION_INIT_LIBRARY.equals(action)) {
handleAction();
}
}
}
private void handleAction() {
if (LeakCanary.isInAnalyzerProcess(AppContext.mAppContext)) {
return;
}
//api网关
// AppConfigurationInitializer.init();
//初始化自定义字体
// CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
// .setDefaultFontPath("fonts/black.ttf")
// .setFontAttrId(R.attr.fontPath)
// .build());
//chrome调试
// Stetho.initializeWithDefaults(App.getInstance());
//bugly
// CrashReport.initCrashReport(getApplicationContext(), AppConstants.BUGLY_APPID, false);
if (BuildConfig.DEBUG) {
// initStrictMode();
LeakCanary.install(AppContext.getContext());
BlockCanary.install(this, new AppBlockCanaryContext(getApplicationContext())).start();
}else {
AppCrashHandler.getInstance().init();
}
}
private void initStrictMode() {
StrictMode.noteSlowCall("slowCallInThread");
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectCustomSlowCalls()//自定义的耗时调用
.detectDiskReads()//磁盘读取操作
.detectDiskWrites()//磁盘写入操作
.detectNetwork()//网络操作
.detectAll()
.penaltyDeath()
.penaltyLog()
.penaltyDialog()
.penaltyFlashScreen()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedClosableObjects()
.detectLeakedSqlLiteObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
}
<file_sep>package com.samhaus.mylibrary.application;
import android.os.Looper;
import com.samhaus.mylibrary.util.ToastUtil;
/**
* Created by starry on 2016/10/18.
*/
public class AppCrashHandler implements Thread.UncaughtExceptionHandler {
private Thread.UncaughtExceptionHandler mDefaultHandler;
private static final AppCrashHandler INSTANCE = new AppCrashHandler();
private AppCrashHandler() {
}
public static AppCrashHandler getInstance() {
return INSTANCE;
}
public void init() {
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
mDefaultHandler.uncaughtException(thread, ex);
} else {
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
}
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
ex.printStackTrace();
new Thread() {
@Override
public void run() {
Looper.prepare();
ToastUtil.show("出现未知异常,即将退出.");
Looper.loop();
}
}.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return true;
}
}
<file_sep># BaseLibrary
rxjava2+retrof2+mvp解耦demo
个人项目
<file_sep>package com.samhaus.mylibrary.util;
import com.samhaus.mylibrary.BuildConfig;
import com.socks.library.KLog;
public class LogUtil {
private static final boolean isDebug = BuildConfig.DEBUG;
private LogUtil() {
throw new UnsupportedOperationException("cannot be instantiated");
}
public static void i(String msg) {
if (isDebug) {
KLog.i(msg);
}
}
public static void i(String tag, String msg) {
if (isDebug) {
KLog.i(msg);
}
}
public static void d(String msg) {
if (isDebug) {
KLog.d(msg);
}
}
public static void d(String tag, String msg) {
if (isDebug) {
KLog.d(msg);
}
}
public static void e(String msg) {
if (isDebug) {
KLog.e(msg);
}
}
public static void e(String tag, String msg) {
if (isDebug) {
KLog.e(tag, msg);
}
}
public static void v(String msg) {
if (isDebug) {
KLog.v(msg);
}
}
public static void v(String tag, String msg) {
if (isDebug) {
KLog.v(msg);
}
}
public static void json(String msg) {
if (isDebug) {
KLog.json(msg);
}
}
public static void json(String tag, String msg) {
if (isDebug) {
KLog.json(tag, msg);
}
}
}
<file_sep>package com.samhaus.mylibrary.network;
/**
* Created by jiaoyu on 17/4/20.
*/
public interface ErrorVerify {
void call(int code, String desc);
}
<file_sep>package com.samhaus.baselibrary.constant;
/**
* Created by samhaus on 2018/2/7.
*/
public class AppConstant {
public static String URL_MAIN="http://www.wanandroid.com/tools/mockapi/204/";
}
<file_sep>package com.samhaus.baselibrary.presenter;
import android.content.Context;
import com.samhaus.baselibrary.network.ApiFactory;
import com.samhaus.baselibrary.network.Apis;
import com.samhaus.mylibrary.network.BaseNetWork;
import com.samhaus.mylibrary.network.BaseObserver;
import com.samhaus.mylibrary.network.BasePresenter;
import com.samhaus.mylibrary.network.RxTransformerHelper;
import com.samhaus.mylibrary.util.LogUtil;
import io.reactivex.Observable;
/**
* Created by samhaus on 2018/2/7.
*/
public class MainPresenter extends BasePresenter<BaseNetWork> {
private Apis apis;
private Context mContext;
private BaseNetWork baseInterface;
private Observable observable;
public MainPresenter(Context mContext, BaseNetWork baseInterface) {
this.mContext = mContext;
this.baseInterface = baseInterface;
attachView(baseInterface);
apis = ApiFactory.build();
}
public void getTest() {
observable = apis.getTest();
getResponse();
}
public void getTest2() {
observable = apis.getTest2();
getResponse();
}
private void getResponse() {
baseInterface.loadding();
observable
.compose(RxTransformerHelper.applySchedulerAndAllFilter(mContext))
.subscribe(new BaseObserver() {
@Override
protected void onHandleSuccess(Object o) {
baseInterface.requestSuccess(o);
}
@Override
protected void onHandleError(String msg) {
baseInterface.requestError(msg);
}
@Override
public void onError(Throwable e) {
LogUtil.e("error " + e.getMessage());
baseInterface.requestError(e.getMessage());
}
});
}
}
<file_sep>package com.samhaus.mylibrary.network;
import android.content.Context;
import com.samhaus.mylibrary.base.BaseActivity;
import com.samhaus.mylibrary.util.ToastUtil;
import java.lang.ref.SoftReference;
/**
* Created by jiaoyu on 17/4/20.
*/
public class SimpleErrorVerify implements ErrorVerify {
//软引用
private SoftReference<Context> mContext;
public SimpleErrorVerify(Context mContext) {
this.mContext = new SoftReference<>(mContext);
}
@Override
public void call(int code, String desc) {
if (mContext != null && mContext.get() != null && mContext.get() instanceof BaseActivity) {
ToastUtil.show(desc);
((BaseActivity) mContext.get()).hideWaitDialog();
}
}
}
| dde5f4cb86a5e6fab6b7abf17b7f0880d9c0a67b | [
"Markdown",
"Java"
] | 9 | Java | samhaus/BaseLibrary | 592d3e67e8986308aa864505a2e61142168d8705 | e7b714d56bd0378fc7010b79e45694f78877fc19 |
refs/heads/master | <file_sep>require 'test_helper'
class FreeboardsControllerTest < ActionController::TestCase
setup do
@freeboard = freeboards(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:freeboards)
end
test "should get new" do
get :new
assert_response :success
end
test "should create freeboard" do
assert_difference('Freeboard.count') do
post :create, freeboard: { num: @freeboard.num, title: @freeboard.title, user: @freeboard.user }
end
assert_redirected_to freeboard_path(assigns(:freeboard))
end
test "should show freeboard" do
get :show, id: @freeboard
assert_response :success
end
test "should get edit" do
get :edit, id: @freeboard
assert_response :success
end
test "should update freeboard" do
patch :update, id: @freeboard, freeboard: { num: @freeboard.num, title: @freeboard.title, user: @freeboard.user }
assert_redirected_to freeboard_path(assigns(:freeboard))
end
test "should destroy freeboard" do
assert_difference('Freeboard.count', -1) do
delete :destroy, id: @freeboard
end
assert_redirected_to freeboards_path
end
end
<file_sep>json.array!(@freeboards) do |freeboard|
json.extract! freeboard, :id, :title, :user, :num
json.url freeboard_url(freeboard, format: :json)
end
<file_sep>require 'test_helper'
class FreeboardsHelperTest < ActionView::TestCase
end
<file_sep>class MainController < ApplicationController
def home
@freeboards = Freeboard.last(2)
end
def about
end
end
<file_sep>json.extract! @freeboard, :id, :title, :user, :num, :created_at, :updated_at
<file_sep>class FreeboardsController < ApplicationController
before_action :set_freeboard, only: [:show, :edit, :update, :destroy]
# GET /freeboards
# GET /freeboards.json
def index
@freeboards = Freeboard.all
end
# GET /freeboards/1
# GET /freeboards/1.json
def show
end
# GET /freeboards/new
def new
@freeboard = Freeboard.new
end
# GET /freeboards/1/edit
def edit
end
# POST /freeboards
# POST /freeboards.json
def create
@freeboard = Freeboard.new(freeboard_params)
respond_to do |format|
if @freeboard.save
format.html { redirect_to @freeboard, notice: 'Freeboard was successfully created.' }
format.json { render action: 'show', status: :created, location: @freeboard }
else
format.html { render action: 'new' }
format.json { render json: @freeboard.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /freeboards/1
# PATCH/PUT /freeboards/1.json
def update
respond_to do |format|
if @freeboard.update(freeboard_params)
format.html { redirect_to @freeboard, notice: 'Freeboard was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @freeboard.errors, status: :unprocessable_entity }
end
end
end
# DELETE /freeboards/1
# DELETE /freeboards/1.json
def destroy
@freeboard.destroy
respond_to do |format|
format.html { redirect_to freeboards_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_freeboard
@freeboard = Freeboard.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def freeboard_params
params.require(:freeboard).permit(:title, :user, :num)
end
end
| 1049406885fd479ec9027e57d085e1e6e552292d | [
"Ruby"
] | 6 | Ruby | corzej/test_soul | 258a8737b490085627e3a7feb00926a3b89a20fd | c0b3419dabe37f9058f82d53e5e402af8bafd0df |
refs/heads/master | <repo_name>vash050/site_mosquito<file_sep>/readme.txt
1.на данный момент в проекте не вижу антипаттернов
(кроме тех, которые мы добавили специально в учебных целях:
изобретение велосипеда - сам фреймворк,
Изобретение квадратного колеса - своя ORM)
2.В своем коде я допускал(и иногда допускаю) следующие антипаттерныЖ
Магические цифры - в данный момент так не делаю
Спаггети-код - иногда, исправляю при рефакторинге
Слепая вера - в данный момент стараюсь делать проверки правельности данных
Шифрованный код - бывает при решении маленьких учебных задач(строк на 5) или когда долго не могу найти решение
и приходит мысль для быстроты(если задача решена сразу rename)
Жесткое кодирования - для теста
Преждевременная оптимизация - бывает часто, с опытом уменьшается
Возврат из функции переменных разных типов - бывает забываю о этом антипаттерне
Отдельное присваевание вместо распаковки - бывает забываю о этом антипаттерне
<file_sep>/run.py
from mosquito_framework.main import Mosquito, DebugApplication, FakeApplication
from url import fronts
from wsgiref.simple_server import make_server
from views import routes
application = Mosquito(routes, fronts)
# application = DebugApplication(routes, fronts)
# application = FakeApplication(routes, fronts)
with make_server('', 8080, application) as httpd:
print('Serving on port 8080...')
httpd.serve_forever()
<file_sep>/views.py
from datetime import date
from mosquito_framework.templator import render
from patterns.architectul_system_patterns_mappers import MapperRegistry
from patterns.architectural_system_pattern_unit_of_work import UnitOfWork
from patterns.creational_patterns import Engine, Logger
from patterns.structural_patterns import AppRoute, Debug
from patterns.behavioral_patterns import EmailNotifier, SmsNotifier, BaseSerializer, ListView, CreateView
site = Engine()
logger = Logger('main')
email_notifier = EmailNotifier()
sms_notifier = SmsNotifier()
UnitOfWork.new_current()
UnitOfWork.get_current().set_mapper_registry(MapperRegistry=MapperRegistry)
routes = {}
@AppRoute(routes=routes, url='/')
class IndexView:
@Debug(name='IndexView')
def __call__(self, request):
return '200 OK', render('index.html', object_list=site.categories)
@AppRoute(routes=routes, url='/about/')
class AboutView:
@Debug(name='AboutView')
def __call__(self, request):
return '200 OK', render('contact.html')
class NotFound404View:
@Debug(name='NotFound404View')
def __call__(self, request):
return '404 WHAT', '404 PAGE Not Found'
@AppRoute(routes=routes, url='/study-programs/')
class StudyPrograms:
@Debug(name='StudyPrograms')
def __call__(self, request):
return '200 OK', render('study-programs.html', data=date.today())
@AppRoute(routes=routes, url='/courses-list/')
class CoursesList:
@Debug(name='CoursesList')
def __call__(self, request):
logger.log('список курсов')
try:
category = site.find_category_by_id(int(request['request_params']['id']))
return '200 OK', render('course_list.html', object_list=category.courses, name=category.name,
id=category.id)
except KeyError:
return '200 OK', 'No courses have been added yet'
@AppRoute(routes=routes, url='/create-course/')
class CreateCourse:
category_id = -1
@Debug(name='CreateCourse')
def __call__(self, request):
if request['method'] == 'POST':
data = request['data']
name = data['name']
name = site.decode_value(name)
category = None
if self.category_id != -1:
category = site.find_category_by_id(int(self.category_id))
course = site.create_course('offline', name, category)
# course.observers.append(email_notifier)
# course.observers.append(sms_notifier)
site.courses.append(course)
return '200 OK', render('course_list.html', object_list=category.courses, name=category.name,
id=category.id)
else:
try:
self.category_id = int(request['request_params']['id'])
category = site.find_category_by_id(int(self.category_id))
return '200 OK', render('create_course.html', name=category.name, id=category.id)
except KeyError:
return '200 OK', 'No categories have been added yet'
@AppRoute(routes=routes, url='/create-category/')
class CreateCategory:
@Debug(name='CreateCategory')
def __call__(self, request):
if request['method'] == 'POST':
print(request)
data = request['data']
name = data['name']
name = site.decode_value(name)
category_id = data.get('category_id')
category = None
if category_id:
category = site.find_category_by_id(int(category_id))
new_category = site.create_category(name, category)
site.categories.append(new_category)
return '200 OK', render('index.html', object_list=site.categories)
else:
categories = site.categories
return '200 OK', render('create_category.html', categories=categories)
@AppRoute(routes=routes, url='/category-list/')
class CategoryList:
@Debug(name='CategoryList')
def __call__(self, request):
logger.log('список категорий')
return '200 OK', render('category_list.html', object_list=site.categories)
@AppRoute(routes=routes, url='/copy-course/')
class CopyCourse:
@Debug(name='CopyCourse')
def __call__(self, request):
request_params = request['request_params']
try:
name = request_params['name']
old_course = site.get_course(name)
if old_course:
new_name = f'copy_{name}'
new_course = old_course.clone()
new_course.name = new_name
site.courses.append(new_course)
return '200 OK', render('course_list.html', object_list=site.courses)
except KeyError:
return '200 OK', 'No courses have been added yet'
@AppRoute(routes=routes, url='/student-list/')
class StudentListView(ListView):
template_name = 'student_list.html'
def get_queryset(self):
mapper = MapperRegistry.get_current_mapper('student')
return mapper.all()
@AppRoute(routes=routes, url='/create-student/')
class StudentCreateView(CreateView):
template_name = 'create_student.html'
def create_obj(self, data):
name = data['name']
name = site.decode_value(name)
new_obj = site.create_user('student', name)
site.students.append(new_obj)
new_obj.mark_new()
UnitOfWork.get_current().commit()
@AppRoute(routes=routes, url='/add-student/')
class AddStudentByCourseCreateView(CreateView):
template_name = 'add_student.html'
def get_context_data(self):
context = super().get_context_data()
context['courses'] = site.courses
context['students'] = site.students
return context
def create_obj(self, data):
course_name = data['course_name']
course_name = site.decode_value(course_name)
course = site.get_course(course_name)
student_name = data['student_name']
student_name = site.decode_value(student_name)
student = site.get_student(student_name)
course.add_student(student)
@AppRoute(routes=routes, url='/api/')
class CourseApi:
@Debug(name='CourseApi')
def __call__(self, request):
for el in site.courses:
print(f'course: {el.name}')
for elem in el.students:
print(f'user: {elem.name}')
print(f'course category: {site.categories}')
return '200 OK', BaseSerializer(site.courses).save()
| 5d4ed5dab86bf6558e3449d404480014150a2614 | [
"Python",
"Text"
] | 3 | Text | vash050/site_mosquito | 9719d12576412c4ab301bae615b19f86762d90c6 | dd995780e75f05c135e581524f45b747c3f2db80 |
refs/heads/master | <repo_name>Nanase46/circle_detection<file_sep>/README.md
# circle_detection
#霍夫圆检测
<file_sep>/findCircle.py
import cv2 as cv
import numpy as np
'''
:param
image为输入图像,要求是灰度图像
circles为输出圆向量,每个向量包括三个浮点型的元素——圆心横坐标,圆心纵坐标和圆半径
method为使用霍夫变换圆检测的算法,Opencv2.4.9只实现了2-1霍夫变换,它的参数是CV_HOUGH_GRADIENT
dp为第一阶段所使用的霍夫空间的分辨率,dp=1时表示霍夫空间与输入图像空间的大小一致,dp=2时霍夫空间是输入图像空间的一半,以此类推
minDist为圆心之间的最小距离,如果检测到的两个圆心之间距离小于该值,则认为它们是同一个圆心
param1为边缘检测时使用Canny算子的高阈值
param2为步骤1.5和步骤2.5中所共有的阈值
minRadius和maxRadius为所检测到的圆半径的最小值和最大值
'''
src = cv.imread('./circle.jpg', cv.IMREAD_COLOR)
img = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
img = cv.medianBlur(img, 5)
cimg = src.copy()
font = cv.FONT_HERSHEY_SIMPLEX
circles = cv.HoughCircles(img, cv.HOUGH_GRADIENT, 1,20, np.array([]),100,12, 10, 20)
if circles is not None:
a, b, c = circles.shape
print(str(circles))
for i in range(b):
cv.circle(cimg, (circles[0][i][0], circles[0][i][1]), circles[0][i][2], (0, 0, 255), 2, cv.LINE_AA)
cv.circle(cimg, (circles[0][i][0], circles[0][i][1]), 2, (0, 255, 0), 2, cv.LINE_AA) # draw center of circle
x_1= str(circles[0][i][0])
y_1= str(circles[0][i][1])
c = x_1+y_1
d= str(i)
cv.putText(cimg, d, (circles[0][i][0], circles[0][i][1]), font, 0.5, (255, 255, 255), 1)
cv.imshow("detected circles", cimg)
cv.imwrite('./result.jpg', cimg)
cv.waitKey(0)
| 1a619d479a2b5d7266c3d5a47df54ae24dc957b0 | [
"Markdown",
"Python"
] | 2 | Markdown | Nanase46/circle_detection | 2a282751507945421aefcb376d81e16254d6f18a | 295a6d2edb9c61256db01bd2f13db5f95b188aa0 |
refs/heads/main | <repo_name>oussamabenakka/G-re-Banque<file_sep>/Courant.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace GereBanque
{
[Serializable]
class Courant:Compte
{
public Courant()
{ }
public Courant(double solde, int num_compte, DateTime date_depart) : base(solde, num_compte, date_depart)
{
}
public override double GetSolde()
{
return solde;
}
}
}
<file_sep>/LesList.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace GereBanque
{
[Serializable]
class LesList
{
public static List<Compte> comptes = new List<Compte>();
public static List<Client> clients = new List<Client>();
}
}
<file_sep>/SupprimerCmpte.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GereBanque
{
public partial class SupprimerCmpte : Form
{
public SupprimerCmpte()
{
InitializeComponent();
}
private void SupprimerCmpte_Load(object sender, EventArgs e)
{
foreach (Client cl in LesList.clients)
{
comboBox1.Items.Add(cl.Num);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Client cl = (Client)LesList.clients[comboBox1.SelectedIndex];
textBox1.Text = cl.Num.ToString();
textBox2.Text = cl.Nom_prenom;
foreach (Compte cp in cl.List_compte)
{
comboBox2.Items.Add(cp.Num_compte);
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
Client cl = (Client)LesList.clients[comboBox1.SelectedIndex];
Compte cp = (Compte)cl.List_compte[comboBox2.SelectedIndex];
if (cp is Courant)
{
textBox3.Text = "Courant";
textBox4.Text = cp.Num_compte.ToString();
textBox5.Text = cp.GetSolde().ToString();
}
else if (cp is Epargne)
{
textBox3.Text = "Eparne";
textBox4.Text = cp.Num_compte.ToString();
textBox5.Text = cp.GetSolde().ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult rep = MessageBox.Show("Voulez vous Supprimer ?", "Suppression", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (rep == DialogResult.Yes)
{
Client cl = (Client)LesList.clients[comboBox1.SelectedIndex];
Compte cp = (Compte)cl.List_compte[comboBox2.SelectedIndex];
cl.Supprimer(cp);
foreach(Control c in this.Controls)
{
if (c is TextBox)
{
c.Text = "";
comboBox1.Focus();
}
}
}
}
}
}
<file_sep>/AfficherClient.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GereBanque
{
public partial class AfficherClient : Form
{
public AfficherClient()
{
InitializeComponent();
}
private void AfficherClient_Load(object sender, EventArgs e)
{
foreach (Client cl in LesList.clients)
{
comboBox1.Items.Add(cl.Num);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
dataGridView1.Rows.Clear();
Client cl = (Client)LesList.clients[comboBox1.SelectedIndex];
foreach (Compte cp in cl.List_compte)
{
if (cp is Courant)
{
dataGridView1.Rows.Add(cl.Num, cl.Nom_prenom, cp.Num_compte, "Courant", cp.Date_depart.ToShortDateString(), Math.Round(cp.GetSolde(), 2));
}
else if (cp is Epargne)
{
dataGridView1.Rows.Add(cl.Num, cl.Nom_prenom, cp.Num_compte, "Epargne", cp.Date_depart.ToShortDateString(), Math.Round(cp.GetSolde(), 2));
}
}
}
}
}
<file_sep>/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace GereBanque
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ajouterToolStripMenuItem_Click(object sender, EventArgs e)
{
AjouterClient ac = new AjouterClient();
ac.MdiParent = this;
ac.Show();
}
private void supprimerToolStripMenuItem_Click(object sender, EventArgs e)
{
SupprimerClient sc = new SupprimerClient();
sc.MdiParent = this;
sc.Show();
}
private void afficherToolStripMenuItem_Click(object sender, EventArgs e)
{
AfficherClient ac = new AfficherClient();
ac.MdiParent = this;
ac.Show();
}
private void ajouterToolStripMenuItem1_Click(object sender, EventArgs e)
{
AjouterComte aj = new AjouterComte();
aj.MdiParent = this;
aj.Show();
}
private void supprimerToolStripMenuItem1_Click(object sender, EventArgs e)
{
SupprimerCmpte sp = new SupprimerCmpte();
sp.MdiParent = this;
sp.Show();
}
private void deposerToolStripMenuItem_Click(object sender, EventArgs e)
{
Deposer_Retirer dr = new Deposer_Retirer();
dr.MdiParent = this;
dr.Show();
}
private void sauvgarderToolStripMenuItem_Click(object sender, EventArgs e)
{
FileStream F = new FileStream("banc.txt", FileMode.Create);
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(F, LesList.clients);
F.Close();
MessageBox.Show("Sauvgarder");
}
private void restaurerToolStripMenuItem_Click(object sender, EventArgs e)
{
FileStream F = new FileStream("banc.txt", FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
LesList.clients = (List<Client>)bf.Deserialize(F);
F.Close();
MessageBox.Show("Restaurer");
}
private void ewAffichageToolStripMenuItem_Click(object sender, EventArgs e)
{
DeuxGrid dg = new DeuxGrid();
dg.MdiParent = this;
dg.Show();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void cascadeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.LayoutMdi(MdiLayout.Cascade);
}
private void horizontaleToolStripMenuItem_Click(object sender, EventArgs e)
{
this.LayoutMdi(MdiLayout.TileHorizontal);
}
private void verticaleToolStripMenuItem_Click(object sender, EventArgs e)
{
this.LayoutMdi(MdiLayout.TileVertical);
}
private void iconsToolStripMenuItem_Click(object sender, EventArgs e)
{
}
}
}
<file_sep>/Epargne.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace GereBanque
{
[Serializable]
class Epargne:Compte
{
private double taux = 6;
public double Taux
{
get { return this.taux; }
}
public Epargne() : base()
{ }
public Epargne(double solde, int num_compte, DateTime date_depart) : base(solde, num_compte, date_depart)
{
}
public override double GetSolde()
{
int nbj = DateTime.Now.Subtract(this.date_depart).Days;
solde += ((nbj * taux * solde) / 100) / 365;
return solde;
}
}
}
<file_sep>/Deposer_Retirer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GereBanque
{
public partial class Deposer_Retirer : Form
{
public Deposer_Retirer()
{
InitializeComponent();
}
private void Deposer_Retirer_Load(object sender, EventArgs e)
{
foreach (Client cl in LesList.clients)
{
comboBox1.Items.Add(cl.Num);
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
Client cl = (Client)LesList.clients[comboBox1.SelectedIndex];
Compte cp = (Compte)cl.List_compte[comboBox2.SelectedIndex];
if (cp is Courant)
{
textBox3.Text = "Courant";
textBox4.Text = cp.Num_compte.ToString();
textBox5.Text = cp.GetSolde().ToString();
}
else if (cp is Epargne)
{
textBox3.Text = "Eparne";
textBox4.Text = cp.Num_compte.ToString();
textBox5.Text = cp.GetSolde().ToString();
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Client cl = (Client)LesList.clients[comboBox1.SelectedIndex];
textBox1.Text = cl.Num.ToString();
textBox2.Text = cl.Nom_prenom;
foreach (Compte cp in cl.List_compte)
{
comboBox2.Items.Add(cp.Num_compte);
}
}
private void button1_Click(object sender, EventArgs e)
{
Client cl = (Client)LesList.clients[comboBox1.SelectedIndex];
Compte cp = (Compte)cl.List_compte[comboBox2.SelectedIndex];
if (cp is Courant)
{
cp.Deposer(double.Parse(textBox6.Text));
textBox5.Text = cp.GetSolde().ToString();
}
else if (cp is Epargne)
{
cp.Deposer(double.Parse(textBox6.Text));
textBox5.Text = cp.GetSolde().ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
Client cl = (Client)LesList.clients[comboBox1.SelectedIndex];
Compte cp = (Compte)cl.List_compte[comboBox2.SelectedIndex];
if (cp is Courant)
{
cp.Retierer(double.Parse(textBox6.Text));
textBox5.Text = cp.GetSolde().ToString();
}
else if (cp is Epargne)
{
cp.Retierer(double.Parse(textBox6.Text));
textBox5.Text = cp.GetSolde().ToString();
}
}
}
}
<file_sep>/AjouterClient.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GereBanque
{
public partial class AjouterClient : Form
{
public AjouterClient()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
char c = e.KeyChar;
if (!char.IsNumber(c) && !char.IsControl(c))
e.Handled = true;
}
private void nbr_KeyPress(object sender, KeyPressEventArgs e)
{
char c = e.KeyChar;
if (!char.IsNumber(c) && !char.IsControl(c))
e.Handled = true;
}
private void textBox4_KeyPress(object sender, KeyPressEventArgs e)
{
char c = e.KeyChar;
if (!char.IsNumber(c) && !char.IsControl(c))
e.Handled = true;
}
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
char c = e.KeyChar;
if (!char.IsNumber(c) && !char.IsControl(c))
e.Handled = true;
}
private void AjouterClient_Load(object sender, EventArgs e)
{
listBox1.Items.Clear();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox1.SelectedIndex == -1)
{
foreach (Control c in groupBox2.Controls)
{
if (c is TextBox)
c.Enabled = false;
}
}
else
{
foreach (Control c in groupBox2.Controls)
{
if (c is TextBox)
c.Enabled = true;
}
}
}
private void button3_Click_1(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("Donner le numero de client");
textBox1.Focus();
}
else if (textBox2.Text == "")
{
MessageBox.Show("Donner le nom et le prenom de client");
textBox2.Focus();
}
else if (nbr.Text == "")
{
MessageBox.Show("Donner le nombre des comptes");
nbr.Focus();
}
else
{
Client cl = new Client(textBox2.Text, int.Parse(textBox1.Text));
LesList.clients.Add(cl);
listBox1.Items.Add(cl.Num + " " + cl.Nom_prenom);
}
}
int i = 0;
private void button1_Click_1(object sender, EventArgs e)
{
if (!radioButton1.Checked && !radioButton2.Checked)
{
MessageBox.Show("Donner le type de compte");
groupBox1.Focus();
}
else if (textBox4.Text == "")
{
MessageBox.Show("Donner le numero de compte");
textBox4.Focus();
}
else if (textBox3.Text == "")
{
MessageBox.Show("Donner le solde");
textBox3.Focus();
}
else if (monthCalendar1.SelectionStart >= monthCalendar1.TodayDate)
{
MessageBox.Show("la date n'est pas valide");
monthCalendar1.Focus();
}
else if (listBox1.SelectedIndex == -1)
{
MessageBox.Show("Selectionner un Client");
listBox1.Focus();
}
else
{
DialogResult rep = MessageBox.Show("Voulez vous enregistrer ?", "Enregistrement", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (rep == DialogResult.Yes)
{
//Compte Courant
if (radioButton1.Checked)
{
i++;
Client cl = (Client)LesList.clients[listBox1.SelectedIndex];
Courant cu = new Courant(double.Parse(textBox3.Text), int.Parse(textBox4.Text), monthCalendar1.SelectionStart);
cl.Ajouter(cu);
MessageBox.Show("Compte Courant Ajouter");
textBox4.Clear(); textBox3.Clear();
if (int.Parse(nbr.Text) <= i)
{
MessageBox.Show("impossible de ajouter un autre compte");
textBox4.Clear(); textBox3.Clear(); textBox1.Clear(); textBox2.Clear(); textBox3.Clear();
i = 0;
}
}
//Compte Epargne
else if (radioButton2.Checked)
{
i++;
Client cl = (Client)LesList.clients[listBox1.SelectedIndex];
Epargne ep = new Epargne(double.Parse(textBox3.Text), int.Parse(textBox4.Text), monthCalendar1.SelectionStart);
cl.Ajouter(ep);
MessageBox.Show("Compte Epargne Ajouter");
textBox4.Clear(); textBox3.Clear();
if (int.Parse(nbr.Text) <= i)
{
MessageBox.Show("impossible de ajouter un autre compte");
textBox4.Clear(); textBox3.Clear(); textBox1.Clear(); textBox2.Clear(); textBox3.Clear();
i = 0;
}
}
}
}
}
}
}
<file_sep>/Compte.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace GereBanque
{[Serializable]
class Compte
{
protected double solde;
protected int num_compte;
protected DateTime date_depart;
public double Solde
{
get { return this.Solde; }
}
public int Num_compte
{
get { return this.num_compte; }
set { this.num_compte = value; }
}
public DateTime Date_depart
{
get { return this.date_depart; }
set { this.date_depart = value; }
}
public Compte()
{ }
public Compte(double solde, int num_compte, DateTime date_depart)
{
this.solde = solde;
this.num_compte = num_compte;
this.date_depart = date_depart;
}
public void Deposer(double somme)
{
this.solde += somme;
}
public void Retierer(double somme)
{
this.solde -= somme;
}
public virtual double GetSolde()
{
return Solde;
}
}
}
<file_sep>/SupprimerClient.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GereBanque
{
public partial class SupprimerClient : Form
{
public SupprimerClient()
{
InitializeComponent();
}
private void SupprimerClient_Load(object sender, EventArgs e)
{
foreach(Client cl in LesList.clients)
{
comboBox1.Items.Add(cl.Num);
}
}
private void button1_Click(object sender, EventArgs e)
{
DialogResult rep = MessageBox.Show("Voulez vous Supprimer ?", "Suppresion", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (rep == DialogResult.Yes)
{
Client cl = (Client)LesList.clients[comboBox1.SelectedIndex];
LesList.clients.Remove(cl);
foreach(Control c in this.Controls)
{
if(c is TextBox)
{
c.Text = string.Empty;
comboBox1.Focus();
}
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Client cl = (Client)LesList.clients[comboBox1.SelectedIndex];
textBox1.Text = cl.Num.ToString();
textBox2.Text = cl.Nom_prenom;
}
}
}
<file_sep>/AjouterComte.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GereBanque
{
public partial class AjouterComte : Form
{
public AjouterComte()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox4.Text == "")
{
MessageBox.Show("Donner le numero de compte");
textBox4.Focus();
}
else if (textBox3.Text == "")
{
MessageBox.Show("Donner le solde");
textBox3.Focus();
}
else if (monthCalendar1.SelectionStart >= monthCalendar1.TodayDate)
{
MessageBox.Show("la date n'est pas valide");
monthCalendar1.Focus();
}
if(!radioButton1.Checked && !radioButton2.Checked)
{
MessageBox.Show("selectionner le type de compte");
}
else
{
DialogResult rep = MessageBox.Show("Voulez vous enregistrer ?", "Enregistrement", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (rep == DialogResult.Yes)
{
//Compte courant
if (radioButton1.Checked)
{
Courant cu = new Courant(double.Parse(textBox3.Text), int.Parse(textBox4.Text), monthCalendar1.SelectionStart);
LesList.comptes.Add(cu);
Client cl=(Client)LesList.clients[comboBox1.SelectedIndex];
cl.Ajouter(cu);
MessageBox.Show("Compte Courant Ajoutée");
textBox1.Clear();textBox2.Clear();textBox3.Clear();textBox4.Clear();comboBox1.Focus();
}
//Compte Epargne
else if (radioButton2.Checked)
{
Epargne ep = new Epargne(double.Parse(textBox3.Text), int.Parse(textBox4.Text), monthCalendar1.SelectionStart);
LesList.comptes.Add(ep);
Client cl = (Client)LesList.clients[comboBox1.SelectedIndex];
cl.Ajouter(ep);
MessageBox.Show("Compte Epargne Ajoutée");
textBox1.Clear(); textBox2.Clear(); textBox3.Clear(); textBox4.Clear(); comboBox1.Focus();
}
}
}
}
private void AjouterComte_Load(object sender, EventArgs e)
{
foreach(Client cl in LesList.clients)
{
comboBox1.Items.Add(cl.Num);
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
Client cl = (Client)LesList.clients[comboBox1.SelectedIndex];
textBox1.Text = cl.Num.ToString();
textBox2.Text = cl.Nom_prenom;
}
}
}
<file_sep>/Client.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace GereBanque
{
[Serializable]
class Client
{
private string nom_prenom;
private int num;
private List<Compte> list_compte = new List<Compte>();
public string Nom_prenom
{
get { return this.nom_prenom; }
set { this.nom_prenom = value; }
}
public List<Compte> List_compte
{
get { return this.list_compte; }
set { this.list_compte = value; }
}
public int Num
{
get { return this.num; }
set { this.num = value; }
}
public Client()
{ }
public Client(string nom_prenom, int num)
{
this.nom_prenom = nom_prenom;
this.num = num;
}
public void Ajouter(Compte C)
{
this.list_compte.Add(C);
}
public void Supprimer(Compte C)
{
this.list_compte.Remove(C);
}
}
}
| fbd94e0ff732615a5c552d441c4840ce4d739699 | [
"C#"
] | 12 | C# | oussamabenakka/G-re-Banque | 287a128bb295686acd82e37fbdb6dbc7c61dcf71 | ce1e753cb0a3ccdb875c5c269cc61a173ca0c498 |
refs/heads/master | <repo_name>mokcrimea/Event-Horizon<file_sep>/public/js/slideShow.js
window.onload = function() {
var arraySrcSlideList = [], //Массив адресов фотографий
slideWidthSize, //Размер окна обозревателя фото
mainWindowSlide = document.getElementById('slideShow'), // Главный блок обозреваля фото
slideImagePlace = document.getElementById('slide-img'), //img Обозревателя фото
slideLoadImg = document.getElementsByClassName('slide-load-img')[0], //Индикатор загрузки фото
slideNextButton = document.getElementsByClassName('slide-next-btn')[0], // Кнопка "следующий слайд"
slidePrevButton = document.getElementsByClassName('slide-prev-btn')[0], // Кнопка "предыдущий слайд"
slideCloseButton = document.getElementsByClassName('slide-close-btn')[0], // Кнопка "закрыть"
slideImageContent = document.getElementsByClassName('slide-img-content')[0], // Блок загрузки фото
mainBackgroundSpace = document.getElementsByClassName('backgroundSpace')[0]; // Тёмный фон при открытии обозревателя фото
window.addEventListener('resize', changeBckgroundSlideSize); //Фон обозревателя подстраивается под размер окна при зуммировании или изменении размера окна
document.body.addEventListener('click', function(event) {
if (event.target.className.search('gallery-zoom-btn') != -1) openSlideShow(event.target.parentNode);
if ((event.target.className.search('slide-close-btn') != -1) || (event.target.className.search('backgroundSpace') != -1))
closeSlideShow(event.target.parentNode);
if (event.target.className.search('slide-next-btn') != -1) changePhotoSlide(true);
if (event.target.className.search('slide-prev-btn') != -1) changePhotoSlide(false);
}, true);
function getClientWidth() {
return document.compatMode == 'CSS1Compat' && !window.opera ? document.documentElement.clientWidth : document.body.clientWidth;
}
function getClientHeight() {
return document.compatMode == 'CSS1Compat' && !window.opera ? document.documentElement.clientHeight : document.body.clientHeight;
}
// Функция открывает окно слайд-обозревателя
function openSlideShow(imgContainerGallery) {
var thisImgSrc = imgContainerGallery.getElementsByTagName('img')[0].src, //Адрес фото, открытой из галереи
mainBlockWidthSize = document.getElementsByClassName('main')[0].offsetWidth, // Получает ширину страницы
positionScroll = window.pageYOffset || document.documentElement.scrollTop,
positionPhoto;
for (var i = 0; i < inputDataObject.length; i++) { // Записываем адреса фото на странице в массив
arraySrcSlideList[i] = inputDataObject[i].links.orig.href;
}
mainWindowSlide.style.display = 'block'; // Отображаем окно обозревателя фото
slideLoadImg.style.display = 'block';
//Центрируем обозреватель фото по высоте и ширине
if (getClientHeight() < 730) {
mainWindowSlide.style.position = "absolute";
mainWindowSlide.style.top = positionScroll + 'px';
} else {
mainWindowSlide.style.position = "fixed";
mainWindowSlide.style.top = (getClientHeight() - 730) / 2 + 'px';
}
if (mainBlockWidthSize >= 1200) {
slideWidthSize = 1100;
mainWindowSlide.style.marginLeft = '-150px';
} else {
slideWidthSize = 990;
mainWindowSlide.style.marginLeft = '-67px';
}
//Центрируем элементы управления обозревателя
slideNextButton.style.marginLeft = slideWidthSize - 90 + 'px';
slideCloseButton.style.marginLeft = slideWidthSize - 100 + 'px';
slideImageContent.style.width = slideWidthSize + 'px';
//Включаем задний фон обозревателя
mainBackgroundSpace.style.display = 'block';
//Подстраиваем задний фон обозревателя под размер экрана
changeBckgroundSlideSize();
mainWindowSlide.style.width = slideWidthSize + 'px';
thisImgSrc = thisImgSrc.substring(0, thisImgSrc.length - 1) + 'orig';
positionPhoto = findPosition(arraySrcSlideList, thisImgSrc);
setPhotoToSlide(thisImgSrc, positionPhoto);
document.addEventListener('keydown', setSlideKeyNavigate);
}
//Функция управления обозревателем кнопками
function setSlideKeyNavigate(e) {
if (e.keyCode == 37) return changePhotoSlide(false);
if (e.keyCode == 39) return changePhotoSlide(true);
if (e.keyCode == 27) return closeSlideShow(event.target.parentNode);
}
//Функция закрытия слайд-обозревателя
function closeSlideShow() {
//Прячем окно обозревателя
mainWindowSlide.style.display = "none";
mainBackgroundSpace.style.display = "none";
slideImagePlace.style.opacity = '0';
document.removeEventListener('keydown', setSlideKeyNavigate);
}
// Функция открывает фотографию в слайд-обозревателе
function setPhotoToSlide(inputPhoto, positionPhoto) {
var originalImg = new Image();
// Сбрасываем атрибуты фото в обозревателе, и заливаем новую фото
slideImagePlace.removeAttribute('width');
slideImagePlace.removeAttribute('height');
slideImagePlace.src = inputPhoto;
originalImg.src = inputPhoto;
//Скрываем кнопки листания на последней фотографии в списке
slideNextButton.style.display = "block";
slidePrevButton.style.display = "block";
if (positionPhoto + 1 == arraySrcSlideList.length) {
slideNextButton.style.display = "none";
}
if (positionPhoto - 1 == -1) {
slidePrevButton.style.display = "none";
}
//В зависимости от разрешения фото - подгоняем её под окно обозревателя
originalImg.onload = function() {
var originalHeight = originalImg.height,
originalWidth = originalImg.width,
differentSize;
if ((originalHeight > 730) || (originalWidth > slideWidthSize)) {
if (originalHeight > originalWidth) {
slideImagePlace.setAttribute('height', '730px');
}
if (originalWidth > originalHeight) {
differentSize = slideWidthSize * originalHeight / originalWidth;
if (differentSize > 730) {
slideImagePlace.setAttribute('height', '730px');
} else {
slideImagePlace.setAttribute('width', slideWidthSize + 'px');
}
}
}
slideLoadImg.style.display = "none";
slideImagePlace.style.opacity = "1";
return;
}
}
//функция определения позиции в массиве текущей отображённой фото
function findPosition(array, value) {
for (var i = 0; i < array.length; i++) {
if (array[i] == value) return i;
}
return -1;
}
// Функция определяет следующую необходимую фотографию
function changePhotoSlide(bool) {
positionPhoto = findPosition(arraySrcSlideList, slideImagePlace.src);
if (bool) {
if (positionPhoto != arraySrcSlideList.length - 1) {
slideImagePlace.style.opacity = '0';
slideLoadImg.style.display = 'block';
setPhotoToSlide(arraySrcSlideList[positionPhoto + 1], positionPhoto + 1);
}
} else {
if (positionPhoto != 0) {
slideImagePlace.style.opacity = '0';
slideLoadImg.style.display = 'block';
setPhotoToSlide(arraySrcSlideList[positionPhoto - 1], positionPhoto - 1);
}
}
}
// Функция подстройки зайднего фона при режиме обозревателя фото
function changeBckgroundSlideSize() {
mainBackgroundSpace.style.width = getClientWidth() + 'px';
mainBackgroundSpace.style.height = getClientHeight() + 'px';
}
}
<file_sep>/controllers/users.js
/**
* Основные зависимости
*/
var mongoose = require('mongoose'),
User = mongoose.model('User'),
log = require('../lib/log')(module),
HttpError = require('../lib/error').HttpError;
/**
* Загружает информацию о пользователе в req.reqUser
*/
exports.load = function(req, res, next, id) {
User.findById(id, 'id authToken name username tracks created', function(err, user) {
if (err) return next(404, err);
if (user) {
req.reqUser = user;
next();
} else {
next(new HttpError(404, 'Пользователь не существует'));
}
});
};
/**
* Отображает страницу принятия пользовательского соглашения Яндекс.Фото
*/
exports.signup = function(req, res, next) {
if (req.session.become == 'yandex-terms') {
delete req.session.become;
res.render('user/signup', {
title: 'Необходимо принять пользовательское соглашение'
});
} else {
next(new HttpError(403, 'Ошибка доступа'));
}
};
/**
* Редиретит на страницу которая была перед логином
*/
exports.redirect = function(req, res) {
var redirect = req.session.returnTo || '/';
delete req.session.returnTo;
res.redirect(redirect);
};
/**
* Список треков пользователя
*/
exports.list = function(req, res) {
User.list(req.user.id, function(err, user) {
var tracks = user.tracks;
if (tracks.length === 0) {
return res.render('track/upload', {
title: 'Загрузка нового трека',
success: 'У вас нет загруженных треков. Можете загрузить новый с помощью формы ниже'
});
}
res.render('track/list', {
title: 'Список загруженных треков',
tracks: tracks
});
});
};
/**
* Профиль пользователя
*/
exports.show = function(req, res) {
res.render('user/profile', {
title: 'Ваш профиль',
user: req.reqUser
});
};
/**
* Выход
*/
exports.logout = function(req, res) {
req.logout();
res.redirect('/');
};
<file_sep>/middleware/helpers.js
/**
* Упрощает доступ к переменным в шаблонах
*/
exports.transport = function(req, res, next) {
res.locals.req = req;
if (req.flash !== undefined) {
res.locals.success = req.flash('success');
res.locals.err = req.flash('error');
}
next();
};
/**
* Функция записывает CSRF токен в cookie
*/
exports.csrf_cookie = function(req, res, next) {
res.cookie('X-CSRF-Token', req.csrfToken());
next();
};
/**
* Функция принимаюзая запрос и возвращающая токен
* @type {Object}
*/
exports.value = {
value: function(req) {
var token = (req.headers['x-csrf-token']) || (req.headers['x-xsrf-token']) || (req.cookies['X-CSRF-Token']);
return token;
}
};
<file_sep>/controllers/tracks.js
/**
* Основные зависимости
*/
var mongoose = require('mongoose'),
Track = mongoose.model('Track'),
fs = require("fs"),
HttpError = require('../lib/error').HttpError,
createFolders = require('../lib/utils').createFolders,
tracksPath = require('../lib/utils').getTracksPath(),
log = require('../lib/log')(module);
/**
* Загрузка информации о треке
*/
exports.load = function(req, res, next, id) {
Track.findById(id, 'name _creator created images album inform', function(err, track) {
if (err) return next(404, err);
if (track) {
req.track = track;
next();
} else {
next(new HttpError(404, 'Трек не существует'));
}
});
};
/**
* Главная страница
*/
exports.index = function(req, res) {
res.render('index', {
title: 'Главная'
});
};
/**
* Загрузка нового трека
*/
exports.new = function(req, res) {
res.render('track/upload', {
title: 'Загрузка нового трека',
});
};
/**
* Показывает трек
*/
exports.show = function(req, res, next) {
var images = [];
req.track.images.forEach(function(image) {
/**
* Передаем в track/show только те картинки которые имеют GPS кординаты
* и их размер минимум M (300px)
*/
if (image.coordinates[0]) {
if (!image.links.L) {
try {
images.push([image.coordinates[0], image.links.M.href, image.title]);
} catch (e) {
log.debug('Картинка очень маленького размера');
}
} else {
images.push([image.coordinates[0], image.links.L.href, image.title]);
}
}
});
var track = req.track;
fs.readFile(tracksPath + req.track.id + '/track', function(err, data) {
if (err) return next(404, err);
res.render('track/show', {
title: track.name,
coord: data.toString(),
track: track,
images: images
});
});
};
/**
* Создает новый трека
*/
exports.create = function(req, res, next) {
// Библиотеки для загрузки файла и для парсинга .gpx
var formidable = require('formidable'),
parseTrack = require('../lib/parseTrack');
var track = new Track({}),
form = new formidable.IncomingForm(),
trackId = track.id,
reTitle = /(^[A-zА-я0-9\s-.,_еЁ]{3,55}$)/;
form.parse(req, function(error, fields, files) {
if (!reTitle.test(fields.title)) {
return next(new HttpError(400, 'Недопустимые символы в названии'));
}
createFolders(trackId, function(err) {
if (err) throw err;
try {
fs.readFile(files.upload.path, function(err, Data) {
if (err) throw err;
parseTrack(Data, tracksPath + trackId, function(err, inform) {
// На случай если формат файла не правильный
if (err) {
fs.unlink(files.upload.path, function(err) {
if (err) log.error(err);
});
fs.rmdir(tracksPath + trackId + '/', function(err) {
if (err) log.error(err);
});
return next(new HttpError(415, 'Неправильный формат загружаемого файла'));
}
// Удаляем загруженный в /tmp/ файл потому что его уже распарсили
fs.unlink(files.upload.path, function(err) {
if (err) log.error(err);
});
track.create(fields.title, req.user, inform, function(err) {
if (err) throw err;
log.debug('Трек успешно создан');
req.flash('success', 'Трек успешно создан');
res.redirect('/track/' + track.id);
});
});
});
} catch (e) {
log.error(e);
res.redirect('/upload');
}
});
});
};
/**
* Удаляет трек
*/
exports.delete = function(req, res, next) {
Track.findByIdAndRemove(req.track.id, function(err) {
if (err) return next(404, err);
log.info('Трек успешно удален из базы');
});
fs.unlink(tracksPath + req.track.id + '/track', function(err) {
if (err) log.error(err);
fs.unlink(tracksPath + req.track.id + '/full', function(err) {
fs.rmdir(tracksPath + req.track.id + '/', function(err) {
if (err) log.error(err);
});
});
});
next();
};
<file_sep>/earseDb.js
var mongoose = require('lib/mongoose');
var async = require('async');
async.series([
open,
dropDatabase
], function(err) {
console.log(arguments);
mongoose.disconnect();
process.exit(err ? 255 : 0);
});
function open(callback) {
mongoose.connection.on('open', callback);
}
function dropDatabase(callback) {
var db = mongoose.connection.db;
db.dropDatabase(callback);
}
<file_sep>/config/express.js
/**
* Module dependencies.
*/
var express = require('express'),
MongoStore = require('connect-mongo')(express),
log = require('../lib/log')(module),
path = require('path'),
flash = require('connect-flash'),
HttpError = require('../lib/error').HttpError;
module.exports = function(app, config, passport, mongoose) {
app.use(express.compress({
filter: function(req, res) {
return /json|text|css|javascript|image|otf/.test(res.getHeader('Content-Type'));
},
level: 9
}));
app.use(express.favicon(path.join(path.resolve(__dirname, '../public/img/favicon.ico'))));
app.use(express.static(path.join(path.resolve(__dirname, '../public'))));
app.set('views', path.resolve(__dirname, '../template'));
app.set('view engine', 'jade');
// Логирование
if (app.get('env') == 'development') {
app.use(express.logger('dev'));
} else {
app.use(express.logger('default'));
}
app.on('error', function(err) {
console.error(err);
});
app.configure(function() {
app.use(express.cookieParser());
app.use(require('../middleware/sendHttpError'));
app.use(express.urlencoded());
app.use(express.json());
app.use(express.methodOverride());
// настройки mongo-session
app.use(express.session({
secret: config.get('session:secret'),
key: config.get('session:key'),
cookie: config.get('session:cookie'),
store: new MongoStore({
mongoose_connection: mongoose.connection
})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(require('../middleware/helpers').transport);
// подключаем CSRF в куки
app.use(express.csrf(require('../middleware/helpers').value));
app.use(require('../middleware/helpers').csrf_cookie);
app.use(app.router);
// обрабокта ошибок
app.use(function(err, req, res, next) {
if (typeof err == 'number') { // next(404);
err = new HttpError(err);
}
if (err instanceof HttpError) {
res.sendHttpError(err);
} else {
if (app.get('env') == 'development') {
express.errorHandler()(err, req, res, next);
} else {
log.error(err);
err = new HttpError(500);
res.sendHttpError(err);
}
}
});
});
// красивое отображение html кода
app.configure('development', function() {
app.locals.pretty = true;
});
};
<file_sep>/config/passport.js
var mongoose = require('mongoose'),
YandexStrategy = require('passport-yandex').Strategy,
User = mongoose.model('User');
module.exports = function (passport, config) {
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use(new YandexStrategy({
clientID: config.get('yandex:clientID'),
clientSecret: config.get('yandex:clientSecret'),
callbackURL: config.get('yandex:callbackURL')
},
function(accessToken, refreshToken, profile, done) {
User.findOne({ 'yandex.id': profile.id }, function (err, user) {
if (!user) {
user = new User({
authToken: accessToken,
name: profile.displayName,
email: profile.emails[0].value,
username: profile.username,
provider: 'yandex',
yandex: profile._json
});
user.save(function(err){
if (err) console.log(err);
return done(err, user);
});
} else {
/**
* Перезаписывает токен. В документации написанно, что он выдается на
* неограниченный срок. При изменении прав приложения - текущий токен
* становится недействительным.
*/
user.setToken(accessToken, function(err){
if (err) console.log(err);
});
return done(err, user);
}
});
}
));
};<file_sep>/models/track.js
/**
* Основные зависимости
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Схема трека
*/
var TrackSchema = new Schema({
name: { type: String, require: true},
_creator: { type : Schema.ObjectId, ref : 'User'},
created: { type: Date, default: Date.now},
inform: {
distance: Number,
time: String,
center: Array
},
album: {
title: String,
id: String,
link: String,
self: String,
updated: Date,
},
images: [{
links : {},
param: String,
self: String,
title: String,
coordinates: [],
created: Date,
id: Schema.ObjectId
}]
});
/**
* Методы
*/
TrackSchema.methods = {
/**
* Создает новый трек и записывает пользователю ссылку на него (ObjectId)
*
* @param {String} name Название трека
* @param {Object} user Создатель
* @param {Object} inform Информация о маршруте
* @param {Function} callback
*/
create: function(name, user, inform, callback) {
var id = user._id;
var that = this;
this.name = name;
this._creator = id;
this.inform = {
center: inform.center,
distance: inform.distance,
time: inform.time || undefined
};
this.save(function(err) {
if (err) throw err;
user.tracks.push(that.id);
user.save(function(err) {
if (err) throw err;
});
});
return callback(undefined);
},
/**
* Записывает данные по альбому в БД
* @param {Object} obj данные альбома
* @param {Function} callback
*/
addAlbum: function(obj, callback) {
this.album = {
title: obj.title,
id: obj.id,
link: obj.links.photos,
self: obj.links.self,
updated: obj.updated
};
this.save(callback);
},
/**
* Записывает ссылки на загруженные фотографии
* @param {Object} obj Объект ответа от сервера яндекса.
* @param {Function} callback
*/
addPhoto: function(obj, callback) {
var that = this;
this.images.push({
links: {
M: obj.img.M,
L: obj.img.L,
S: obj.img.S,
orig: obj.img.orig
},
title: obj.title,
created: obj.created,
self: obj.links.self,
param: obj.id
});
this.save(function(err, track) {
if (err) console.log(err);
callback(track.images[track.images.length - 1]._id);
});
},
/**
* Добавляет координаты изображения если они есть, в
* противном случае записыват null.
* @param {Array || null} coord
* @param {Number} id
*/
addCoordinates: function(coord, id) {
mongoose.model('Track').findById(this.id, 'images', function(err, track) {
if (err) console.log(err);
image = track.images.id(id);
if (image) {
if (coord !== null) {
var x = parseFloat(coord[0]);
var y = parseFloat(coord[1]);
image.coordinates.push([x, y]);
} else {
image.coordinates.push(null);
}
track.save(function(err){
if (err) console.log(err);
});
}
});
}
};
TrackSchema.statics = {
/**
* Находит треки созданные пользователем
* @param {ObjectId} id
* @param {Function} callback
*/
list: function(id, callback) {
this.findOne({
_id: id
}).populate('_creator', 'name id distance').exec(callback);
}
};
mongoose.model('Track', TrackSchema);
<file_sep>/README.md
Event-Horizon
=============
Для работы необходимо иметь установленную MongoDB.
Установка и запуск приложения:
1. `git clone <EMAIL>:mokcrimea/Event-Horizon.git`
2. `npm install`
3. `npm start`
По умолчанию приложение запускается на 3000 порту.
Для работы требуются ClientID, clientSecret указанные в конфиге (config/config.json) - этой настройки которые дает Яндекс при регистрации приложения. callbackURL - настроен на http://127.0.0.1:3000/auth/yandex/callback, для локальной авторизации. При запуске на внешнем сервере этот параметр надо изменить. Проще создать свое клиентское приложение [тут](https://oauth.yandex.ru/client/new) и изменить параметры в config.json. Для корректной работы клиентского приложения нужны вот такие права:
Удаление альбомов, фотографий и тегов с Яндекс.Фоток
Загрузка новых альбомов и фотографий на Яндекс.Фотки
Просмотр открытых и приватных альбомов и фотографий на Яндекс.Фотках
Адрес электронной почты
Имя пользователя, ФИО, пол
Данное описание отлично подходит для запуска приложения в UNIX платформе. В Windows могут возникнуть проблемы с установкой пакета `libxmljs`.
<file_sep>/models/user.js
/**
* Основные зависимости
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Схема пользователя
*/
var UserSchema = new Schema({
name: { type: String},
email: { type: String},
username: { type: String},
provider: {type: String},
authToken: { type: String},
created: { type: Date, default: Date.now},
tracks: [{ type: Schema.ObjectId, ref: 'Track'}],
yandex: { type: Object}
});
/**
* Mетоды
*/
UserSchema.methods = {
/**
* Записывает AuthToken пользователя
* @param {String} token
* @param {Function} callback
*/
setToken: function(token, callback) {
this.authToken = token;
this.save(callback);
},
/**
* Обновляет поле username в документе пользователя
* @param {String} username
* @param {Function} callback
*/
updateUsername: function(username, callback) {
this.username = username;
this.save(callback);
}
};
UserSchema.statics = {
/**
* Находит треки созданные пользователем
* @param {ObjectId} id
* @param {Function} callback
*/
list: function(id, callback) {
this.findOne({
_id: id
}).populate('tracks', 'name id inform').exec(callback);
}
};
mongoose.model('User', UserSchema);
| 05116816f4fd82f829426636114852f16371aeac | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | mokcrimea/Event-Horizon | 24e0f854b7b12c1e4724bf22f4204a7dfa842510 | 3095c62c9cd73e4fcadb93692674af02622524cd |
refs/heads/main | <repo_name>nathanieltagg/16-puzzle<file_sep>/puzzle.js
// <NAME> (<EMAIL>)
//
// Notes: gotta admit, this was a lot of fun to write.
// submitted to Hopscotch for a code test as first part of job application, Jun 3 2021
// Globals
// Should properly be moved to an object so multiple puzzles can be instantiated.
// Configuration: we can change the size of the puzzle if we want.
const n_x = 4; // These are hard-coded for a 15-tile puzzle, but you can adjust these
const n_y = 4; // Also need to change CSS tile sizes. if you do that.
//
// The tiles are represented by simple objects:
// { val: The number printed on this tile
// ix: <0-3> The current horizontal grid position of this tile
// ix: <0-3> The current vertical grid position of this tile
// elem: div> A JQuery handle to this tile's DOM element.
// }
// We keep these in an array that's sorted only by the puzzle intial configuraton.
var tiles = [];
const n_tiles = n_x*n_y -1;
var tile_width, tile_height;
var space = {ix:n_x-1, iy:n_y-1}; // Empty spot starts in lower right-hand corner.
$(function(){
// create the tiles
// Each tile object
for(var i = 1;i<n_tiles+1;i++) { // note we are indexing by 1, not zero
var elem = $("<div class='tile'></div>");
var tile = {elem, val:i};
elem.text(i);
elem.data("tile",tile);
tiles.push(tile)
$('#puzzle').append(tile.elem);
}
tile_width = $("#puzzle").width()/n_x;
tile_height= $("#puzzle").height()/n_y;
$('#puzzle').on('click','div.tile',tile_clicked);
$("#win").on("click",function(){
$("#win").hide()
reset_puzzle(true);
});
$("#reset").on("click",reset_puzzle);
reset_puzzle(false); // FIXME production: For the purposes of testing, it's useful to have the puzzle start out solved.
});
function reset_puzzle(shuffle)
{
if(shuffle) shuffleArray(tiles);
for(var i=0;i<n_tiles;i++) {
var tile = tiles[i];
tile.ix = i%n_x;
tile.iy = Math.floor(i/n_x);
move_tile(tile);
}
space = {ix:n_x-1, iy:n_y-1}; // Space goes in lower right hand position.
}
// Shuffling
//
// There isn't builtin shuffle methond in javascript, like there is in python,
// One solution is this one:
//
function shuffleArray(array) {
// track pairity
var pairity = 1;
// Randomize array in-place using Durstenfeld shuffle algorithm
// Cribbed from https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
if(i!=j) pairity*=-1; // No swap is even pairity; all else are odd
}
// We want an even number of swaps, to give us an even pairty, which means a solvable. puzzle.
// If we don't have it, just swap the first two elements. (Or move the empty space!)
if(pairity==-1) {
// This was an odd number of swaps
tmp = array[0];
array[0] = array[1];
array[1] = tmp;
}
}
function shake_tile(tile)
{
// Abuse CSS a bit to cause the shake animation in the case of an illegal move.
tile.elem.removeClass("shake");
void tile.elem[0].offsetWidth; // trigger reflow
tile.elem.addClass("shake");
}
function tile_clicked(event) {
// A tile was clicked! This is the core:
var elem = $(event.target);
if(!elem.data("tile")) console.log("Tile clicked with no .data-tile attribute?"); // Sanity check - shouldn't happen.
var hit_tile = elem.data("tile");
// Valid move?
if((hit_tile.ix != space.ix) && (hit_tile.iy != space.iy))
{
shake_tile(hit_tile);
//console.log("invalid move");
return;
}
// Ok, this is a valid move. Figure out which tiles are going to move:
var moved_tiles = [];
var dix=0,diy=0; // delta x,y movement of affected tiles.
if(hit_tile.ix == space.ix) {
// Column shift
if(hit_tile.iy > space.iy) {
// Column shift up
diy = -1;
for(var iy=space.iy+1;iy<=hit_tile.iy;iy++)
moved_tiles.push(find_tile(space.ix,iy));
} else {
// Column shift down
diy = +1;
for(var iy=space.iy-1;iy>=hit_tile.iy;iy--)
moved_tiles.push(find_tile(space.ix,iy));
}
} else {
// Row shift
if(hit_tile.ix > space.ix) {
// row shift left
dix = -1;
for(var ix=space.ix+1;ix<=hit_tile.ix;ix++)
moved_tiles.push(find_tile(ix,space.iy));
} else {
// row shift right
dix = +1;
for(var ix=space.ix-1;ix>=hit_tile.ix;ix--)
moved_tiles.push(find_tile(ix,space.iy));
}
}
// console.log("moving",moved_tiles,dix,diy)
// Set their new ix,iy grid positions, use those to set CSS offsets. Animation will start going after this function finishes.
for(var tile of moved_tiles) {
tile.ix += dix;
tile.iy += diy;
move_tile(tile);
}
space.ix -= dix*moved_tiles.length; // If tiles move right, the space displaces left by the number of tiles.
space.iy -= diy*moved_tiles.length; // ditto up/down
if( check_for_win() ) $('#win').show(); // yay!
}
// Given a grid position, find the tile object
function find_tile(ix,iy)
{
// This is inefficient, but it's only 15 tiles. Dont' let the perfect be the enemy of the good.
// To do this more properly, we could keep an ordered list after every move, or an array-of-arrays to track the grid.
// OR we could store ix,iy in the tile DOM element, then search the DOM
for(var tile of tiles)
if(tile.ix == ix && tile.iy==iy) return tile;
console.log("could not file tile",ix,iy);
}
// Puts the tile screen position so it matches the ix,iy grid coordinate in the tile object.
// Give me the correct screen x,y positions for a tile at this grid location.
function move_tile(tile)
{
var x = tile.ix * tile_width+2.5;
var y = tile.iy * tile_height+2.5;
tile.elem.css("left",x);
tile.elem.css("top",y);
}
// Winning:
function check_for_win()
{
// The empty space must be in the lower-right corner if we're complete, so this is an efficient check.
if(space.ix != n_x-1 || space.iy != n_y-1 ) { console.log("space not in bottom right"); return false;}
// For each grid position, check that the tile is in the right place.
for(var ix=0; ix<n_x; ix++) {
for(var iy=0;iy<n_y; iy++) {
if(ix==n_x-1 && iy==n_y-1) continue; // don't check the space.
var tile = find_tile(ix,iy);
var should_be = iy*n_x + ix +1; // Ordinal value of x,y. Remember value is 1-based not zero-based
if(tile.val != iy*n_x + ix +1) { console.log(ix,iy," is ",tile.val," should be ",iy*n_x + ix+1); return false;}
}
}
return true;
}
//each tile knows it's ix,iy coord.
// Create tiles in positions
// When clicking a tile, compute new positions for all tiles
// Set positions and animate.
// Then check ix,iy against coords to see if you get victory. | 857291d85a8014365f9573ee36c05cc02f48868d | [
"JavaScript"
] | 1 | JavaScript | nathanieltagg/16-puzzle | 91b9f7ff908e34bfe720c6acc2f2ace65539b4ac | 5977787db75da2c715089cc50ec420219f81b983 |
refs/heads/master | <file_sep>module Xliffle
class File
attr_reader :original, :strings, :source_locale, :target_locale, :headers, :datatype
def initialize(original, source_locale, target_locale, options = {})
@strings = []
@headers = []
@original = original
@source_locale = source_locale
@target_locale = target_locale
@datatype = options[:datatype] || 'plaintext'
end
def string(id, source, target, options={})
string = Xliffle::String.new(id, source, target, options)
@strings << string
string
end
def header(type, options = {})
element = Xliffle::Header.create(type, options)
@headers << element
element
end
def to_xliff(xliff)
xliff.file(original: @original, datatype: @datatype, 'source-language' => @source_locale, 'target-language' => @target_locale) do |file|
if headers.any?
file.header do |header|
self.headers.each do |element|
element.to_xliff(header)
end
end
end
file.body do |body|
self.strings.each do |string|
string.to_xliff(body)
end
end
end
end
end
end
<file_sep>require 'xliffle/creator'
require 'xliffle/file'
require 'xliffle/string'
require 'xliffle/note'
require 'xliffle/header'
require 'xliffle/headers/count_group'
module Xliffle
def self.new
Xliffle::Creator.new
end
end
<file_sep>module Xliffle
class Header
def self.create(type, options = {})
# TODO: make this work outside of Rails
"Xliffle::Headers::#{type.to_s.camelcase}".constantize.new(options)
end
def initialize(options={})
end
def type
self.class.name.split('::').last.underscore.gsub('_', '-')
end
def to_xliff(xliff)
xliff.tag!(type, { priority: @priority }, @note)
end
end
end
<file_sep>module Xliffle
module Headers
class CountGroup
attr_reader :name, :counts
def initialize(options={})
@name = options[:name] || 'count'
@counts = []
end
def add_count(type, value)
@counts << {
type: type,
value: value
}
end
def to_xliff(xliff)
xliff.tag!('count-group', {:name => @name}) do |header|
self.counts.each do |element|
header.tag!('count', {'count-type' => element[:type]}, element[:value])
end
end
end
end
end
end
<file_sep>module Xliffle
class Note
attr_reader :note, :priority, :lang, :from
def initialize(note, options={})
@note = note
@priority = options[:priority] || 2
@lang = options[:lang]
@from = options[:from]
end
def to_xliff(xliff)
xliff.tag!('note', { priority: @priority }, @note)
end
end
end
| 555a2134c07ec36f6646d300e96d77a455330e70 | [
"Ruby"
] | 5 | Ruby | translationexchange/xliffle | fe273280dbc9c25bd9a31eed3bedaa0e51530d6b | a901ea12d69ad05a6981d433111cd5f56ceda32d |
refs/heads/master | <file_sep>package com.dhiel.mamuc.nuerkeyboard;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class keyboard extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.input);
}
}
| 409cac2ab612dacb8b3b5d3d83d3e90657c1de9d | [
"Java"
] | 1 | Java | mamuch/JunubKeyboard | 1503e376137d1c4827451bb53c10a51a532f2e5b | 99835962bce6ed65be7274fad832593cee9dc35a |
refs/heads/master | <repo_name>lsc-project/lsc-microsoft-graph-api-plugin<file_sep>/README.md
# Microsoft Graph API plugin
[](https://travis-ci.org/lsc-project/lsc-microsoft-graph-api-plugin)
This a plugin for LSC, using Microsoft Graph API
### Goal
The object of this plugin is to synchronize users from a Microsoft Azure active directory to a referential.
For example it can be used to synchronize the users in an Azure AD to an LDAP repository.
### Configuration
The plugin connects to Microsoft Graph API as a [deamon app](https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-daemon-overview). More information on how to register it on Microsoft Azure can
be found [here](https://docs.microsoft.com/en-us/azure/active-directory/develop/scenario-daemon-app-registration).
The application must have the `Application permission` `User.Read.All` permission granted. The documentation about permissions and consent can be found [here](https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent).
At the time being the plugin only allows to connect to the API using a client secret.
### Usage
There are examples of configuration in the `sample` directory. The `lsc.xml` file describes a synchronization from Microsoft Graph API to an LDAP repository.
The values to configure are:
#### Source service
##### Connection
- `connections.pluginConnection.msGraphApiConnectionSettings.authenticationURL`: The base URL used for authentication (default is https://login.microsoftonline.com/) (optional)
- `connections.pluginConnection.msGraphApiConnectionSettings.usersURL`: The base URL used for operations on users (default is https://graph.microsoft.com) (optional)
- `connections.pluginConnection.msGraphApiConnectionSettings.scope`: The scope url used during authentication (default is https://graph.microsoft.com/.default) (optional)
- `connections.pluginConnection.msGraphApiConnectionSettings.clientId`: The client id for the application
- `connections.pluginConnection.msGraphApiConnectionSettings.clientSecret`: The client secret used to connect to the application
- `connections.pluginConnection.msGraphApiConnectionSettings.tenant`: The Azure AD tenant
##### API parameters
- `tasks.task.pluginSourceService.filter`: (Optional, default none) The filter to use for fetching the list of pivots. For the syntax to use in those filters the syntax can be found [here](https://docs.microsoft.com/en-us/graph/query-parameters#filter-parameter).
- `tasks.task.pluginSourceService.pivot`: (Optional, default `mail`) The field to use as pivot.
- `tasks.task.pluginSourceService.pageSize`: (Optional, default none) The page size used to paginate the results from the graph API. Default is no page size, but the API has a `100` default page size.
- `tasks.task.pluginSourceService.select`: (Optional, default none) The comma separated list of fields to gather when getting the details of a user. The syntax to use can be found [here](https://docs.microsoft.com/en-us/graph/query-parameters#select-parameter). By default the API returns a default set of properties.
The jar of the Microsoft graph API LSC plugin must be copied in the `lib` directory of your LSC installation. Then you can launch it with the following command line:
```
JAVA_OPTS="-DLSC.PLUGINS.PACKAGEPATH=org.lsc.plugins.connectors.msgraphapi.generated" bin/lsc --config /path/to/sample/msgraphapi-to-ldap/ --synchronize users --clean users --threads 5
```
### Packaging
WIP
<file_sep>/src/main/java/org/lsc/plugins/connectors/msgraphapi/MsGraphApiUsersSrcService.java
/*
****************************************************************************
* Ldap Synchronization Connector provides tools to synchronize
* electronic identities from a list of data sources including
* any database with a JDBC connector, another LDAP directory,
* flat files...
*
* ==LICENSE NOTICE==
*
* Copyright (c) 2008 - 2019 LSC Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the LSC Project nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ==LICENSE NOTICE==
*
* (c) 2008 - 2019 LSC Project
* <NAME> <<EMAIL>>
****************************************************************************
*/
package org.lsc.plugins.connectors.msgraphapi;
import static org.lsc.plugins.connectors.msgraphapi.MsGraphApiDao.ID;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.WebApplicationException;
import org.lsc.LscDatasets;
import org.lsc.beans.IBean;
import org.lsc.configuration.PluginConnectionType;
import org.lsc.configuration.TaskType;
import org.lsc.exception.LscServiceCommunicationException;
import org.lsc.exception.LscServiceConfigurationException;
import org.lsc.exception.LscServiceException;
import org.lsc.plugins.connectors.msgraphapi.beans.User;
import org.lsc.plugins.connectors.msgraphapi.generated.MsGraphApiConnectionSettings;
import org.lsc.plugins.connectors.msgraphapi.generated.MsGraphApiUsersService;
import org.lsc.service.IService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
public class MsGraphApiUsersSrcService implements IService {
protected static final Logger LOGGER = LoggerFactory.getLogger(MsGraphApiUsersSrcService.class);
/**
* Preceding the object feeding, it will be instantiated from this class.
*/
private final Class<IBean> beanClass;
private final MsGraphApiUsersService service;
private final MsGraphApiDao dao;
private final MsGraphApiConnectionSettings settings;
public MsGraphApiUsersSrcService(TaskType task) throws LscServiceConfigurationException {
try {
if (task.getPluginSourceService().getAny() == null || task.getPluginSourceService().getAny().size() != 1 || !((task.getPluginSourceService().getAny().get(0) instanceof MsGraphApiUsersService))) {
throw new LscServiceConfigurationException("Unable to identify the msgraphapi service configuration " + "inside the plugin source node of the task: " + task.getName());
}
service = (MsGraphApiUsersService) task.getPluginSourceService().getAny().get(0);
beanClass = (Class<IBean>) Class.forName(task.getBean());
if (task.getPluginSourceService().getConnection() == null || task.getPluginSourceService().getConnection().getReference() == null || ! (task.getPluginSourceService().getConnection().getReference() instanceof PluginConnectionType)) {
throw new LscServiceConfigurationException("Unable to identify the msgraphapi service connection " + "inside the plugin source node of the task: " + task.getName());
}
PluginConnectionType pluginConnectionType = (PluginConnectionType)task.getPluginSourceService().getConnection().getReference();
if (pluginConnectionType.getAny() == null || pluginConnectionType.getAny().size() != 1 || !(pluginConnectionType.getAny().get(0) instanceof MsGraphApiConnectionSettings)) {
throw new LscServiceConfigurationException("Unable to identify the msgraphapi connection settings " + "inside the connection node of the task: " + task.getName());
}
settings = (MsGraphApiConnectionSettings) pluginConnectionType.getAny().get(0);
String token = new MsGraphApiAuthentication()
.authenticate(settings.getTenant(), settings.getAuthenticationURL(), settings.getScope(), settings.getClientId(), settings.getClientSecret())
.getAccessToken();
dao = new MsGraphApiDao(token, settings, service);
} catch (ClassNotFoundException | AuthorizationException e) {
throw new LscServiceConfigurationException(e);
}
}
@Override
public IBean getBean(String pivotAttributeName, LscDatasets pivotAttributes, boolean fromSameService) throws LscServiceException {
LOGGER.debug(String.format("Call to getBean(%s, %s, %b)", pivotAttributeName, pivotAttributes, fromSameService));
if (pivotAttributes.getAttributesNames().size() < 1) {
return null;
}
String pivotAttribute = pivotAttributes.getAttributesNames().get(0);
String pivotValue = pivotAttributes.getStringValueAttribute(pivotAttribute);
if (fromSameService) {
return getBeanFromSameService(pivotAttributeName, pivotAttributes, pivotValue);
} else {
return getBeanForClean(pivotAttributeName, pivotValue);
}
}
private IBean getBeanForClean(String pivotAttributeName, String pivotValue) throws LscServiceException {
try {
Optional<User> maybeUser = dao.getFirstUserWithId(pivotValue);
if (maybeUser.isPresent()) {
return userIdToBean(maybeUser.get().getId());
} else {
return null;
}
} catch (ProcessingException e) {
LOGGER.error(String.format("ProcessingException while getting bean %s/%s (%s)",
pivotAttributeName, pivotValue, e));
LOGGER.error(e.toString(), e);
throw new LscServiceCommunicationException(e);
} catch (NotFoundException e) {
LOGGER.debug(String.format("%s/%s not found", pivotAttributeName, pivotValue));
return null;
} catch (WebApplicationException e) {
LOGGER.error(String.format("WebApplicationException while getting bean %s/%s (%s)",
pivotAttributeName, pivotValue, e));
LOGGER.debug(e.toString(), e);
throw new LscServiceException(e);
} catch (InstantiationException | IllegalAccessException e) {
LOGGER.error("Bad class name: " + beanClass.getName() + "(" + e + ")");
LOGGER.debug(e.toString(), e);
throw new LscServiceException(e);
}
}
private IBean getBeanFromSameService(String pivotAttributeName, LscDatasets pivotAttributes, String pivotValue) throws LscServiceException {
String idValue = pivotAttributes.getStringValueAttribute(ID);
if (idValue == null) {
return null;
}
try {
Map<String, Object> user = dao.getUserDetails(idValue);
return mapToBean(idValue, user);
} catch (ProcessingException e) {
LOGGER.error(String.format("ProcessingException while getting bean %s/%s with id %s (%s)",
pivotAttributeName, pivotValue, idValue, e));
LOGGER.error(e.toString(), e);
throw new LscServiceCommunicationException(e);
} catch (NotFoundException e) {
LOGGER.debug(String.format("%s/%s with id %s not found", pivotAttributeName, idValue, pivotValue));
return null;
} catch (WebApplicationException e) {
LOGGER.error(String.format("WebApplicationException while getting bean %s/%s with id %s (%s)",
pivotAttributeName, pivotValue, idValue, e));
LOGGER.debug(e.toString(), e);
throw new LscServiceException(e);
} catch (InstantiationException | IllegalAccessException e) {
LOGGER.error("Bad class name: " + beanClass.getName() + "(" + e + ")");
LOGGER.debug(e.toString(), e);
throw new LscServiceException(e);
}
}
@VisibleForTesting
IBean mapToBean(String idValue, Map<String, Object> user) throws InstantiationException, IllegalAccessException {
IBean bean = beanClass.newInstance();
bean.setMainIdentifier(idValue);
LscDatasets datasets = new LscDatasets();
user.entrySet().stream()
.forEach(entry -> datasets.put(entry.getKey(), entry.getValue() == null ? new LinkedHashSet<>() : entry.getValue()));
bean.setDatasets(datasets);
return bean;
}
private IBean userIdToBean(String idValue) throws InstantiationException, IllegalAccessException {
IBean bean = beanClass.newInstance();
bean.setMainIdentifier(idValue);
bean.setDatasets(new LscDatasets(ImmutableMap.of("id", idValue)));
return bean;
}
@Override
public Map<String, LscDatasets> getListPivots() throws LscServiceException {
try {
List<User> userList = dao.getUsersList();
Map<String, LscDatasets> listPivots = new HashMap<String, LscDatasets>();
for (User user: userList) {
listPivots.put(user.getValue(), user.toDatasets());
}
return ImmutableMap.copyOf(listPivots);
} catch (ProcessingException e) {
LOGGER.error(String.format("ProcessingException while getting pivot list (%s)", e));
LOGGER.debug(e.toString(), e);
throw new LscServiceCommunicationException(e);
} catch (WebApplicationException e) {
LOGGER.error(String.format("WebApplicationException while getting pivot list (%s)", e));
LOGGER.debug(e.toString(), e);
throw new LscServiceException(e);
}
}
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.lsc.plugins.connectors</groupId>
<artifactId>microsoft-graph-api</artifactId>
<name>LDAP Synchronization Connector for Microsoft graph API</name>
<version>1.1</version>
<description>
This project provides a Microsoft graph API source plugin for LSC
</description>
<url>http://lsc-project.org/</url>
<issueManagement>
<system>github</system>
<url>https://github.com/lsc-project/lsc-microsoft-graph-api-plugin/issues</url>
</issueManagement>
<inceptionYear>2019</inceptionYear>
<developers>
<developer>
<id>rouazana</id>
<name><NAME></name>
<email><EMAIL></email>
<organization>LINAGORA</organization>
<organizationUrl>http://www.linagora.com/</organizationUrl>
<roles>
<role>Developer</role>
</roles>
<timezone>+1</timezone>
</developer>
<developer>
<id>rkowalski</id>
<name><NAME></name>
<email><EMAIL></email>
<organization>LINAGORA</organization>
<organizationUrl>http://www.linagora.com/</organizationUrl>
<roles>
<role>Developer</role>
</roles>
<timezone>+1</timezone>
</developer>
</developers>
<licenses>
<license>
<name>BSD</name>
<url>http://www.opensource.org/licenses/bsd-license.php</url>
</license>
</licenses>
<scm>
<connection>scm:git:git://github.com:lsc-project/lsc-microsoft-graph-api-plugin.git</connection>
<developerConnection>scm:git:<EMAIL>:lsc-project/lsc-microsoft-graph-api-plugin.git</developerConnection>
<url>https://github.com/lsc-project/lsc-microsoft-graph-api-plugin/</url>
</scm>
<build>
<defaultGoal>package</defaultGoal>
<finalName>lsc-microsoft-graph-api-plugin-${project.version}</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.0</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
<executions>
<execution>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.4.3</version>
<configuration>
<encoding>utf-8</encoding>
</configuration>
</plugin>
<plugin>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8</version>
<configuration>
<show>public</show>
<links>
<link>http://java.sun.com/j2se/1.6.0/docs/api/</link>
</links>
<encoding>utf-8</encoding>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>javadoc</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<descriptors>
<descriptor>assembly.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<extensions>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ssh</artifactId>
<version>2.12</version>
</extension>
</extensions>
</build>
<repositories>
<repository>
<id>lsc-site</id>
<url>http://lsc-project.org/maven</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>Codehaus Snapshot</id>
<url>https://nexus.codehaus.org/content/repositories/codehaus-snapshots/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
<pluginRepository>
<id>Codehaus</id>
<url>https://nexus.codehaus.org/content/repositories/releases/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>org.lsc</groupId>
<artifactId>lsc-core</artifactId>
<version>2.1.4</version>
<type>jar</type>
<optional>false</optional>
<exclusions>
<exclusion>
<artifactId>google-collections</artifactId>
<groupId>com.google.collections</groupId>
</exclusion>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
<exclusion>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
</exclusion>
<exclusion>
<groupId>org.forgerock.opendj</groupId>
<artifactId>opendj-server</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>3.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>3.3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>3.3.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.10.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-json-jackson</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.2.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.21.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>testcontainers</artifactId>
<version>1.11.1</version>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
<scope>compile</scope>
</dependency>
</dependencies>
<distributionManagement>
<repository>
<id>lsc-project.org</id>
<url>scp://lsc-project.org:/home/lsc-project/maven</url>
</repository>
<snapshotRepository>
<id>lsc-project.org</id>
<url>scp://lsc-project.org:/home/lsc-project/maven</url>
<uniqueVersion>false</uniqueVersion>
</snapshotRepository>
</distributionManagement>
<ciManagement>
<system>travis</system>
<url>https://travis-ci.org/lsc-project/</url>
</ciManagement>
</project>
<file_sep>/src/test/java/org/lsc/plugins/connectors/msgraphapi/MsGraphApiAuthenticationTest.java
/*
****************************************************************************
* Ldap Synchronization Connector provides tools to synchronize
* electronic identities from a list of data sources including
* any database with a JDBC connector, another LDAP directory,
* flat files...
*
* ==LICENSE NOTICE==
*
* Copyright (c) 2008 - 2019 LSC Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the LSC Project nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ==LICENSE NOTICE==
*
* (c) 2008 - 2019 LSC Project
* <NAME> <<EMAIL>>
****************************************************************************
*/
package org.lsc.plugins.connectors.msgraphapi;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.util.StringUtils;
import org.lsc.plugins.connectors.msgraphapi.beans.AuthenticationResponse;
import com.auth0.jwt.JWT;
class MsGraphApiAuthenticationTest {
private final static String CLIENT_ID = System.getenv("TEST_MS_GRAPH_API_CLIENT_ID");
private final static String CLIENT_SECRET = System.getenv("TEST_MS_GRAPH_API_CLIENT_SECRET");
private final static String TENANT = System.getenv("TEST_MS_GRAPH_API_TENANT");
private final static String AUTHENTICATION_URL = System.getenv("TEST_MS_GRAPH_API_AUTHENTICATION_URL");
private final static String SCOPE = System.getenv("TEST_MS_GRAPH_API_SCOPE");
private final MsGraphApiAuthentication msGraphApiAuthentication;
MsGraphApiAuthenticationTest() {
msGraphApiAuthentication = new MsGraphApiAuthentication();
}
@BeforeAll
static void setup() {
assumeTrue(StringUtils.isNotBlank(CLIENT_ID));
assumeTrue(StringUtils.isNotBlank(CLIENT_SECRET));
assumeTrue(StringUtils.isNotBlank(TENANT));
}
@Test
void shouldObtainValidAccessToken() throws AuthorizationException {
AuthenticationResponse response = msGraphApiAuthentication.authenticate(TENANT, AUTHENTICATION_URL, SCOPE, CLIENT_ID, CLIENT_SECRET);
assertThat(response.getAccessToken()).isNotBlank();
assertThatCode(() -> JWT.decode(response.getAccessToken())).doesNotThrowAnyException();
}
@Test
void shouldThrowIfInvalidTenant() {
assertThatThrownBy(() -> msGraphApiAuthentication.authenticate("NOT_A_TENANT", AUTHENTICATION_URL, SCOPE, CLIENT_ID, CLIENT_SECRET)).isInstanceOf(AuthorizationException.class);
}
@Test
void shouldThrowIfInvalidClientId() {
assertThatThrownBy(() -> msGraphApiAuthentication.authenticate(TENANT, AUTHENTICATION_URL, SCOPE, "NOT_A_CLIENT_ID", CLIENT_SECRET)).isInstanceOf(AuthorizationException.class);
}
@Test
void shouldThrowIfInvalidClientSecret() {
assertThatThrownBy(() -> msGraphApiAuthentication.authenticate(TENANT, AUTHENTICATION_URL, SCOPE, CLIENT_ID, "NOT_A_SECRET")).isInstanceOf(AuthorizationException.class);
}
}
<file_sep>/src/main/java/org/lsc/plugins/connectors/msgraphapi/generated/MsGraphApiConnectionSettings.java
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.11.29 at 11:43:47 AM CET
//
package org.lsc.plugins.connectors.msgraphapi.generated;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="authenticationURL" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="usersURL" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="scope" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="clientId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="clientSecret" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="tenant" type="{http://www.w3.org/2001/XMLSchema}string"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"authenticationURL",
"usersURL",
"scope",
"clientId",
"clientSecret",
"tenant"
})
@XmlRootElement(name = "msGraphApiConnectionSettings", namespace = "http://lsc-project.org/XSD/lsc-microsoft-graph-api-plugin-1.0.xsd")
public class MsGraphApiConnectionSettings {
@XmlElement(namespace = "http://lsc-project.org/XSD/lsc-microsoft-graph-api-plugin-1.0.xsd", required = false)
protected String authenticationURL;
@XmlElement(namespace = "http://lsc-project.org/XSD/lsc-microsoft-graph-api-plugin-1.0.xsd", required = false)
protected String usersURL;
@XmlElement(namespace = "http://lsc-project.org/XSD/lsc-microsoft-graph-api-plugin-1.0.xsd", required = false)
protected String scope;
@XmlElement(namespace = "http://lsc-project.org/XSD/lsc-microsoft-graph-api-plugin-1.0.xsd", required = true)
protected String clientId;
@XmlElement(namespace = "http://lsc-project.org/XSD/lsc-microsoft-graph-api-plugin-1.0.xsd", required = true)
protected String clientSecret;
@XmlElement(namespace = "http://lsc-project.org/XSD/lsc-microsoft-graph-api-plugin-1.0.xsd", required = true)
protected String tenant;
/**
* Gets the value of the authenticationURL property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAuthenticationURL() {
return authenticationURL;
}
/**
* Sets the value of the authenticationURL property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAuthenticationURL(String value) {
this.authenticationURL = value;
}
/**
* Gets the value of the usersURL property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUsersURL() {
return usersURL;
}
/**
* Sets the value of the usersURL property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUsersURL(String value) {
this.usersURL = value;
}
/**
* Gets the value of the scope property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getScope() {
return scope;
}
/**
* Sets the value of the scope property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setScope(String value) {
this.scope = value;
}
/**
* Gets the value of the clientId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClientId() {
return clientId;
}
/**
* Sets the value of the clientId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClientId(String value) {
this.clientId = value;
}
/**
* Gets the value of the clientSecret property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getClientSecret() {
return clientSecret;
}
/**
* Sets the value of the clientSecret property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setClientSecret(String value) {
this.clientSecret = value;
}
/**
* Gets the value of the tenant property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTenant() {
return tenant;
}
/**
* Sets the value of the tenant property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTenant(String value) {
this.tenant = value;
}
}
<file_sep>/src/main/java/org/lsc/plugins/connectors/msgraphapi/beans/AuthenticationResponse.java
/*
****************************************************************************
* Ldap Synchronization Connector provides tools to synchronize
* electronic identities from a list of data sources including
* any database with a JDBC connector, another LDAP directory,
* flat files...
*
* ==LICENSE NOTICE==
*
* Copyright (c) 2008 - 2019 LSC Project
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the LSC Project nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ==LICENSE NOTICE==
*
* (c) 2008 - 2019 LSC Project
* <NAME> <<EMAIL>>
****************************************************************************
*/
package org.lsc.plugins.connectors.msgraphapi.beans;
import org.codehaus.jackson.annotate.JsonCreator;
import org.codehaus.jackson.annotate.JsonProperty;
public class AuthenticationResponse {
private final String tokenType;
private final int expiresIn;
private final int extExpiresIn;
private final String accessToken;
@JsonCreator
public AuthenticationResponse(
@JsonProperty("token_type") String tokenType,
@JsonProperty("expires_in") int expiresIn,
@JsonProperty("ext_expires_in") int extExpiresIn,
@JsonProperty("access_token") String accessToken) {
this.tokenType = tokenType;
this.expiresIn = expiresIn;
this.extExpiresIn = extExpiresIn;
this.accessToken = accessToken;
}
public String getTokenType() {
return tokenType;
}
public int getExpiresIn() {
return expiresIn;
}
public int getExtExpiresIn() {
return extExpiresIn;
}
public String getAccessToken() {
return accessToken;
}
}
| c7efba069d33187cafbbc6794c5155ac15731338 | [
"Markdown",
"Java",
"Maven POM"
] | 6 | Markdown | lsc-project/lsc-microsoft-graph-api-plugin | 2be5f6be6fba963abddb77bec39f40ce3a6db11d | 3324911d3ba904d08f51d09c4f5998562d696830 |
refs/heads/main | <repo_name>Mid-Salmon/ytclipper-1<file_sep>/downloadVideo.js
const videoprocessing = require('./videoprocessing');
process.on('message', async(message) => {
const result = await videoprocessing.downloadVideoAsync(message.url, message.fileName, message.videoName);
process.send(result);
})
// const downloadVideoAsync = async (url, videoPath, videoName) =>
// new Promise(resolve => {
// const video = youtubedl(url);
//
// video.on('info', info => {
// console.log('SERVER -- Download started')
// console.log('SERVER -- filename: ' + info._filename)
// console.log('SERVER -- size: ' + info.size)
// })
//
// video.pipe(fs.createWriteStream(videoPath));
//
// video.on('end', info => {
// resolve(videoName);
// })
// }
// );
// module.exports = {
// downloadVideoAsync,
// }
<file_sep>/README.md
# ytclipper
Simple web application to create clips from youtube videos and download them.
1. Enter YouTube URL
2. Enter start time
3. Enter end time
4. Download Clip
## Built With
- express.js
- handlebars
- fluent-ffmpeg
- youtube-dl
- tailwind css
- toastr
## TODO
- [x] input validation
- [x] let users enter the end time instead of duration
- [x] add loading-screen, or some kind of progress indicator
- [x] do video processing with background workers as its CPU heavy
- [x] add dark mode
- [ ] embed video player into the site
- [ ] let users set start and end time using a slider embedded in the video player
<file_sep>/videoprocessing.js
const youtubedl = require('youtube-dl')
const ffmpeg = require('fluent-ffmpeg')
const fs = require('fs')
const getVideoDurationAsync = (url) => new Promise(resolve => {
youtubedl.getInfo(url, (err, info) => {
'use strict'
if (err) {
throw err
}
resolve(info.duration);
})
})
const downloadVideoAsync = (url, videoPath, videoName) =>
new Promise(resolve => {
const video = youtubedl(url);
video.on('info', info => {
console.log('SERVER - DOWNLOADVIDEOASYNC - Download started')
console.log('SERVER - DOWNLOADVIDEOASYNC - Download filename: ' + info._filename)
console.log('SERVER - DOWNLOADVIDEOASYNC - Download size: ' + info.size)
})
console.log('SERVER - DOWNLOADVIDEOASYNC - Create filestream to: ' + videoPath);
video.pipe(fs.createWriteStream(videoPath));
video.on('end', info => {
console.log('SERVER - DOWNLOADVIDEOASYNC - Downloading video finished');
resolve(videoName);
})
video.on('error', error => {
console.log('SERVER - DOWNLOADVIDEOASYNC - Error occurred while downloading video: ');
console.log(error)
})
}
);
const cutVideoAsync = (fileName, clipName, from, to) =>
new Promise(resolve => {
ffmpeg(fileName).seekInput(from).withDuration(to)
.on('end', function () {
resolve(clipName);
})
.on('error', (error) => {
console.log('SERVER - CUTVIDEOASYNC - Error occurred while cutting video: ');
console.log(error)
})
.save(clipName);
})
module.exports = {
cutVideoAsync,
downloadVideoAsync,
getVideoDurationAsync
}<file_sep>/release.sh
#!/bin/bash
# tmpreaper 5m videos/
# mkdir videos | 2ba8769be74d2008a3154d1318992bc0ae01e0ef | [
"JavaScript",
"Markdown",
"Shell"
] | 4 | JavaScript | Mid-Salmon/ytclipper-1 | 2546cfae4a67ee0357c7efaddc44766129021123 | b793acee5ea5ece11ec1da81d7edbec3c50f13af |
refs/heads/main | <repo_name>birukm61/alx-system_engineering-devops-1<file_sep>/0x00-shell_basics/5-listfilesdigitonly
#!/bin/bash
ls -ltr
<file_sep>/0x00-shell_basics/12-file_type
#!/bin/bash
ls /tmp
| dea3d736418b617b41f03f1a33682eb4eedb9c0d | [
"Shell"
] | 2 | Shell | birukm61/alx-system_engineering-devops-1 | e763a9a0f18392dc02bd57e59ff4d353e2013393 | d3e225f71cbf7d309b11c1e76769099fb30d8019 |
refs/heads/master | <repo_name>aalvesjr/99bottles-exercises<file_sep>/lib/bottles.rb
class Bottles
def verse(number)
"#{first_phrase(number)}\n#{second_phrase(number)}\n"
end
def verses(init, finish)
verses = (finish..init).to_a.reverse.map do |verse_number|
verse(verse_number)
end
verses.join("\n")
end
def song
verses(99, 0)
end
private
def bottle_text(n)
if n <= 0
'no more bottles'
elsif n > 1
"#{n} bottles"
else
"#{n} bottle"
end
end
def take(number)
(number == 1)? 'it' : 'one'
end
def first_phrase(number)
"#{bottle_text(number).capitalize} of beer on the wall, #{bottle_text(number)} of beer."
end
def second_phrase(number)
if number > 0
"Take #{take(number)} down and pass it around, #{bottle_text(number-1)} of beer on the wall."
else
"Go to the store and buy some more, 99 bottles of beer on the wall."
end
end
end
<file_sep>/Rakefile
desc "Run minitest"
task :test do
system("ruby -Ilib:test test/*")
end
task default: :test
| c6440341c43abb7622fed7503e03c3c4bd7e5fb8 | [
"Ruby"
] | 2 | Ruby | aalvesjr/99bottles-exercises | b5a481718fc059702cce024894367f36cdbb9d7b | 8930308c2bad273223e7c564489042c2bb04d78a |
refs/heads/master | <file_sep>import java.util.HashMap;
public class Data {
int dataIndex;
int dataValue;
DataManager site;
HashMap<Transaction, Integer> uncommittedValues = new HashMap<Transaction, Integer>();
long lastCommitTime;
HashMap<Transaction, Long> transactionAccessTime = new HashMap<Transaction, Long>();
public Data(int dataIndex, int dataValue, DataManager site) {
this.dataIndex = dataIndex;
this.dataValue = dataValue;
this.site = site;
lastCommitTime = System.currentTimeMillis();
}
public int getDataValue() {
return dataValue;
}
public void setDataValue(int dataValue) {
this.dataValue = dataValue;
}
public long getLastCommitTime() {
return lastCommitTime;
}
public void setLastCommitTime(long lastCommitTime) {
this.lastCommitTime = lastCommitTime;
}
public HashMap<Transaction, Long> getTransactionAccessTime() {
return transactionAccessTime;
}
public void setTransactionAccessTime(HashMap<Transaction, Long> transactionAccessTime) {
this.transactionAccessTime = transactionAccessTime;
}
public void commit(Transaction t) {
lastCommitTime = System.currentTimeMillis();
if(uncommittedValues.containsKey(t)) {
dataValue = uncommittedValues.get(t);
}
}
public void addAccess(Transaction t) {
transactionAccessTime.put(t, System.currentTimeMillis());
}
public void addValue(Transaction t, int value) {
uncommittedValues.put(t, value);
}
}
<file_sep>import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Every data manager is responsible for one data site
* It handles locks on data items that it houses, and it handles site failure and recovery.
*/
public class DataManager {
public static final boolean FAILED = false;
public static final boolean RUNNING = true;
//The structure containing the data items and their values. The key is the data item index, and the value is the data item value.
HashMap<Integer, Data> data = new HashMap<Integer, Data>();
HashMap<Integer, Data> failedData = new HashMap<Integer, Data>();
//The lock table structure
//The key is the data item
//The value is an ArrayList of all the transactions and lock types they hold. ArrayList is used to preserve the order
HashMap<Integer, ArrayList<LockTuple>> lockTable = new HashMap<Integer, ArrayList<LockTuple>>();
int siteId;
boolean status;
long lastRecovery;
public DataManager(int i) {
this.siteId = i;
status = RUNNING;
lastRecovery = System.currentTimeMillis();
lockTable = new HashMap<Integer, ArrayList<LockTuple>>();
}
public void addItem(int item, int value) {
data.put(item, new Data(item, value, this));
failedData.put(item, new Data(item, value, this));
}
public void deleteItem(int item) {
if(data.containsKey(item)) {
data.remove(item);
}
}
/**
* Update an item at commit time
* If the item is a duplicated item after the site recovery, it "removes" it from the failed data list
*
* @param item
* @param value
* @param t
* @return
*/
public boolean updateItem(int item, int value, Transaction t) {
if(data.containsKey(item) && lockTable.containsKey(item)) {
if(lockTable.get(item).get(0).transaction == t.transactionID && lockTable.get(item).get(0).lockType == LockTuple.WRITE) {
data.get(item).setDataValue(value);
if(failedData.get(item) == null)
failedData.put(item, new Data(item, value, this));
else
failedData.get(item).setDataValue(value);
lockTable.get(item).remove(0);
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* a site failure will erase its lock table, and will cause all the transactions that have interacted with it
* previously to abort
*
* @throws Exception
*/
public void fail() throws Exception {
if(status == RUNNING) {
lockTable = new HashMap<Integer, ArrayList<LockTuple>>();
status = FAILED;
System.out.println("Site " + siteId + " failed.");
Driver.driver.transactionManager.siteFail(this);
} else {
System.out.println("Site " + siteId + " is already failed.");
}
}
/**
* When a site recovers, it makes the data entry that can only be found on it available for reads and writes immediately.
* Other data items are set to be failed data items until their values are committed by a write from a transaction
*/
public void recover() {
if(status == FAILED) {
status = RUNNING;
lastRecovery = System.currentTimeMillis();
System.out.println("Site " + siteId + " recovered.");
HashMap<Integer, Boolean> replicatedData = new HashMap<Integer, Boolean>();
for (Map.Entry<Integer, Data> integerIntegerEntry : data.entrySet()) {
replicatedData.put(integerIntegerEntry.getKey(), false);
}
for (DataManager dataSite : Driver.driver.dataSites) {
if (dataSite != this) {
for (Map.Entry<Integer, Data> integerIntegerEntry : dataSite.data.entrySet()) {
if (replicatedData.containsKey(integerIntegerEntry.getKey())) {
replicatedData.put(integerIntegerEntry.getKey(), true);
}
}
}
}
for (Map.Entry<Integer, Data> entry : data.entrySet()) {
if (replicatedData.get(entry.getKey())) {
failedData.put(entry.getKey(), null);
} else {
failedData.put(entry.getKey(), entry.getValue());
}
}
} else {
System.out.println("Site " + siteId + " is already running.");
}
}
//print all the values that are on this site
public void dump() {
for (Integer dataItem : data.keySet()) {
System.out.print("x" + dataItem + "." + siteId + " = " + data.get(dataItem).getDataValue());
if(failedData.get(dataItem) != null) {
System.out.println("");
} else {
System.out.println(" not available for read until a write command is committed");
}
}
System.out.println();
}
//print the value of this particular data item on this site
public boolean dump(int dataItem) {
if (data.containsKey(dataItem)) {
System.out.print("x" + dataItem + "." + siteId + " = " + data.get(dataItem).getDataValue());
if(failedData.get(dataItem) != null) {
System.out.println("");
} else {
System.out.println(" not available for read until a write command is committed");
}
return true;
} else {
return false;
}
}
@Override
public String toString() {
String statusOutput = "Site " + siteId + " is " + (status == FAILED ? "failed" : "running");
for (Integer integer : lockTable.keySet()) {
statusOutput += "\n" + "x" + integer;
for (LockTuple lockTuple : lockTable.get(integer)) {
statusOutput += "\t" + lockTuple.toString();
}
}
return statusOutput;
}
}
| 97ecd30e6cea206a3554259b39b51ae165ff291d | [
"Java"
] | 2 | Java | dima-taji/RepCRec | 97ea2be36b45a2b0c228ab975d09fb0fb37d312a | c14b9d5cedcb7c34b6f1c7fbbdf521252e9e9f14 |
refs/heads/master | <repo_name>Miao-cc/dockerHub<file_sep>/pulsarENV/docker-compose.yml
version: '2'
services:
dspsr-fast:
build: .
shm_size: 16gb
container_name: pulsar_env
volumes:
- /tmp/.X11-unix:/tmp/.X11-unix:ro
environment:
- DISPLAY=$DISPLAY
hostname: localhost
expose:
- "22"
ports:
- "2222:22/tcp"
image: "pulsar-env:base"
#command: "/usr/sbin/sshd -D"
tty: false
<file_sep>/README.md
# docker images for fast pulsar searching and timing
## how to create
1. create pulsarENV
2. create pulsarSEARCH
3. create pulsarTIMING
## Notes
1. pulsarENV
This image is for the base environment. We installed the useful softwate and
python module.
2. pulsarSEARCH
This image is for pulsar search. We installed psrcat, tempo, ubc_AI and presto-3.0.1.
3. pulsarTIMING
This image is for pulsar timing. We installed tempo2, psrchive and dspsr.
Contained pulsar search software also.
4. some example
docker run -it -p 2223:22 -v ./:/work --name fast_pulsar_env /bin/bash pulsar-env:base
docker run -it -p 2223:22 -v ./:/work --name fast_pulsar_search fast_psr:search /bin/bash
docker run -it -p 2224:22 -v ./:/work --name fast_pulsar_timing fast_psr:timing /bin/bash
<file_sep>/pulsarENV/start.py
#!/usr/bin//python
import os
from subprocess import Popen, PIPE, check_call
#start up presto service
check_call(["docker-compose","up","-d"])
p = Popen(["docker","ps","-aq"],stdout=PIPE,stderr=PIPE)
p.wait()
#copy public keys into root and psr user directories
#container = "presto"
#print("docker cp ~/.ssh/id_rsa.pub %s:/root/.ssh/authorized_keys"%container)
#os.system("docker cp ~/.ssh/id_rsa.pub %s:/root/.ssh/authorized_keys"%container)
#print("docker cp ~/.ssh/id_rsa.pub %s:/home/psr/.ssh/authorized_keys"%container)
#os.system("docker cp ~/.ssh/id_rsa.pub %s:/home/psr/.ssh/authorized_keys"%container)
#print("docker cp ./prestoall %s:/home/psr/software/presto/bin/"%container)
#os.system("docker cp ./prestoall %s:/home/psr/software/presto/bin/"%container)
#print("docker cp ./threadit.py %s:/home/psr/software/presto/lib/python/"%container)
#os.system("docker cp ./threadit.py %s:/home/psr/software/presto/lib/python/"%container)
#print("docker cp ./obsys.dat %s:/home/psr/software/tempo/"%container)
#os.system("docker cp ./obsys.dat %s:/home/psr/software/tempo/"%container)
#print("docker cp ./misc_util.c %s:/home/psr/software/presto/src"%container)
#os.system("docker cp ./misc_util.c %s:/home/psr/software/presto/src/"%container)
<file_sep>/pulsarSEARCH/README.md
We had installed psrcat, tempo, presto-3.0.1, ubc_AI
# build pulsar base image
docker build -f Dockerfile_fast.search -t fast_psr:search .
# create container
./start.py docker-compose.yml
Or
docker run -it -p 2223:22 -v ./:/work --name fast_pulsar_search fast_psr:search /bin/bash
## login to the container
ssh -X -p 2223 psr@localhost
passwd: psr
## Note:
We had editted the $PRESTO/src/sigproc_fb.c for FAST filterbank data.
In this image, telescope_id 9 is FAST not ATA.
--------------------------------------------------------------------------------
All this will need root
So login root by
docker exec -it container-name /bin/bash
######
There will some errors when login in
1. X11 forwarding request failed on channel 0
https://www.cyberciti.biz/faq/how-to-fix-x11-forwarding-request-failed-on-channel-0/
In Ubuntu is not 'sshd' but 'ssh'
So please run
/etc/init.d/ssh reload
2. "X11 proxy: wrong authorisation protocol attempted"
cp /home/psr/.Xauthority /root/
<file_sep>/pulsarENV/README.md
1 pulsarENV
We had installed python environment and linux environment for puslar search
and timing.
# build pulsar base image
docker build -f Dockerfile_pulsar.env -t pulsar-env:base .
# create container
./start.py docker-compose.yml
Note:
If you want to build this image. You need to download the python module
pakages.
mkdir modulePy
pip download -d modulePy -r pythonENV.txt
<file_sep>/pulsarTIMING/README.md
We had installed psrcat, tempo, presto-3.0.1, tempo2, psrchive, dspsr
# build pulsar base image
docker build -f Dockerfile_fast.timing -t fast_psr:timing .
# create container
./start.py docker-compose.yml
Or
docker run -it -p 2224:22 -v ./:/work --name fast_pulsar_timing fast_psr:timing /bin/bash
## login to the container
ssh -X -p 2224 psr@localhost
passwd: psr
Note:
If you want to create this image, you need to copy the fast2gps.clk to this
folder.
--------------------------------------------------------------------------------
All this will need root
So login root by
docker exec -it container-name /bin/bash
######
There will some errors when login in
1. X11 forwarding request failed on channel 0
https://www.cyberciti.biz/faq/how-to-fix-x11-forwarding-request-failed-on-channel-0/
In Ubuntu is not 'sshd' but 'ssh'
So please run
/etc/init.d/ssh reload
2. "X11 proxy: wrong authorisation protocol attempted"
cp /home/psr/.Xauthority /root/
| 49d659b1d509b4e01c3cd38ec6efa10c85b38e86 | [
"Markdown",
"Python",
"YAML"
] | 6 | YAML | Miao-cc/dockerHub | d80b95d409db7df65228b4f747b0ff3845f77c28 | 9f0b9bb5e7dac4144e71d40655b098cdcafee1f1 |
refs/heads/master | <repo_name>Skymirrh/Simple-pLANner<file_sep>/README.md
Simple pLANner
==============
A simple LAN party planning tool using Django.
Players and LAN party planning system, with registration and comments.
Players register on the website and then can register to/comment on LAN party
events created by the admin(s).
Who's that for?
---------------
If you're a small LAN party club, organizing several LAN parties, in need of a
simple tool to plan out your events, then this is for you :)
It will help you keep track of your club members and organize your LAN parties
easily, all you have to do is set up the website, ask your members to register,
and create events!
When an event is created, a mail will be sent to your members to let them know
they can register.<file_sep>/lan_planner/models.py
# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
class LanParty(models.Model):
theme = models.CharField(max_length=42)
date_added = models.DateTimeField()
text = models.TextField(null=True)
players = models.ManyToManyField(User,
through='Registration',
related_name="lan_party_registrations")
comments = models.ManyToManyField(User,
through='Comment',
related_name="lan_party_comments")
def __unicode__(self):
return "Soirée {} du {}".format(self.theme, self.date)
class Registration(models.Model):
date_joined = models.DateTimeField(auto_now_add=True)
player = models.ForeignKey(User)
lan_party = models.ForeignKey(LanParty,
related_name="registration_lan_party")
def __unicode__(self):
return "{} est inscrit à {}".format(self.player, self.lan_party)
class Comment(models.Model):
text = models.TextField(null=False)
date_added = models.DateTimeField(auto_now_add=True)
player = models.ForeignKey(User)
lan_party = models.ForeignKey(LanParty, related_name="comment_lan_party")
def __unicode__(self):
return self.text | 6abdec4b0ce79a0c5f681639f0fb1d8e9ebf48e3 | [
"Markdown",
"Python"
] | 2 | Markdown | Skymirrh/Simple-pLANner | 520e2dcb63272c89266ff03e21fa639a4c905275 | 4e7f31e7ed90e4a8c6d2c1e258982829caada57b |
refs/heads/master | <file_sep><?php
namespace AppBundle\Service;
class Utils
{
public function generateSlug($name)
{
return strtolower(preg_replace('/\s+/', '-', $name));
}
}
<file_sep><?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
class ProjectType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name')
->add('description')
->add('status',ChoiceType::class,array(
"choices" => array(
"En cours" => "waiting",
"Terminé" => "ended"
)
))
->add('file',null,["required" => false]);
}/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Project'
));
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_project';
}
}
| 7ea175c26d7e19da945d0a1465c87af32f7c03eb | [
"PHP"
] | 2 | PHP | MaximeDetaille/kennedy | d2443e4cf469592ae0cca4b2348d6a553b2a5dd3 | 06151285bb6ddcbe87c1042c3611c963b0e054e0 |
refs/heads/main | <repo_name>charlestanev/Functions-Exercise<file_sep>/8. Perfect Number.js
// Write a function that receive a number and return if this number is perfect or NOT.
// A perfect number is a positive integer that is equal to the sum of its proper positive divisors. That is the sum of its positive divisors excluding the number itself (also known as its aliquot sum).
function perfectNumber(integer) {
let arrayOfNums = findDivisors(integer);
sumOfDivisors(arrayOfNums);
if (sumOfDivisors(arrayOfNums) === integer) {
console.log('We have a perfect number!');
} else {
console.log(`It's not so perfect.`);
}
function findDivisors(num) {
let arrayOfDivisors = [];
for (let i = 1; i <= Math.floor(num / 2); i++) {
if (num % i === 0) {
arrayOfDivisors.push(i);
}
}
return arrayOfDivisors;
}
function sumOfDivisors(array) {
let sum = 0;
for (let i = 0; i < array.length; i++) {
sum += array[i];
}
return sum;
}
}
perfectNumber(
1236498
);<file_sep>/2. Add and Subtract.js
// You will receive three integer numbers.
// Write a function sum() to get the sum of the first two integers and subtract() function that subtracts the third integer from the result.
function аddАndSubtract(x, y, z) {
let sum = (a, b) => a + b;
let substact = (a, b) => a - b;
return substact(sum(x, y), z);
}
аddАndSubtract(
42,
58,
100
)<file_sep>/1. Smallest of Three Numbers.js
// Write a function which receives three integer numbers to print the smallest. Use appropriate name for the function.
function smallestOfThree(x, y, z) {
let smallestNumber = Number.MAX_SAFE_INTEGER;
function getSmaller(n) {
if (n < smallestNumber) {
smallestNumber = n;
}
}
for (const n of arguments) {
getSmaller(n);
}
return smallestNumber;
}
smallestOfThree(
600,
342,
123
);<file_sep>/10. Factorial Division.js
// Write a function that receives two integer numbers. Calculate factorial of each number. Divide the first result by the second and print the division formatted to the second decimal point.
function factorialDiv(x, y) {
function factorial(n) {
let f = 1;
for (let i = 1; i <= n; i++) {
f *= i;
}
return f;
}
return (factorial(x) / factorial(y)).toFixed(2);
}
factorialDiv(
5, 2
);<file_sep>/9. Loading Bar.js
// You will receive a single number between 0 and 100 which is divided with 10 without residue (0, 10, 20, 30...).
// Your task is to create a function that visualize a loading bar depending on that number you have received in the input.
function loadingBar(n) {
function fullRow(n) {
return '%'.repeat(n / 10);
}
function emptyRow(n) {
return '.'.repeat(10 - n / 10);
}
let result = '';
if (n === 100) {
result = `100% Complete!\n` + `[${fullRow(n)}]`
} else {
result = `${n}% [${fullRow(n)}${emptyRow(n)}]\nStill loading...`
}
return result;
}
loadingBar(
30
);
// 30% [%%%.......]
// Still loading...
// 100% Complete!
// [%%%%%%%%%%]<file_sep>/3. Characters in Range.js
// Write a function that receives two characters and prints on a single line all the characters in between them according to the ASCII code. Keep in mind that the second character code might be before the first one inside the ASCII table.
function charsInRange(a, b) {
let first = a.charCodeAt();
let second = b.charCodeAt();
function charsInLine(x, y) {
let line = '';
for (let i = x + 1; i < y; i++) {
line += String.fromCharCode(i) + ' ';
}
return line;
}
return first > second ? charsInLine(second, first) : charsInLine(first, second);
}
charsInRange(
'#',
':'
);<file_sep>/5. Palindrome Integers.js
// A palindrome is a number which reads the same backward as forward, such as 323 or 1001. Write a function which receives an array of positive integer and checks if each integer is a palindrome or not.
function palindrome(arr) {
function isPalindrome(n) {
let reversedN = n.toString().split('').reverse().join('');
return Number(reversedN) === n ? true : false;
}
let printLines = '';
for (const n of arr) {
printLines += isPalindrome(n) + '\n';
}
return printLines;
}
palindrome(
[32, 2, 232, 1010]
);<file_sep>/README.md
# Functions-Exercise
Functions Exercise
<file_sep>/6. Password Validator.js
// Write a function that checks if a given password is valid. Password validations are:
// • The length should be 6 - 10 characters (inclusive)
// • It should consists only of letters and digits
// • It should have at least 2 digits
// If a password is valid print "Password is valid".
// If it is NOT valid, for every unfulfilled rule print a message:
// • "Password must be between 6 and 10 characters"
// • "Password must consist only of letters and digits"
// • "Password must have at least 2 digits"
function passValidator(pass) {
function passLength(str) {
if (str.length >= 6 && str.length <= 10) {
return '';
} else {
return `Password must be between 6 and 10 characters\n`;
}
}
function onlyLettersAndDigits(str) {
let isLetterDigit = true;
for (const char of str) {
let code = char.charCodeAt();
if (code < 48 || code > 57 && code < 65 || code > 90 && code < 97 || code > 122) {
isLetterDigit = false;
}
}
return isLetterDigit ? '' : `Password must consist only of letters and digits\n`;
}
function twoDigits(str) {
let count = 0;
for (const char of str) {
let code = char.charCodeAt();
if (code >= 48 && code <= 57) {
count++;
}
}
if (count >= 2) {
return '';
} else {
return `Password must have at least 2 digits\n`;
}
}
let result = '';
result = passLength(pass) + onlyLettersAndDigits(pass) + twoDigits(pass);
return result ? result : `Password is valid`;
}
passValidator(
'<PASSWORD>'
);<file_sep>/7. NxN Matrix.js
// Write a function that receives a single integer number n and prints nxn matrix with that number.
function matrix(num) {
let matrixArray = createNxNMatrix(num);
printMatrix(matrixArray);
function createNxNMatrix(number) {
let zeroMatrix = [];
for (let i = 0; i < number; i++) {
zeroMatrix[i] = [];
for (let j = 0; j < number; j++) {
zeroMatrix[i][j] = number;
}
}
return zeroMatrix;
}
function printMatrix(array) {
for (let i = 0; i < array.length; i++) {
let row = '';
for (let j = 0; j < array.length; j++) {
if (j < array.length - 1) {
row += array[i][j] + ' ';
} else {
row += array[i][j];
}
}
console.log(row);
}
}
}
matrix(
7
); | 84e6aab11f13d118e0f98e729e61b002ff247572 | [
"JavaScript",
"Markdown"
] | 10 | JavaScript | charlestanev/Functions-Exercise | 9602ed8ff5c59583045c403bcb4d5d8b0d9784c6 | 876c341266361b13c69d704eaa9b49389459438c |
refs/heads/master | <file_sep># Ionic Contact app
[](https://www.linkedin.com/in/charles-ligony-893177134/)
***
This app is an exercise to understand how ionic can be used
You can't use this app because there is no database.
___The goal:___
- Understand how to use ionic
- create an app in one week
***
___Specification:___
- Back : `php`
- Front : `Angular Ionic` : `html` + `css` + `ts`
I use easyPHP for the database with this two table :
***
___Form of the BDD:___
CONTACT
<table>
<tr>
<td><b>id</b></td>
<td>first_name</td>
<td>last_name</td>
<td>tel</td>
</tr>
<tr>
<td>1</td>
<td>Smith</td>
<td>James</td>
<td>012345678</td>
</tr>
</table>
USER
<table>
<tr>
<td><b>user</b></td>
<td>pasword</td>
</tr>
<tr>
<td>root</td>
<td>root</td>
</tr>
</table>
_(the data are an exemple)_
<file_sep>import {HttpClient, HttpHeaders} from "@angular/common/http";
export class DAO {
/**
* insert new data in contact database
*/
public static createEntry(http: HttpClient, nom : string, prenom: string, tel:string) : void {
let baseURI : string = "http://127.0.0.1/ionic-contact-app/";
let headers: any = new HttpHeaders({'ContentType': 'json', responseType: 'text'}),
options: any = {
"key": "create",
"first_name": nom,
"last_name": prenom,
"tel": tel,
},
url: any = baseURI + "manage-data.php";
http.post(url, JSON.stringify(options), headers)
.subscribe((data: any) => {
console.log(JSON.parse(data));
// If the request was successful notify the user
});
}
/**
* update data in contact database
*/
public static updateEntry(http: HttpClient, id: number, nom : string, prenom: string, tel:string) : void {
let baseURI: string = "http://localhost/ionic-contact-app/";
let headers: any = new HttpHeaders({'ContentType': 'application/json', responseType: 'json'}),
options: any = {
"key": "update",
"id": id,
"first_name": nom,
"last_name": prenom,
"tel": tel
},
url: any = baseURI + "manage-data.php";
http.post(url, JSON.stringify(options), headers)
.subscribe((data: any) => {
// If the request was successful notify the user
});
}
/**
* verify user and password in DB
*/
public static verifyPasword(http: HttpClient, user: string, pasword: string) : boolean {
let baseURI : string = "http://localhost/ionic-contact-app/";
let headers: any = new HttpHeaders({responseType: 'json'}),
options: any = {'user': user, 'pasword': pasword},
url: any = baseURI + "pasword.php";
http.post(url, options, headers)
.subscribe((data: any) => {
return (data === '1');
});
return false;
}
}<file_sep>export class Contact {
id: number;
nom: string;
prenom: string;
num: string;
constructor(id:number, nom: string, prenom: string, num: string) {
this.id = id;
this.nom = nom;
this.prenom = prenom;
this.num = num;
}
}<file_sep>import {Component, ViewChild} from '@angular/core';
import {NavController, ToastController, LoadingController} from 'ionic-angular';
import {HomePage} from "../home/home";
import {HttpClient} from "@angular/common/http";
// import {DAO} from "../../other/dao";
@Component({
selector: 'page-connection',
templateUrl: 'connection.html'
})
export class ConnectionPage {
@ViewChild('username') user;
@ViewChild('password') psw;
constructor(public navCtrl: NavController,
private toastCtrl: ToastController,
private loadingCtrl: LoadingController,
public http: HttpClient) {
}
/**
* a error that appear on the sreen if the user or the password in incorrect
*/
showToast() {
const toast = this.toastCtrl.create({
message: 'Wrong password and user',
position: 'bottom',
duration: 2000
});
toast.present();
}
/**
* a false waiting page before seing the connection result
*/
presentLoading() {
const loader = this.loadingCtrl.create({
content: "Please wait...",
duration: 100
});
loader.present();
}
/** verify the Identity of the user
* if he exist in the DB we alow hiw to see the users
* if not we send him a message
*/
signIn() {
//TODO -- remove it when api is done
this.navCtrl.push(HomePage);
this.presentLoading();
/*if(DAO.verifyPasword(this.http, this.user.value, this.psw.value)) {
this.navCtrl.push(HomePage);
} else {
this.showToast();
}*/
}
}
<file_sep>import {Component} from '@angular/core';
import {AlertController, NavController, ToastController} from 'ionic-angular';
import {Contact} from "../../other/model";
import {ConnectionPage} from "../connection/connection";
import {HttpClient} from "@angular/common/http";
import {DAO} from "../../other/dao";
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
items: Array<Contact> = [];
constructor(public navCtrl: NavController,
private alertCtrl: AlertController,
private toastCtrl: ToastController,
public http: HttpClient) {
}
/**
* Triggered when template view is about to be entered
* Returns and parses the PHP data through the load() method
*/
ionViewWillEnter() : void {
this.load();
}
/**
* Retrieve the JSON encoded data from the remote server
* Using Angular's Http class and an Observable - then
* assign this to the items array for rendering to the HTML template
*/
load() : void {
this.items = [];
this.http
.get('http://127.0.0.1/ionic-contact-app/retrieve-data.php')
.subscribe((data : any) => {
for (let item of data) {
this.items.push(new Contact(item.id, item.first_name, item.last_name, item.tel));
}
},
(error : any) => {
console.dir(error);
});
}
/**
* insert or update data
*/
public add(id:number, nom :string, prenom :string, num :string) {
const place = this.deepIndexOf(this.items, (new Contact(id, nom, prenom, num)));
console.log(id);
const prompt = this.alertCtrl.create({
title: 'Login',
message: "Enter a name for this new album you're so keen on adding",
inputs: [
{
name: 'nom',
placeholder: 'Nom',
value: nom
},
{
name: 'prenom',
placeholder: 'Prenom',
value: prenom,
},
{
name: 'num',
placeholder: 'Telephone',
value: num,
},
],
buttons: [
{
text: 'Cancel'
},
{
text: 'Save',
handler: data => {
if (data.nom == '' || data.prenom == '' || data.num == ''){
this.showToastInfo();
return false;
} else {
try {
if (place === -1) {
DAO.createEntry(this.http, data.nom, data.prenom, data.num);
this.load();
} else {
DAO.updateEntry(this.http, data.id, data.nom, data.prenom, data.num);
this.load();
}
} catch (e) {
this.showToastError();
}
}
}
}
]
});
prompt.present();
}
/**
* disconnect to the app
*/
public goConnectionPage() {
this.navCtrl.popTo(ConnectionPage);
}
/**
* inform the user that some fields are empty
*/
showToastInfo() {
const toast = this.toastCtrl.create({
message: 'you must fill all fields',
position: 'bottom',
duration: 2000
});
toast.present();
}
/**
* inform the user that an error in back appear
*/
showToastError() {
const toast = this.toastCtrl.create({
message: 'Something went wrong :(',
position: 'bottom',
duration: 2000
});
toast.present();
}
/**
* deeper than findIndex
**/
private deepIndexOf(arr, obj) {
return arr.findIndex(function (cur) {
return Object.keys(obj).every(function (key) {
return obj[key] === cur[key];
});
});
}
}
| e59fe8abdc734123630ccd8408569d14b3ddc173 | [
"Markdown",
"TypeScript"
] | 5 | Markdown | CharlesLgn/ionic-contact-app | 3801cc1b437b984028a47621162f378dbb9e02b8 | 4e590179b2bbbeb89c5254dedcdada1df01a9ee8 |
refs/heads/master | <repo_name>mkbasic/MathQuiz<file_sep>/README.md
# MathQuiz
A simple math game quizzing on addition, subtraction, multiplication, and division.
<a href="https://imgflip.com/gif/2n2zle"><img src="https://i.imgflip.com/2n2zle.gif" title="made at imgflip.com"/></a>
<file_sep>/MathQuiz.py
import random
play_again = "y"
operator = ""
questions = 0
correct = 0
total_correct = 0
total_questions = 0
def addition():
global correct
num1 = random.randint(1,20)
num2 = random.randint(1,20)
print (num1, "+", num2)
while True: #error handling of invalid responses
try:
answer = int(input())
break
except ValueError:
print ("Please enter a valid answer...")
if answer == num1 + num2:
print ("Correct!")
correct = correct + 1
else:
print ("Sorry!")
def subtraction():
global correct
num1 = random.randint(1,20)
num2 = random.randint(1,20)
if num1 > num2:
print (num1, "-", num2)
while True: #error handling of invalid responses
try:
answer = int(input())
break
except ValueError:
print ("Please enter a valid answer...")
if answer == num1 - num2:
print ("Correct!")
correct = correct + 1
else:
print ("Sorry!")
else:
print (num2, "-", num1)
while True: #error handling of invalid responses
try:
answer = int(input())
break
except ValueError:
print ("Please enter a valid answer...")
if answer == num2 - num1:
print ("Correct!")
correct = correct + 1
else:
print ("Sorry!")
def multiplication():
global correct
num1 = random.randint(1,12)
num2 = random.randint(1,12)
print (num1, "*", num2)
while True: #error handling of invalid responses
try:
answer = int(input())
break
except ValueError:
print ("Please enter a valid answer...")
if answer == num1 * num2:
print ("Correct!")
correct = correct + 1
else:
print ("Sorry!")
def division():
global correct
num1 = random.randint(1,100)
num2 = random.randint(1,100)
while num1 % num2 != 0 or num1 == num2 or num2 == 1:
num1 = random.randint(1,100)
num2 = random.randint(1,100)
if num1 > num2:
print (num1, "/", num2)
while True: #error handling of invalid responses
try:
answer = int(input())
break
except ValueError:
print ("Please enter a valid answer...")
if answer == num1 / num2:
print ("Correct!")
correct = correct + 1
else:
print ("Sorry!")
print ("Welcome to Math Quiz!")#opening title
while play_again == "y":
print ("Select Addition(A), Subtraction(S), Multiplication(M), or Division(D)")
operator = input().lower()
print ("")#skip line after user's choice
while operator != "a" and operator != "s" and operator != "m" and operator != "d":
print ("Please enter a valid option.")
print ("Select Addition(A), Subtraction(S), Multiplication(M), or Division(D)")
operator = input().lower()
print ("")#skip line after user's choice
while questions < 5:#limits the number of questions per round
if operator == "a":
addition()
print ("")
questions = questions + 1
elif operator == "s":
subtraction()
print ("")
questions = questions + 1
elif operator == "m":
multiplication()
print ("")
questions = questions + 1
elif operator == "d":
division()
print ("")
questions = questions + 1
print ("You got", correct, "out of 5!")
total_correct = total_correct + correct
total_questions = total_questions + questions
print ("Total:", total_correct, "out of", total_questions)
questions = 0
correct = 0
print ("Would you like to play again? N for No, Y for Yes: ")
play_again = input().lower()
print ("Thank you for playing!")
input()
| 7d038f8908deeb88749127779a1f4109d9da57ad | [
"Markdown",
"Python"
] | 2 | Markdown | mkbasic/MathQuiz | 9b465e41538a581b357cd53efaaac14ebb2c3ca3 | 2b53eaa9f6c549043912a8682cdf1bc8734af333 |
refs/heads/master | <file_sep>//
// AnimationManager.h
// AdvancedUISDKUseAge
//
// Created by kong on 2017/12/7.
// Copyright © 2017年 konglee. All rights reserved.
//
//#ifndef __AdvancedUISDKUseAge__AnimationManager__
//#define __AdvancedUISDKUseAge__AnimationManager__
#import <iostream>
namespace AnimationManager
{
template <typename T>
T& GetMax(T& a, T& b)
{
if (a < b)
{
return b;
}
return a;
}
int abc;
template<typename T>
void DisplayResult(T& t1, T& t2)
{
std::cout<< GetMax(t1, t2)<< std::endl;
}
typedef int (*fun) (int a);
typedef int AFun (int b);
fun funC;
int funB(int b)
{
return b;
}
void getValue(void)
{
funC = funB;
int c = (*funC)(10);
std::cout << "c = " << c <<std::endl;
AFun *funD = funB;
int d = funD(32);
std::cout << "d = " << d <<std::endl;
}
struct job
{
char name[40];
int age;
double salary;
};
template <> void DisplayResult<job>(job& j1, job& j2)
{
double temp1;
int age1;
age1 = j1.age;
temp1 = j1.salary;
j1.age = j2.age;
j1.salary = j2.salary;
j2.age = age1;
j2.salary = temp1;
}
}
<file_sep>//
// defineDocument.h
// AdvancedUISDKUseAge
//
// Created by konglee on 2017/11/17.
// Copyright © 2017年 konglee. All rights reserved.
//
#ifndef defineDocument_h
#define defineDocument_h
#define KWidth [UIScreen mainScreen].bounds.size.width
#define KHeight [UIScreen mainScreen].bounds.size.height
#endif /* defineDocument_h */
<file_sep>
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
target 'AdvancedUISDKUseAge' do
pod 'AFNetworking'
pod 'FMDB'
pod 'SDWebImage'
end
<file_sep>//
// AnimationDataManager.hpp
// AdvancedUISDKUseAge
//
// Created by kong on 2017/12/11.
// Copyright © 2017年 konglee. All rights reserved.
//
#ifndef AnimationDataManager_h
#define AnimationDataManager_h
#include <iostream>
namespace AnimationData
{
}
#endif /* AnimationDataManager_hpp */
| 8a4a66f661dbaf4bd589d4781759d203f3024067 | [
"C",
"Ruby",
"C++"
] | 4 | C++ | kikiloveswift/AdvancedUISDKUseAge | bdfe9b3171782659225e8a071b9f1319919b8940 | ed95c8e66847629d8b1b7925fdf672975b5c76c8 |
refs/heads/main | <file_sep>VUE_APP_URL=http://url-da-aplicacao/
VUE_APP_API_URL=http://url-da-api/
<file_sep>**Otimizador de Coleta - SPA**
----
Interface calcular a melhor coleta num dado intervalo.
Formulário com 2 inputs fixos `int` e um input dinâmico, que pode ser alternado entre um input `text` e múltiplos inputs `int`, utilizando a opção _Utilizar o modo de inserção em lote_.
## Configuração do projeto
Renomeie o arquivo `.env.example` para `.env` (ou para `.env.development.local`) e altere os valores das variáveis de acordo com o seu ambiente.
Na pasta do projeto, execute os comandos:
```
npm install
```
### Compila e atualiza para desenvolvimento
```
npm run serve
```
### Compila e minifica para produção
```
npm run build
```
<file_sep># Colheita
Componente principal
## Methods
<!-- @vuese:Colheita:methods:start -->
|Method|Description|Parameters|
|---|---|---|
|getMaxApples|Obtém número máximo de maçãs em intervalos contínuos K e L, dentro de um determinado array de árvores|{array} A : Array de inteiros - número de maçãs por árvore {int} K : Tamanho do intervalo de coleta de Marcelo {int} L : Tamanho do intervalo de coleta de Carla|
|mutateTreeArray|Converte string para array (ao editar inserção em lote e voltar para inserção item-a-item)|-|
|removeLastTree|Verifica comprimento do array 'trees' e remove o último item, se possível|-|
|showMessage|Exibe mensagens para o usuário.|{string} message : Mensagem a ser exibida. {string} msgType (opcional) : Tipo de mensagem (para definir estilo css)|
|hideMessage|Oculta mensagem atual.|-|
|validateInputs|Valida os valores de entrada e chama a função getMaxApples()|-|
|gatherMark|Verifica se árvore no índice informado deve ter seus frutos coletados por Marcelo ou Carla|{int} treeIndex : Índice do array trees|
|capitalize|Coloca a primeira letra do nome em maiúscula|{string} text : Texto a ser capitalizado|
<!-- @vuese:Colheita:methods:end -->
| 338545e0a2d45acf1e8476b21730e59a6b9e12cc | [
"Markdown",
"Shell"
] | 3 | Shell | lordscorp/frontend_max_gather | 29d2fe067747e59cf5f90c50eb28dfd40d718bc8 | 5414e28671d06fd76ae0ec149bb5cf8736b0c15e |
refs/heads/master | <repo_name>vegardvaage/octocat-herder<file_sep>/src/main/java/com/vimond/herder/service/RepositoryResource.java
package com.vimond.herder.service;
import com.vimond.herder.github.GitClient;
import com.vimond.herder.neo.NeoClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
/**
* Created by vegard on 10/02/14.
*/
@Path("/")
public class RepositoryResource {
private static final Logger logger = LoggerFactory.getLogger(RepositoryResource.class.getSimpleName());
private final NeoClient neo;
private final GitClient git;
private final RepoStorage storage;
public RepositoryResource(NeoClient neoClient, GitClient gitClient, RepoStorage storage) {
this.neo = neoClient;
this.git = gitClient;
this.storage = storage;
}
@GET
@Produces(MediaType.TEXT_HTML)
public IndexView showHtml() {
IndexView indexView = new IndexView();
indexView.setRepositories(storage.getRepositories());
indexView.setProjects(storage.getProjects());
return indexView;
}
}
<file_sep>/src/test/java/com/vimond/herder/maven/ModelComparatorTest.java
package com.vimond.herder.maven;
import org.apache.maven.model.Model;
import org.junit.Before;
import org.junit.Test;
/**
* Created by vegard on 03/02/14.
*/
public class ModelComparatorTest {
private static final String ARTIFACT_ID = "com.vimond.test";
public static final String GROUP_ID = "mavenmodel";
public static final String VERSION = "0.1.alpha";
private Model model1;
private Model model2;
private ModelComparator comparator = new ModelComparator();
@Before
public void init() {
model1 = new Model();
model1.setGroupId(GROUP_ID);
model1.setArtifactId(ARTIFACT_ID);
model1.setVersion(VERSION);
model2 = model1.clone();
}
@Test
public void testEqual() throws Exception {
int result = comparator.compare(model1, model2);
assert(result == 0);
}
@Test
public void testDifferent() {
model2.setArtifactId("foo.com");
assert(comparator.compare(model1, model2) != 0);
model2.setArtifactId(ARTIFACT_ID);
model2.setVersion("2.0");
assert(comparator.compare(model1, model2) != 0);
model2.setVersion(VERSION);
model2.setGroupId("jalla");
assert(comparator.compare(model1, model2) != 0);
}
}
<file_sep>/src/main/java/com/vimond/herder/github/DependencyMapper.java
package com.vimond.herder.github;
import com.google.common.base.Optional;
import com.vimond.herder.maven.MavenDependencyMapper;
import com.vimond.herder.service.Project;
import org.apache.maven.model.Model;
import org.eclipse.egit.github.core.Repository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.*;
/**
* Created by vegard on 03/02/14.
*/
public class DependencyMapper {
private final Logger logger;
private GitClient gitClient;
private MavenDependencyMapper mavenMapper;
private String owner;
private final Map<String,MappedRepository> repos = new HashMap<>();
private final Set<Project> projects = new HashSet<>();
public DependencyMapper(GitClient gitClient, String owner) {
this.gitClient = gitClient;
this.mavenMapper = new MavenDependencyMapper(gitClient, owner);
logger = LoggerFactory.getLogger(this.getClass());
this.owner = owner;
}
/**
* Maps all depenencies within the repositories owned by the specified GitHub user,
* based on the contents of the readme.md file. If the file contains one or more lines of
*
* @param organization
* @return a list of repositories with their dependencies added
* @@dependency>https://github.com/agithubuser/testrepo1 that repo will be added as a dependency of the
* declaring repository as long as they are both owned by "agithubuser".
*/
public List<MappedRepository> mapRepositories(boolean organization) {
try {
List<Repository> unmappedRepos = gitClient.getRepositories(owner, organization);
for (Repository repo : unmappedRepos) {
if (!repos.containsKey(repo.getUrl())) {
MappedRepository newRepo = new MappedRepository(repo);
repos.put(newRepo.getHtmlUrl(), newRepo);
Project project = new Project();
project.setRepository(newRepo);
newRepo.getProjects().add(project);
Optional<Model> model = mavenMapper.getPom(newRepo, Optional.<String>absent());
if (model.isPresent()) {
final Model mavenModel = model.get();
project.setMavenModel(mavenModel);
project.setName(mavenModel.getArtifactId());
final List<String> modules = mavenModel.getModules();
for (String module : modules) {
Project moduleProject = new Project();
Optional<Model> moduleModel = mavenMapper.getPom(newRepo, Optional.of(module));
if (moduleModel.isPresent()) {
moduleProject.setMavenModel(moduleModel.get());
moduleProject.setRepository(newRepo);
moduleProject.setName(moduleModel.get().getArtifactId());
projects.add(moduleProject);
newRepo.getProjects().add(moduleProject);
}
}
} else {
project.setName(newRepo.getName());
projects.add(project);
}
}
}
for (Project project : projects) {
try {
addDependencies(project);
} catch (Exception e) {
if ("Not Found (404)".equals(e.getMessage())) {
logger.debug("readme.md file not found in repo for project {}", project.getName());
} else {
logger.warn("Error adding dependencies for project {}", project.getName(), e);
}
}
mavenMapper.addMavenDependencies(project, projects);
}
} catch (IOException e) {
logger.warn("Error connecting to GitHub", e);
}
return new ArrayList<>(repos.values());
}
private void addDependencies(Project project) throws Exception {
MappedRepository mr = project.getRepository();
String readme = gitClient.getReadmeForRepo(owner, mr.getName());
String[] lines = readme.split("\\r?\\n@@");
for (String line : lines) {
if (line.startsWith("dependency")) {
Optional<Project> dependency = parseLine(line);
if (dependency.isPresent()) {
project.getDependencies().add(dependency.get());
}
}
}
}
private Optional<Project> parseLine(String line) {
Optional<Project> dependency = Optional.absent();
String[] dependencyDeclaration = line.split(">");
if (dependencyDeclaration.length == 2) {
String dependencyUrl = dependencyDeclaration[1].trim();
dependency = findProjectByRepoUrl(dependencyUrl);
if ((!dependency.isPresent()) ) {
logger.warn("Dependency {} not found", dependencyUrl);
}
}
return dependency;
}
private Optional<Project> findProjectByRepoUrl(String dependencyUrl) {
for (Project project : projects) {
if (dependencyUrl.equals(project.getRepository().getHtmlUrl())) {
return Optional.of(project);
}
}
return Optional.absent();
}
public Map<String, MappedRepository> getRepos() {
return repos;
}
public Set<Project> getProjects() {
return projects;
}
}
<file_sep>/src/main/java/com/vimond/herder/service/HerderConfig.java
package com.vimond.herder.service;
import com.yammer.dropwizard.config.Configuration;
/**
* Created by vegard on 10/02/14.
*/
public class HerderConfig extends Configuration {
private String dbDirectory;
public String getDbDirectory() {
return dbDirectory;
}
public void setDbDirectory(String dbDirectory) {
this.dbDirectory = dbDirectory;
}
}
<file_sep>/README.md
octocat-herder
==============
Organizing Github Repos via readme.md since 2014
<file_sep>/src/test/java/com/vimond/herder/github/DependencyMapperTest.java
package com.vimond.herder.github;
import com.vimond.herder.service.Project;
import org.junit.Test;
import java.util.List;
import java.util.Set;
import static org.junit.Assert.assertTrue;
/**
* Created by vegard on 03/02/14.
*/
public class DependencyMapperTest {
@Test
public void testMapping() {
GitClient gitClient = new GitClient();
DependencyMapper mapper = new DependencyMapper(gitClient, "vegardvaage");
mapper.mapRepositories(false);
Set<Project> projects = mapper.getProjects();
assertTrue (projects.size() > 0);
for (Project p : projects) {
if (p.getName().equals("testrepo3")) {
assert(p.getDependencies().size() == 2);
}
}
}
//@Test
public void testVimondRepos() {
GitClient gitClient = new GitClient();
DependencyMapper mapper = new DependencyMapper(gitClient, "vimond");
List<MappedRepository> repositories = mapper.mapRepositories(true);
assert(repositories.size() > 0);
}
}
<file_sep>/src/main/java/com/vimond/herder/neo/NodelLabel.java
package com.vimond.herder.neo;
import org.neo4j.graphdb.Label;
/**
* Created by vegard on 05/02/14.
*/
public enum NodelLabel implements Label {
DEPENDENCY;
}
<file_sep>/src/main/java/com/vimond/herder/maven/MavenDependencyMapper.java
package com.vimond.herder.maven;
import com.google.common.base.Optional;
import com.vimond.herder.github.GitClient;
import com.vimond.herder.github.MappedRepository;
import com.vimond.herder.service.Project;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.StringReader;
import java.util.Set;
/**
* Created by vegard on 03/02/14.
*/
public class MavenDependencyMapper {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final GitClient gitClient;
private final String owner;
public MavenDependencyMapper(GitClient gitClient, String owner) {
this.gitClient = gitClient;
this.owner = owner;
}
/**
* Adds discovered maven dependencies to the MappedRepository mr. Note that the {@link MavenDependencyMapper#getPom(com.vimond.herder.github.MappedRepository, com.google.common.base.Optional)}
* method must be run on all repositories in the repos map prior to this method for any dependencies to be discovered.
* <p>
* Any maven dependencies that have groupId that do not start with "no.tv2" or "com.vimond" will be ignored.
* </p>
*
* @param project The mapped repository to discover maven dependencies for
* @param availableProjects the available repositories
*/
public void addMavenDependencies(Project project, Set<Project> availableProjects) {
Model model = project.getMavenModel();
if (model != null) {
matchDependencies(project, availableProjects);
}
}
private void matchDependencies(Project project, Set<Project> allProjects) {
ModelComparator modelComparator = new ModelComparator();
for (Dependency dependency : project.getMavenModel().getDependencies()) {
String groupId = dependency.getGroupId();
if (groupId.startsWith("com.vimond") || groupId.startsWith("no.tv2")) {
Model dependencyModel = new Model();
dependencyModel.setGroupId(dependency.getGroupId());
dependencyModel.setArtifactId(dependency.getArtifactId());
dependencyModel.setVersion(dependency.getVersion());
for (Project p : allProjects) {
if (p.getMavenModel() != null) {
if (modelComparator.compare(p.getMavenModel(), dependencyModel) == 0) {
project.getDependencies().add(p);
break;
}
}
}
}
}
}
/**
* Looks for a maven pom.xml file at the root of the repository, and parses it if it exists.
*
*
* @param mr the repo that contains the pom.xml file
* @param module the submodule to fetch the pom for, if any. (can be null)
* @return
*/
public Optional<Model> getPom(MappedRepository mr, Optional<String> module) {
Model model = null;
String name = mr.getName();
try {
String pom;
if (module.isPresent()) {
pom = gitClient.getPom(owner, name, module.get());
} else {
pom = gitClient.getPom(owner, name);
}
StringReader r = new StringReader(pom);
MavenXpp3Reader reader = new MavenXpp3Reader();
model = reader.read(r);
} catch (IOException | XmlPullParserException e) {
if ("Not Found (404)".equals(e.getMessage())) {
logger.debug("No pom file found in repo {}", name);
} else {
logger.warn("error fetching pom file from repo {}", name, e);
}
}
return Optional.fromNullable(model);
}
}
<file_sep>/src/test/java/com/vimond/herder/neo/NeoClientTest.java
package com.vimond.herder.neo;
import com.vimond.herder.github.MappedRepository;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import static org.junit.Assert.assertNull;
/**
* Created by vegard on 05/02/14.
*/
public class NeoClientTest {
NeoClient client;
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Before
public void setUp() throws Exception {
client = new NeoClient(temporaryFolder.toString());
client.start();
}
@Test
public void testAddRepo() throws Exception {
MappedRepository repo = new MappedRepository();
String url = "http://github.com/vimond/rest-api";
repo.setHtmlUrl(url);
repo.setName("Rest API");
client.addRepository(repo);
assert(client.findRepository(url).getHtmlUrl().equals(repo.getHtmlUrl()));
client.removeAllRepos();
assertNull(client.findRepository(url));
}
@After
public void tearDown() throws Exception {
client.stop();
}
}
<file_sep>/src/main/java/com/vimond/herder/neo/NeoClient.java
package com.vimond.herder.neo;
import com.vimond.herder.github.MappedRepository;
import com.yammer.dropwizard.lifecycle.Managed;
import org.neo4j.cypher.javacompat.ExecutionEngine;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.ResourceIterable;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import java.util.List;
/**
* Created by vegard on 05/02/14.
*/
public class NeoClient implements Managed {
public static final String REPO_LABEL = "repository";
private GraphDatabaseService db;
private ExecutionEngine engine;
private String dbDirectory;
public NeoClient(String dbDirectory) {
this.dbDirectory = dbDirectory;
}
public void addRepository(MappedRepository repository) {
Transaction tx = db.beginTx();
createRepoNode(repository);
tx.success();
}
public void addRepositories(List<MappedRepository> repositories) {
Transaction tx = db.beginTx();
for (MappedRepository repository : repositories) {
createRepoNode(repository);
}
tx.success();
}
public MappedRepository findRepository(String url) {
ResourceIterable<Node> nodes = db.findNodesByLabelAndProperty(NodelLabel.DEPENDENCY, "url", url);
MappedRepository repo = null;
for (Node node : nodes) {
repo = new MappedRepository();
repo.setHtmlUrl((String) node.getProperty("url"));
repo.setName((String) node.getProperty("name"));
break;
}
nodes.iterator().close();
return repo;
}
public void removeAllRepos() {
Transaction tx = db.beginTx();
engine.execute("MATCH (n:DEPENDENCY) DELETE n");
tx.success();
}
private void createRepoNode(MappedRepository repository) {
Node repo = db.createNode(NodelLabel.DEPENDENCY);
repo.setProperty("url", repository.getHtmlUrl());
repo.setProperty("name", repository.getName());
}
@Override
public void start() throws Exception {
db = new GraphDatabaseFactory().newEmbeddedDatabase(dbDirectory);
this.engine = new ExecutionEngine(db);
}
@Override
public void stop() throws Exception {
db.shutdown();
}
}
| 56587a37b1b725b6a515ed49848340fe1d9e28de | [
"Markdown",
"Java"
] | 10 | Java | vegardvaage/octocat-herder | 780285c2e6e1a1e57af4a59e2f21260bffe55862 | d9fd8ce7b15307245f7f21fd10855d636351ea3e |
refs/heads/master | <file_sep>import pandas as pd
import random
import os
from selenium import webdriver # 從library中引入webdriver
# from selenium.webdriver.common.by import By
# from fake_useragent import UserAgent # !pip install fake-useragent
from selenium.webdriver.chrome.options import Options
import time
import urllib
import argparse
pd.set_option('display.max_rows', 250)
def openBrowser():
try:
browser = webdriver.Chrome('./chromedriver')
except OSError:
browser = webdriver.Chrome('./chromedriver.exe')
return browser
def get_all_posts(ins_id, user_ac, user_pw):
browser = openBrowser() # 開啟chrome browser
browser.get('https://www.instagram.com/'+str(ins_id)+'/?hl=zh-tw') # 開啟想要搜尋的帳號IG
#先進行登入的動作
button = browser.find_element_by_xpath("//button[@type='button'][text()='登入']") #尋找登入點擊按鈕
button.click()
time.sleep(5) #網頁反應沒那麼快,要等一下
account = browser.find_elements_by_xpath("//input[@aria-label='電話號碼、用戶名稱或電子郵件']")
account[0].send_keys(user_ac) #account只為長度1的list,很奇怪。輸入帳號名稱
time.sleep(5)
password = browser.find_elements_by_xpath("//input[@aria-label='密碼']")
password[0].send_keys(user_pw) #account只為長度1的list,很奇怪。輸入帳號名稱
time.sleep(5)
confirm_button = browser.find_element_by_xpath("//button[@type='submit']") #尋找登入點擊按鈕
confirm_button.click() #點擊登入按鈕
time.sleep(5)
num_post = browser.find_elements_by_xpath("//span[@class='-nal3 ']") #定位貼文置的位置
num_post[0].text #顯示貼文數
time.sleep(5)
num_post = browser.find_elements_by_xpath("//span[@class='-nal3 ']") #定位貼文置的位置
num_post[0].text #抓取總文章數
time.sleep(5)
#撈取所有post的超連結
post_hrefs=[]
height = browser.execute_script("return document.body.scrollHeight") #一開始頁面的高度
while str(len(post_hrefs))+' 貼文' != num_post[0].text:
lastHeight = height
# step 1
elements = browser.find_elements_by_xpath('//a[contains(@href, "/p/")]')
# step 2
for element in elements:
if element.get_attribute('href') not in post_hrefs:
post_hrefs.append(element.get_attribute('href'))
# step 3
#browser.execute_script("return arguments[0].scrollIntoView();", elements[-1])
browser.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(5)
browser.close()
return post_hrefs
def login_ins_browser(ac, pw):
browser = openBrowser() # 開啟chrome browser
browser.get('https://www.instagram.com/po_chu_chen/?hl=zh-tw')
#先進行登入的動作
button = browser.find_element_by_xpath("//button[@type='button'][text()='登入']") #尋找登入點擊按鈕
button.click()
time.sleep(2) #網頁反應沒那麼快,要等一下
account = browser.find_elements_by_xpath("//input[@aria-label='電話號碼、用戶名稱或電子郵件']")
account[0].send_keys(ac) #account只為長度1的list,很奇怪。輸入帳號名稱
time.sleep(2)
password = browser.find_elements_by_xpath("//input[@aria-label='密碼']")
password[0].send_keys(pw) #account只為長度1的list,很奇怪。輸入帳號名稱
time.sleep(2)
confirm_button = browser.find_element_by_xpath("//button[@type='submit']") #尋找登入點擊按鈕
confirm_button.click() #點擊登入按鈕
time.sleep(5)
return browser
def scrap_src(post_url, browser):
browser.get(post_url)
time.sleep(2)
src_list = []
img_pos = browser.find_elements_by_xpath('//div[@class="KL4Bh"]/img')
src = img_pos[0].get_attribute('src')
src_list.append(src)
right_click_button = browser.find_elements_by_xpath('//button[@class=" _6CZji"]')
while len(right_click_button)!=0:
right_click_button[0].click()
time.sleep(2)
img_pos = browser.find_elements_by_xpath('//div[@class="KL4Bh"]/img')
src = img_pos[0].get_attribute('src')
src_list.append(src)
right_click_button = browser.find_elements_by_xpath('//button[@class=" _6CZji"]')
return src_list
def download_pic(src_list, save_path):
for i in range(len(src_list)):
# save_path_img = save_path+'/'+str(time.ctime(time.time()))+'.png'
save_path_img = save_path+'/'+str(time.ctime(time.time())).replace(' ','_').replace(':','-')+'123.png'
pic_file = urllib.request.urlopen(src_list[i]).read()
f = open(save_path_img, 'wb')
f.write(pic_file)
f.close()
time.sleep(1)
return
def main(target_id, user_ac, user_pw, save_path):
if save_path == './default_save':
try:
os.mkdir('./default_save')
except FileExistsError:
pass
post_hrefs = get_all_posts(target_id, user_ac, user_pw) # 所有 post 的連結
print('總共文章數為:'+str(len(post_hrefs)))
print('Total number of posts is:'+str(len(post_hrefs)))
print('請輸入您想要抓取的文章數\n'+'Please keyin number of posts you want to scrap')
num_input = input()
print('您所輸入的文章數為:'+num_input+',開始抓取')
print('The number you keyin is:'+num_input+', start scraping')
browser = login_ins_browser(ac=user_ac, pw=user_pw)
browser.get(post_hrefs[0])
for i in range(int(num_input)):
browser.refresh()
try:
download_pic(scrap_src(post_hrefs[i], browser), save_path)
time.sleep(random.uniform(2,5))
except IndexError:
pass
browser.close()
return
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-target_id', action='store')
parser.add_argument('-user_ac', action='store')
parser.add_argument('-user_pw', action='store')
parser.add_argument('-save_path', action='store', default = './default_save')
args = parser.parse_args()
main(args.target_id, args.user_ac, args.user_pw, args.save_path)
<file_sep>## `script_scrap_photo` 爬蟲出你鎖定的IG帳號,所有貼文的照片!!
### 參數說明
* `target_id`: 輸入您想要查找的`ins account`
* `user_ac`: 輸入您所要登入的帳號
* `user_pw`: 輸入您所登入帳號的密碼
* `save_path`: 輸入您檔案要儲存的路徑
- `default='./default_save'`: 預設會建立並儲存在資料夾 `default_save` 中
### 套件需求
* `pandas`
* `selenium`
* [chromerdriver](https://chromedriver.storage.googleapis.com/index.html?path=80.0.3987.106/) for selenium
- version: 80.0.3987.106
- `chrome` is for mac
- `chromedriver.exe` is for windows
### 執行方法
* 程式碼:`script_scrap_photo.py`
* clone this repo and cd into it
* 不指定儲存路徑:<br>
`python3 script_scrap_photo.py -target_id {YOUR_TARGET_ACCT} -user_ac {YOUR_LOGIN_ACCT} -user_pw {YOUR_PASSWORD}`
* 指定儲存路徑:<br>
`python3 script_scrap_photo.py -target_id {YOUR_TARGET_ACCT} -user_ac {YOUR_LOGIN_ACCT} -user_pw {YOUR_PASSWORD} -save_path {YOUR_FILE_SAVING_PATH}`
* 中間段:輸入您想要爬取的文章數
### 貼心小提醒
* 請確保網路連線順利,selenium很容易因為網路不順當掉,小心使用
Happy scraping :)))
***
### Old Version for google chrome
* https://www.slimjet.com/chrome/google-chrome-old-version.php
| 771608c6766aacae09c9f806e3a83e8155d21425 | [
"Markdown",
"Python"
] | 2 | Python | pcchencode/ins_crawl_photo | 3ef9a8f1758f0a3948d4d6b7354faa37c983b41e | 7fd647ff4305c34bdb5eb16438d0bb3f3d857a14 |
refs/heads/master | <file_sep>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
typedef unsigned char bool;
#define false 0
#define true 1
#define MAX 2147483647
struct TListePrem {
int nbrMax;
int* pPrem;
int nbrPrem;
};
void InitialiserTListePrem(struct TListePrem *);
void Erathostene(struct TListePrem *);
void AfficherPremiers(struct TListePrem *);
void DetruireTListePrem(struct TListePrem *);
int main(int argc, char* argv[]) {
struct TListePrem listePrem;
do {
InitialiserTListePrem(&listePrem);
listePrem.nbrMax = ReadIntLimited("\nEnter MAX ? ", 0, MAX);
float time;
clock_t t1, t2;
t1 = clock();
Erathostene(&listePrem);
t2 = clock();
time = (float)(t2-t1)/CLOCKS_PER_SEC;
printf("Time : %.2f\n", time);
AfficherPremiers(&listePrem);
DetruireTListePrem(&listePrem);
} while (!Stop());
return EXIT_SUCCESS;
}
void InitialiserTListePrem(struct TListePrem * listePrem) {
listePrem->nbrMax = 0;
listePrem->nbrPrem = 0;
listePrem->pPrem = NULL;
}
void Erathostene(struct TListePrem * listePrem) {
int nbPrem = ((listePrem->nbrMax % 2 == 0) ? (listePrem->nbrMax/2) : (listePrem->nbrMax/2)+1);
bool * primeBool = (bool *) calloc(nbPrem,sizeof(bool));
int sqrtMax = sqrt(listePrem->nbrMax);
int number = 3, count = 0, p = 1;
while (number <= sqrtMax) {
bool isPrime = true;
int multiple = 2;
while (isPrime == true && multiple < number) {
if (number % multiple == 0) {
isPrime = false;
}
multiple++;
}
if (isPrime == true) {
int k = p + number;
while (k < nbPrem) {
if (primeBool[k] == 0) {
primeBool[k] = 1;
count++;
}
k = k + number;
}
}
number = number + 2;
p++;
}
listePrem->nbrPrem = nbPrem - count;
listePrem->pPrem = (int *) calloc(listePrem->nbrPrem,sizeof(int));
int pos = 1, id = 1;
listePrem->pPrem[0] = 2;
for (int var = 1; var < nbPrem; ++var) {
pos = pos + 2;
if (primeBool[var] == 0) {
listePrem->pPrem[id] = pos;
id++;
}
}
free(primeBool);
}
void AfficherPremiers(struct TListePrem * listePrem) {
printf("%d prime numbers less than %d\n",listePrem->nbrPrem,listePrem->nbrMax);
if (listePrem->nbrPrem > 20) {
for (int i = 0; i < 10; ++i) {
printf("Prime number n %8d : %8d\n",i+1,listePrem->pPrem[i]);
}
printf("\n...\n\n");
for (int i = 9; i >= 0; --i) {
printf("Prime number n %8d : %8d\n",listePrem->nbrPrem-i,listePrem->pPrem[listePrem->nbrPrem-i-1]);
}
} else {
for (int i = 0; i < listePrem->nbrPrem; ++i) {
printf("Prime number n %8d : %8d\n",i+1,listePrem->pPrem[i]);
}
}
}
void DetruireTListePrem(struct TListePrem * listePrem) {
listePrem->nbrMax = 0;
listePrem->nbrPrem = 0;
free(listePrem->pPrem);
}
<file_sep># Grow-with-Eratosthenes
In C and C++ : Program to find prime numbers using Eratosthenes
<file_sep>//---------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
#include <math.h>
#include <time.h>
#include <cstdlib>
//---------------------------------------------------------------------------
using namespace std;
//---------------------------------------------------------------------------
const int MAX = 2147483647; // (2^31-1)
struct TListPrimes {
int maximum;
int* pPrimes;
int cPrimes;
};
void InitializeTListPrimes(TListPrimes &listPrimes);
void Erathostenes2(TListPrimes &listPrimes);
void ShowPrimes2(TListPrimes &listPrimes);
void DestroyTListPrimes(TListPrimes &listPrimes);
//---------------------------------------------------------------------------
// ...
//---------------------------------------------------------------------------
int main(int argc, char* argv[]) {
clock_t ct1, ct2;
TListPrimes listPrimes;
do {
InitializeTListPrimes(listPrimes);
listPrimes.maximum = ReadInt("\nEnter MAX ? ", 0, MAX);
ct1 = clock();
Erathostenes2(listPrimes);
ct2 = clock();
cout << "Time : " << setprecision(4) << ((double)(ct2 - ct1) / CLOCKS_PER_SEC) << endl;
ShowPrimes2(listPrimes);
DestroyTListPrimes(listPrimes);
} while(!Stop());
return 0;
}
//---------------------------------------------------------------------------
void InitializeTListPrimes(TListPrimes &listPrimes) {
listPrimes.maximum = 0;
listPrimes.pPrimes = NULL;
listPrimes.cPrimes = 0;
}
void Erathostenes2(TListPrimes &listPrimes) {
int taille=0, maybePrime=3, notPrimeCount=0, maybePrimePos=1;
if(listPrimes.maximum%2==0)
{ taille = listPrimes.maximum/2; }
else
{ taille = (listPrimes.maximum/2)+1; }
unsigned char * tPrimes=(unsigned char *) calloc(taille,sizeof(unsigned char));
while (maybePrime <= sqrt(listPrimes.maximum)) {
int factor = 2;
bool yesPrime = true;
while (yesPrime == true && factor < maybePrime) {
if (maybePrime % factor == 0) {
yesPrime = false;
}
factor++;
}
if (yesPrime == true) {
int maybeMultiplePos = maybePrimePos + maybePrime;
listPrimes.cPrimes++;
while (maybeMultiplePos < taille) {
if (tPrimes[maybeMultiplePos] == 0) {
tPrimes[maybeMultiplePos] = 1;
notPrimeCount++;
}
maybeMultiplePos = maybeMultiplePos + maybePrime;
}
}
maybePrime = maybePrime + 2;
maybePrimePos++;
}
listPrimes.cPrimes = taille - notPrimeCount;
listPrimes.pPrimes = (int *) calloc(listPrimes.cPrimes,sizeof(int));
listPrimes.pPrimes[0] = 2;
int valuePrime = 1, finalPrimePos = 1;
for (int i = 1; i < taille; ++i) {
valuePrime = valuePrime + 2;
if (tPrimes[i] == 0) {
listPrimes.pPrimes[finalPrimePos] = valuePrime;
finalPrimePos++;
}
}
free(tPrimes);
}
void ShowPrimes2(TListPrimes &listPrimes){
if (listPrimes.cPrimes > 20) {
for (int i = 0; i < 10; ++i) {
cout<<"Prime number n "<<i+1<<" : "<<listPrimes.pPrimes[i]<<endl;
}
cout<<"\n...\n\n";
for (int i = 9; i >= 0; --i) {
cout<<"Prime number n "<<listPrimes.cPrimes-i<<" : "<<listPrimes.pPrimes[listPrimes.cPrimes-i-1]<<endl;
}
} else {
for (int i = 0; i < listPrimes.cPrimes; ++i) {
cout<<"Prime number n "<<i+1<<" : "<<listPrimes.pPrimes[i]<<endl;
}
}
}
void DestroyTListPrimes(TListPrimes &listPrimes)
{
free(listPrimes.pPrimes);
}
//---------------------------------------------------------------------------
| dd7a80bb63f0ec1d633a0ada04087d6d119f10a8 | [
"Markdown",
"C",
"C++"
] | 3 | C | NGHDev/Grow-with-Eratosthenes | 00ca502e3b237d8fc25f9dbbf2cf348e1d2ff46b | 1c54f7329afd9bd191f3ff877df4c080353c22e1 |
refs/heads/main | <file_sep># OOP-Project-File<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace OOP_Project_File
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string Username = "Admin";
string Password = "<PASSWORD>";
if ((textBox1.Text == Username) && (textBox2.Text == Password))
MessageBox.Show("Login Successfull!");
else
MessageBox.Show("Login Failed! Please Check Username &Password again");
}
}
}
| baaad9d2749846e7388c6770bef64f9b5a4df84a | [
"Markdown",
"C#"
] | 2 | Markdown | abdelrahman369/OOP-Project-File | b443718695f2e322a5ba646aa9b8625c79bf391a | 9e14134a17181b33597a6bc168e0bd29c465bc18 |
refs/heads/master | <file_sep># following you tube flask tutorial
from flask import Flask , render_template,url_for
app = Flask(__name__)
posts = [
{
'author':'Shivam',
'title':'blog post 1',
'content':'blog post 1 content',
'date_posted':'25 May 2019'
},
{
'author':'Anna',
'title':'blog post 2',
'content':'blog post 2 content',
'date_posted':'20 May 2019'
}
]
@app.route("/")
@app.route("/home")
def hello():
return render_template("home.html",posts=posts)
@app.route("/about")
def about():
return render_template("about.html",title = 'About Page')
if __name__=="__main__":
app.run(debug = True) | 8b23c6a8cdb2f1912cedc39b5e066fb5573068d1 | [
"Python"
] | 1 | Python | vscodedev/Flask_YT_Tutorial | b4952f7d2c2d0f20217c8e27f953df9a024c656d | db36270d92f30320b57f61d31fd9adddf61f0168 |
refs/heads/master | <repo_name>ducminhquan/traffic-engine-app<file_sep>/src/main/resources/public/javascripts/views/routing-sidebar.js
var Traffic = Traffic || {};
Traffic.views = Traffic.views || {};
(function(A, views, translator, C, dc) {
views.RoutingSidebar = Marionette.Layout.extend({
template: Handlebars.getTemplate('app', 'sidebar-routing'),
regions: {
saveRouteContainer: "#saveRouteContainer",
bookmarkRouteContainer: "#bookmarkRouteContainer",
exportDataContainer: "#exportDataContainer",
},
events : {
'click #resetRoute' : 'resetRoute',
'click #resetRoute2' : 'resetRoute',
'click #resetRoute3' : 'resetRoute',
'change #day' : '',
'change #hour' : 'getRoute',
'change #week1ToList' : 'changeToWeek',
'change #week2ToList' : 'changeToWeek',
'change #week1FromList' : 'changeFromWeek',
'change #week2FromList' : 'changeFromWeek',
'click #toggleFilters' : 'toggleFilters',
'click #toggleFilters2' : 'toggleFilters',
'click #compare' : 'clickCompare',
'change #confidenceInterval' : 'changeConfidenceInterval',
'change #normalizeByTime' : 'changeNormalizeBy',
'click #analyzeByTime' : 'analyzeByTime',
'click #returnToOverall' : 'returnToOverall',
'click #returnToOverall1' : 'returnToOverall'
},
loadRouteFromUrl : function(routeId) {
$.getJSON('/route/' + routeId, function(data) {
if(data.json){
//user's saved route
A.app.sidebar.loadRoute(data.json);
}else{
//anonymous bookmark
A.app.sidebar.loadRoute(data);
}
});
},
loadRoute : function(params) {
A.app.sidebarTabs.resetRoute();
A.app.map.fitBounds(new L.LatLngBounds(
new L.LatLng(params.bounds._southWest.lat,params.bounds._southWest.lng),
new L.LatLng(params.bounds._northEast.lat,params.bounds._northEast.lng)));
for(var i = 0; i < params.routePoints.length; i++){
var evt = {};
evt.latlng = {
lat: params.routePoints[i].lat,
lng: params.routePoints[i].lng
};
if(i == params.routePoints.length -1){
var callback = function() {
A.app.sidebar.routeRendered(params);
};
A.app.sidebarTabs.onMapClick(evt, false, callback);
}else{
A.app.sidebarTabs.onMapClick(evt, true);
}
}
},
routeRendered: function(params){
if(params.hourExtent || params.dayExtent){
this.toggleFilters(null, true);
this.hourlyChart.filter(dc.filters.RangedFilter(params.hourExtent[0], params.hourExtent[1]));
this.dailyChart.filter(dc.filters.RangedFilter(params.dayExtent[0], params.dayExtent[1]));
dc.renderAll();
}
if(params.week1FromList){
$("#week1FromList").val(params.week1FromList);
this.changeFromWeek();
if(params.week1ToList){
$("#week1ToList").val(params.week1ToList);
}
this.changeToWeek();
if(params.week2FromList){
var that = this;
var callback = function() {
that.clickCompareCallback(params)
};
this.$("#compare").prop( "checked", true );
this.clickCompare(callback)
}
}
},
clickCompareCallback: function(params){
$("#week2FromList").val(params.week2FromList);
this.changeFromWeek();
if(params.week2ToList){
$("#week2ToList").val(params.week2ToList);
this.changeToWeek();
}
},
toggleFilters : function(event, overrideState) {
//reset the filter state
this.hourlyChart.filterAll();
this.dailyChart.filterAll();
dc.renderAll();
//flip the filter on/off
var brushOn;
if(overrideState != null){
brushOn = overrideState;
}else{
A.app.sidebarTabs.filterEnabled = !A.app.sidebarTabs.filterEnabled;
brushOn =A.app.sidebarTabs.filterEnabled;
}
this.dailyChart.brushOn(brushOn);
this.hourlyChart.brushOn(brushOn);
if(brushOn){
$(event.target).html(translator.translate("filter_on"))
}else{
$(event.target).html(translator.translate("filter_off"))
A.app.sidebarTabs.getRoute();
}
dc.renderAll();
//reset the cached filter handle positions
A.app.sidebar.hourExtent = A.app.sidebar.hourlyChart.brush().extent();
A.app.sidebar.dayExtent = A.app.sidebar.dailyChart.brush().extent();
},
resetRoute : function() {
$('#routeButtons').hide();
$('#routeCompareNotes').hide();
$('#analyzeByTimeButtons').hide();
$('#returnToOverall').hide();
$('#analyzeByTime').show();
$('#selectedDateAndTime').hide();
A.app.sidebarTabs.resetRoute();
this.$('#routeCompareNotes').hide();
//reset the filter state
$("#toggleFilters").html(translator.translate("filter_off"))
this.hourlyChart.filterAll();
this.dailyChart.filterAll();
this.dailyChart.brushOn(false);
this.hourlyChart.brushOn(false);
dc.redrawAll();
window.history.pushState('', '', '?');
},
getRoute : function() {
A.app.sidebarTabs.getRoute();
},
onShow : function() {
var _this = this;
this.$("#week1To").hide();
this.$("#week2To").hide();
this.$("#compareWeekSelector").hide();
this.$("#percentChangeTitle1").hide();
this.$("#percentChangeTitle2").hide();
this.$("#percentChangeLegend").hide();
this.$("#routeData").hide();
$.getJSON('/weeks', function(data) {
data.sort(function(a, b) {
return a.weekId - b.weekId;
});
A.app.sidebar.weekList = data;
_this.$("#week1FromList").empty();
_this.$("#week1ToList").empty();
_this.$("#week2FromList").empty();
_this.$("#week2ToList").empty();
_this.$("#week1FromList").append('<option value="-1">' + translator.translate("all_weeks") + '</option>');
for(var i in A.app.sidebar.weekList) {
var weekDate = new Date( data[i].weekStartTime);
_this.$("#week1FromList").append('<option value="' + data[i].weekId + '">' + translator.translate("week_of") + ' ' + (weekDate.getUTCMonth() + 1) + '/' + weekDate.getUTCDate() + '/' + weekDate.getUTCFullYear() + '</option>');
}
_this.$("#week2FromList").empty();
_this.$("#week2FromList").append('<option value="-1">' + translator.translate("all_weeks") + '</option>');
for(var i in A.app.sidebar.weekList) {
var weekDate = new Date( data[i].weekStartTime);
_this.$("#week2FromList").append('<option value="' + data[i].weekId + '">' + translator.translate("week_of") + ' ' + (weekDate.getUTCMonth() + 1) + '/' + weekDate.getUTCDate() + '/' + weekDate.getUTCFullYear() + '</option>');
}
});
this.changeFromWeek();
},
onClose : function() {
A.app.sidebarTabs.resetRoute();
},
changeFromWeek : function() {
A.app.sidebar.filterChanged = true;
this.$("#week1To").hide();
this.$("#week2To").hide();
if(this.$("#week1FromList").val() > 0) {
this.$("#week1ToList").empty();
for(var i in A.app.sidebar.weekList) {
if(A.app.sidebar.weekList[i].weekId >= this.$("#week1FromList").val()) {
var weekDate = new Date( A.app.sidebar.weekList[i].weekStartTime);
this.$("#week1ToList").append('<option value="' + A.app.sidebar.weekList[i].weekId + '">' + translator.translate("week_of") + ' ' + (weekDate.getUTCMonth() + 1) + '/' + weekDate.getUTCDate() + '/' + weekDate.getUTCFullYear() + '</option>');
}
this.$("#week1To").show();
}
}
if(this.$("#week2FromList").val() > 0) {
this.$("#week2ToList").empty();
for(var i in A.app.sidebar.weekList) {
if(A.app.sidebar.weekList[i].weekId >= this.$("#week2FromList").val()) {
var weekDate = new Date( A.app.sidebar.weekList[i].weekStartTime);
this.$("#week2ToList").append('<option value="' + A.app.sidebar.weekList[i].weekId + '">' + translator.translate("week_of") + ' ' + (weekDate.getUTCMonth() + 1) + '/' + weekDate.getUTCDate() + '/' + weekDate.getUTCFullYear() + '</option>');
}
this.$("#week2To").show();
}
}
this.update();
},
changeNormalizeBy: function() {
A.app.sidebar.filterChanged = true;
this.update();
},
changeConfidenceInterval : function() {
A.app.sidebar.filterChanged = true;
this.update();
},
changeToWeek : function() {
A.app.sidebar.filterChanged = true;
this.update();
},
clickCompare : function(callback) {
if(typeof callback != "function")
callback = null;
A.app.sidebar.filterChanged = true;
if(this.$("#compare").prop( "checked" )) {
this.$("#compareWeekSelector").show();
this.$("#percentChangeTitle1").show();
this.$("#percentChangeTitle2").show();
this.$("#percentChangeLegend").show();
this.$("#speedLegend").hide();
A.app.sidebar.percentChange = true;
this.$('#routeCompareNotes').show();
}
else {
this.$("#compareWeekSelector").hide();
this.$("#percentChangeTitle1").hide();
this.$("#percentChangeTitle2").hide();
this.$("#percentChangeLegend").hide();
this.$("#speedLegend").show();
A.app.sidebar.percentChange = false;
this.$('#routeCompareNotes').hide();
}
this.update(callback);
},
update : function(callback) {
A.app.sidebar.filterChanged = true;
if(!A.app.sidebar.hourlyChart)
return;
A.app.sidebar.hourExtent = A.app.sidebar.hourlyChart.brush().extent();
A.app.sidebar.dayExtent = A.app.sidebar.dailyChart.brush().extent();
var minHour, maxHour, minDay, maxDay;
if(!A.app.sidebar.hourExtent || (A.app.sidebar.hourExtent[0] < 1 && A.app.sidebar.hourExtent[1] < 1)) {
minHour = 1
maxHour = 24;
}
else {
minHour = Math.ceil(A.app.sidebar.hourExtent[0]);
maxHour = Math.floor(A.app.sidebar.hourExtent[1]);
}
if(!A.app.sidebar.dayExtent || (A.app.sidebar.dayExtent[0] < 1 && A.app.sidebar.dayExtent[1] < 1)) {
minDay = 1
maxDay = 7;
}
else {
minDay = Math.ceil(A.app.sidebar.dayExtent[0]);
maxDay = Math.floor(A.app.sidebar.dayExtent[1]);
}
var hours = new Array();
for(d = minDay; d <= maxDay; d++) {
for(h = minHour; h <= maxHour; h++) {
hours.push(h + (24 * (d -1)));
}
}
A.app.sidebarTabs.getRoute(hours, null, null, callback);
},
getWeek1List : function() {
var wFrom = this.$("#week1FromList").val();
var wList = new Array();
if(wFrom == -1) {
for(var i in A.app.sidebar.weekList) {
wList.push(A.app.sidebar.weekList[i].weekId );
}
} else {
var wTo = this.$("#week1ToList").val();
for(var i in A.app.sidebar.weekList) {
if(A.app.sidebar.weekList[i].weekId >= wFrom && A.app.sidebar.weekList[i].weekId <= wTo)
wList.push(A.app.sidebar.weekList[i].weekId);
}
}
return wList;
},
getWeek2List : function() {
var wFrom = this.$("#week2FromList").val();
var wList = new Array();
if(wFrom == -1) {
for(var i in A.app.sidebar.weekList) {
wList.push(A.app.sidebar.weekList[i].weekId );
}
} else {
var wTo = this.$("#week2ToList").val();
for(var i in A.app.sidebar.weekList) {
if(A.app.sidebar.weekList[i].weekId >= wFrom && A.app.sidebar.weekList[i].weekId <= wTo)
wList.push(A.app.sidebar.weekList[i].weekId);
}
}
return wList;
},
loadChartData : function(data) {
var compareCheckbox = this.$('#compare');
var utcAdjustment = A.app.instance.utcTimezoneOffset || 0;
data.hours.forEach(function (d) {
d.hourOfDay = (d.h % 24) + 1;
d.dayOfWeek = ((d.h - d.hourOfDay) / 24) + 1;
// TODO: convert UTC to local
if (utcAdjustment) {
var fixDay = false;
if((d.hourOfDay + utcAdjustment) % 24 > 0)
fixDay = true;
d.hourOfDay = (d.hourOfDay + utcAdjustment) % 24;
if(fixDay){
d.dayOfWeek = d.dayOfWeek + 1;
if(d.dayOfWeek > 7)
d.dayOfWeek = d.dayOfWeek % 7;
}
}
d.s = d.s * 3.6; // convert from m/s km/h
});
if(!this.chartData) {
this.chartData = C(data.hours);
this.dayCount = this.chartData.dimension(function (d) {
return d.dayOfWeek; // add the magnitude dimension
});
this.dayCountGroup = this.dayCount.group().reduce(
/* callback for when data is added to the current filter results */
function (p, v) {
p.count += v.c;
p.sum += v.s;
if(p.count > 0)
p.avg = (p.sum / p.count);
else
p.avg = 0;
return p;
},
/* callback for when data is removed from the current filter results */
function (p, v) {
p.count -= v.c;
p.sum -= v.s;
if(p.count > 0)
p.avg = (p.sum / p.count);
else
p.avg = 0;
return p;
},
/* initialize p */
function () {
return {
count: 0,
sum: 0,
avg: 0
};
}
);
this.hourCount = this.chartData.dimension(function (d) {
return d.hourOfDay; // add the magnitude dimension
});
this.hourCountGroup = this.hourCount.group().reduce(
/* callback for when data is added to the current filter results */
function (p, v) {
p.count += v.c;
p.sum += v.s;
if(p.count > 0)
p.avg = (p.sum / p.count);
else
p.avg = 0;
return p;
},
/* callback for when data is removed from the current filter results */
function (p, v) {
p.count -= v.c;
p.sum -= v.s;
if(p.count > 0)
p.avg = (p.sum / p.count);
else
p.avg = 0;
return p;
},
/* initialize p */
function () {
return {
count: 0,
sum: 0,
avg: 0
};
}
);
var dayLabel = new Array();
dayLabel[1] = translator.translate("mon");
dayLabel[2] = translator.translate("tue");
dayLabel[3] = translator.translate("wed");
dayLabel[4] = translator.translate("thu");
dayLabel[5] = translator.translate("fri");
dayLabel[6] = translator.translate("sat");
dayLabel[7] = translator.translate("sun");
this.dailyChart = dc.barChart("#dailyChart");
if(this.$("#compare").prop( "checked" ))
A.app.sidebar.percentChange = true;
else
A.app.sidebar.percentChange = false;
this.dailyChart.width(430)
.height(150)
.margins({top: 5, right: 10, bottom: 20, left: 40})
.dimension(this.dayCount)
.group(this.dayCountGroup)
.transitionDuration(0)
.centerBar(true)
.valueAccessor(function (p) {
return p.value.avg;
})
.gap(10)
.x(d3.scale.linear().domain([0.5, 7.5]))
.renderHorizontalGridLines(true)
.elasticY(true)
.brushOn(false)
.xAxis().tickFormat(function (d) {
return dayLabel[d]
});
this.hourlyData = data.hours;
var that = this;
this.dailyChart.title(function (d) {
if(!compareCheckbox.prop('checked') && !isNaN(d.value.avg) && d.value.avg > 0){
var wsd = that.wsd(d.key, that.hourlyData, 'dayOfWeek');
return translator.translate("avg_speed") + ' ' + Math.round(d.value.avg)
+ ' KPH, ' + translator.translate("std_dev") + ': ' + wsd;
}
return null;
});
this.dailyChart.yAxis().ticks(4);
this.dailyChart.yAxis().tickFormat(function (d) {
if(A.app.sidebar.percentChange)
return Math.round(d * 100) + "%"
else
return d;
});
this.dailyChart.brush().on("brushend.custom", A.app.sidebar.update);
this.hourlyChart = dc.barChart("#hourlyChart");
this.hourlyChart.width(430)
.height(150)
.margins({top: 5, right: 10, bottom: 20, left: 40})
.dimension(this.hourCount)
.group(this.hourCountGroup)
.transitionDuration(0)
.centerBar(true)
.valueAccessor(function (p) {
return p.value.avg;
})
.gap(5)
.brushOn(false)
.x(d3.scale.linear().domain([0.5, 24.5]))
.renderHorizontalGridLines(true)
.elasticY(true)
.xAxis().tickFormat();
this.hourlyChart.title(function (d) {
if(!compareCheckbox.prop('checked') && !isNaN(d.value.avg) && d.value.avg > 0){
var wsd = that.wsd(d.key, that.hourlyData, 'hourOfDay');
return translator.translate("avg_speed") + ' ' + Math.round(d.value.avg)
+ ' KPH, ' + translator.translate("std_dev") + ': ' + wsd;
}
return null;
});
this.hourlyChart.yAxis().ticks(6);
this.hourlyChart.yAxis().tickFormat(function (d) {
if(A.app.sidebar.percentChange)
return Math.round(d * 100) + "%"
else
return d;
});
this.hourlyChart.brush().on("brushend.custom", A.app.sidebar.update);
}
else {
this.hourlyChart.filterAll();
this.dailyChart.filterAll();
this.chartData.remove();
this.chartData.add(data.hours);
if(A.app.sidebar.hourExtent && ( A.app.sidebar.hourExtent[0] >= 1.0 || A.app.sidebar.hourExtent[1] >= 1.0)) {
this.hourlyChart.filter(dc.filters.RangedFilter(A.app.sidebar.hourExtent[0], A.app.sidebar.hourExtent[1]));
}
if(A.app.sidebar.dayExtent && ( A.app.sidebar.dayExtent[0] >= 1.0 || A.app.sidebar.dayExtent[1] >= 1.0)) {
this.dailyChart.filter(dc.filters.RangedFilter(A.app.sidebar.dayExtent[0], A.app.sidebar.dayExtent[1]));
}
this.hourlyChart.brush().on("brushend.custom", A.app.sidebar.update);
this.dailyChart.brush().on("brushend.custom", A.app.sidebar.update);
this.hourlyData = data.hours;
var that = this;
this.dailyChart.title(function (d) {
if(!compareCheckbox.prop('checked') && !isNaN(d.value.avg) && d.value.avg > 0){
var wsd = that.wsd(d.key, that.hourlyData, 'dayOfWeek');
return translator.translate("avg_speed") + ' ' + Math.round(d.value.avg)
+ ' KPH, ' + translator.translate("std_dev") + ': ' + wsd;
}
return null;
});
}
dc.renderAll();
},
wsd: function(key, hourlyData, keyParam){
var hours = [];
hourlyData.forEach(function (d) {
if(d[keyParam] == key && d.c > 0){
hours.push(d);
}
});
var WSD = 0; //Weighted std dev
var totalCount = 0;
hours.forEach(function (d) {
WSD += d.c * d.std;
totalCount += d.c;
});
WSD /= totalCount;
WSD = Math.round(WSD * 100) / 100;
return WSD;
},
returnToOverall: function(){
$('#routeData').show();
$('#routeButtons').show();
$('#routeSelections').hide();
$('#analyzeByTimeButtons').hide();
$('#selectedDateAndTime').hide();
$('#analyzeByTime').show();
$('#returnToOverall').hide();
this.getRoute();
},
renderHourButtons: function() {
$('#byHourRouteButtons').hide();
$('#routeSelections').hide();
var timeButtons = $('#hourButtons');
for(var i = 0; i < 24; i++){
var caption = (i < 10 ? '0' + i : i) + ":00";
var r = $('<span type="button" class="col-md-4 btn hourButton" data-toggle="button" hour="' + i + '">' + caption + '</span>');
timeButtons.append(r)
}
$(".hourButton").hover(
function () {
$(this).addClass('btn-primary');
},
function () {
$(this).removeClass('btn-primary');
$(this).removeClass('active');
}
);
$(".hourButton").click(
function (evt) {
var hour = $(evt.target).attr('hour');
$(evt.target).removeClass('active');
A.app.sidebarTabs.hourSelect(hour);
}
);
$('.daySelect').click(function(){
if ($(this).is(':checked'))
{
$(".hourButton").removeClass('disabled');
}
});
},
analyzeByTime: function(){
if($('.hourButton').length == 0) {
this.renderHourButtons();
}
$('#routeData').hide();
$('#routeButtons').hide();
$('#routeSelections').show();
$('#analyzeByTimeButtons').show();
$('.daySelect').attr('checked', false);
$(".hourButton").addClass('disabled');
$('#toggleFilters2').hide();
},
initialize : function() {
$.getJSON('/colors', function(data) {
var binWidth = 240 / data.colorStrings.length;
$('#maxSpeedInKph').html(data.maxSpeedInKph);
var parent = $('#speedLegend').children('svg');
for(var i in data.colorStrings) {
var colorString = data.colorStrings[i];
var bin = $(document.createElementNS("http://www.w3.org/2000/svg", "rect")).attr({
fill: colorString,
x: i * binWidth,
width: binWidth,
height: 24
});
parent.append(bin);
}
});
_.bindAll(this, 'update', 'changeFromWeek', 'changeToWeek', 'clickCompare', 'changeConfidenceInterval', 'changeNormalizeBy');
},
onRender : function () {
var user = A.app.instance.user;
if( !(user && user.isLoggedIn()) ){
this.saveRouteContainer.show(new views.SaveRouteButton());
this.exportDataContainer.show(new views.ExportDataButton());
setTimeout(function() {
$('#saveroute').show();
$('#saveRouteContainer').removeClass('col-md-0').addClass('col-md-6');
$('#bookmarkRouteContainer').removeClass('col-md-12').addClass('col-md-6');
}, 200);
}
this.bookmarkRouteContainer.show(new views.BookmarkRouteButton());
}
});
})(Traffic, Traffic.views, Traffic.translations, crossfilter, dc);<file_sep>/src/main/java/io/opentraffic/engine/app/data/TrafficPathEdge.java
package io.opentraffic.engine.app.data;
import io.opentraffic.engine.app.TrafficEngineApp;
import io.opentraffic.engine.data.stats.SummaryStatistics;
import io.opentraffic.engine.geom.StreetSegment;
import org.jcolorbrewer.ColorBrewer;
import org.opentripplanner.util.PolylineEncoder;
import org.opentripplanner.util.model.EncodedPolylineBean;
import java.awt.*;
/**
* Created by kpw on 7/19/15.
*/
public class TrafficPathEdge {
private Color[] colors;
public String geometry;
public String color;
public double length;
public double speed;
public double stdDev;
public boolean inferred;
private static int numberOfBins = Integer.parseInt(TrafficEngineApp.appProps.getProperty("application.numberOfBins"));
private static double maxSpeedInKph = Double.parseDouble(TrafficEngineApp.appProps.getProperty("application.maxSpeedInKph"));
public TrafficPathEdge(StreetSegment streetSegment, SummaryStatistics summaryStatistics) {
this(streetSegment, summaryStatistics, null);
}
public TrafficPathEdge(StreetSegment streetSegment, SummaryStatistics summaryStatistics, Color comparisonColor) {
EncodedPolylineBean encodedPolyline = PolylineEncoder.createEncodings(streetSegment.getGeometry());
geometry = encodedPolyline.getPoints();
if(comparisonColor == null){
colors = ColorBrewer.RdYlBu.getColorPalette(numberOfBins + 1);
if(summaryStatistics.count < 1){
color = "#808080";
}else{
int colorNum = (int) (numberOfBins / (maxSpeedInKph / (summaryStatistics.getMean() * WeeklyStatsObject.MS_TO_KMH)));
if(colorNum > numberOfBins)
colorNum = numberOfBins;
color = String.format("#%02x%02x%02x", colors[colorNum].getRed(), colors[colorNum].getGreen(), colors[colorNum].getBlue());
}
}else{
color = String.format("#%02x%02x%02x", comparisonColor.getRed(), comparisonColor.getGreen(), comparisonColor.getBlue());
}
length = streetSegment.length;
speed = summaryStatistics.getMean();
stdDev = summaryStatistics.getStdDev();
inferred = summaryStatistics.inferred;
}
}
| 922ef435943abac538388b3399ee9fed733907d0 | [
"JavaScript",
"Java"
] | 2 | JavaScript | ducminhquan/traffic-engine-app | 21b32a88975c2a7be2515f2b4d7d9905f40fd9df | 7181f7b2cedb97f278d1d21cc6caf203164b0ebc |
refs/heads/master | <repo_name>Maartyl/lrb-parser<file_sep>/README.md
# lrb-parser
scribble phase -- (naive) Left Reducing Backtracking Parser
Order matters. Evaluation is always equivalent to trying all alternatives in order.
- The only exception is left recursion: those branches
For now, mostly a proof of concept (it probably alraedy exists, but I haven't found it)
- The point was to be able to use LL-ish parser with left recursion.
- All nice-to-use parsers I've found could not handle left recursion.
- I found a way to remove it, without a need to change 'handlers' (code generating ast nodes; after rule-alt)
- Surely nothing new. Maybe even wrong. I just haven't found it.
I also wanted a tiny parser, that can easily be included in projects, etc. (also portable; hence jvm)
If you feel I stole your idea, please tell me! I will most likely prefer to use your parser than spend time writing this.
(but I swear I thought of it myself - not copying anything I've found)
(honestly, it's so small that it probaly doesn't merit much rights, but whatever)
### Limitations
When a rule-alt does not start with left recursion (including indirect), but contains it:
all of the terminals combined before reaching the recursive step **must not** match empty string.
If the parser does not move before reaching recursion, it will allow infinite loop.
As a rule of thumb: terminals that match empty string may only be at the end of a chain.
Only reduces left recursion in first element of a chain (rule-alt)
## TODO
- error reporting
- [x] track row,col
- general improvements
- proper testing
- providing better 'position+context' interface to handlers
- optimization/limitation: optionally Limit backtracking to N(+c) characters
- as is right now, will keep buffer of entire top-level structure in memory
- not a problem for parsing smaller files
- BUT: can start parsing before full file is loaded - will load more as needed
- optimization: if an elem in chain is a chain: splice (those not branching only)
- last is simple; others will need some smart way to compose handlers
- optimization: somehoe merge lexemes, so I don't need to try one at a time
- load yacc files (only the tree part; this has no separate lexer)
- (for me) Learn terminology of parts of grammar.
#### tmp terminology
- `rule`: top level yacc construct. Has a list of alternatives.
- `chain`: a sequence of elements
- `rule-alt`: a chain that is one of the alternatives of a rule
- `element`: (rule reference OR lexem)
- `bracnh`: a path through graph, either matching the input, or failing (followed by trying another branch)
- `lexem`: something that will actually match some length of text
- for now, a regexp
... idk. those are very crude... <file_sep>/settings.gradle
rootProject.name = 'dotScriptJava0'
<file_sep>/src/main/kotlin/MaaParser.kt
package cz.maa.parser
import org.intellij.lang.annotations.Language
import java.io.Reader
import java.io.StringReader
import java.io.StringWriter
import java.io.Writer
import java.lang.IllegalStateException
import kotlin.reflect.KProperty
// my own parser, that handles eft recursion fine
/*
name: Naive LeftReducing Backtracking Parser / ParserGenerator(future)
:: dubbed LRB
* */
//imagined usage
//term("regex") : Parser<string>
// - BETTTER: Parser<RegexMatch>
//term("regex", str=>T) : Parser<T>
//ALSO!!! somehow pass line nubers, etc.
// - maybe that will just e on some kind of ParserContext
//nonterminal... or compose
//nt("name").alt(parser..., (...)=>T) : Parser<T>
// - will need all the overloads for special generics, fine
//parser itself can: recursively fix itself to remove left recursion
// - rules with only left recursion will throw error
//
//2 VERSION::
// PushParse(c :char, x: Context):NextParser / failed
// and
// PullParse(s: CharSource): T or error
// -- this one could be recursive descent..
// I want to TRY make the FIRST
// -- that pushes state and such, has explicit stack...
// -- instead of returning, will just sometimes
// SOOO.... yeah, cannot do the pushing one...
// - oh well; still should be nice
//IMPORTANTLY: must keep the buffer of unparsed stuff...
//class T
//
//fun T.alt(t: T, f: (T) -> T): T = t
//
//val t = T()
//
//val x = t.alt(t) {
// it
//}.alt(t) {
// it
//}
// ... hmm... stateful recursive rules? dammit...
// - needs some kind of stack...
object TEST : Factory() {
@JvmStatic
fun main(args: Array<String>) {
StringReader("1a5aa6 28b3").use {
//val yy = Context(it)
val p = mgram()
println("\n---------")
val rslt = p.parseAll(it).take(10).toList()
println(rslt)
}
}
private fun mgram(): LRBParser<Node> {
val num = term("[0-9]+")
val ows = term("[ \n\t]*")
val expr = rule<Node>("expr")
expr
.alt(expr, term("[abc]+"), expr) { _, l, o, r ->
//Node.Y(Node.Leaf("."), o, r)
Node.Y(l, o, r)
}
.alt(num) { _, n -> Node.Leaf(n) }
val root = rule<Node>("root")
.alt(expr, ows) { _, l, _ -> l }
return fin(root)
}
private fun simplest(): LRBParser<Node> {
return fin(term("[0-9]+") { _, m -> Node.Leaf(m.value) })
}
private fun alt2(): LRBParser<Node> {
val e = rule<Node>("e")
val num: Parser<Node> = term("[0-9]+") { _, m -> Node.Leaf("I:" + m.value) }
val alf: Parser<Node> = term("[a-z]+") { _, m -> Node.Leaf("A:" + m.value) }
e.alt(num)
e.alt(alf)
return fin(e)
}
// private fun fin(expr: Parser<Node>) = rule<Node>("root")
// .alt(expr).compileSubtree(emptySet())
private fun fin(expr: Parser<Node>) = LRBParser(rule<Node>("root").alt(expr))
sealed class Node {
data class Leaf(val s: String) : Node() {
override fun toString() = "($s)"
}
data class Y(
val l: Node,
val op: String,
val r: Node
) : Node() {
override fun toString() = "($l $op $r)"
}
}
}
class LRBParser<T : Any>(rootParserDefinition: Parser<T>) {
private val p = compileParser(rootParserDefinition)
@Suppress("UNCHECKED_CAST")
fun parseOne(r: Reader) = Context(r).let { yy ->
p.parse(frameEmpty, yy, Stack.top)?.also {
yy.informParsedTopLevel()
} as? T
}
@Suppress("ReplaceSingleLineLet", "UNCHECKED_CAST")
fun parseAll(r: Reader) = Context(r).let { yy ->
generateSequence {
p.parse(frameEmpty, yy, Stack.top)?.let {
yy.informParsedTopLevel()
it as T
}
}
}
}
open class Factory {
class R<T : Any> {
private val self = mutableMapOf<String, Alt<T>>()
operator fun getValue(thisRef: Any?, property: KProperty<*>): Alt<T> {
return self[property.name] ?: rule<T>(property.name).also {
self[property.name] = it
}
}
}
companion object {
/**
IMPORTANT: must not use MatchResult after leaving wrap
-- MatchResult becomes unusable, and you may not retain reference to it
*/
fun <T : Any> term(@Language("RegExp") rgx: String, name: String? = null, wrap: (Pin, MatchResult) -> T) =
Terminal(name, Regex("\\A$rgx"), wrap)
fun term(@Language("RegExp") rgx: String, name: String? = null) = term(rgx, name) { _, m -> m.value }
fun <T : Any> rule(name: String) = Alt<T>(name)
fun <T : Any> lrb(root: Parser<T>) = LRBParser(root)
//DANGEROUS:: when in loop: will never move -> infinite loop
fun <T : Any> Parser<T>.opt(dflt: T) =
rule<T>("anon_${this.name}_opt")
.alt(this)
.alt(Chain("empty", emptyList()) { _, _ -> dflt })
}
}
//TODO: will include: col,row, sbOffset after allowed to delete too old.. etc.
data class Pin(
val pos: Int,
val row: Int,
val col: Int,
//who it came from + provides context to handlers
// - Pin will implement some intrerface exposed to handlers
private val yy: Context
)
class Stack(
val next: Stack?,
val creator: Named,
val pin: Pin? = null,
var chainPos: Int? = null
) {
fun showInto(w: Writer) {
next?.showInto(w)
w.write(" / ")
pin?.let { w.write("(${it.pos})") }
w.write(creator.name)
chainPos?.let { w.write(" .$it") }
}
override fun toString() =
StringWriter().use { showInto(it); it.toString() }
companion object {
val top = Stack(null, object : Named {
override val name = "-"
})
}
}
//mutable; not thread safe
class Context(private val src: Reader) : CharSequence {
private val cbuf = CharArray(2048) //buffer for reading from src
private val sb = StringBuffer()
private var srcEmpty = false //set to true once I read last data from src:Reader
private var pos = 0 //position of 'parser head' from start of src
private var shift = 0 //how much was deleted from left of buffer
//(pos-shift) = position of 'parser head' in sb
// - shift comes from shifting the 'window' along, instead of just growing it
// -- also, in js and in bash : that method removes from start
private inline val posSb get() = pos - shift
//as parser progresses: pos ONLY increases
// -- decreased == went back == backtracking
private var row = 0 //how many \n seen in src before pos --- dubs row
private var col = 0 //#of chars from nearest \n|startOfSrc to pos --- dubs column
//if I want to prevent full search, and instead limit bugger
// - can turn into ~LL(c) by only keeping some size of buffer
// -- after some point I 'commited' to the selected branch
// --- then errors will be thrown as if I
// - but that is optimization; first I need proof of concept, that it works at all
// -- same with char 'array map switch' for Alt
// - THEN: Include arg Int, max number of characters for backtracking
// --- btw. it will be impossible to read regexes longer than this
// - FOR NOW: NO BUFFER DELETING
// DO NOT STORE SHIFT -- shift cannot be undone
fun pin() = Pin(pos, row, col, this)
class CannotBacktrack(str: String) : IllegalStateException(str)
fun reset(pin: Pin) {
if ((pin.pos - shift) < 0) {
throw CannotBacktrack(
"buffer no longer available. (required:${pin.pos}, minimal:$shift); buffer:${
substring(0, posSb)}"
)
//TODO: better buffer substring: make it until FURTHEST failure yet
// -- all of that must have matched, before backtracked all the way here
// - problem only with very long regexes, but it's STATED that regex cannot match more than backtracking N
}
pos = pin.pos
row = pin.row
col = pin.col
}
//-1 == unprotected
// - otherwise: any auto-buffer-delete CANNOT delete before and including this pos
private var protectPosFromDelete = 0
private inline fun <T> protectingPos(p: Int = pos, body: () -> T): T {
val outer = protectPosFromDelete
try {
protectPosFromDelete = p
return body()
} finally {
protectPosFromDelete = outer
}
}
private tailrec fun nom(): Boolean {
// read more into buffer
// ret==read anything
if (srcEmpty) return false
val lenRead = src.read(cbuf)
if (lenRead < 0) {
srcEmpty = true
return false
} else {
sb.append(cbuf, 0, lenRead)
}
if (lenRead == 0) //must either READ or END
return nom()
return true
}
@Suppress("NOTHING_TO_INLINE")
private inline fun moveCore(by: Int): Boolean {
pos += by
while (posSb >= sb.length) {
if (!nom())
return false
}
return true
}
fun move(by: Int): Boolean {
//check (by>=0) ... is it needed?
// - could underflow buffer... yeah...
// - NEEDED for row,col computing;; only backtracking can move back
// if (by + posSb < 0)
// throw IndexOutOfBoundsException("pos:$pos shift:$shift by:$by")
if (by <= 0)
throw IllegalArgumentException("must be (>0); is: by:$by")
//in future, nom will also be able to delete? ... NO
//count #of \n in (pos, pos+by)
//
//actually, this protecting should not be needed
// - I CAN NEVER DELETE what is under pos.... obviously
// OOOH! . but it ISN'T -- this has moved position, by the time nom is called
// OK, makes sense! nice ^^
protectingPos {
val start = posSb
var end = posSb + by //NOT INCLUSIVE (for search);; by is len
return moveCore(by).also {
if (!it) //end of Reader:: do not read after end
end = sb.length
var ncount = 0 //#of seen \n-s
var npos = -1 //last seen \n
//UNTIL: do not process the current pos yet
// - included at the start of this loop (next time)
for (i in start until end) {
if (sb[i] == '\n') {
ncount++
npos = i
}
}
row += ncount
if (npos >= 0) {
//seen \n -- col is len from that
col = (end - npos)
} else {
//not seen \n -- just add to current col
col += (end - start)
}
}
}
}
fun informFailedBranch(s: Stack) {
//TODO: store last N, providing them as 'what went wrong' information
// - better: N that went furthest, maybe?
//for now, for testing: just show right away
println("failed: $s IS: ${substring(0, 10).replace("\n", "\\n")}")
}
fun informParsedTopLevel() {
//trim buffer: before 'here' is not needed anymore - already fully parsed
ltrimSb(0)
}
private fun ltrimSb(untilPosRelative: Int) {
val u = posSb + untilPosRelative //exclusive shift end
//will delete buffer up to (posSb+arg)
//out of range values are handled as maximum in that direction
when {
u < 0 -> return //buffer already shorter
u > posSb -> throw IllegalArgumentException("ltrimSb: only (<=0) arguments allowed")
else -> {
sb.delete(0, u) //end is exclusive
shift += u
}
}
}
private fun ensureLookahead(pp: Int) {
//pp is position in buffer
if (pp < 0)
return //for now: always fine, and getc will just return 0
while (pp >= sb.length) {
if (!nom()) {
if (pp - 100 > sb.length) //only throw when out by a lot
throw UnexpectedEofInLookahead()
else return
}
}
}
override val length: Int //seems to work
get() = /*if (srcEmpty) sb.length - pos else*/ (Int.MAX_VALUE - 1000)
override fun get(index: Int): Char {
val i = posSb + index
ensureLookahead(i)
return getc(i)
}
private fun getc(i: Int) = if (i >= 0 && i < sb.length) sb[i] else Char.MIN_VALUE
override fun subSequence(startIndex: Int, endIndex: Int): CharSequence {
val ia = posSb + startIndex
val ie = posSb + endIndex
ensureLookahead(ie - 1)
if (ie >= sb.length) {
//cannot use normal: sb is shorter
// -- this should not be problem: shold only happen at the end
return buildString {
for (i in ia until ie)
append(getc(i))
}
}
//can use normal, fast
return sb.subSequence(ia, ie)
}
class UnexpectedEofInLookahead : Exception()
}
//part of it is 'character enumerator'
// - can move (set new current) and always provide current
class Frame(val args: MutableList<Any>? = null, val pin: Pin? = null)
val frameEmpty = Frame()
class LeftResult(
//for both: order must stay the same as was in alts
//those start with a term
val termParsers: List<IParser>,
//those do not have start: must compose at the top
//WRONG!!!! - needs to be a list of suffix0 chains... right?
// outer list: alts; inner list: suffix-chain
val suffixes: List<List<Suffix>>
) {
fun isExactly(p: IParser) = suffixes.isEmpty() && termParsers.singleOrNull() == p
companion object {
fun exact(p: IParser) = LeftResult(listOf(p), emptyList())
fun suffix0(p: Suffix) = LeftResult(emptyList(), listOf(listOf(p)))
}
}
var dbg_uniq = 0
val dbgUniqNext get() = dbg_uniq++
inline fun <T> protectRecur(p: IParser, vs: MutableSet<IParser>, none: () -> T, body: () -> T): T {
return if (vs.contains(p))
none()
else try {
vs += p
body()
} finally {
vs -= p
}
}
inline fun <T> protectRecurSame(p: IParser, vs: MutableSet<IParser>, body: () -> T) = protectRecur(p, vs, body, body)
fun compileParser(root: IParser): IParser {
val vertices = mutableSetOf<IParser>()
root.collectAllVertices(vertices)
root.printAll()
println("^--------START")
val vertPass2 = mutableListOf<IParser>()
for (v in vertices) {
if (v != v.reduceSelfPass1())
vertPass2.add(v)
}
for (v2 in vertPass2) {
v2.reduceSelfPass2()
}
root.printAll()
println("^--------REDUCED")
//TODO: maybe: simplify wold KEEP vars
// -- then inline would inline all it can...
// var == Alt(1)
// SPLITTING ONLY if needed: I think doing it once works well enough?
// ... or, mayb I cold just simplify twice...
// ---- or even crazier: simplify until no change
val root = root.simplify(mutableSetOf())
root.printAll()
println("^--------SIMPLIFIED")
return root
}
interface Named {
val name: String
}
interface IParser : Named {
//...can do infinite loop? ... could return to chain...
// - but if chain is it's own first arg: that will be infinite anyway...
// ... hmm... maybe one day
// --- may actually se second in alt, and so not inherently infinite...
// -- ok, needs that.
// -- how come splitLeftRecursionBy didn't? ... it probably did, and I just made a mistake
// - will SPLIT such that
fun divideLeft(p: IParser, parents: MutableSet<IParser>): LeftResult
//implementor must: add self, and all nodes it points to (calling this on them)
// - AND if it is in set already, just return: handle loops
fun collectAllVertices(ns: MutableSet<IParser>)
fun reduceSelfPass1() = this
//called on those, who did not return itself in pass 1
fun reduceSelfPass2() {}
fun print(depth: Int, ns: MutableSet<IParser>)
fun printAll() {
val vs = mutableSetOf<IParser>()
collectAllVertices(vs)
for (v in vs)
println(v.printSelf())
}
fun printSelf(): String
fun printRef(): String
fun simplify(vs: MutableSet<IParser>) = this
/*
either returns parsed subtree
or returns null == branch failed
- if returns null, should also set some error on context
-- that is important if it was the last path, and the error will be thrown
-- even better: should keep track exactly where in stack of rules it is
--- so, ideally: have some list
* */
fun parse(f: Frame, yy: Context, stackUp: Stack): Any?
//fun prepareFrame(): Frame
//TODO: optimization: ask
//fun frameArgsMaxSize(): Int = 0
val isTerminal get() = false
}
//typed are parser DEFINITIONS
// - IParser is used internally
// -- always assured to conform to the types: no checking, but casted for typed wrap fns
sealed class Parser<T : Any> : IParser {
//abstract override val name: String
}
class Terminal<T : Any>(
private val name_: String?,
private val rgx: Regex, // BEWARE!!! - must be prepared to ONLY match from start - otherwise, broken
internal val wrap: (Pin, MatchResult) -> T
) : Parser<T>() {
override val name: String get() = name_ ?: "\"${rgx.pattern.substring(2)}\""
override val isTerminal: Boolean get() = true
override fun collectAllVertices(ns: MutableSet<IParser>) {
ns += this
}
override fun divideLeft(p: IParser, parents: MutableSet<IParser>): LeftResult = LeftResult.exact(this)
//@Language("RegExp", "", "") -- intellij highlighting
init {
if (!rgx.pattern.startsWith("\\A"))
throw IllegalArgumentException("Parser.Terminal - regex MUST start with \\A")
}
override fun print(depth: Int, ns: MutableSet<IParser>) {
print(name)
}
override fun printSelf() = "(term $name = \"${rgx.pattern.substring(2)}\")"
override fun printRef() = name
//override fun prepareFrame() = frameEmpty
//ON FAILURE: keeps yy position where it was at the start
override fun parse(f: Frame, yy: Context, stackUp: Stack): Any? = try {
//println("term ${name} @ ${yy.substring(0, 2)}")
val pin = yy.pin()
rgx.find(yy)?.let {
//println("match ${name} = ${it.value}")
println("match: ${Stack(stackUp, this, pin)} == \"${it.value}\"")
val ret = wrap(pin, it)
//matchResult has ref to yy: must not change, until processed
// - hence move must be after wrap
yy.move(it.value.length)
ret
}.also {
if (it == null) {
yy.informFailedBranch(Stack(stackUp, this, pin))
}
}
} catch (e: Context.UnexpectedEofInLookahead) {
//TODO: SET err on yy
null
}
}
class Suffix(
override val name: String, //from what chain is it derived
val ps: List<IParser>,
//takes ONE MORE ARGS than ps.size
// - first extra ergument //is just a suffix0
val wrapPlus: (Pin, List<Any>) -> Any
) : Named {
fun print(depth: Int, ns: MutableSet<IParser>) {
print("($name--")
for (p in ps) {
print(" ")
p.print(depth + 1, ns)
}
print(")")
}
fun simplify(vs: MutableSet<IParser>) = ps.map { it.simplify(vs) }.let {
if (eqList(ps, it))
this
else
Suffix(name, it, wrapPlus)
}
}
class Chain<T : Any>(
override val name: String,
private val ps: List<IParser>,
private val wrap: (Pin, List<Any>) -> T
) : Parser<T>() {
//all must match
//name is UNDER what alt it was defined
// - they do not have their own names, but alts will move around during compilation
// - for errors reporting: good to know
//override fun prepareFrame(): Frame = Frame(arrayOfNulls(frameArgsMaxSize()))
//override fun frameArgsMaxSize(): Int = ps.size
override fun collectAllVertices(ns: MutableSet<IParser>) {
if (ns.contains(this))
return
ns += this
for (p in ps) {
p.collectAllVertices(ns)
}
}
private val suffix get() = Suffix(name, ps.drop(1), wrap)
override fun divideLeft(p: IParser, parents: MutableSet<IParser>) =
//maybe exact? maybe empty?
protectRecur<LeftResult>(this, parents, { throw IllegalStateException("weird loop to self : $name") }) {
//if empty ps : will always match -- can just return myself
if (ps.isEmpty())
return LeftResult.exact(this)
//otherwise, I have some first, so divide it, and if needed, replace myself
if (ps[0] == p)
return LeftResult.suffix0(suffix)
val r = ps[0].divideLeft(p, parents)
if (r.isExactly(ps[0]))
return LeftResult.exact(this)
return LeftResult(
r.termParsers.map { this.replaceFirst(it) },
r.suffixes.map { it + suffix }
)
}
override fun print(depth: Int, ns: MutableSet<IParser>) {
protectRecur(this, ns, { print("@-$name") }) {
print("($name-:")
for (p in ps) {
print(" ")
p.print(depth + 1, ns)
}
print(")")
}
}
override fun printSelf() = "(all $name = ${ps.joinToString(" ") { it.printRef() }})"
override fun printRef() = name
// fun parse2(f: Frame, yy: Context): Any? {
// println("chain $name @ ${yy.substring(0, 2)}")
// val pin = f.pin ?: yy.pin()
//
// if (ps.isEmpty()) {
// return wrap(pin, emptyList())
// }
//
// //always must be passed CLEARED
// val args = f.args ?: mutableListOf()
//
// //they all must match
// for (p in ps) {
// //cannot reuse f: all but first start elsewhere
// val r = p.parse(frameEmpty, yy,)
// if (r == null) {
// yy.reset(pin)
// return null //did not match: fail all
// } else {
// args.add(r)
// }
// }
//
// //after all matched
// return wrap(pin, args)
// }
override fun parse(f: Frame, yy: Context, stackUp: Stack): Any? {
//println("chain $name @ ${yy.substring(0, 2)}")
val pin = f.pin ?: yy.pin()
val s = Stack(stackUp, this, pin)
println("enter: $s")
//println("enter: $s ;; ${yy.substring(0,40).replace("\n", "\\n")}")
if (ps.isEmpty()) {
return wrap(pin, emptyList())
}
//always must be passed CLEARED
val args = f.args ?: mutableListOf()
return if (parseAll(pin, args, ps, yy, s)) {
wrap(pin, args) //after all matched
} else {
null //did not match: fail all
}
}
override fun simplify(vs: MutableSet<IParser>) =
protectRecur(this, vs, { this }) {
Chain(name, ps.map { it.simplify(vs) }, wrap)
}
private fun replaceFirst(p0: IParser, nm: String = name) =
Chain(nm, ps.mapIndexed { i, y -> if (i == 0) p0 else y }, wrap)
}
fun parseAll(
pin: Pin,
args: MutableList<Any>,
ps: List<IParser>,
yy: Context,
stack: Stack
): Boolean {
//they all must match
var i = stack.chainPos ?: 0
for (p in ps) {
stack.chainPos = i++
//cannot reuse f: all but first start elsewhere
val r = p.parse(frameEmpty, yy, stack)
if (r == null) {
yy.reset(pin)
stack.chainPos = null
return false
} else {
args.add(r)
}
}
return true
}
fun composeSuffixChain(ss: List<Suffix>) = ss.reduce { l, r ->
Suffix(l.name + "+" + r.name, l.ps + r.ps) { pin, a ->
//overall I KNOW that a.size MUST== l.ps.size + r.ps.size + 1
// -- or it's bigger, beacuse it is used for all... true
// --- it would be exact, if this was the last one to be processed
val lv = l.wrapPlus(pin, a)
val ma = mutableListOf(lv) //and this replaces the +1 th
ma.addAll(a.drop(l.ps.size + 1)) //took ps+1 args; put r after lv
r.wrapPlus(pin, ma)
}
}
class Reducing<T : Any>(
override val name: String,
private var head: IParser,
//WRONG: that chain still might need to do dispatch...
// - so, alt is possible...
// ... some special, that can prepend arg to ... it's arguments? ...
// ---- can later be unified with 'prefix sharing' if multiple alts have the same
private var repeatAlts: List<Suffix>
) : Parser<T>() {
//must match head
//after that: will try to match repeat as many time as possible
// - repeat MUST NOT be used on it's own
// --- it's wrap functions expects EXTRA FIRST ARG
// --- I always have to provide it
// --- initially head, then previous result
private fun parseAnyAlt(
hv: Any,
pin: Pin,
args: MutableList<Any>,
yy: Context,
stack: Stack
): Any? {
//println("reducA $name @ ${yy.substring(0, 2)}")
for (s in repeatAlts) {
args.clear()
args.add(hv)
stack.chainPos = 1
if (parseAll(pin, args, s.ps, yy, stack)) {
return s.wrapPlus(pin, args)
}
}
return null
}
override fun parse(f: Frame, yy: Context, stackUp: Stack): Any? {
var hv = head.parse(f, yy, Stack(stackUp, this))
?: return null //parser already failed: nothing else needed
//parsed head
// now try to match suffix as many times as possible
var pin = yy.pin()
val args = mutableListOf<Any>()
while (true) {
//println("LOOP $name: acc: $hv")
// always must try all alts in order; if any matches: I repeat
// val sv = parseAnyAlt(hv, pin, args, yy, Stack(stackUp, this, pin))
// if (sv == null)
// return hv
// else {
// hv = sv
// }
//reducing:: update acc with next value
hv = parseAnyAlt(hv, pin, args, yy, Stack(stackUp, this, pin))
?: return hv
val pinOldPos = pin.pos
pin = yy.pin()
if (pinOldPos == pin.pos)
throw InfiniteRecursion(
"in rule: $name ; input.pos: $pinOldPos ; " +
"alts-suffixes: ${repeatAlts.joinToString(" ") { it.name }}"
)
}
}
class InfiniteRecursion(msg: String) : Exception(msg)
//ALSO: only rules need to be compiled... - chains are fine as they are
// -- chains only need to be inlined later, but that is still fine...
// --- that is mostly just a performance optimization
override fun collectAllVertices(ns: MutableSet<IParser>) {
if (ns.contains(this))
return
ns += this
head.collectAllVertices(ns)
for (ra in repeatAlts)
for (p in ra.ps)
p.collectAllVertices(ns)
}
override fun divideLeft(p: IParser, parents: MutableSet<IParser>) =
//TODO: VARIANT where none and body are the same
protectRecurSame(this, parents) {
head.divideLeft(p, parents)
}
override fun print(depth: Int, ns: MutableSet<IParser>) =
protectRecur(this, ns, { print("@*$name") }) {
print("($name*: ")
head.print(depth + 1, ns)
print(" **")
for (p in repeatAlts) {
print(" | ")
p.print(depth + 1, ns)
}
print(")")
}
override fun printSelf() =
"(reducing $name = ${head.printRef()} ** ${repeatAlts.joinToString(" ")
{
"(alt ${it.name} = ${it.ps.joinToString(" ", transform = IParser::printRef)})"
}})"
override fun printRef() = name
override fun simplify(vs: MutableSet<IParser>) =
protectRecur<IParser>(this, vs, { this }) {
head = head.simplify(vs)
repeatAlts = repeatAlts.map { it.simplify(vs) }
this
}
}
fun <T> eqList(l: List<T>, r: List<T>): Boolean {
if (l.size != r.size)
return false
return l.zip(r).all { (a, b) -> a == b }
}
@Suppress("UNCHECKED_CAST")
class Alt<T : Any>(
override val name: String,
private val ps: MutableList<IParser> = mutableListOf()
) : Parser<T>() {
//any must match
var compiledTmp: IParser? = null
override fun collectAllVertices(ns: MutableSet<IParser>) {
if (ns.contains(this))
return
ns += this
for (p in ps) {
p.collectAllVertices(ns)
}
}
override fun divideLeft(p: IParser, parents: MutableSet<IParser>) =
//BEWARE: when parents.contains, maybe returning exact is not correct? idk...
protectRecur(this, parents, { LeftResult.exact(this) }) {
val rs = ps.map { Pair(it, it.divideLeft(p, parents)) }
if (rs.all { (x, r) -> r.isExactly(x) })
return LeftResult.exact(this)
return LeftResult(
rs.map { it.second }.flatMap { it.termParsers },
rs.map { it.second }.flatMap { it.suffixes })
}
override fun parse(f: Frame, yy: Context, stackUp: Stack): Any? {
//println("alt $name @ ${yy.substring(0, 2)}")
if (ps.isEmpty())
return null
val pin = yy.pin()
val args = mutableListOf<Any>()
val ff = Frame(args, pin)
for (p in ps) {
val r = p.parse(ff, yy, Stack(stackUp, this, pin)) //if fails: will itself reset pin
if (r != null)
return r
else
args.clear()
}
return null //no matched
}
override fun reduceSelfPass1(): IParser {
val r = this.divideLeft(this, mutableSetOf())
if (r.isExactly(this))
return this
val ss = r.suffixes.map { composeSuffixChain(it) }
//_T for terminals
val head = Alt<T>(name + "_T$dbgUniqNext", r.termParsers.toMutableList())
if (ss.isEmpty()) {
compiledTmp = head
return head
}
//suffixes would be S, but do not haev a name on their own
val loop = Reducing<T>(name + "_R$dbgUniqNext", head, ss)
compiledTmp = loop
// SOLUTION: second compilation pass: will SET myself from the tmp
return loop
}
override fun reduceSelfPass2() {
compiledTmp?.let {
ps.clear()
ps.add(it)
}
}
private fun simplify0() = if (ps.size == 1) ps[0] else this
override fun simplify(vs: MutableSet<IParser>) =
protectRecur(this, vs, { simplify0() }) {
ps.replaceAll { it.simplify(vs) }
simplify0()
}
override fun print(depth: Int, ns: MutableSet<IParser>) =
protectRecur(this, ns, { print("@|$name") }) {
val s = ""//"\n" + " ".repeat(depth)
val s2 = " "//""\n" + " ".repeat(depth + 2)
print("$s($name::")
for (p in ps) {
print("$s2| ")
p.print(depth + 1, ns)
}
print("$s2)")
}
override fun printSelf() = "(any $name = ${ps.joinToString(" ") { it.printRef() }})"
override fun printRef() = name
//user API
private var ord = 0
private val nameNext get() = name + "_" + ord++
fun alt(wrap: (Pin) -> T): Alt<T> {
ps.add(Chain(nameNext, emptyList()) { p, _ -> wrap(p) })
return this
}
fun <A1 : Any> alt(p1: Parser<A1>, wrap: (Pin, A1) -> T): Alt<T> {
ps.add(Chain(nameNext, listOf(p1)) { p, a -> wrap(p, a[0] as A1) })
return this
}
fun alt(p1: Parser<T>): Alt<T> {
//ps.add(Chain(name, listOf(p1)) { p, a -> a[0] as T })
ps.add(p1)
return this
}
fun <A1 : Any, A2 : Any> alt(p1: Parser<A1>, p2: Parser<A2>, wrap: (Pin, A1, A2) -> T): Alt<T> {
ps.add(Chain(nameNext, listOf(p1, p2)) { p, a -> wrap(p, a[0] as A1, a[1] as A2) })
return this
}
fun <A1 : Any, A2 : Any, A3 : Any>
alt(
p1: Parser<A1>, p2: Parser<A2>, p3: Parser<A3>,
wrap: (Pin, A1, A2, A3) -> T
): Alt<T> {
ps.add(Chain(nameNext, listOf(p1, p2, p3))
{ p, a -> wrap(p, a[0] as A1, a[1] as A2, a[2] as A3) })
return this
}
fun <A1 : Any, A2 : Any, A3 : Any, A4 : Any>
alt(
p1: Parser<A1>, p2: Parser<A2>, p3: Parser<A3>, p4: Parser<A4>,
wrap: (Pin, A1, A2, A3, A4) -> T
): Alt<T> {
ps.add(Chain(nameNext, listOf(p1, p2, p3, p4))
{ p, a -> wrap(p, a[0] as A1, a[1] as A2, a[2] as A3, a[3] as A4) })
return this
}
fun <A1 : Any, A2 : Any, A3 : Any, A4 : Any, A5 : Any>
alt(
p1: Parser<A1>, p2: Parser<A2>, p3: Parser<A3>, p4: Parser<A4>, p5: Parser<A5>,
wrap: (Pin, A1, A2, A3, A4, A5) -> T
): Alt<T> {
ps.add(Chain(nameNext, listOf(p1, p2, p3, p4, p5))
{ p, a -> wrap(p, a[0] as A1, a[1] as A2, a[2] as A3, a[3] as A4, a[4] as A5) })
return this
}
fun <A1 : Any, A2 : Any, A3 : Any, A4 : Any, A5 : Any, A6 : Any>
alt(
p1: Parser<A1>, p2: Parser<A2>, p3: Parser<A3>, p4: Parser<A4>,
p5: Parser<A5>, p6: Parser<A6>,
wrap: (Pin, A1, A2, A3, A4, A5, A6) -> T
): Alt<T> {
ps.add(Chain(nameNext, listOf(p1, p2, p3, p4, p5, p6))
{ p, a ->
wrap(
p,
a[0] as A1, a[1] as A2, a[2] as A3, a[3] as A4,
a[4] as A5, a[5] as A6
)
})
return this
}
fun <A1 : Any, A2 : Any, A3 : Any, A4 : Any, A5 : Any, A6 : Any, A7 : Any>
alt(
p1: Parser<A1>, p2: Parser<A2>, p3: Parser<A3>, p4: Parser<A4>,
p5: Parser<A5>, p6: Parser<A6>, p7: Parser<A7>,
wrap: (Pin, A1, A2, A3, A4, A5, A6, A7) -> T
): Alt<T> {
ps.add(Chain(nameNext, listOf(p1, p2, p3, p4, p5, p6, p7))
{ p, a ->
wrap(
p,
a[0] as A1, a[1] as A2, a[2] as A3,
a[3] as A4, a[4] as A5, a[5] as A6, a[6] as A7
)
})
return this
}
fun <A1 : Any, A2 : Any, A3 : Any, A4 : Any, A5 : Any, A6 : Any, A7 : Any, A8 : Any>
alt(
p1: Parser<A1>, p2: Parser<A2>, p3: Parser<A3>, p4: Parser<A4>,
p5: Parser<A5>, p6: Parser<A6>, p7: Parser<A7>, p8: Parser<A8>,
wrap: (Pin, A1, A2, A3, A4, A5, A6, A7, A8) -> T
): Alt<T> {
ps.add(Chain(nameNext, listOf(p1, p2, p3, p4, p5, p6, p7, p8))
{ p, a ->
wrap(
p,
a[0] as A1, a[1] as A2, a[2] as A3, a[3] as A4,
a[4] as A5, a[5] as A6, a[6] as A7, a[7] as A8
)
})
return this
}
fun <A1 : Any, A2 : Any, A3 : Any, A4 : Any, A5 : Any, A6 : Any, A7 : Any, A8 : Any, A9 : Any>
alt(
p1: Parser<A1>, p2: Parser<A2>, p3: Parser<A3>, p4: Parser<A4>,
p5: Parser<A5>, p6: Parser<A6>, p7: Parser<A7>, p8: Parser<A8>,
p9: Parser<A9>,
wrap: (Pin, A1, A2, A3, A4, A5, A6, A7, A8, A9) -> T
): Alt<T> {
ps.add(Chain(nameNext, listOf(p1, p2, p3, p4, p5, p6, p7, p8, p9))
{ p, a ->
wrap(
p,
a[0] as A1, a[1] as A2, a[2] as A3, a[3] as A4,
a[4] as A5, a[5] as A6, a[6] as A7, a[7] as A8,
a[8] as A9
)
})
return this
}
fun <A1 : Any, A2 : Any, A3 : Any, A4 : Any, A5 : Any, A6 : Any, A7 : Any, A8 : Any, A9 : Any, AA : Any>
alt(
p1: Parser<A1>, p2: Parser<A2>, p3: Parser<A3>, p4: Parser<A4>,
p5: Parser<A5>, p6: Parser<A6>, p7: Parser<A7>, p8: Parser<A8>,
p9: Parser<A9>, pa: Parser<AA>,
wrap: (Pin, A1, A2, A3, A4, A5, A6, A7, A8, A9, AA) -> T
): Alt<T> {
ps.add(Chain(nameNext, listOf(p1, p2, p3, p4, p5, p6, p7, p8, p9, pa))
{ p, a ->
wrap(
p,
a[0] as A1, a[1] as A2, a[2] as A3, a[3] as A4,
a[4] as A5, a[5] as A6, a[6] as A7, a[7] as A8,
a[8] as A9, a[9] as AA
)
})
return this
}
fun <A1 : Any, A2 : Any, A3 : Any, A4 : Any, A5 : Any, A6 : Any, A7 : Any, A8 : Any,
A9 : Any, AA : Any, AB : Any>
alt(
p1: Parser<A1>, p2: Parser<A2>, p3: Parser<A3>, p4: Parser<A4>,
p5: Parser<A5>, p6: Parser<A6>, p7: Parser<A7>, p8: Parser<A8>,
p9: Parser<A9>, pa: Parser<AA>, pb: Parser<AB>,
wrap: (Pin, A1, A2, A3, A4, A5, A6, A7, A8, A9, AA, AB) -> T
): Alt<T> {
ps.add(Chain(nameNext, listOf(p1, p2, p3, p4, p5, p6, p7, p8, p9, pa, pb))
{ p, a ->
wrap(
p,
a[0] as A1, a[1] as A2, a[2] as A3, a[3] as A4,
a[4] as A5, a[5] as A6, a[6] as A7, a[7] as A8,
a[8] as A9, a[9] as AA, a[10] as AB
)
})
return this
}
fun <A1 : Any, A2 : Any, A3 : Any, A4 : Any, A5 : Any, A6 : Any, A7 : Any, A8 : Any,
A9 : Any, AA : Any, AB : Any, AC : Any>
alt(
p1: Parser<A1>, p2: Parser<A2>, p3: Parser<A3>, p4: Parser<A4>,
p5: Parser<A5>, p6: Parser<A6>, p7: Parser<A7>, p8: Parser<A8>,
p9: Parser<A9>, pa: Parser<AA>, pb: Parser<AB>, pc: Parser<AC>,
wrap: (Pin, A1, A2, A3, A4, A5, A6, A7, A8, A9, AA, AB, AC) -> T
): Alt<T> {
ps.add(Chain(nameNext, listOf(p1, p2, p3, p4, p5, p6, p7, p8, p9, pa, pb, pc))
{ p, a ->
wrap(
p,
a[0] as A1, a[1] as A2, a[2] as A3, a[3] as A4,
a[4] as A5, a[5] as A6, a[6] as A7, a[7] as A8,
a[8] as A9, a[9] as AA, a[10] as AB, a[11] as AC
)
})
return this
}
fun <A1 : Any, A2 : Any, A3 : Any, A4 : Any, A5 : Any, A6 : Any, A7 : Any, A8 : Any,
A9 : Any, AA : Any, AB : Any, AC : Any, AD : Any>
alt(
p1: Parser<A1>, p2: Parser<A2>, p3: Parser<A3>, p4: Parser<A4>,
p5: Parser<A5>, p6: Parser<A6>, p7: Parser<A7>, p8: Parser<A8>,
p9: Parser<A9>, pa: Parser<AA>, pb: Parser<AB>, pc: Parser<AC>,
pd: Parser<AD>,
wrap: (Pin, A1, A2, A3, A4, A5, A6, A7, A8, A9, AA, AB, AC, AD) -> T
): Alt<T> {
ps.add(Chain(nameNext, listOf(p1, p2, p3, p4, p5, p6, p7, p8, p9, pa, pb, pc, pd))
{ p, a ->
wrap(
p,
a[0] as A1, a[1] as A2, a[2] as A3, a[3] as A4,
a[4] as A5, a[5] as A6, a[6] as A7, a[7] as A8,
a[8] as A9, a[9] as AA, a[10] as AB, a[11] as AC, a[12] as AD
)
})
return this
}
fun <A1 : Any, A2 : Any, A3 : Any, A4 : Any, A5 : Any, A6 : Any, A7 : Any, A8 : Any,
A9 : Any, AA : Any, AB : Any, AC : Any, AD : Any, AE : Any>
alt(
p1: Parser<A1>, p2: Parser<A2>, p3: Parser<A3>, p4: Parser<A4>,
p5: Parser<A5>, p6: Parser<A6>, p7: Parser<A7>, p8: Parser<A8>,
p9: Parser<A9>, pa: Parser<AA>, pb: Parser<AB>, pc: Parser<AC>,
pd: Parser<AD>, pe: Parser<AE>,
wrap: (Pin, A1, A2, A3, A4, A5, A6, A7, A8, A9, AA, AB, AC, AD, AE) -> T
): Alt<T> {
ps.add(Chain(nameNext, listOf(p1, p2, p3, p4, p5, p6, p7, p8, p9, pa, pb, pc, pd, pe))
{ p, a ->
wrap(
p,
a[0] as A1, a[1] as A2, a[2] as A3, a[3] as A4,
a[4] as A5, a[5] as A6, a[6] as A7, a[7] as A8,
a[8] as A9, a[9] as AA, a[10] as AB, a[11] as AC,
a[12] as AD, a[13] as AE
)
})
return this
}
fun <A1 : Any, A2 : Any, A3 : Any, A4 : Any, A5 : Any, A6 : Any, A7 : Any, A8 : Any, A9 : Any, AA : Any, AB : Any, AC : Any, AD : Any, AE : Any, AF : Any>
alt(
p1: Parser<A1>, p2: Parser<A2>, p3: Parser<A3>, p4: Parser<A4>,
p5: Parser<A5>, p6: Parser<A6>, p7: Parser<A7>, p8: Parser<A8>,
p9: Parser<A9>, pa: Parser<AA>, pb: Parser<AB>, pc: Parser<AC>,
pd: Parser<AD>, pe: Parser<AE>, pf: Parser<AF>,
wrap: (Pin, A1, A2, A3, A4, A5, A6, A7, A8, A9, AA, AB, AC, AD, AE, AF) -> T
): Alt<T> {
ps.add(Chain(nameNext, listOf(p1, p2, p3, p4, p5, p6, p7, p8, p9, pa, pb, pc, pd, pe, pf))
{ p, a ->
wrap(
p,
a[0] as A1, a[1] as A2, a[2] as A3, a[3] as A4,
a[4] as A5, a[5] as A6, a[6] as A7, a[7] as A8,
a[8] as A9, a[9] as AA, a[10] as AB, a[11] as AC,
a[12] as AD, a[13] as AE, a[14] as AF
)
})
return this
}
fun <A1 : Any, A2 : Any, A3 : Any, A4 : Any, A5 : Any, A6 : Any, A7 : Any, A8 : Any, A9 : Any, AA : Any, AB : Any, AC : Any, AD : Any, AE : Any, AF : Any, AG : Any>
alt(
p1: Parser<A1>, p2: Parser<A2>, p3: Parser<A3>, p4: Parser<A4>,
p5: Parser<A5>, p6: Parser<A6>, p7: Parser<A7>, p8: Parser<A8>,
p9: Parser<A9>, pa: Parser<AA>, pb: Parser<AB>, pc: Parser<AC>,
pd: Parser<AD>, pe: Parser<AE>, pf: Parser<AF>, pg: Parser<AG>,
wrap: (Pin, A1, A2, A3, A4, A5, A6, A7, A8, A9, AA, AB, AC, AD, AE, AF, AG) -> T
): Alt<T> {
ps.add(Chain(nameNext, listOf(p1, p2, p3, p4, p5, p6, p7, p8, p9, pa, pb, pc, pd, pe, pf, pg))
{ p, a ->
wrap(
p,
a[0] as A1, a[1] as A2, a[2] as A3, a[3] as A4,
a[4] as A5, a[5] as A6, a[6] as A7, a[7] as A8,
a[8] as A9, a[9] as AA, a[10] as AB, a[11] as AC,
a[12] as AD, a[13] as AE, a[14] as AF, a[15] as AG
)
})
return this
}
}<file_sep>/src/main/kotlin/YaccForm.kt
import cz.maa.parser.Factory
import cz.maa.parser.Parser
import java.io.FileReader
import java.io.Reader
import java.io.StringReader
object YF : Factory() {
private val testInput = """
a
: a '[+-*/]' b
| '[0-9]+' { fine {{} lol {}}{{ } { } {{} }}}
;
b
: a ;; whoa
| '[a-z]'
;
""".trimIndent()
///home/maartyl/dev/IdeaProjects/dotScriptJava1/TEST.txt
val ti2 = """
input
: q n5 AA a_88 a f ahshlafj asdlfjk adkf adjfk adfs
| input line
;
line:
'\n'
| exp '\n' { printf ("\t%.10g\n", ${'$'}1); }
| error '\n' { yyerrok; }
;
exp: NUM { ${'$'}${'$'} = ${'$'}1; }
| VAR { ${'$'}${'$'} = ${'$'}1->value.var; }
| VAR '=' exp { ${'$'}${'$'} = ${'$'}3; ${'$'}1->value.var = ${'$'}3; }
| FNCT '(' exp ')' { ${'$'}${'$'} = (*(${'$'}1->value.fnctptr))(${'$'}3); }
| exp '+' exp { ${'$'}${'$'} = ${'$'}1 + ${'$'}3; }
| exp '-' exp { ${'$'}${'$'} = ${'$'}1 - ${'$'}3; }
| exp '*' exp { ${'$'}${'$'} = ${'$'}1 * ${'$'}3; }
| exp '/' exp { ${'$'}${'$'} = ${'$'}1 / ${'$'}3; }
| '-' exp prec NEG { ${'$'}${'$'} = -${'$'}2; }
| exp '^' exp { ${'$'}${'$'} = pow (${'$'}1, ${'$'}3); }
| '(' exp ')' { ${'$'}${'$'} = ${'$'}2; }
;
""".trimIndent()
@JvmStatic
fun main(args: Array<String>) {
if (args.isEmpty()) {
StringReader(ti2).use(::parsePrint)
} else {
FileReader(args[0]).use(::parsePrint)
}
}
private fun parsePrint(r: Reader) {
val p = lrb(grammar())
val l = p.parseAll(r).toList()
if (l.isEmpty()){
println("nothing matched")
}
for (d in l) {
d.print()
}
}
fun grammar(): Parser<Rule> {
//beware: MATCHES EMPTY //optional whitespce
val ows = term("""([ \t\r\n]|;;([^\n]*)\n)*""", "ows")
val ref = term("""[\p{Alpha}_][\p{Alnum}_]*""", "ref")
val str = term("""['](([^'\\]|\\.)*)[']""", "str") { _, m -> m.groups[1]?.value ?: "!!!" }
fun <T : Any> Parser<T>.rtrim() =
rule<T>("anon_${this.name}_ows").alt(this, ows) { _, a, _ -> a }
val rule by R<Rule>()
val chain by R<List<Elem>>()
val chainTop by R<Chain>()
val elem by R<Elem>()
val body by R<List<Chain>>()
//val bodyTop by R<Body>()
//for now only temporary
// - to parse yacc grammar, need to handle {...} blocks
// - IGNORED for now
val codeYacc by R<String>()
val codeYaccInner by R<String>()
rule
.alt(ows, ref.rtrim(), term(":").rtrim(), body, term(";"))
{ _, _, name, _, b, _ -> Rule(name, Body(b)) }
chain
.alt(elem)
{ _, s -> listOf(s) }
.alt(chain, ows, elem)
{ _, a, _, e -> a + e }
//FUTURE will include optional {fn}
chainTop.alt(chain.rtrim(), codeYacc) { _, a, c -> Chain(a,c) }
//chainTop.alt(chain.rtrim()) { _, a -> Chain(a) }
//for now: any nested {}
// - a? mst not be in a loop, but it's own thingy... yes
codeYacc/// .... hmm... how to make it skipable?
.alt(term("[{]"), codeYaccInner.opt(""), term("[}]")) { _, _, s, _ -> s }
//.alt(term("[{][}]"))
.alt(ows)// ACTUALLY FINE ///thought: ILLEGAL: would match EMPTY ... - infinite loop
val nocpar = term("[^{}]+")
codeYaccInner
.alt(term("[{]"), codeYaccInner, term("[}]")) { _, a, b, c -> a+b+c }
//MAYBE problem: if left matches NOTHING ... becomes LEFT RECURSIVE ???
// .... but for left to match nothing, next must be [{}] ...
// ,... yes, I think {}} will create infinite recursion: let's try
// YES IT HAS
//.alt(term("")) //this the casethat is problematic:maybe will work now?
// ... no, now it ALWAYS matches;; ok, attempt: change to + on first only
//.alt(term("[^{}]+"), codeYaccInner, term("[^{}]*")){_,a,b,c->a+b+c}
.alt(nocpar)
.alt(term("[{][}]"))
.alt(codeYaccInner, codeYaccInner){_,a,b->a+b}
// ... WHY problem? ... where would the loop be? - WORKS!
// - if not LEFT recursion part...
//bodyTop.alt(body) { _, a -> Body(a) }
body
.alt(chainTop, ows)
{ _, x, _ -> listOf(x) }
.alt(body, term("\\|").rtrim(), chainTop.rtrim())
{ _, a, _, e -> a + e }
elem
.alt(str) { _, a -> Rgx(a) }
.alt(ref) { _, a -> Ref(a) }
return rule.rtrim()
}
//fun pos(Pin):Pos -- FUTURE
}
//FUTURE: row, col
//class Pos()
class Rule(val name: String, val body: Body) {
fun print() {
println("$name:")
body.print()
}
}
class Body(val alts: List<Chain>) {
fun print() {
for (a in alts) {
print(" |")
a.print()
println()
}
}
}
data class Chain(val elems: List<Elem>, val code:String) {
fun print() {
for (e in elems) {
print(" ")
print(e)
}
print(" ")
print("{$code}")
}
}
//FUTURE: handler name
sealed class Elem {
override fun toString() = when {
this is Rgx -> "/${this.rgx}/"
this is Ref -> this.name
else -> "?${this.javaClass.name}?"
}
}
class Rgx(val rgx: String) : Elem()
class Ref(val name: String) : Elem() | 41f2fae52b5fb112de5bdeff9915ffd6824a74ca | [
"Markdown",
"Kotlin",
"Gradle"
] | 4 | Markdown | Maartyl/lrb-parser | fb8f370743c24f63b3017102babc9351b71a44ff | 7d63d0befba27b13b114f29088d221bb920462b6 |
refs/heads/master | <repo_name>goutilpkg/go-sdk<file_sep>/upyun/form/policy.go
package form
import (
"encoding/base64"
"encoding/json"
"fmt"
"net/url"
"sort"
)
/*
from: http://docs.upyun.com/api/form_api/
### 表单 API 参数
| 参数 | 必选 | 说明 |
|----------------------|------|-----------------------------------------------------------------------------------------------------|
| bucket | 是 | 保存所上传的文件的 UPYUN 空间名 |
| save-key | 是 | 保存路径,如: '/path/to/file.ext',可用占位符 [\[注1\]](#note1) |
| expiration | 是 | 请求的过期时间,UNIX 时间戳(秒) |
| allow-file-type | 否 | 文件类型限制,制定允许上传的文件扩展名 |
| content-length-range | 否 | 文件大小限制,格式:`min,max`,单位:字节,如 `102400,1024000`,允许上传 100Kb~1Mb 的文件 |
| content-md5 | 否 | 所上传的文件的 MD5 校验值,UPYUN 根据此来校验文件上传是否正确 |
| content-secret | 否 | 原图访问密钥 [\[注2\]](#note2) |
| content-type | 否 | UPYUN 默认根据扩展名判断,手动指定可提高精确性 |
| image-width-range | 否 | 图片宽度限制,格式:`min,max`,单位:像素,如 `0,1024`,允许上传宽度为 0~1024px 之间 |
| image-height-range | 否 | 图片高度限制,格式:`min,max`,单位:像素,如 `0,1024`,允许上传高度在 0~1024px 之间 |
| notify-url | 否 | 异步通知 URL,见 [\[通知规则\]](#notify_return) |
| return-url | 否 | 同步通知 URL,见 [\[通知规则\]](#notify_return) |
| x-gmkerl-thumbnail | 否 | 缩略图版本名称,仅支持图片类空间,可搭配其他 `x-gmkerl-*` 参数使用 [\[注3\]](#note3) |
| x-gmkerl-type | 否 | 缩略类型 [\[注4\]](#note4) |
| x-gmkerl-value | 否 | 缩略类型对应的参数值 [\[注4\]](#note5) |
| x-gmkerl-quality | 否 | **默认 95**缩略图压缩质量 |
| x-gmkerl-unsharp | 否 | **默认锐化(true)**是否进行锐化处理 |
| x-gmkerl-rotate | 否 | 图片旋转(顺时针),可选:`auto`,`90`,`180`,`270` 之一 |
| x-gmkerl-crop | 否 | 图片裁剪,格式:`x,y,width,height`,均需为正整型 |
| x-gmkerl-exif-switch | 否 | 是否保留 exif 信息,仅在搭配 `x-gmkerl-crop`,`x-gmkerl-type`,`x-gmkerl-thumbnail` 时有效。 |
| ext-param | 否 | 额外参数,UTF-8 编码,并小于 255 个字符 [\[注5\]](#note5) |
*/
type Policy interface {
Set(string, interface{})
Get(string) interface{}
Encode() string
StrEncode() string
UrlEncode() string
Decode(jsonstr string) error
Signature() string
}
type Signature interface {
SigBolocks(Policy) string
SigFile(Policy) string
}
type DefaultPolicy map[string]interface{}
func (dp *DefaultPolicy) Get(key string) interface{} {
return (*dp)[key]
}
func (dp *DefaultPolicy) Set(key string, value interface{}) {
(*dp)[key] = value
}
func (dp *DefaultPolicy) UrlEncode() string {
uv := url.Values{}
for k, v := range *dp {
uv.Set(k, fmt.Sprint(v))
}
return uv.Encode()
}
func (dp *DefaultPolicy) StrEncode() string {
sortKeys := []string{}
for k, _ := range *dp {
sortKeys = append(sortKeys, k)
}
sort.Strings(sortKeys)
dictString := ""
for _, v := range sortKeys {
dictString += v + fmt.Sprint(dp.Get(v))
}
return dictString
}
func (dp *DefaultPolicy) Encode() string {
j, _ := json.Marshal(dp)
return base64.StdEncoding.EncodeToString(j)
}
func (dp *DefaultPolicy) Decode(jsonstr string) error {
return json.Unmarshal([]byte(jsonstr), dp)
}
type formPolicy struct {
ks Signature
DefaultPolicy
}
func NewformPolicy(bucket string, savekey string, expiration int64, ks Signature) (Policy, error) {
return &formPolicy{
ks: ks,
DefaultPolicy: DefaultPolicy{
"bucket": bucket,
"save-key": savekey,
"expiration": expiration,
},
}, nil
}
func (p *formPolicy) Signature() string {
return p.ks.SigFile(p)
}
type mutiformPolicy struct {
ks Signature
DefaultPolicy
}
func NewMutiformPolicy(path string, expiration int64, file_blocks int64, file_hash string, file_size int64, ks Signature) (Policy, error) {
return &mutiformPolicy{
ks: ks,
DefaultPolicy: DefaultPolicy{
"path": path,
"expiration": expiration,
"file_blocks": file_blocks,
"file_hash": file_hash,
"file_size": file_size,
},
}, nil
}
func (p *mutiformPolicy) Signature() string {
return p.ks.SigBolocks(p)
}
type KeySignature struct {
key string
}
func NewKeySignature(key string) Signature {
return &KeySignature{key: key}
}
func (s *KeySignature) SigBolocks(p Policy) string {
sig, _ := SumStrMd5(p.StrEncode() + s.key)
return sig
}
func (s *KeySignature) SigFile(p Policy) string {
sig, _ := SumStrMd5(p.Encode() + "&" + s.key)
return sig
}
<file_sep>/upyun/form/utils.go
package form
import (
"crypto/md5"
"fmt"
"io"
"os"
)
func SumStrMd5(str string) (string, error) {
return fmt.Sprintf("%x", md5.Sum([]byte(str))), nil
}
func SumFileMd5(filename string) (string, error) {
f, err := os.Open(filename)
if err != nil {
return "", err
}
h := md5.New()
io.Copy(h, f)
return fmt.Sprintf("%x", h.Sum(nil)), nil
}
<file_sep>/upyun/form/form.go
package form
import (
"bytes"
"crypto/md5"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
"os"
"time"
)
const (
Auto = "v0.api.upyun.com"
Telecom = "v1.api.upyun.com"
Cnc = "v2.api.upyun.com"
Ctt = "v3.api.upyun.com"
Muti = "m0.api.upyun.com"
)
const (
OneM = int64(1024 * 1024)
)
type UpForm struct {
client *http.Client
sig Signature
bucket string
ks Signature
}
func NewUpForm(bucket string, ks Signature) *UpForm {
return &UpForm{
client: &http.Client{},
bucket: bucket,
ks: ks,
}
}
func (uf *UpForm) PostFile(filepath string, remotepath string) error {
file, err := os.Open(filepath)
if err != nil {
return err
}
defer file.Close()
return uf.PostData(file, remotepath)
}
func (uf *UpForm) PostData(file io.Reader, remotepath string) error {
p, err := NewformPolicy(uf.bucket, remotepath, time.Now().Add(time.Minute*5).Unix(), uf.ks)
if err != nil {
return err
}
return uf.postData(Auto, file, p)
}
func (uf *UpForm) postData(server string, file io.Reader, p Policy) error {
var b bytes.Buffer
w := multipart.NewWriter(&b)
fw, err := w.CreateFormFile("file", "file.data")
if nil != err {
return err
}
io.Copy(fw, file)
fw, _ = w.CreateFormField("policy")
fw.Write([]byte(p.Encode()))
fw, _ = w.CreateFormField("signature")
fw.Write([]byte(p.Signature()))
w.Close()
posturl := fmt.Sprintf("http://%s/%v", server, uf.bucket)
rsp, err := uf.client.Post(posturl, w.FormDataContentType(), &b)
if nil != err {
return err
}
if http.StatusOK != rsp.StatusCode {
return fmt.Errorf("Post File Data Failed: %v", rsp.StatusCode)
}
return nil
}
func (uf *UpForm) postForm(server string, p Policy) (io.ReadCloser, error) {
param := url.Values{}
param.Set("policy", p.Encode())
param.Set("signature", p.Signature())
posturl := fmt.Sprintf("http://%s/%v", server, uf.bucket)
rsp, err := uf.client.PostForm(posturl, param)
if nil != err {
return nil, err
}
if http.StatusOK != rsp.StatusCode {
bd, _ := ioutil.ReadAll(rsp.Body)
fmt.Println(string(bd), uf, uf.bucket)
return nil, fmt.Errorf(rsp.Status)
}
return rsp.Body, nil
}
type uploadStatus struct {
SaveToken string `json:"save_token"` //分块上传索引key,下一步分块上传数据时必须携带本参数
BucketName string `json:"bucket_name"` //文件保存空间
Blocks int64 `json:"blocks"` //文件分块数量
Status []int `json:"status"` //分块文件上传状态,true表示已完成上传,false表示分块未完成上传。数组索引表示分块序号,从0开始;
ExpiredAt int64 `json:"expired_at"` //当前分块上传数据有效期,超过有效期之后数据将会被清理
TokenSecret string `json:"token_secret"`
}
func (uf *UpForm) SlicePostFile(filepath string, remotepath string) error {
file, err := os.Open(filepath)
if nil != err {
return err
}
defer file.Close()
return uf.SlicePostData(file, remotepath)
}
func (uf *UpForm) SlicePostData(file io.Reader, remotepath string) error {
var b bytes.Buffer
fileSize, err := io.Copy(&b, file)
if nil != err {
return err
}
h := md5.New()
copySize, err := io.Copy(h, bytes.NewReader(b.Bytes()))
if nil != err {
return err
}
if copySize != fileSize {
return fmt.Errorf("io.Copy Length Error. Origin: %v bytes, Copyed: %v bytes", fileSize, copySize)
}
fileHash := fmt.Sprintf("%x", h.Sum(nil))
fileBlocks := fileSize / OneM
if fileSize > fileBlocks*OneM {
fileBlocks += 1
}
expiration := time.Now().Add(time.Minute * 5).Unix()
p, _ := NewMutiformPolicy(remotepath, expiration, fileBlocks, fileHash, fileSize, uf.ks)
body, err := uf.postForm(Muti, p)
if nil != err {
return err
}
defer body.Close()
data, err := ioutil.ReadAll(body)
if nil != err {
return err
}
var upstatus uploadStatus
err = json.Unmarshal(data, &upstatus)
if nil != err {
return err
}
//Begin Post file slice
offset := int64(0)
for k, v := range upstatus.Status {
if 2 != v {
index := int64(k)
bufferSize := OneM
if (index+1)*OneM > fileSize {
bufferSize = fileSize - index*OneM
}
data := make([]byte, bufferSize)
br := bytes.NewReader(b.Bytes())
rd, err := br.ReadAt(data, offset)
if nil != err && io.EOF != err {
return err
}
offset += int64(rd)
if int64(rd) != bufferSize {
return fmt.Errorf("Read Failed")
}
h := md5.New()
h.Write(data)
blockHash := fmt.Sprintf("%x", h.Sum(nil))
bp := &mutiformPolicy{
ks: &KeySignature{key: upstatus.TokenSecret},
DefaultPolicy: DefaultPolicy{
"save_token": upstatus.SaveToken,
"expiration": upstatus.ExpiredAt,
"block_index": index,
"block_hash": blockHash,
},
}
err = uf.postData(Muti, bytes.NewReader(data), bp)
if nil != err {
return err
}
}
}
fp := &mutiformPolicy{
ks: &KeySignature{key: upstatus.TokenSecret},
DefaultPolicy: DefaultPolicy{
"save_token": upstatus.SaveToken,
"expiration": time.Now().Add(time.Minute * 5).Unix(),
},
}
_, err = uf.postForm(Muti, fp)
if nil != err {
return err
}
return nil
}
| 71d893ebd4624d5c02b7b978dd7d4280a0dbfbeb | [
"Go"
] | 3 | Go | goutilpkg/go-sdk | e26b2c364142a34ec540986466ccb1428e9e1b5b | f8581b448f5199da9d5321f1f4acb2f5e62676ef |
refs/heads/master | <repo_name>drdrongo/rails-stupid-coaching<file_sep>/app/controllers/questions_controller.rb
class QuestionsController < ApplicationController
def ask
@members = %w[<NAME>]
end
def answer
@answer = dummy_coach(params[:question])
end
private
def dummy_coach(input)
if input[-1] == '?'
'Silly question, get dressed and go to work!'
elsif input == 'I am going to work'
'Great!'
else "I don't care, get dressed and go to work!"
end
end
end
| e05fcc14527df6d4a527f8bd6100f7818da422fb | [
"Ruby"
] | 1 | Ruby | drdrongo/rails-stupid-coaching | 8dfb2120c05801db5e44df769245b599c3370b43 | e8be1c9bc2b6ec8db50c533ef0de2a8bbac2ce35 |
refs/heads/master | <repo_name>JosephT5566/ptt-client<file_sep>/test/favorite.ts
import assert from 'assert';
import pttbot from '../src';
import { username, password } from './config';
const newbot = async () => {
const ptt = new pttbot();
await (() => new Promise(resolve => {
ptt.once('connect', resolve);
}))();
const ret = await ptt.login(username, password)
if (!ret) {
throw 'login failed';
}
return ptt;
};
describe('Favorite', () => {
let ptt;
describe('getFavorite', () => {
before('login', async () => {
ptt = await newbot();
});
after('logout', async () => {
await ptt.logout();
});
it('should get favorite list', async () => {
let favorites = await ptt.getFavorite();
assert(favorites.length>0);
favorites.forEach(favorite => {
assert('bn' in favorite && typeof favorite.bn === 'number');
assert('read' in favorite && typeof favorite.read === 'boolean');
assert('boardname' in favorite);
assert('category' in favorite);
assert('title' in favorite);
assert('folder' in favorite && typeof favorite.folder === 'boolean');
assert('divider' in favorite && typeof favorite.divider === 'boolean');
});
});
});
});
<file_sep>/src/utils/keymap.ts
export default {
Enter: '\r',
ArrowLeft: '\x1b[D',
ArrowRight: '\x1b[C',
ArrowUp: '\x1b[A',
ArrowDown: '\x1b[B',
PgUp: '\x1b[5~',
PgDown: '\x1b[6~',
Home: '\x1b[1~',
End: '\x1b[4~',
Backspace: '\b',
CtrlP: '\x10',
CtrlU: '\x15',
CtrlZ: '\x1a',
};
<file_sep>/src/sites/ptt/Board.ts
import {substrWidth} from '../../utils/char';
export class Board {
boardname: string;
bn: number;
read: boolean;
category: string;
title: string;
users: string;
admin: string;
folder: boolean = false;
divider: boolean = false;
constructor() {
}
static fromLine(line: string): Board {
let board = new Board();
board.bn =+substrWidth('dbcs', line, 3, 4).trim();
board.read = substrWidth('dbcs', line, 8, 2).trim() === '';
board.boardname = substrWidth('dbcs', line, 10, 12).trim();
board.category = substrWidth('dbcs', line, 23, 4).trim();
switch (board.boardname) {
case 'MyFavFolder':
board.title = substrWidth('dbcs', line, 30);
board.users = '';
board.admin = '';
board.folder = true;
break;
case '------------':
board.title = substrWidth('dbcs', line, 30);
board.users = '';
board.admin = '';
board.divider = true;
break;
default:
board.title = substrWidth('dbcs', line, 30, 31);
board.users = substrWidth('dbcs', line, 62, 5).trim();
board.admin = substrWidth('dbcs', line, 67 ).trim();
break;
}
return board;
}
};
<file_sep>/src/sites/ptt/bot.ts
import EventEmitter from 'eventemitter3';
import sleep from 'sleep-promise';
import Terminal from 'terminal.js';
import Socket from '../../socket';
import {
decode,
encode,
keymap as key,
} from '../../utils';
import {
getWidth,
indexOfWidth,
substrWidth,
} from '../../utils/char';
import Config from '../../config';
import defaultConfig from './config';
import {Article} from './Article';
import {Board} from './Board';
class Condition {
private typeWord: string;
private criteria: string;
constructor(type: 'push'|'author'|'title', criteria: string) {
switch (type) {
case 'push':
this.typeWord = 'Z';
break;
case 'author':
this.typeWord = 'a';
break;
case 'title':
this.typeWord = '/';
break;
default:
throw `Invalid condition: ${type}`;
}
this.criteria = criteria;
}
toSearchString(): string {
return `${this.typeWord}${this.criteria}`;
}
}
class Bot extends EventEmitter {
static initialState = {
connect: false,
login: false,
};
static forwardEvents = [
'message',
'error',
];
searchCondition = {
conditions: null,
init: function() {
this.conditions = [];
},
add: function(type, criteria) {
this.conditions.push(new Condition(type, criteria));
}
};
private config: Config;
private term: Terminal;
private _state: any;
private currentCharset: string;
private socket: Socket;
private preventIdleHandler: ReturnType<typeof setTimeout>;
constructor(config?: Config) {
super();
this.config = {...defaultConfig, ...config};
this.init();
}
async init(): Promise<void> {
const { config } = this;
this.term = new Terminal(config.terminal);
this._state = { ...Bot.initialState };
this.term.state.setMode('stringWidth', 'dbcs');
this.currentCharset = 'big5';
switch (config.protocol.toLowerCase()) {
case 'websocket':
case 'ws':
case 'wss':
break;
case 'telnet':
case 'ssh':
default:
throw `Invalid protocol: ${config.protocol}`;
break;
}
const socket = new Socket(config);
socket.connect();
Bot.forwardEvents.forEach(e => {
socket.on(e, this.emit.bind(this, e));
});
socket
.on('connect', (...args) => {
this._state.connect = true;
this.emit('connect', ...args);
this.emit('stateChange', this.state);
})
.on('disconnect', (closeEvent, ...args) => {
this._state.connect = false;
this.emit('disconnect', closeEvent, ...args);
this.emit('stateChange', this.state);
})
.on('message', (data) => {
if (this.currentCharset != this.config.charset && !this.state.login &&
decode(data, 'utf8').includes('登入中,請稍候...')) {
this.currentCharset = this.config.charset;
}
const msg = decode(data, this.currentCharset);
this.term.write(msg);
this.emit('redraw', this.term.toString());
})
.on('error', (err) => {
});
this.socket = socket;
}
get state(): any {
return {...this._state};
}
getLine = (n) => {
return this.term.state.getLine(n);
};
async getLines() {
const { getLine } = this;
const lines = [];
lines.push(getLine(0).str);
while (!getLine(23).str.includes("100%")) {
for(let i=1; i<23; i++) {
lines.push(getLine(i).str);
}
await this.send(key.PgDown);
}
const lastLine = lines[lines.length-1];
for(let i=0; i<23; i++) {
if (getLine(i).str == lastLine) {
for(let j=i+1; j<23; j++) {
lines.push(getLine(j).str);
}
break;
}
}
while (lines.length > 0 && lines[lines.length-1].length == 0) {
lines.pop();
}
return lines;
}
send(msg: string): Promise<void> {
this.config.preventIdleTimeout && this.preventIdle(this.config.preventIdleTimeout);
return new Promise((resolve, reject) => {
if (this.state.connect) {
if (msg.length > 0) {
this.socket.send(encode(msg, this.currentCharset));
this.once('message', msg => {
resolve(msg);
});
} else {
console.warn(`Sending message with 0-length`);
resolve();
}
} else {
reject();
}
});
}
preventIdle(timeout: number): void {
clearTimeout(this.preventIdleHandler);
if (this.state.login) {
this.preventIdleHandler = setTimeout(async () => {
await this.send(key.CtrlU);
await this.send(key.ArrowLeft);
}, timeout * 1000);
}
}
async login(username: string, password: string, kick: boolean=true): Promise<any> {
if (this.state.login) return;
username = username.replace(/,/g, '');
if (this.config.charset === 'utf8') {
username += ',';
}
await this.send(`${username}${key.Enter}${password}${key.Enter}`);
let ret;
while ((ret = await this.checkLogin(kick)) === null) {
await sleep(400);
}
if (ret) {
const { _state: state } = this;
state.login = true;
state.position = {
boardname: "",
};
this.searchCondition.init();
this.emit('stateChange', this.state);
}
return ret;
}
async logout(): Promise<boolean> {
if (!this.state.login) return;
await this.send(`G${key.Enter}Y${key.Enter.repeat(2)}`);
this._state.login = false;
this.emit('stateChange', this.state);
return true;
}
private async checkLogin(kick: boolean): Promise<any> {
const { getLine } = this;
if (getLine(21).str.includes("密碼不對或無此帳號")) {
this.emit('login.failed');
return false;
} else if (getLine(23).str.includes("請稍後再試")) {
this.emit('login.failed');
return false;
} else if (getLine(22).str.includes("您想刪除其他重複登入的連線嗎")) {
await this.send(`${key.Backspace}${kick?'y':'n'}${key.Enter}`);
} else if (getLine(23).str.includes("請勿頻繁登入以免造成系統過度負荷")) {
await this.send(`${key.Enter}`);
} else if (getLine(23).str.includes("按任意鍵繼續")) {
await this.send(`${key.Enter}`);
} else if (getLine(23).str.includes("您要刪除以上錯誤嘗試的記錄嗎")) {
await this.send(`${key.Backspace}y${key.Enter}`);
} else if ((getLine(22).str+getLine(23).str).toLowerCase().includes("y/n")) {
await this.send(`${key.Backspace}y${key.Enter}`);
} else if (getLine(23).str.includes("我是")) {
this.emit('login.success');
return true;
} else {
await this.send(`q`);
}
return null;
}
private checkArticleWithHeader(): boolean {
const authorArea = substrWidth('dbcs', this.getLine(0).str, 0, 6).trim();
return authorArea === "作者";
}
setSearchCondition(type: string, criteria: string): void {
this.searchCondition.add(type, criteria);
}
resetSearchCondition(): void {
this.searchCondition.init();
}
isSearchConditionSet(): boolean {
return (this.searchCondition.conditions.length !== 0);
}
async getArticles(boardname: string, offset: number=0): Promise<Article[]> {
await this.enterBoard(boardname);
if (this.isSearchConditionSet()){
let searchString = this.searchCondition.conditions.map(condition => condition.toSearchString()).join(key.Enter);
await this.send(`${searchString}${key.Enter}`);
}
if (offset > 0) {
offset = Math.max(offset-9, 1);
await this.send(`${key.End}${key.End}${offset}${key.Enter}`);
}
const { getLine } = this;
let articles: Article[] = [];
for(let i=3; i<=22; i++) {
const line = getLine(i).str;
const article = Article.fromLine(line);
article.boardname = boardname;
articles.push(article);
}
// fix sn
if (articles.length >= 2 && articles[0].sn === 0) {
for(let i=1; i<articles.length; i++) {
if (articles[i].sn !== 0) {
articles[0].sn = articles[i].sn - i;
break;
}
}
}
for(let i=1; i<articles.length; i++) {
articles[i].sn = articles[i-1].sn+1;
}
await this.enterIndex();
return articles.reverse();
}
async getArticle(boardname: string, sn: number, article: Article = new Article()): Promise<Article> {
await this.enterBoard(boardname);
if (this.isSearchConditionSet()){
let searchString = this.searchCondition.conditions.map(condition => condition.toSearchString()).join(key.Enter);
await this.send(`${searchString}${key.Enter}`);
}
const { getLine } = this;
await this.send(`${sn}${key.Enter}${key.Enter}`);
const hasHeader = this.checkArticleWithHeader();
article.sn = sn;
article.boardname = boardname;
if (hasHeader) {
article.author = substrWidth('dbcs', getLine(0).str, 7, 50).trim();
article.title = substrWidth('dbcs', getLine(1).str, 7 ).trim();
article.timestamp = substrWidth('dbcs', getLine(2).str, 7 ).trim();
}
article.lines = await this.getLines();
await this.enterIndex();
return article;
}
async getFavorite(offsets: number|number[]=[]) {
if (typeof offsets === "number") {
offsets = [offsets];
}
await this.enterFavorite(offsets);
const { getLine } = this;
const favorites: Board[] = [];
while (true) {
let stopLoop = false;
for(let i=3; i<23; i++) {
let line = getLine(i).str;
if (line.trim() === '') {
stopLoop = true;
break;
}
let favorite = Board.fromLine(line);
if (favorite.bn !== favorites.length + 1) {
stopLoop = true;
break;
}
favorites.push(favorite);
}
if (stopLoop) {
break;
}
await this.send(key.PgDown);
}
await this.enterIndex();
return favorites;
}
async getMails(offset: number=0) {
await this.enterMail();
if (offset > 0) {
offset = Math.max(offset-9, 1);
await this.send(`${key.End}${key.End}${offset}${key.Enter}`);
}
const { getLine } = this;
let mails = [];
for(let i=3; i<=22; i++) {
const line = getLine(i).str;
const mail = {
sn: +substrWidth('dbcs', line, 1, 5).trim(),
date: substrWidth('dbcs', line, 9, 5).trim(),
author: substrWidth('dbcs', line, 15, 12).trim(),
status: substrWidth('dbcs', line, 30, 2).trim(),
title: substrWidth('dbcs', line, 33 ).trim(),
};
mails.push(mail);
}
await this.enterIndex();
return mails.reverse();
}
async getMail(sn: number) {
await this.enterMail();
const { getLine } = this;
await this.send(`${sn}${key.Enter}${key.Enter}`);
const hasHeader = this.checkArticleWithHeader();
let mail = {
sn,
author: "",
title: "",
timestamp: "",
lines: [],
};
if (this.checkArticleWithHeader()) {
mail.author = substrWidth('dbcs', getLine(0).str, 7, 50).trim();
mail.title = substrWidth('dbcs', getLine(1).str, 7 ).trim();
mail.timestamp = substrWidth('dbcs', getLine(2).str, 7 ).trim();
}
mail.lines = await this.getLines();
await this.enterIndex();
return mail;
}
async enterIndex(): Promise<boolean> {
await this.send(`${key.ArrowLeft.repeat(10)}`);
return true;
}
async enterBoard(boardname: string): Promise<boolean> {
await this.send(`s${boardname}${key.Enter} ${key.Home}${key.End}`);
boardname = boardname.toLowerCase();
const { getLine } = this;
if (getLine(23).str.includes("按任意鍵繼續")) {
await this.send(` `);
}
if (getLine(0).str.toLowerCase().includes(`${boardname}`)) {
this._state.position.boardname = boardname;
this.emit('stateChange', this.state);
return true;
}
return false;
}
async enterFavorite(offsets: number[]=[]): Promise<boolean> {
const enterOffsetMessage =
offsets.map(offset => `${offset}${key.Enter.repeat(2)}`).join();
await this.send(`F${key.Enter}${key.Home}${enterOffsetMessage}`);
return true;
}
async enterMail(): Promise<boolean> {
await this.send(`M${key.Enter}R${key.Enter}${key.Home}${key.End}`);
return true;
}
}
export default Bot;
<file_sep>/README.md
# ptt-client
**ptt-client** is an unofficial client to fetch data from PTT ([ptt.cc]), the
famous BBS in Taiwan, over WebSocket. This module works in browser and Node.js.
PTT supports connection with WebSocket by [official].
[ptt.cc]: https://www.ptt.cc
[official]: https://www.ptt.cc/bbs/SYSOP/M.1496571808.A.608.html
## Installation
```
npm install ptt-client
```
## Example
```js
import PTT from 'ptt-client';
// if you are using this module in node.js, 'ws' is required as WebSocket polyfill.
// you don't need this in modern browsers
global.WebSocket = require('ws');
(async function() {
const ptt = new PTT();
ptt.once('connect', () => {
const kickOther = true;
if (!await ptt.login('guest', 'guest', kickOther))
return;
// get last 20 articles from specific board. the first one is the latest
let articles = await ptt.getArticles('C_Chat');
// get articles with offset
let offset = articles[article.length-1].sn - 1;
let articles2 = await ptt.getArticles('C_Chat', offset);
// get articles with search filter (type: 'push', 'author', 'title')
ptt.setSearchCondition('title', '閒聊');
articles2 = await ptt.getArticles('C_Chat');
// get the content of specific article
let article = await ptt.getArticle('C_Chat', articles[articles.length-1].sn);
// get your favorite list
let favorites = await ptt.getFavorite();
// get favorite list in a folder
if (favorites[0].folder)
await ptt.getFavorite(favorites[0].bn);
let mails = await ptt.getMails();
let mail = await ptt.getMail(mails[0].sn);
await ptt.logout();
});
})();
```
## Development
```
npm run test
npm run build
```
## License
MIT
<file_sep>/src/sites/ptt/Article.ts
import {substrWidth} from '../../utils/char';
export class Article {
boardname: string;
sn: number;
push: string;
date: string;
timestamp: string;
author: string;
status: string;
title: string;
fixed: boolean;
private _content: string[] = [];
constructor() {
}
static fromLine(line: string): Article {
let article = new Article();
article.sn =+substrWidth('dbcs', line, 1, 7).trim();
article.push = substrWidth('dbcs', line, 9, 2).trim();
article.date = substrWidth('dbcs', line, 11, 5).trim();
article.author = substrWidth('dbcs', line, 17, 12).trim();
article.status = substrWidth('dbcs', line, 30, 2).trim();
article.title = substrWidth('dbcs', line, 32 ).trim();
article.fixed = substrWidth('dbcs', line, 1, 7).trim().includes('★');
return article;
}
get content(): ReadonlyArray<string> {
return this._content;
}
set content(data: ReadonlyArray<string>) {
this._content = data.slice();
}
/**
* @deprecated
*/
get lines(): ReadonlyArray<string> {
return this.content;
}
set lines(data: ReadonlyArray<string>) {
this.content = data;
}
};
export default Article;
<file_sep>/test/articles.ts
import assert from 'assert';
import pttbot from '../src';
import { username, password } from './config';
const newbot = async () => {
const ptt = new pttbot();
await (() => new Promise(resolve => {
ptt.once('connect', resolve);
}))();
const ret = await ptt.login(username, password)
if (!ret) {
throw 'login failed';
}
return ptt;
};
describe('Articles', () => {
let ptt;
before('login', async () => {
ptt = await newbot();
});
after('logout', async () => {
await ptt.logout();
});
describe('getArticles', () => {
let articles;
const boardname = 'C_Chat';
it('should get correct article list from board', async () => {
articles = await ptt.getArticles(boardname);
assert(articles.length > 0);
articles.forEach(article => {
assert('sn' in article);
assert('push' in article);
assert('date' in article);
assert('author' in article);
assert('status' in article);
assert('title' in article);
assert((new RegExp(/^\d{1,2}\/\d{1,2}$/)).test(article.date));
});
});
it('should get correct article list with offset argument', async () => {
let articles2 = await ptt.getArticles(boardname, articles[articles.length-1].sn-1);
let article1Info = `${articles[articles.length-1].sn} ${articles[articles.length-1].author} ${articles[articles.length-1].title}`;
let article2Info = `${articles2[0].sn} ${articles2[0].author} ${articles2[0].title}`;
assert.equal(articles2[0].sn, articles[articles.length-1].sn-1, `${article1Info}\n${article2Info}`);
});
});
describe('getArticle', () => {
it('should get correct article from board', async () => {
const article = await ptt.getArticle('Gossiping', 100000);
assert('sn' in article);
assert('author' in article);
assert('title' in article);
assert('timestamp' in article);
assert('lines' in article);
assert.strictEqual(article.sn, 100000);
});
});
describe('getSearchArticles by push', () => {
after('resetSearchCondition', () => {
ptt.resetSearchCondition();
});
let board = 'C_Chat';
let push = '50';
it('should get correct articles with specified push number from board', async () => {
ptt.setSearchCondition('push', push);
let articles = await ptt.getArticles(board);
assert(articles.length > 0);
articles.forEach(article => {
let pushCheck = false;
let articleInfo = `${article.sn} ${article.push} ${article.title}`;
let pushNumber = (article.push === '爆') ? '100' : article.push;
assert(Number(pushNumber) >= Number(push), articleInfo);
});
});
})
describe('getSearchArticles by author', () => {
after('resetSearchCondition', () => {
ptt.resetSearchCondition();
});
let board = 'Gossiping'
let author = 'Gaiaesque';
it('should get correct articles with specified author name from board', async () => {
ptt.setSearchCondition('author', author);
let articles = await ptt.getArticles(board);
assert(articles.length > 0);
articles.forEach(article => {
let articleInfo = `${article.sn} ${article.author} ${article.title}`;
assert.equal(article.author.toLowerCase(), author.toLowerCase(), articleInfo);
});
});
})
describe('getSearchArticles by title', () => {
after('resetSearchCondition', () => {
ptt.resetSearchCondition();
});
let board = 'C_Chat';
let title = '閒聊';
it('should get correct articles contain specified title word from board', async () => {
ptt.setSearchCondition('title', title);
let articles = await ptt.getArticles(board);
assert(articles.length > 0);
articles.forEach(article => {
let articleInfo = `${article.sn} ${article.push} ${article.title}`;
assert(article.title.toLowerCase().includes(title), articleInfo);
});
});
})
describe('getSearchArticles by title and push', () => {
after('resetSearchCondition', () => {
ptt.resetSearchCondition();
});
let board = 'C_Chat';
let title = '閒聊';
let push = '50';
it('should get correct articles contain specified title word AND push number from board', async () => {
ptt.setSearchCondition('title', title);
ptt.setSearchCondition('push', push);
let articles = await ptt.getArticles(board);
assert(articles.length > 0);
articles.forEach(article => {
let articleInfo = `${article.sn} ${article.push} ${article.title}`;
let pushNumber = (article.push === '爆') ? '100' : article.push;
assert(article.title.toLowerCase().includes(title), articleInfo);
assert(Number(pushNumber) >= Number(push), articleInfo);
});
});
})
});
| 35be33c602c1033c0347619d73af35670a0bf0c4 | [
"JavaScript",
"TypeScript",
"Markdown"
] | 7 | TypeScript | JosephT5566/ptt-client | bb0fc6fc60d0b544f1dceba5de1f4d675a14573e | d4a3a672ffb705c8ecb3a1539ce122ecf516bbc2 |
refs/heads/master | <repo_name>KsenyW/angular-works<file_sep>/homeworks/lesson4/task1.js
/**
* Created by Kseny on 29.08.2016.
*/
//
//Задача 1
//
//Создайте сервис, который предоставляет стандартные математические операции – сложение, умножение и т.д.
// Используйте три разных способа для создания сервиса.
var providerModule = angular.module('providerModule', [])
.provider('providerCalc', function(){
return{
$get: function(){
return function(op1, op2, operation){
switch(operation){
case '+': return op1- -op2;
case '-': return op1-op2;
case '*': return op1*op2;
case '/': return op1/op2;
default: return false;
}
}
}
}
});
var helloWorldApp = angular.module("App", ['providerModule']);
helloWorldApp.controller("mainCtrl", function ($scope, factoryCalc, providerCalc) {
$scope.op1 = 0;
$scope.op2 = 0;
$scope.factoryOutput = 0;
$scope.serviceOutput = 0;
$scope.providerOutput = 0;
$scope.clickFactory = function(operation){
$scope.factoryOutput = factoryCalc($scope.op1, $scope.op2, operation);
$scope.serviceOutput = serviceCalc($scope.op1, $scope.op2, operation);
$scope.providerOutput = providerCalc($scope.op1, $scope.op2, operation);
}
})
.factory('factoryCalc', function(){
return function(op1, op2, operation){
switch(operation){
case '+': return op1- -op2;
case '-': return op1-op2;
case '*': return op1*op2;
case '/': return op1/op2;
default: return false;
}
}
}).service('serviceCalc', serviceCalc);
function serviceCalc(op1, op2, operation){
switch(operation){
case '+': return op1- -op2;
case '-': return op1-op2;
case '*': return op1*op2;
case '/': return op1/op2;
default: return false;
}
}<file_sep>/classworks/lesson5/task3.js
/**
* Created by Kseny on 23.08.2016.
// */
//Задача 3
//
//Разработайте сервис, которой можно будет использовать для записи данных в cookie. Продемонстрируйте работу сервиса.
var app = angular.module('App', ['ngCookies'])
.controller('mainCtrl', ['$scope', '$cookieStore', function ($scope, $cookieStore){
$scope.cookieId = '';
$scope.cookieVal = '';
$scope.output = [];
var myCookie = 'cookies on this site: ';
$scope.makeCookie = function () {
$cookieStore.put($scope.cookieId, $scope.cookieVal);
myCookie = $cookieStore.get($scope.cookieId);
$scope.output.push({val: myCookie, id: $scope.cookieId});
}
}]);<file_sep>/classworks/lesson4/task3.js
/**
* Created by Kseny on 21.08.2016.
*/
//
//Задача 3
//
//Используйте сервис $http для получения данных из файла data.json, который находится в папке data.
// Отобразите полученные данные на странице в виде таблицы. Предусмотрите обработку ошибок в запросе (используя Promise).
var app = angular.module('App', [])
.controller('mainCtrl', function ($scope, $http) {
$scope.sendRequest1 = function () {
var promise = $http.get("data/data.json");
promise.then(successFunc, errorFunc);
};
function successFunc(response){
$scope.items = response.data;
}
function errorFunc(error){
console.error(error.status);
console.error(error.statusText);
}
$scope.sendRequest1();
});<file_sep>/classworks/lesson8/task3.js
/**
* Created by Kseny on 29.08.2016.
*/
//
//Задача 3
//
//Имеется html-разметка:
//
//<div custom-directive>’myButton’</div>
//Создайте директиву, результатом работы которой станет кнопка с текстом 'myButton'. Используйте свойство transclude.
var App = angular.module('App', [])
.directive('customDirective', function () {
return {
restrict: 'A',
transclude: true,
template: '<button class="btn btn-default" ng-transclude></div>'
}
});<file_sep>/homeworks/lesson2/task3.js
/**
* Created by Kseny on 19.08.2016.
*/
//Задача 3
//Реализуйте SPA приложение, в котором пользователю представляется пройти тест из 5 вопросов,
// в каждом вопросе по 4 варианта ответа. Вопросы должны выбираться с помощью radio-button и когда выбран,
// например, вопрос №1, то на странице должны появится варианты ответа только для этого вопроса.
// В конце тестирования отобразите результат теста. При решении данной задачи используйте директиву ng-switch.
var app = angular.module('App', [])
.controller('mainCtrl', function ($scope) {
});<file_sep>/lesson16/WebApplication1/classwork-task2.js
/**
* Created by Kseny on 23.08.2016.
*/
//
//Задача 2
//
//Добавьте в код предыдущей задачи путь, который будет использоваться по умолчанию и поддержку режима html5Mode
var app = angular.module('App', ['ngRoute'])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/view1', {
templateUrl: 'task/view1.html'
})
.when('/view2', {
templateUrl: 'task/view2.html'
})
.otherwise({
redirectTo: 'task/view1.html'
});
$locationProvider.html5Mode(true);
})
.controller('mainCtrl', function ($scope, $location) {
$scope.goHome = function () {
$location.path('/view1');
};
$scope.goToView1 = function () {
$location.path('/view1')
};
$scope.goToView2 = function () {
$location.path('/view2')
}
});<file_sep>/homeworks/lesson8/task3.js
/**
* Created by Kseny on 30.08.2016.
*/
//
//Задача 3
//
//Создайте директиву dialogBox, которая будет выводить на экран в диалоговом окне содержимое элемента,
// к которому привязана директива.
var App = angular.module('App', [])
.directive('dialogBox', function () {
return function (scope, element, attributes) {
var text = element.text();
var children = element.children();
alert("Text: " + text + "; Children: " + children);
}
});<file_sep>/classworks/lesson 1/task1.js
/**
* Created by Kseny on 16.08.2016.
*/
//Создайте приложение, которое выводит на экран надпись 'Hello World!'.
var model = "Hello world";
var helloWorldApp = angular.module("helloWorldApp", []);
helloWorldApp.controller("HelloWorldCtrl", function ($scope) {
$scope.message = model;
});<file_sep>/classworks/lesson2/task2.js
/**
* Created by Kseny on 17.08.2016.
*/
//Задача 2
//
//Используйте таблицу с данными массива items из предыдущей задачи. Реализуйте следующее:
//
// Добавьте на страницу 5 элементов checkbox с именами свойств элементов массива items(name, price и т.д.)
//Нажатие на каждый из checkbox скрывает/отображает соответствующее свойство элементов массива items в таблице
//Используйте директиву ng-switch
var helloWorldApp = angular.module("App", []);
helloWorldApp.controller("mainCtrl", function ($scope) {
$scope.mode = {
check1: '',
check2: '',
check3: '',
check4: '',
check5: '',
check6: ''
};
$scope.checkResult = '';
$scope.items = [
{ name: "B Item", price: 10.9, category: "Category 1", count: 10, tax: 1.12, expiration: 10 },
{ name: "A Item", price: 1.1, category: "Category 1", count: 8, tax: 0.55, expiration: 12 },
{ name: "D Item", price: 2.6, category: "Category 2", count: 7, tax: 0.22, expiration: 5 },
{ name: "C Item", price: 17.5, category: "Category 2", count: 33, tax: 2.77, expiration: 10 }];
});
<file_sep>/classworks/lesson3/task3.js
/**
* Created by Kseny on 18.08.2016.
*/
//Задача3
//Используйте таблицу с данными массива items из первой задачи.
// Напишите свой фильтр, который выведет на экран только те элементы масства items,
// у которых значение свойства expiration больше 10.
var helloWorldApp = angular.module("App", []);
helloWorldApp.controller("mainCtrl", function ($scope) {
$scope.items = [
{ name: "B Item", price: 10.9, category: "Category 1", count: 10, tax: 1.12, expiration: 10 },
{ name: "A Item", price: 1.1, category: "Category 1", count: 8, tax: 0.55, expiration: 12 },
{ name: "D Item", price: 2.6, category: "Category 2", count: 7, tax: 0.22, expiration: 5 },
{ name: "C Item", price: 17.5, category: "Category 2", count: 33, tax: 2.77, expiration: 10 }];
})
.filter('expirationSort', function () {
return function (arr) {
for (i = 0; i < arr.length; i++) {
if (arr[i].expiration > 10) {
arr = arr.splice(i, 1);
}
}
return arr;
}
});<file_sep>/classworks/lesson5/task1.js
/**
* Created by Kseny on 23.08.2016.
*/
//
//Задача 1
//
//Создайте страницу с произвольным количеством блоков текста с заголовками.
// Создайте список заголовков вверху страницы.
// Используя сервис $anchorScroll, реализуйте навигацию на странице.
// При нажатии на заголовок в списке вверху страницы, страница должна быть автоматически прокручена до
// блока текста с соответствующим заголовком.
var app = angular.module('App', [])
.controller('mainCtrl', function ($scope, $anchorScroll, $location) {
$location.path('');
$scope.show = function (id) {
$location.hash(id);
}
});
<file_sep>/classworks/lesson5/task2.js
/**
* Created by Kseny on 23.08.2016.
*/
//
//Задача 2
//
//Создайте страницу с двумя кнопками Start и Stop. Реализуйте следующее:
//
// при нажатии на кнопку start, на страницу начинают выводиться чила в возрастающем порядке с интервалом 1 с.
// При нажатии на кнопку stop вывод чисел останавливается.
// При нажатии на кнопку start отсчет начинается всегда с 0.
var app = angular.module('App', [])
.controller('mainCtrl', function ($scope, $interval, $window) {
$scope.counter = 0;
var begin, stopped = false;
$scope.startCount= function(){
if(angular.isDefined(begin))return false;
if(stopped === true) {
$scope.counter = 0;
stopped = false;
}
begin = $interval(function(){
$scope.counter++;
}, 1000);
};
$scope.killCount = function(){
if(stopped === false){stopped = true}
$interval.cancel(begin);
begin = undefined;
};
});<file_sep>/homeworks/lesson3/task1.js
/**
* Created by Kseny on 18.08.2016.
*/
//Задача 1
//Создайте три разных CSS класса, которые по-разному будут оформлять блок текста на странице.
// Реализуйте возможность выбирать стиль для оформления страницы с помощью кнопок или checkbox
var helloWorldApp = angular.module("App", []);
helloWorldApp.controller("mainCtrl", function ($scope) {
$scope.styles = {
color: false,
size: false,
shadow: false
};
});<file_sep>/homeworks/lesson3/task3.js
/**
* Created by Kseny on 18.08.2016.
*/
//Задача 3
//Создайте форму для регистрации нового пользователя.
// Форма должна содержать поля: ФИО, email, телефон, пароль, подтверждение пароля.
// Реализуйте real-time валидацию пользовательского ввода.
var App = angular.module("App", []);
App.controller("mainCtrl", function ($scope) {
$scope.errPhone = "Invalid Phone!";
$scope.errPass = "<PASSWORD>!";
$scope.passValid = true;
$scope.phoneRegexp = /^[0-9]+$/;
$scope.showMsg = function () {
if($scope.newUser.passConf != $scope.newUser.pass){
$scope.passValid = false;
}
};
$scope.showError = function (err) {
if (angular.isDefined(err)) {
if (err.required) {
return 'no data entered!'
}
else if (err.email) {
return "invalid email!";
}
}
}
});<file_sep>/homeworks/lesson8/task2.js
/**
* Created by Kseny on 30.08.2016.
*/
//
//Задача 2
//
//Создайте две директивы. Первая создает список ul с произвольным количеством элементов.
//Вторая директива добавляет четным элементам списка CSS класс ‘red’ со следующим значением:
//
// .red {
// color: red
//}
//Обе директивы используются в качестве атрибутов и применяются к одному и тому же элементу.
//При решении задачи используйте приоритет директив.
var App = angular.module('App', [])
.controller('mainCtrl', function($scope){
$scope.itemsNum = 10;
$scope.items = [];
for (var i = 0; i < $scope.itemsNum; i++) {
$scope.items[i] = "Some element " + i;
}
})
.directive('listCreate', function(){
return{
priority: 1,
link: function(scope, element, attributes){
var ul = element.append(angular.element('<ul>'));
for (var i = 0; i < scope.itemsNum; i++) {
ul.append(angular.element('<li>').text(scope.items[i]));
}
}
}
})
.directive('makeRed', function(){
return{
priority: 2,
link: function(scope, element, attributes){
var elems = element.find("li");
for (var i = 0; i < elems.length; i++) {
if (i % 2 == 0) {
elems.eq(i).addClass("red");
}
}
}
}
});<file_sep>/classworks/lesson4/task2.js
//
//Задача 2
//
//Создайте сервис из пердыдущей задачи, используя метод провайдера.
var providerModule = angular.module('providerModule', [])
.provider('clickCounter', function () {
var limitCount = false;
var limit = null;
return {
enableCounterLimit:function (setting, value) {
if (angular.isDefined(setting)) {
limitCount = setting;
if (angular.isDefined(value)) {
if (limitCount == true) {
limit = value;
return limit;
}
}
}
},
$get: function () {
var clickCounter = 1;
return function () {
if (limit && clickCounter < limit || limit == null) {
output = clickCounter++;
}
else {
output = 'count limit exceeded!';
}
return output;
};
}
}
});
var app = angular.module('App', ['providerModule'])
.config(function (clickCounterProvider) {
clickCounterProvider.enableCounterLimit(true, 10);
})
.controller('mainCtrl', function ($scope, clickCounter) {
$scope.output = 0;
$scope.countClicks = function () {
$scope.output = clickCounter();
};
});<file_sep>/homeworks/lesson 5/task1.js
/**
* Created by Kseny on 23.08.2016.
// */
//Задача 1
//
//Создайте сервис, который предоставляет стандартные математические операции – сложение, умножение и т.д.
// Создайте сервис тремя разными способами.
<file_sep>/classworks/lesson8/task1.js
/**
* Created by Kseny on 29.08.2016.
*/
//
//Задача 1
//
//Создайте директиву, которая создает кнопку, при нажатии на которую запускается
// счетчик (на экран начинают выводиться числа в возрастающей последовательности с интервалом в 1 с).
//
//Задача 2
//
//Добавьте в код предыдущей задачи еще одну директиву, которая будет выводить значение переменной счетчика в консоль.
// Организуйте код так, чтобы обе директивы использовали один и тот же контроллер. Используйте свойство require.
var app = angular.module('App', [])
.directive('counter', function () {
return {
restrict: 'E',
templateUrl: 'templ1.html',
controller: function ($scope, $interval) {
$scope.counter = 0;
var interval;
$scope.startCounter = function () {
interval = $interval(function () {
$scope.counter++;
}, 1000)
};
$scope.stopCounter = function () {
$interval.cancel(interval);
$interval.cancel(interval2);
};
this.showInConsole = function () {
interval2 = $interval(function () {
console.log($scope.counter);
}, 1000)
};
}
}
})
.directive('counterConsole', function () {
return {
restrict: 'A',
require: 'counter',
link: function (scope, elem, attrs, counterCtrl) {
counterCtrl.showInConsole();
}
}
});
<file_sep>/homeworks/lesson 5/task3.js
/**
* Created by Kseny on 23.08.2016.
*/
//Задача 3
//
//Разработайте приложение-секундомер. На странице должно быть 3 кнопки:
//
//start – начать отсчет
//stop – остановить отсчет
//clear – сброс отсчета
var helloWorldApp = angular.module("App", []);
helloWorldApp.controller("mainCtrl", function ($scope, $interval) {
$scope.minuteCounter = 0;
$scope.secondCounter = 0;
var beginMinutes, beginSeconds;
$scope.startCount= function(){
if(angular.isDefined(beginSeconds) || angular.isDefined(beginMinutes))return false;
beginMinutes = $interval(function(){
$scope.minuteCounter++;
}, 60000);
beginSeconds = $interval(function(){
if($scope.secondCounter === 59) {
$scope.secondCounter=0;
return;
}
$scope.secondCounter++;
}, 1000);
};
$scope.stopCount = function(){
$interval.cancel(beginSeconds);
$interval.cancel(beginMinutes);
beginMinutes = beginSeconds = undefined;
};
$scope.clearCounters = function(){
$scope.minuteCounter = $scope.secondCounter = 0;
};
});<file_sep>/lesson16/WebApplication1/homework-task2.js
/**
* Created by Kseny on 23.08.2016.
*/
<file_sep>/homeworks/lesson6/task3.js
/**
* Created by Kseny on 23.08.2016.
*/
//Задача 3
//
//Добавьте на страницу следующий функционал:
//
// При клике по элементу списка на странице home, пользователь пеенаправляется на страницу contact по адресу ‘/contact + routeParams’, где routeParams – параметры маршрутизации, созданные с помощью сервиса $routeParams, представляющие собой значения свойств массива people для элемента, по которому кликнул пользователь.
// Используйте данные, переданные через $routeParams, для автозаполнения формы на странице contact
var app = angular.module('App', ['ngRoute'])
.config(function ($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'task/home.html'
})
.when('/contact', {
templateUrl: 'task/contact.html'
})
.otherwise({
redirectTo: 'task/home.html'
});
})
.controller('mainCtrl', function ($scope, $location) {
$scope.people = [{ name: 'Vasya', age: 20, email: '<EMAIL>', employed: false },
{ name: 'Masha', age: 25, email: 'm@m', employed: true },
{ name: 'Petya', age: 27, email: 'petya@stuff', employed: true },
{ name: 'John', age: 36, email: '<EMAIL>', employed: true },
{ name: 'Jane', age: 28, email: '<EMAIL>', employed: false }];
});
//
//var app = angular.module('App', ['ngRoute'])
// .config(function ($routeProvider) {
// $routeProvider
// .when('/home', {
// templateUrl: 'task/home.html'
// })
// .when('/contact/:name/:age/:email/:employed', {
// templateUrl: 'task/contact.html',
// controller: 'megaCtrl'
// })
// .otherwise({
// redirectTo: 'task/home.html'
// });
// })
//
// .controller('mainCtrl', function ($scope, $location) {
//
// $scope.people = [{ name: 'Vasya', age: 20, email: '<EMAIL>', employed: false },
// { name: 'Masha', age: 25, email: 'm@m', employed: true },
// { name: 'Petya', age: 27, email: 'petya@stuff', employed: true },
// { name: 'John', age: 36, email: '<EMAIL>', employed: true },
// { name: 'Jane', age: 28, email: '<EMAIL>', employed: false }];
//
// $scope.setParam = function (name, age, email, employed) {
// var params = name + "/" + age + "/" + email + "/" + employed;
// $location.path('/contact/' + params);
// }
// })
//
// .controller('megaCtrl', function ($scope, $routeParams) {
// $scope.name = $routeParams.name;
// $scope.age = $routeParams.age;
// $scope.email = $routeParams.email;
// if ($routeParams.employed == 'true') { $scope.employed = true }
// else { $scope.employed = false };
// });<file_sep>/classworks/lesson7/task3.js
/**
* Created by Kseny on 25.08.2016.
*/
//
//Задача 3
//
//Модифицируйте код предыдущей задачи для реализации валидации формы.
var app = angular.module('App', [])
.directive('form', function () {
return {
link: function (scope, element, attributes) {
scope.data = scope[attributes["listArr"]];
},
restrict: "A",
scope: false,
templateUrl: 'formTemplate.html'
}
})
.controller('mainCtrl', function ($scope) {
$scope.userValidation = /\D/;
$scope.loginValidation = /\D/;
$scope.passValidation = /\D/;
$scope.mailValidation = /\D/;
$scope.showMsg = function () {
$scope.message = 'userName: ' + $scope.newUser.name;
$scope.message += 'userEmail: ' + $scope.newUser.email;
};
$scope.showError = function (err) {
if (angular.isDefined(err)) {
if (err.required) {
return 'no data entered!'
}
else if (err.email) {
return "invalid email!";
}
}
};
});<file_sep>/homeworks/lesson1/main.js
/**
* Created by Kseny on 16.08.2016.
*/
//Задача 1
//
//Откройте файл Task/Task.html.Вам необходимо разработать приложение “To do List”.
//Задача приложения отображать пользователю таблицу с задачами и предоставлять возможность добавлять новые задачи.
//Приложение должно быть построено по шаблону, который находится в папке Task в файле template.png
//
//Задача2
//
//Добавьте в предыдущую задачу возможность пользователя редактировать задачи и сохранять результат после редактирования.
var inptname = document.getElementById('name'),
inptdescr = document.getElementById('descr'),
inptdate = document.getElementById('taskdate'),
check = document.getElementById('compl'),
tasksItem, btn_chng = document.getElementById('btn');
var model = {
tasks: [{ name: "Купить молоко", description: "Сходить на рынок и купить молоко", date: "01.01.2016", completed: false },
{ name: "Посмотреть урок по AngularJS", description: "Досмотреть до конца", date: "01.01.2016", completed: false },
{ name: "Станцевать ламбаду", description: "на крыше поезда метро", date: "01.01.2016", completed: false },
{ name: "Проверить почту", description: "всюду", date: "01.01.2016", completed: false },
{ name: "Найти второй носок", description: "или купить новую пару", date: "01.01.2016", completed: false }]
};
var selectedRow= 0;
var helloWorldApp = angular.module("App", []);
helloWorldApp.controller("mainCtrl", function ($scope) {
$scope.data = model;
$scope.del = true;
$scope.addNewTask = function(){
$scope.data.tasks.push({
name: $scope.taskname,
description: $scope.descr,
date: $scope.taskdate,
completed: $scope.compl
});
};
$scope.changeTask = function(e, task){
selectedRow = e.target.parentElement;
tasksItem = task;
inptname.value = task.name;
inptdescr.value = task.description;
inptdate.value = task.date;
check.value = task.completed;
$scope.anotherTask = function(){
selectedRow.innerHTML = "";
$scope.data.tasks.push({
name: inptname.value,
description: inptdescr.value,
date: inptdate.value,
completed: check.value
});
}
};
});<file_sep>/homeworks/lesson6/task1-2.js
/**
* Created by Kseny on 23.08.2016.
*/
//
//Задача 1
//
//Создайте страницу с панелью навигации со следуюшими пунктами: home, contact.
// Используйте маршрутизацию для переключения меду пунктами меню.
// Файлы для задачи находятся в папке Task.
//
//Задача 2
//
// Добавьте в шаблон страницы home список со свойством name из следующего массива:
//
// var people = [{name: 'Vasya', age: 20, email: '<EMAIL>', employed: false},
// {name: 'Masha', age: 25, email: 'm@m', employed: true},
// {name: 'Petya', age: 27, email: '<EMAIL>', employed: true},
// {name: 'John', age: 36, email: '<EMAIL>', employed: true},
// {name: 'Jane', age: 28, email: '<EMAIL>', employed: false}]
//Добавьте на страницу поддержку htm5Mode.
//
var app = angular.module('App', ['ngRoute'])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/home', {
templateUrl: 'task/home.html'
})
.when('/contact', {
templateUrl: 'task/contact.html'
})
.otherwise({
redirectTo: 'task/home.html'
});
$locationProvider.html5Mode(true);
})
.controller('mainCtrl', function ($scope, $location) {
$scope.people = [{ name: 'Vasya', age: 20, email: '<EMAIL>', employed: false },
{ name: 'Masha', age: 25, email: 'm@m', employed: true },
{ name: 'Petya', age: 27, email: '<EMAIL>', employed: true },
{ name: 'John', age: 36, email: '<EMAIL>', employed: true },
{ name: 'Jane', age: 28, email: '<EMAIL>', employed: false }];
$scope.goHome = function () {
$location.path('/home');
};
$scope.goToContact = function () {
$location.path('/contact')
};
$scope.goToHome2 = function () {
$location.path('/home')
}
});<file_sep>/homeworks/lesson4/task2.js
/**
* Created by Kseny on 29.08.2016.
*/
//
//Задача 2
//
//Создайте приложение с интерфейсом показанном в файле template.png. Файл находится в папке Task.
// При этом реализуйте возможность сохранять данные введенные пользователем на серверной стороне.
// Для реализации серверной стороны используйте deployed. Используйте для взаимодействия с сервером сервис $http.
var inptname = document.getElementById('name'),
inptdescr = document.getElementById('descr'),
inptdate = document.getElementById('taskdate'),
check = document.getElementById('compl'),
tasksItem, btn_chng = document.getElementById('btn');
var model = {
tasks: [{ name: "Купить молоко", description: "Сходить на рынок и купить молоко", date: "01.01.2016", completed: false },
{ name: "Посмотреть урок по AngularJS", description: "Досмотреть до конца", date: "01.01.2016", completed: false },
{ name: "Станцевать ламбаду", description: "на крыше поезда метро", date: "01.01.2016", completed: false },
{ name: "Проверить почту", description: "всюду", date: "01.01.2016", completed: false },
{ name: "Найти второй носок", description: "или купить новую пару", date: "01.01.2016", completed: false }]
};
var App = angular.module("App", []);
App.factory('sendJSON', function($http){
return function (obj) {
var config = {
headers: {
"content-type": "application/json"
},
transformRequest: function (data, headers) {
alert(JSON.stringify(data));
}
};
$http.post("NotExist", obj, config);
}
});
App.controller("mainCtrl", function ($scope, $http, sendJSON) {
$scope.data = model;
$scope.addNewTask = function(){
var task = {
name: $scope.taskname,
description: $scope.descr,
date: $scope.taskdate,
completed: $scope.compl
};
$scope.data.tasks.push(task);
sendJSON(task);
};
});
<file_sep>/classworks/lesson2/task3.js
/**
* Created by Kseny on 20.08.2016.
*/
//
//Задача 3
//
//Перепишите код предыдущей задачи с использованием директивы ng-include
var helloWorldApp = angular.module("App", []);
helloWorldApp.controller("mainCtrl", function ($scope) {
$scope.mode = {
check1: '',
check2: '',
check3: '',
check4: '',
check5: '',
check6: ''
};
$scope.checkResult = '';
$scope.items = [
{ name: "B Item", price: 10.9, category: "Category 1", count: 10, tax: 1.12, expiration: 10 },
{ name: "A Item", price: 1.1, category: "Category 1", count: 8, tax: 0.55, expiration: 12 },
{ name: "D Item", price: 2.6, category: "Category 2", count: 7, tax: 0.22, expiration: 5 },
{ name: "C Item", price: 17.5, category: "Category 2", count: 33, tax: 2.77, expiration: 10 }];
});
<file_sep>/classworks/lesson 1/task2-3.js
/**
* Created by Kseny on 16.08.2016.
*/
//Создайте страницу с полем ввода и кнопкой. При нажатии на кнопку содержимое поля ввода должно отображаться на странице.
var helloWorldApp = angular.module("App", []);
helloWorldApp.controller("WriteCtrl", function ($scope) {
$scope.clickHandler = function () {
$scope.message = $scope.text;
}
});
//Задача3
//Модифицируйте код предыдущей задачи таким образом, чтобы содержимое поля ввода выводилось на страницу сразу(без нажатия на кнопку)
helloWorldApp.controller("anotherWriteCtrl", function ($scope) {});<file_sep>/classworks/lesson3/task2.js
/**
* Created by Kseny on 18.08.2016.
*/
//Задача2
//Дано массив items:
//
// $scope.items = [
// { name: "B Item", price: 10.9, category: "Category 1", count: 10, tax: 1.12, expiration: 10 },
// { name: "A Item", price: 1.1, category: "Category 1", count: 8, tax: 0.55, expiration: 12 },
// { name: "D Item", price: 2.6, category: "Category 2", count: 7, tax: 0.22, expiration: 5 },
// { name: "C Item", price: 17.5, category: "Category 2", count: 33, tax: 2.77, expiration: 10 }];
//С помощью директивы ng-repeat создайте таблицу , отображающую данные массива.
//
// Отфильтруйте данные массива таким образом, чтобы:
//
//Пользователь мог выбирать количество элементов, отображаемых в таблице
//Элементы отображались в алфавитном порядке (по свойству name)
//Свойство tax отображалось в формате currency
var helloWorldApp = angular.module("App", []);
helloWorldApp.controller("mainCtrl", function ($scope) {
$scope.items = [
{ name: "B Item", price: 10.9, category: "Category 1", count: 10, tax: 1.12, expiration: 10 },
{ name: "A Item", price: 1.1, category: "Category 1", count: 8, tax: 0.55, expiration: 12 },
{ name: "D Item", price: 2.6, category: "Category 2", count: 7, tax: 0.22, expiration: 5 },
{ name: "C Item", price: 17.5, category: "Category 2", count: 33, tax: 2.77, expiration: 10 }];
$scope.rowsNum = 1;
});<file_sep>/homeworks/lesson2/task2.js
/**
* Created by Kseny on 19.08.2016.
*/
//Задача 2
//
//Дано массив items:
//
// $scope.items = [
// { name: "B Item", price: 10.9, category: "Category 1", count: 10, tax: 1.12, expiration: 10 },
// { name: "A Item", price: 1.1, category: "Category 1", count: 8, tax: 0.55, expiration: 12 },
// { name: "D Item", price: 2.6, category: "Category 2", count: 7, tax: 0.22, expiration: 5 },
// { name: "C Item", price: 17.5, category: "Category 2", count: 33, tax: 2.77, expiration: 10 }];
//Создайте страницу с элементом select. Реализуйте следующее: В зависимости от выбранного варианта в списке select,
// на экране отображаются данные массива или в виде таблицы, или в виде списка
var app = angular.module('App', [])
.controller('mainCtrl', function ($scope) {
$scope.options = [{ display: 'Таблица', value: 'table' }, { display: 'Список', value: 'list' }];
$scope.items = [
{ name: "B Item", price: 10.9, category: "Category 1", count: 10, tax: 1.12, expiration: 10 },
{ name: "A Item", price: 1.1, category: "Category 1", count: 8, tax: 0.55, expiration: 12 },
{ name: "D Item", price: 2.6, category: "Category 2", count: 7, tax: 0.22, expiration: 5 },
{ name: "C Item", price: 17.5, category: "Category 2", count: 33, tax: 2.77, expiration: 10 }];
$scope.mode = $scope.options[0];
});<file_sep>/homeworks/lesson2/task1.js
/**
* Created by Kseny on 19.08.2016.
*/
//Создайте приложение-калькулятор. В приложении должно быть два поля ввода и кнопки «+», «-», «*», «/».
// Реализуйте двунаправленную привязку таким образом, чтобы при нажатии на кнопки результат арифметических
// операций выводился на странице.
var helloWorldApp = angular.module("App", []);
helloWorldApp.controller("mainCtrl", function ($scope) {
$scope.result = 0;
$scope.calc = function(operation){
return $scope.result = eval($scope.operand1+operation+$scope.operand2);
}
}); | 1ae1be9f8d7290f50d5bba56d7822ddd9f2fb1d3 | [
"JavaScript"
] | 30 | JavaScript | KsenyW/angular-works | 831c7e3ea6dcfecb50331de9eb4efdf1c11eea84 | c54c369a5eb0bdb7b53d30e0128f07c981ee3d24 |
refs/heads/master | <repo_name>davidoluseun/my-newstartng<file_sep>/js/certificate-request.js
(function() {
"use strict";
// jQuery document ready fn
$(function() {
// Bootstrap form validation
// Fetch the form to apply custom Bootstrap validation style to
var forms = document.getElementsByClassName("cert-request");
// Loop over it and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener("submit", function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add("was-validated");
}, false);
});
}); // jQuery document ready function
})(); // Immediately Invoked Function Expression (IIFE) | 629443ac9e16bdcc5171db3b4ed6211abcea45a6 | [
"JavaScript"
] | 1 | JavaScript | davidoluseun/my-newstartng | af3401d0c4defedc6d83a4917a9633d9b70dd937 | ad775e699c816e1056a7ccb5420d5a908499566c |
refs/heads/main | <file_sep>function animatedForm() {
const arrows = document.querySelectorAll(".fa-arrow-down");
//console.log(arrows);
Array.from(arrows).map((arrow, index) => {
//console.log(arrow);
arrow.addEventListener("click", function (arrow) {
var input = arrow.srcElement.previousElementSibling.value;
const parent = arrow.srcElement.parentElement;
var nextForm = parent.nextElementSibling;
//check
//console.log("here");
const result = validateUser(input);
if (result) {
parent.style.display = "none";
//console.log(nextForm);
nextForm.style.display = "flex";
} else if (input.type === "email" && validateEmail(input)) {
parent.style.display = "none";
nextForm.style.display = "flex";
} else if (input.type === "password" && validateUser(input)) {
parent.style.display = "none";
nextForm.style.display = "flex";
} else {
parent.style.animation = "shake 0.5s ease";
}
});
});
}
function validateUser(value) {
if (value.length < 6) {
console.log("not enough characters");
errorColor("rgb(189,87,87)");
return false;
} else {
errorColor("rgb(87, 189, 130)");
return true;
}
}
function validateEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (re.test(email.value)) {
errorColor("rgb(87, 189, 130)");
return true;
} else {
errorColor("rgb(189,87,87)");
}
}
function errorColor(color) {
document.body.style.backgroundColor = color;
}
animatedForm();
| 4b1dc2878ed7c89636a7cfea24f8db7b81d607b8 | [
"JavaScript"
] | 1 | JavaScript | vasu-56/form_check | a422548214164f26ab50265f75f6cac5a0fd996f | ea59b75afb3a78f77a5bc4dd01e165d2da262f06 |
refs/heads/master | <file_sep>"""
============================
Author:柠檬班-木森
Time:2020/4/20 17:50
E-mail:<EMAIL>
Company:湖南零檬信息技术有限公司
============================
"""
import setuptools
from distutils.core import setup
"""
打包模块还没来的及去写
"""
setup(
name='',
version='v0.0.1',
author='musen',
maintainer_email='<EMAIL>',
requires=[],
py_modules=[],
packages=setuptools.find_packages(),
)
<file_sep># 滑动验证码识别模块V0.0.1
基于opencv-python模块实现的滑动验证码模块,目前只实现了滑动验证,后续会持续更新其他类型验证码的解决方案
- 使用案例如下:
```python
from selenium import webdriver
from slideVerfication import SlideVerificationCode
# 访问目标页面
self.driver = webdriver.Chrome()
self.driver.get(url="https://www.baidu.com/xxxxxx/")
driver.switch_to.frame(if_ele)
# 获取背景图,滑动图片的节点
background_ele = driver.find_element_by_xpath("//img[@id='slideBg']")
slider_ele = driver.find_element_by_xpath("//img[@id='slideBlock']")
# 获取滑动块元素
slide_element = driver.find_element_by_id('tcaptcha_drag_button')
#1、创建一个验证对象
sv = SlideVerificationCode()
#2、获取滑动距离
distance = sv.get_slide_distance(slider_ele, background_ele)
#3、误差校准(滑动距离*背景图的缩放比,减去滑块在背景图的左边距)
distance = distance * (280.0 / 680.0) - 31
#4、滑动验证码进行验证
sv.slide_verification(driver, slide_element, distance)
```
<file_sep>opencv-python==4.2.0.34
numpy>==1.16.2
Pillow== 6.0.0
| 10e3d19b859d6dc779b97d8a4985c3681fed216d | [
"Markdown",
"Python",
"Text"
] | 3 | Python | musen123/SlideVerification | 07ecf38155f7f87d904ff5174d704ef2ec2249c8 | ae253c46f52ce802fce24f836cd9da0f1d781ca2 |
refs/heads/master | <repo_name>iMaximuz/Graficas<file_sep>/Proyecto graficas/Proyecto graficas/CoreEngine.h
#ifndef _COREENGINE_H_
#define _COREENGINE_H_
#define GLEW_STATIC
#include <glew.h>
#include "Window.h"
#include "Game.h"
#include "RenderEngine.h"
#include "Input.cpp"
enum {
GLEW_Failed,
CoreEngine_Failed,
CoreEngine_Ok
};
class CoreEngine {
Window* window;
Game* game;
RenderEngine* renderEngine;
int state;
public:
CoreEngine( Game* _game, Window* _window );
~CoreEngine();
void Run();
inline int GetCoreEngineState() { return state; }
};
#endif // !_COREENGINE_H_
<file_sep>/Proyecto graficas/Proyecto graficas/Window.cpp
#include "Window.h"
Window::Window( int _width, int _height, const char * title ) : width(_width), height(_height){
glfwInit();
glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 3 );
glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 3 );
glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );
glfwWindowHint( GLFW_RESIZABLE, GL_FALSE );
this->glfwWindow = glfwCreateWindow( _width, _height, title, nullptr, nullptr );
if ( !this->glfwWindow ) {
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
state = Window_Failed;
}
else {
state = Window_Success;
}
glfwMakeContextCurrent( this->glfwWindow );
}
Window::~Window()
{
glfwTerminate();
}
<file_sep>/Proyecto graficas/Proyecto graficas/RenderEngine.h
#ifndef _RENDERENGINE_H_
#define _RENDERENGINE_H_
class RenderEngine{
public:
RenderEngine() {}
~RenderEngine() {}
private:
};
#endif // !_RENDERENGINE_H_
<file_sep>/Proyecto graficas/Proyecto graficas/CoreEngine.cpp
#include "CoreEngine.h"
CoreEngine::CoreEngine( Game * _game, Window * _window ) : game(_game), window(_window)
{
glewExperimental = GL_TRUE;
if ( glewInit() != GLEW_OK ) {
std::cout << "Failed to Initialize GLEW: " << glewGetErrorString( glewInit() ) << std::endl;
state = GLEW_Failed;
}
glfwSetKeyCallback( window->glfwWindow, Key_Callback );
glfwSetScrollCallback( window->glfwWindow, Scroll_callback );
glfwSetCursorPosCallback( window->glfwWindow, Mouse_Callback );
//TODO: Implementar lectura de botones del mouse
//glfwSetMouseButtonCallback( window->glfwWindow, )
glViewport( 0, 0, 800, 600 );
game->SetWindow( this->window );
renderEngine = new RenderEngine();
}
CoreEngine::~CoreEngine()
{
delete renderEngine;
delete game;
delete window;
}
void CoreEngine::Run()
{
GLfloat deltaTime = 0.0f;
GLfloat lastFrame = 0.0f;
if ( game ) {
game->Init();
while ( !glfwWindowShouldClose( window->glfwWindow ) ) {
GLfloat currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
glfwPollEvents();
game->Input( g_Input, deltaTime );
game->RootInput(g_Input, deltaTime );
game->Update( deltaTime );
game->RootUpdate( deltaTime );
game->Render();
game->RootRender();
glfwSwapBuffers( window->glfwWindow );
}
}
else {
state = CoreEngine_Failed;
}
}
<file_sep>/Proyecto graficas/Proyecto graficas/GameObject.cpp
#include "GameObject.h"
GameObject::~GameObject()
{
for ( int i = 0; i < children.size(); i++ ) {
delete children[i];
}
children.clear();
for ( int i = 0; i < components.size(); i++ ) {
delete components[i];
}
components.clear();
}
void GameObject::Input(InputInfo input, GLfloat dt )
{
for ( int i = 0; i < children.size(); i++ )
children[i]->Input(input, dt );
for ( int i = 0; i < children.size(); i++ )
components[i]->Input(input, dt );
}
void GameObject::Update( GLfloat dt )
{
for ( int i = 0; i < children.size(); i++ )
children[i]->Update( dt );
for ( int i = 0; i < children.size(); i++ )
components[i]->Update( dt );
}
void GameObject::Render( )
{
for ( int i = 0; i < children.size(); i++ )
children[i]->Render( );
for ( int i = 0; i < children.size(); i++ )
components[i]->Render( );
}
void GameObject::AddChild( GameObject* child )
{
this->children.push_back( child );
}
void GameObject::AddComponent( GameComponent* component )
{
component->SetParent( this );
this->components.push_back( component );
}<file_sep>/Proyecto graficas/Proyecto graficas/Input.cpp
#pragma once
#include "Input.h"
//#include <glew.h>
//#include <glfw3.h>
//static struct Input {
// GLboolean keys[1024];
// GLboolean leftMouse;
// GLboolean rightMouse;
// GLdouble mousePosX;
// GLdouble mousePosY;
// GLdouble scrollAxis;
//} input;
inline void Key_Callback( GLFWwindow* window, int key, int scancode, int action, int mode ) {
if ( action == GLFW_PRESS )
g_Input.keys[key] = true;
else if ( action == GLFW_RELEASE )
g_Input.keys[key] = false;
}
inline void Mouse_Callback( GLFWwindow* window, double xpos, double ypos ) {
g_Input.mousePosX = xpos;
g_Input.mousePosY = ypos;
//if ( firstMouse )
//{
// lastX = xpos;
// lastY = ypos;
// firstMouse = false;
//}
//GLfloat xoffset = xpos - lastX;
//GLfloat yoffset = lastY - ypos; // Reversed since y-coordinates go from bottom to left
//lastX = xpos;
//lastY = ypos;
//mainCamera.Rotate( xoffset, yoffset );
}
inline void Scroll_callback( GLFWwindow* window, double xoffset, double yoffset )
{
g_Input.scrollAxis = yoffset;
//mainCamera.Zoom( yoffset );
}<file_sep>/Proyecto graficas/Proyecto graficas/Window.h
#ifndef _WINDOW_H_
#define _WINDOW_H_
#include <glfw3.h>
#include <iostream>
enum {
Window_Success,
Window_Failed,
};
class Window{
int state;
public:
int width;
int height;
GLFWwindow* glfwWindow;
Window(int _width, int _height, const char* Title);
~Window();
inline int GetWindowState() { return state; }
inline void LockMouse(bool lockMouse){
lockMouse ? glfwSetInputMode( glfwWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED ) : glfwSetInputMode( glfwWindow, GLFW_CURSOR, GLFW_CURSOR_NORMAL );
}
};
#endif // !_WINDOW_H_
<file_sep>/Proyecto graficas/Proyecto graficas/SpaceGame.cpp
#include "SpaceGame.h"
SpaceGame::SpaceGame(){
}
SpaceGame::~SpaceGame(){
}
void SpaceGame::Init(){
}
void SpaceGame::Input( InputInfo input, GLfloat dt){
if ( input.keys[GLFW_KEY_ESCAPE] ) {
this->LockMouse( false );
}
}
void SpaceGame::Update( GLfloat dt ){
}
void SpaceGame::Render(){
glClearColor( 0.2f, 0.2f, 0.2f, 1.0f );
glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
}
<file_sep>/Proyecto graficas/Proyecto graficas/GameComponent.h
#ifndef _GAMECOMPONENT_H_
#define _GAMECOMPONENT_H_
#include "Shader.h"
#include "Transform.h"
#include "Input.h"
class GameObject;
class GameComponent
{
public:
void SetParent( GameObject* parent );
virtual void Input( InputInfo input, GLfloat dt ) = 0;
virtual void Update( GLfloat dt ) = 0;
virtual void Render( ) = 0;
Transform* GetTransform();
private:
GameObject* parent;
};
#endif // !_GAMECOMPONENT_H_
<file_sep>/Proyecto graficas/Proyecto graficas/Transform.h
#ifndef _TRANSFORM_H_
#define _TRANSFORM_H_
#include "MathLib.h"
struct Transform {
glm::mat4 worldMatrix;
public:
Transform() : worldMatrix( glm::mat4() ) {}
Transform( glm::mat4 _worldMatrix ) : worldMatrix( _worldMatrix ) { }
void Translate( glm::vec3 transVec );
void Rotate( GLfloat rads, glm::vec3 rotVec );
void Scale( glm::vec3 scaleVec );
inline void LoadIdentity() { worldMatrix = glm::mat4(); }
inline glm::mat4 GetWorldMatrix() { return worldMatrix; }
};
#endif<file_sep>/Proyecto graficas/Proyecto graficas/Precompiled.h
#ifndef _PRECOMPILED_H_
#define _PRECOMPILED_H_
#endif<file_sep>/Proyecto graficas/Proyecto graficas/Camera.cpp
#include "Camera.h"
glm::mat4 Camera::GetViewMatrix() {
return glm::lookAt( this->Position, this->Front + this->Position, this->Up );
}
void Camera::UpdateVectors() {
glm::vec3 front;
front.x = cos( glm::radians( Pitch ) ) * cos( glm::radians( Yaw ) );
front.y = sin( glm::radians( Pitch ) );
front.z = cos( glm::radians( Pitch ) ) * sin( glm::radians( Yaw ) );
this->Front = front;
this->Right = glm::normalize( glm::cross( this->Front, this->WorldUp ) );
this->Up = glm::normalize( glm::cross( this->Right, this->Front ) );
}
void Camera::Rotate( GLfloat xoffset, GLfloat yoffset, GLboolean maxedPitch ) {
xoffset *= this->MouseSensitivity;
yoffset *= this->MouseSensitivity;
this->Yaw += xoffset;
this->Pitch += yoffset;
if ( maxedPitch ) {
if ( this->Pitch > 89.0f )
Pitch = 89.0f;
else if ( this->Pitch < -89.0f )
Pitch = -89.0f;
}
this->UpdateVectors();
}
void Camera::Move( CameraMovement direction, GLfloat deltaTime ) {
GLfloat velocity = this->MovementSpeed * deltaTime;
if ( Sprinting )
velocity *= 2;
if ( direction == FORWARD )
this->Position += this->Front * velocity;
if ( direction == BACKWARD )
this->Position -= this->Front * velocity;
if ( direction == LEFT )
this->Position += this->Right * velocity;
if ( direction == RIGHT )
this->Position -= this->Right * velocity;
if ( direction == UP )
this->Position += this->Up * velocity;
if ( direction == DOWN )
this->Position -= this->Up * velocity;
}
void Camera::Zoom( GLfloat yoffset ) {
if ( this->ZoomAmount >= 1.0f && this->ZoomAmount <= 45.0f )
this->ZoomAmount -= yoffset;
if ( this->ZoomAmount < 1.0f )
this->ZoomAmount = 1.0f;
if ( this->ZoomAmount > 45.0f )
this->ZoomAmount = 45.0f;
}<file_sep>/Proyecto graficas/Proyecto graficas/Mesh.h
#ifndef _MESH_H_
#define _MESH_H_
#include <iostream>
#include <sstream>
#include <string>
#include <glew.h>
#include <vector>
#include "MathLib.h"
#include "Shader.h"
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
struct Vertex
{
glm::vec3 position;
glm::vec3 normal;
glm::vec2 texCoord;
};
struct Texture {
GLuint id;
std::string type;
aiString path;
};
class Mesh {
GLuint VBO, EBO, VAO;
public:
std::vector<Vertex> vertices;
std::vector<GLuint> indices;
std::vector<Texture> textures;
void setupMesh();
Mesh();
Mesh( std::vector<Vertex> vertices, std::vector<GLuint> indices, std::vector<Texture> textures );
~Mesh();
void Draw( Shader shader );
};
#endif<file_sep>/Proyecto graficas/Proyecto graficas/Game.h
#ifndef _GAME_H_
#define _GAME_H_
#include <glew.h>
#include "Window.h"
#include "GameObject.h"
#include "Input.h"
class Game {
GameObject root;
Window* window;
public:
virtual void Init() = 0;
inline void RootInput( InputInfo input, GLfloat dt ) { root.Input(input, dt ); }
inline void RootUpdate( GLfloat dt ) { root.Update( dt ); }
inline void RootRender() { root.Render(); }
virtual void Input( InputInfo input, GLfloat dt) = 0;
virtual void Update(GLfloat dt) = 0;
virtual void Render() = 0;
inline void AddObject( GameObject* newObject ) {
root.AddChild( newObject );
}
inline GameObject* GetRootObject() { return &root; }
inline void SetWindow( Window* newWindow ) { window = newWindow; }
inline void CloseWindow() { glfwSetWindowShouldClose( window->glfwWindow, GL_TRUE ); }
inline void LockMouse( bool lock ) { window->LockMouse( lock ); }
};
#endif
<file_sep>/Proyecto graficas/Proyecto graficas/GameObject.h
#ifndef _GAMEOBJECT_H_
#define _GAMEOBJECT_H_
#include <vector>
#include <memory>
#include "GameComponent.h"
#include "MathLib.h"
#include "Shader.h"
#include "Transform.h"
#include "Input.h"
class GameObject {
std::vector<GameObject*> children;
std::vector<GameComponent*> components;
public:
~GameObject();
Transform transform;
void Input(InputInfo input, GLfloat dt );
void Update( GLfloat dt );
void Render( );
void AddChild( GameObject* child );
void AddComponent( GameComponent* component );
};
#endif<file_sep>/Proyecto graficas/Proyecto graficas/Input.h
#pragma once
#include <glew.h>
#include <glfw3.h>
struct InputInfo {
GLboolean keys[1024];
GLboolean leftMouse;
GLboolean rightMouse;
GLdouble mousePosX;
GLdouble mousePosY;
GLdouble scrollAxis;
};
static InputInfo g_Input;
//void Key_Callback( GLFWwindow* window, int key, int scancode, int action, int mode );
//
//void Mouse_Callback( GLFWwindow* window, double xpos, double ypos );
//
//void Scroll_callback( GLFWwindow* window, double xoffset, double yoffset );<file_sep>/Proyecto graficas/Proyecto graficas/Heightmap.h
#ifndef _HEIGHTMAP_H_
#define _HEIGHTMAP_H_
#include <stdlib.h>
#include <array>
#include "GameObject.h"
#include "Mesh.h"
class NoiseMap {
void GenerateNoise(GLfloat* data){
for ( int y = 0; y < sizeY; y++ ) {
for ( int x = 0; x < sizeX; x++ )
{
data[y * sizeX + x] = (rand() % 32768) / 32768.0;
}
}
}
double smoothNoise(GLfloat* data, double x, double y )
{
//get fractional part of x and y
double fractX = x - int( x );
double fractY = y - int( y );
//wrap around
int x1 = (int( x ) + sizeX) % sizeX;
int y1 = (int( y ) + sizeY) % sizeY;
//neighbor values
int x2 = (x1 + sizeX - 1) % sizeX;
int y2 = (y1 + sizeY - 1) % sizeY;
//smooth the noise with bilinear interpolation
double value = 0.0;
value += fractX * fractY * data[y1 * sizeX + x1];
value += (1 - fractX) * fractY * data[y1 * sizeX + x2];
value += fractX * (1 - fractY) * data[y2 * sizeX + x1];
value += (1 - fractX) * (1 - fractY) * data[y2 * sizeX + x2];
return value;
}
double turbulence(GLfloat* data, double x, double y, double size )
{
double value = 0.0, initialSize = size;
while ( size >= 1 )
{
value += smoothNoise(data, x / size, y / size ) * size;
size /= 2.0;
}
return myMath::MapValue( (128.0 * value / initialSize), 0, 255, 0, 1 );
}
void PerlinNoise2D(int size) {
GLfloat* tempData = new GLfloat[sizeX*sizeY];
GenerateNoise(tempData);
for ( int y = 0; y < sizeY; y++ ) {
for ( int x = 0; x < sizeX; x++ )
{
noiseData[y * sizeX + x] = turbulence(tempData, x, y, size );
}
}
delete tempData;
}
GLint sizeX, sizeY;
public:
GLfloat* noiseData;
NoiseMap( GLuint seed, GLint noiseSize, GLint sizeX, GLint sizeY ) {
srand( seed );
this->sizeX = sizeX;
this->sizeY = sizeY;
noiseData = nullptr;
GenerateNewNoiseMap( noiseSize, sizeX, sizeY);
}
~NoiseMap() {
delete noiseData;
}
void GenerateNewNoiseMap( GLint noiseSize, GLint sizeX, GLint sizeY ) {
if ( noiseData )
delete noiseData;
noiseData = new GLfloat[sizeX*sizeY];
memset( noiseData, 0, sizeX*sizeY * sizeof(GLfloat) );
if ( noiseSize > 0 ) {
PerlinNoise2D( noiseSize );
}
}
};
class Heightmap : public GameObject{
Mesh mesh;
GLuint gridSize;
GLfloat worldSize;
GLuint sizeX;
GLuint sizeY;
GLfloat maxHeight;
public:
Heightmap( GLuint seed, GLuint noiseSize, GLuint gridSize, GLfloat worldSize, GLfloat maxHeight){
this->gridSize = gridSize;
this->worldSize = worldSize;
this->maxHeight = maxHeight;
GenerateNewTerrain( seed, noiseSize, this->gridSize, this->worldSize, this->maxHeight );
}
Heightmap( const GLchar* path, GLfloat worldSize, GLfloat maxHeight ) {
this->worldSize = worldSize;
this->maxHeight = maxHeight;
LoadTerrain( path, this->maxHeight );
}
void Draw( Shader shader );
void GenerateNewTerrain( GLuint seed, GLuint noiseSize, GLuint gridSize, GLfloat worldSize, GLfloat maxHeight );
void LoadTerrain( const GLchar* path, GLfloat maxHeight );
};
#endif<file_sep>/Proyecto graficas/Proyecto graficas/SpaceGame.h
#ifndef _SPACEGAME_H_
#define _SPACEGAME_H_
#include "Game.h"
#include "Input.h"
class SpaceGame : public Game{
public:
SpaceGame ();
~SpaceGame ();
void Init();
void Input( InputInfo input, GLfloat dt );
void Update( GLfloat dt );
void Render();
};
#endif // !_SPACEGAME_H_
<file_sep>/Proyecto graficas/Proyecto graficas/Transform.cpp
#include "Transform.h"
void Transform::Translate( glm::vec3 transVec ) {
this->worldMatrix = glm::translate( this->worldMatrix, transVec );
}
void Transform::Rotate( GLfloat rads, glm::vec3 rotVec ) {
this->worldMatrix = glm::rotate( this->worldMatrix, rads, rotVec );
}
void Transform::Scale( glm::vec3 scaleVec ) {
this->worldMatrix = glm::scale( this->worldMatrix, scaleVec );
}<file_sep>/Proyecto graficas/Proyecto graficas/Heightmap.cpp
#include "Heightmap.h"
void Heightmap::Draw( Shader shader )
{
// glUniformMatrix4fv( glGetUniformLocation( shader.program, "localSpace" ), 1, GL_FALSE, glm::value_ptr( localSpace ) );
mesh.Draw( shader );
}
void Heightmap::GenerateNewTerrain( GLuint seed, GLuint noiseSize, GLuint gridSize, GLfloat worldSize, GLfloat maxHeight )
{
this->maxHeight = maxHeight;
GLuint vertexCount = gridSize + 1;
GLfloat quadSize = worldSize / gridSize;
NoiseMap noiseMap( seed, noiseSize, vertexCount, vertexCount );
mesh.vertices.clear();
mesh.indices.clear();
mesh.vertices.reserve( vertexCount * vertexCount );
mesh.indices.reserve( gridSize * gridSize * 2 * 3);
//std::vector<glm::vec3> normals;
glm::vec3* normals = new glm::vec3[gridSize * gridSize * 2];
//normals.reserve( gridSize * gridSize * 2 );
int adsasd = 0;
for ( int z = 0; z < vertexCount; z++ ) {
for ( int x = 0; x < vertexCount; x++ ) {
Vertex vert;
vert.position.x = (GLfloat)x * quadSize;
vert.position.y = noiseMap.noiseData[z*vertexCount + x] * maxHeight;
vert.position.z = (GLfloat)z * quadSize;
vert.normal = glm::vec3( 0.0f, 1.0f, 0.0f );
vert.texCoord.x = (1 / vertexCount)*x;
vert.texCoord.y = (1 / vertexCount)*z;
mesh.vertices.push_back( vert );
}
}
int index = 0;
for ( GLuint z = 0; z < gridSize; z++ )
{
for ( GLuint x = 0; x < gridSize; x++ ) {
GLuint start = z * vertexCount + x;
glm::vec3 v1 = (mesh.vertices[start + vertexCount].position - mesh.vertices[start].position);
glm::vec3 v2 = (mesh.vertices[start + 1].position - mesh.vertices[start].position);
//normals.push_back( glm::normalize( glm::cross( v1, v2 ) ) );
normals[index++] = glm::normalize( glm::cross( v1, v2 ) );
v1 = (mesh.vertices[start + vertexCount].position - mesh.vertices[start + vertexCount + 1].position);
v2 = (mesh.vertices[start + 1].position - mesh.vertices[start + vertexCount + 1].position);
//normals.push_back( glm::normalize( glm::cross( v2, v1 ) ) );
normals[index++] = glm::normalize( glm::cross( v2, v1 ) );
mesh.indices.push_back( start );
mesh.indices.push_back( start + vertexCount );
mesh.indices.push_back( start + 1 );
mesh.indices.push_back( start + 1 );
mesh.indices.push_back( start + vertexCount );
mesh.indices.push_back( start + vertexCount + 1 );
}
}
int asdasddasasd = 0;
for ( GLuint z = 0; z < gridSize - 1; z++ )
{
for ( GLuint x = 0; x < gridSize - 1; x++ ) {
GLuint start = z * gridSize + x;
glm::vec3 normalAverage;
normalAverage += normals[start + 1];
normalAverage += normals[start + 2];
normalAverage += normals[start + 3];
normalAverage += normals[start + gridSize];
normalAverage += normals[start + gridSize + 1];
normalAverage += normals[start + gridSize + 2];
glm::normalize( normalAverage );
GLuint vertexIndex = (z + 1) * vertexCount + (x + 1);
mesh.vertices[vertexIndex].normal = normalAverage;
}
}
delete normals;
mesh.setupMesh();
}
void Heightmap::LoadTerrain(const GLchar* path, GLfloat maxHeight) {
int width, height;
//unsigned char* image = SOIL_load_image( "Textures//container.jpg", &width, &height, 0, SOIL_LOAD_RGB );
}
<file_sep>/Proyecto graficas/Proyecto graficas/Shader.cpp
#pragma once
#include "Shader.h"
Shader::Shader( const char* vertexPath, const char* fragmentPath ) {
GLuint vertexShader, fragmentShader;
std::string vertexBuffer, fragmentBuffer;
const GLchar* vertexCode;
const GLchar* fragmentCode;
FILE *pFile;
pFile = fopen( vertexPath, "r" );
if ( pFile ) {
char ch;
while ( (ch = fgetc( pFile )) != EOF ) {
vertexBuffer += ch;
}
fclose( pFile );
}
else {
std::cout << "ERROR_SHADER_VERTEX: File not found" << std::endl;
}
pFile = fopen( fragmentPath, "r" );
if ( pFile ) {
char ch;
while ( (ch = fgetc( pFile )) != EOF ) {
fragmentBuffer += ch;
}
fclose( pFile );
}
else {
std::cout << "ERROR_SHADER_FRAGMENT: File not found" << std::endl;
}
vertexCode = vertexBuffer.c_str();
fragmentCode = fragmentBuffer.c_str();
vertexShader = glCreateShader( GL_VERTEX_SHADER );
fragmentShader = glCreateShader( GL_FRAGMENT_SHADER );
glShaderSource( vertexShader, 1, &vertexCode, NULL );
glShaderSource( fragmentShader, 1, &fragmentCode, NULL );
glCompileShader( vertexShader );
glCompileShader( fragmentShader );
GLint success;
GLchar infoLog[2048];
glGetShaderiv( vertexShader, GL_COMPILE_STATUS, &success );
if ( !success ) {
glGetShaderInfoLog( vertexShader, 512, NULL, infoLog );
std::cout << "ERROR_SHADER_VERTEX: Compilation failed.\n" << infoLog << std::endl;
}
glGetShaderiv( fragmentShader, GL_COMPILE_STATUS, &success );
if ( !success ) {
glGetShaderInfoLog( fragmentShader, 512, NULL, infoLog );
std::cout << "ERROR_SHADER_FRAGMENT: Compilation failed.\n" << infoLog << std::endl;
}
program = glCreateProgram();
glAttachShader( program, vertexShader );
glAttachShader( program, fragmentShader );
glLinkProgram( program );
glGetProgramiv( program, GL_LINK_STATUS, &success );
if ( !success ) {
glGetProgramInfoLog( program, 512, NULL, infoLog );
std::cout << "ERROR_SHADER_PROGRAM: Linking failed.\n" << infoLog << std::endl;
}
glDeleteShader( vertexShader );
glDeleteShader( fragmentShader );
}
void Shader::SetUniformf(const GLchar* uniformName, int uniformSize, GLfloat* value) {
GLint uniformLocation = glGetUniformLocation( this->program, uniformName );
if ( uniformLocation < 0 ) {
std::cout << "WARNING_SHADER: Uniform \"" << uniformName << "\" not found." << std::endl;
}
else {
switch ( uniformSize )
{
case 1:
glUniform1f( uniformLocation, *value);
break;
case 2:
glUniform2f( uniformLocation, value[0], value[1] );
break;
case 3:
glUniform3f( uniformLocation, value[0], value[1], value[2] );
break;
case 4:
glUniform4f( uniformLocation, value[0], value[1], value[2], value[3] );
break;
default:
std::cout << "WARNING_SHADER: Uniform size not acepted" << std::endl;
break;
}
}
}
<file_sep>/Proyecto graficas/Proyecto graficas/MathLib.h
#ifndef _MATHLIB_H_
#define _MATHLIB_H_
#define PI 3.14159265358979323846f
#include <glew.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
namespace myMath {
inline GLfloat MapValue( GLfloat value, GLfloat inputMin, GLfloat inputMax, GLfloat outputMin, GLfloat outputMax ) {
GLfloat result;
result = ((value - inputMin) / (inputMax - inputMin)) * (outputMax - outputMin) + outputMin;
return result;
}
}
#endif
<file_sep>/Proyecto graficas/Proyecto graficas/GameComponent.cpp
#pragma once
#include "GameComponent.h"
#include "GameObject.h"
void GameComponent::SetParent( GameObject* parent ) {
this->parent = parent;
}
Transform * GameComponent::GetTransform(){
return &(parent->transform);
}
<file_sep>/Proyecto graficas/Proyecto graficas/Source.cpp
#include<iostream>
#include <string>
//#include <glfw3.h>
#include "CoreEngine.h"
#include "SpaceGame.h"
//#include "Shader.h"
#include <SOIL\SOIL.h>
//#include "MathLib.h"
#include "Camera.h"
//#include "Heightmap.h"
//#include "GameObject.h"
//#include "Geometry.h"
//#include "Model.h"
//#include "Window.h"
#define WINDOW_WIDTH 800
#define WINDOW_HEIGHT 600
//TODO LIST:
/*
- Terminar el engine
*/
bool keys[1024];
Camera mainCamera(glm::vec3(0.0f, 1, 5.0f));
GLfloat lastX = 400, lastY = 300;
bool firstMouse = true;
GLfloat lightPosY;
void DoCameraMovement(Camera* camToMove, GLfloat deltaTime ) {
if ( keys[GLFW_KEY_W] )
camToMove->Move( FORWARD, deltaTime );
if ( keys[GLFW_KEY_S] )
camToMove->Move( BACKWARD, deltaTime );
if ( keys[GLFW_KEY_A] )
camToMove->Move( RIGHT, deltaTime );
if ( keys[GLFW_KEY_D] )
camToMove->Move( LEFT, deltaTime );
if ( keys[GLFW_KEY_SPACE] )
camToMove->Move( UP, deltaTime );
if ( keys[GLFW_KEY_LEFT_CONTROL] )
camToMove->Move( DOWN, deltaTime );
if ( keys[GLFW_KEY_LEFT_SHIFT] )
camToMove->Sprinting = true;
else
camToMove->Sprinting = false;
}
GLuint LoadTexture( const char* texturePath ) {
GLuint result;
glGenTextures( 1, &result );
int width, height;
unsigned char* image = SOIL_load_image( texturePath, &width, &height, 0, SOIL_LOAD_RGB );
glBindTexture( GL_TEXTURE_2D, result );
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image );
glGenerateMipmap( GL_TEXTURE_2D );
SOIL_free_image_data( image );
glBindTexture( GL_TEXTURE_2D, 0 );
return result;
}
int main() {
Window* window = new Window( 800, 600, "Graficas Computacionales" );
window->LockMouse( true );
Game* game = new SpaceGame();
CoreEngine coreEngine( game, window );
coreEngine.Run();
//Shader basicShader( "Shaders//basic.vs", "Shaders//basic.fs" );
//glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
//glEnable( GL_DEPTH_TEST );
//Model testModel( "Models//Arwing_001.obj" );
//Shader terrainShader( "Shaders//terrain.vert", "Shaders//terrain.frag" );
////Heightmap hMap( 5, 5, 10 );
//GLfloat heigthMapSize = 64.0f;
//GameObject* hMap = new Heightmap(0, 12, 64, 64, 10 );
//GameObject* sphere = new Sphere( 10.0f, 8, 8 );
//GLfloat deltaTime = 0.0f;
//GLfloat lastFrame = 0.0f;
//while ( !glfwWindowShouldClose( window.glfwWindow ) ) {
// GLfloat currentFrame = glfwGetTime();
// deltaTime = currentFrame - lastFrame;
// lastFrame = currentFrame;
// glfwPollEvents();
// DoCameraMovement( &mainCamera, deltaTime );
// glm::mat4 model;
// glm::mat4 view;
// glm::mat4 projection;
// projection = glm::perspective( glm::radians(mainCamera.ZoomAmount), (float)WINDOW_WIDTH / (float)WINDOW_HEIGHT, 0.1f, 100.0f );
// view = mainCamera.GetViewMatrix();
// hMap->localSpace = glm::mat4();
// hMap->localSpace = glm::translate( hMap->localSpace, glm::vec3( -(heigthMapSize * 0.5), 0.0f, -(heigthMapSize * 0.5) ) );
// //hMap->localSpace = glm::scale(hMap->localSpace,glm::vec3(64.0f, 10.0f, 64.0f));
// //hMap->localSpace = glm::translate( hMap->localSpace, glm::vec3( -(heigthMapSize * 0.5), 0.0f, -(heigthMapSize * 0.5)) );
//
// //if ( mainCamera.Position.y > 20.0f ) {
// // mainCamera.Position.y = 15.0f;
// // ((Heightmap*)hMap)->GenerateNewTerrain(0, 8, 256, heigthMapSize, 10.0f );
// //}
// glClearColor( 0.05f, 0.05f, 0.05f, 1.0f );
// glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// //glm::vec3 lightPosition = glm::vec3( 0, 10.0f, 0 );
// glm::vec3 lightPosition = glm::vec3( std::sin( PI/16 * glfwGetTime() * 2) * 32.0f, 15.0f, std::cos( PI / 16 * glfwGetTime() * 2 ) * 32.0f );
// glm::vec3 lightColor = glm::vec3( 1.0f, 1.0f, 1.0f );
// glm::vec3 objectColor = glm::vec3( 0.7f, 0.5f, 0.2f );
// terrainShader.Use();
// glUniformMatrix4fv( glGetUniformLocation( terrainShader.program, "view" ), 1, GL_FALSE, glm::value_ptr( view ) );
// glUniformMatrix4fv( glGetUniformLocation( terrainShader.program, "projection" ), 1, GL_FALSE, glm::value_ptr( projection ) );
// glUniformMatrix4fv( glGetUniformLocation( terrainShader.program, "model" ), 1, GL_FALSE, glm::value_ptr( model ) );
// glUniform3f( glGetUniformLocation( terrainShader.program, "viewPosition" ), mainCamera.Position.x, mainCamera.Position.y, mainCamera.Position.z );
// glUniform3f( glGetUniformLocation( terrainShader.program, "lightPosition" ), lightPosition.x, lightPosition.y, lightPosition.z );
// glUniform3f( glGetUniformLocation( terrainShader.program, "lightColor" ), lightColor.r, lightColor.g, lightColor.b );
// glUniform3f( glGetUniformLocation( terrainShader.program, "objectColor" ), objectColor.r, objectColor.g, objectColor.b );
//
//
// hMap->Render( terrainShader );
// //sphere->Draw( terrainShader );
// model = glm::translate( model, glm::vec3( 0.0, 15.0f, 0.0 ) );
// objectColor = glm::vec3( 0.2f, 0.3f, 0.7f );
// glUniformMatrix4fv( glGetUniformLocation( terrainShader.program, "model" ), 1, GL_FALSE, glm::value_ptr( model ) );
// glUniform3f( glGetUniformLocation( terrainShader.program, "objectColor" ), objectColor.r, objectColor.g, objectColor.b );
// testModel.Draw( terrainShader );
// glfwSwapBuffers( window.glfwWindow );
//}
//glfwTerminate();
return 0;
}
<file_sep>/Proyecto graficas/Proyecto graficas/Camera.h
#ifndef _CAMERA_H_
#define _CAMERA_H_
#include <glew.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
// Defines several possible options for camera movement. Used as abstraction to stay away from window-system specific input methods
enum CameraMovement {
FORWARD,
BACKWARD,
LEFT,
RIGHT,
UP,
DOWN
};
// Default camera values
const GLfloat YAW = -90.0f;
const GLfloat PITCH = 0.0f;
const GLfloat SPEED = 3.0f;
const GLfloat SENSITIVTY = 0.25f;
const GLfloat ZOOM = 45.0f;
class Camera {
glm::vec3 Front;
glm::vec3 Right;
glm::vec3 Up;
glm::vec3 WorldUp;
GLfloat Yaw;
GLfloat Pitch;
GLfloat MovementSpeed;
GLfloat MouseSensitivity;
void UpdateVectors();
public:
GLboolean Sprinting;
GLfloat ZoomAmount;
glm::vec3 Position;
// Constructor with vectors
Camera( glm::vec3 position = glm::vec3( 0.0f, 0.0f, 0.0f ), glm::vec3 up = glm::vec3( 0.0f, 1.0f, 0.0f ), GLfloat yaw = YAW,
GLfloat pitch = PITCH ) : Front( glm::vec3( 0.0f, 0.0f, -1.0f ) ), MovementSpeed( SPEED ), MouseSensitivity( SENSITIVTY ), ZoomAmount( ZOOM )
{
this->Position = position;
this->WorldUp = up;
this->Yaw = yaw;
this->Pitch = pitch;
this->UpdateVectors();
}
// Constructor with scalar values
Camera( GLfloat posX, GLfloat posY, GLfloat posZ, GLfloat upX, GLfloat upY, GLfloat upZ, GLfloat yaw, GLfloat pitch ) : Front( glm::vec3( 0.0f, 0.0f, -1.0f ) ),
MovementSpeed( SPEED ), MouseSensitivity( SENSITIVTY ), ZoomAmount( ZOOM )
{
this->Position = glm::vec3( posX, posY, posZ );
this->WorldUp = glm::vec3( upX, upY, upZ );
this->Yaw = yaw;
this->Pitch = pitch;
this->UpdateVectors();
}
glm::mat4 GetViewMatrix();
void Rotate(GLfloat xoffset, GLfloat yoffset, GLboolean maxedPitch = true);
void Move(CameraMovement direction, GLfloat deltaTime);
void Zoom(GLfloat yoffset);
};
#endif
<file_sep>/Proyecto graficas/Proyecto graficas/Mesh.cpp
#include "Mesh.h"
Mesh::Mesh() {
this->vertices.reserve( 100 );
this->indices.reserve( 600 );
this->textures.reserve( 10 );
this->VAO = 0;
this->VBO = 0;
this->EBO = 0;
}
Mesh::Mesh( std::vector<Vertex> vertices, std::vector<GLuint> indices, std::vector<Texture> textures )
{
this->vertices = vertices;
this->indices = indices;
this->textures = textures;
this->VAO = 0;
this->VBO = 0;
this->EBO = 0;
}
Mesh::~Mesh() {
if ( this->VAO != 0 && this->VBO != 0 && this->EBO != 0 ) {
glDeleteVertexArrays( 1, &this->VAO );
glDeleteBuffers( 1, &this->VBO );
glDeleteBuffers( 1, &this->EBO );
}
}
void Mesh::setupMesh() {
if ( this->VAO != 0 && this->VBO != 0 && this->EBO != 0 ) {
glDeleteVertexArrays( 1, &this->VAO );
glDeleteBuffers( 1, &this->VBO );
glDeleteBuffers( 1, &this->EBO );
}
glGenVertexArrays( 1, &this->VAO );
glGenBuffers( 1, &this->VBO );
glGenBuffers( 1, &this->EBO );
glBindVertexArray( this->VAO );
glBindBuffer( GL_ARRAY_BUFFER, this->VBO );
glBufferData( GL_ARRAY_BUFFER, this->vertices.size() * sizeof( Vertex ), &this->vertices[0], GL_STATIC_DRAW );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, this->EBO );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, this->indices.size() * sizeof( GLuint ), &this->indices[0], GL_STATIC_DRAW );
glEnableVertexAttribArray( 0 );
glEnableVertexAttribArray( 1 );
glEnableVertexAttribArray( 2 );
glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, sizeof( Vertex ), (GLvoid*)0 );
glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, sizeof( Vertex ), (GLvoid*)offsetof( Vertex, normal ) );
glVertexAttribPointer( 2, 2, GL_FLOAT, GL_FALSE, sizeof( Vertex ), (GLvoid*)offsetof( Vertex, texCoord ) );
glBindVertexArray( 0 );
}
void Mesh::Draw( Shader shader ) {
GLuint diffuseNr = 1;
GLuint specularNr = 1;
for ( GLuint i = 0; i < this->textures.size(); i++ )
{
glActiveTexture( GL_TEXTURE0 + i ); // Activate proper texture unit before binding
// Retrieve texture number (the N in diffuse_textureN)
std::stringstream ss;
std::string number;
std::string name = this->textures[i].type;
if ( name == "texture_diffuse" )
ss << diffuseNr++; // Transfer GLuint to stream
else if ( name == "texture_specular" )
ss << specularNr++; // Transfer GLuint to stream
number = ss.str();
glUniform1f( glGetUniformLocation( shader.program, ("material." + name + number).c_str() ), i );
glBindTexture( GL_TEXTURE_2D, this->textures[i].id );
}
glActiveTexture( GL_TEXTURE0 );
glBindVertexArray( this->VAO );
//glDrawArrays( GL_TRIANGLES, 0, vertices.size() );
glDrawElements( GL_TRIANGLES, this->indices.size(), GL_UNSIGNED_INT, 0 );
glBindVertexArray( 0 );
for ( GLuint i = 0; i < this->textures.size(); i++ )
{
glActiveTexture( GL_TEXTURE0 + i );
glBindTexture( GL_TEXTURE_2D, 0 );
}
}<file_sep>/README.md
# Graficas
- Licenciatura en Multimedia y Animacion Digital.
- Graficas computacionales.
<file_sep>/Proyecto graficas/Proyecto graficas/Shader.h
#ifndef _SHADER_H_
#define _SHADER_H_
#include <glew.h>
#include <iostream>
#include <string>
class Shader {
public:
GLuint program;
Shader(const char* vertexPath, const char* fragmentPath);
~Shader() {}
void Use() { glUseProgram( this->program ); }
void SetUniformf( const GLchar* uniformName, int uniformSize, float* value );
};
#endif<file_sep>/Proyecto graficas/Proyecto graficas/Geometry.h
#ifndef _GEOMETRY_H_
#define _GEOMETRY_H_
#include "GameObject.h"
#include "MathLib.h"
#include "Shader.h"
#include "Mesh.h"
class Sphere : public GameObject{
Mesh mesh;
GLfloat rad;
GLfloat slices;
GLfloat stacks;
void GenerateSphere();
public:
Sphere( GLfloat rad, GLfloat slices, GLfloat stacks );
void Draw( Shader shader );
};
#endif<file_sep>/Proyecto graficas/Proyecto graficas/Geometry.cpp
#include "Geometry.h"
//TODO: Quitar el radio de la esfera, la esfera debe ser unitaria.
Sphere::Sphere( GLfloat rad, GLfloat slices, GLfloat stacks )
{
this->rad = rad;
this->slices = slices;
this->stacks = stacks;
GenerateSphere();
}
void Sphere::GenerateSphere()
{
for ( int i = 0; i < slices; i++ ) {
for ( int j = 0; j < stacks; j++ ) {
GLfloat theta = i*PI *2 / slices;
GLfloat phi = j*PI / stacks;
Vertex vert;
//TODO: Acomodar el orden correcto
vert.position.x = rad * (cosf( theta )* sinf( phi ));
vert.position.y = rad * sinf( theta )* sinf( phi );
vert.position.z = rad * cosf( phi );
mesh.vertices.push_back( vert );
}
}
//TODO: Calcular Indices
}
void Sphere::Draw( Shader shader )
{
// glUniformMatrix4fv( glGetUniformLocation( shader.program, "localSpace" ), 1, GL_FALSE, glm::value_ptr( localSpace ) );
mesh.Draw( shader );
}
| 65890e046c9418f7ba07bdc5f6f4d9b215397f5e | [
"Markdown",
"C",
"C++"
] | 30 | C++ | iMaximuz/Graficas | 5ddff31c904d5316eacb036b97cb4681f950ecc8 | e0ffce14e55cbdb31ac4b6c36cd69efe1327ce49 |
refs/heads/main | <file_sep>/*
* Copyright (C) 2017 skydoves
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.preferenceroomdemo.components;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import com.skydoves.preferenceroom.InjectPreference;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class JunitComponentTest {
@InjectPreference public PreferenceComponent_JunitComponent junitComponent;
/** dependency injection {@link com.skydoves.preferenceroomdemo.components.JunitComponent} */
@Before
public void inject() throws Exception {
PreferenceComponent_JunitComponent.getInstance().inject(this);
}
/**
* injection test
*
* @throws Exception NullPointerException
*/
@Test
public void injectionTest() throws Exception {
Assert.assertNotNull(junitComponent);
Assert.assertNotNull(junitComponent.TestProfile());
}
@Test
public void entityListTest() throws Exception {
assertThat(junitComponent.getEntityNameList().get(0).toString(), is("TestProfile"));
}
}
<file_sep>apply plugin: 'java-library'
apply from: '../dependencies.gradle'
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
dependencies {
api "androidx.annotation:annotation:$versions.androidxAnnotation"
}
apply plugin: "com.vanniktech.maven.publish"
apply from: '../spotless.gradle'
<file_sep>/*
* Copyright (C) 2017 skydoves
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.preferenceroomdemo
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.skydoves.preferenceroom.InjectPreference
import com.skydoves.preferenceroomdemo.components.PreferenceComponent_UserProfileComponent
import com.skydoves.preferenceroomdemo.databinding.ActivityLoginBinding
import com.skydoves.preferenceroomdemo.entities.Preference_UserProfile
import com.skydoves.preferenceroomdemo.models.PrivateInfo
/**
* Developed by skydoves on 2017-11-26.
* Copyright (c) 2017 skydoves rights reserved.
*/
class LoginActivity : AppCompatActivity() {
/**
* UserProfile entity.
* [com.skydoves.preferenceroomdemo.entities.Profile]
*/
@InjectPreference
lateinit var userProfile: Preference_UserProfile
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
PreferenceComponent_UserProfileComponent.getInstance().inject(this)
binding.loginButton.setOnClickListener {
val inputNick = binding.loginEditTextNick.text.toString()
val inputAge = binding.loginEditTextAge.text.toString()
when (inputNick.isNotEmpty() && inputAge.isNotEmpty()) {
true -> {
userProfile.putLogin(true)
userProfile.putNickname(inputNick)
userProfile.putUserinfo(PrivateInfo(inputNick, Integer.parseInt(inputAge)))
startActivity(Intent(this, MainActivity::class.java))
finish()
}
false -> Toast.makeText(this, "please fill all inputs", Toast.LENGTH_SHORT).show()
}
}
}
}
<file_sep>/*
* Copyright (C) 2017 skydoves
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.processor;
import static javax.lang.model.element.Modifier.PUBLIC;
import androidx.annotation.Nullable;
import com.skydoves.preferenceroom.AESEncryption;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.MethodSpec;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings({"WeakerAccess", "SpellCheckingInspection"})
public class PreferenceFieldMethodGenerator {
private final PreferenceKeyField keyField;
private final PreferenceEntityAnnotatedClass annotatedEntityClazz;
private final String preference;
private static final String SETTER_PREFIX = "put";
private static final String GETTER_PREFIX = "get";
private static final String KEYNAME_POSTFIX = "KeyName";
private static final String HAS_PREFIX = "contains";
private static final String REMOVE_PREFIX = "remove";
private static final String INSTANCE_CONVERTER = "value";
private static final String EDIT_METHOD = "edit()";
private static final String APPLY_METHOD = "apply()";
public PreferenceFieldMethodGenerator(
PreferenceKeyField keyField,
PreferenceEntityAnnotatedClass annotatedClass,
String preference) {
this.keyField = keyField;
this.annotatedEntityClazz = annotatedClass;
this.preference = preference;
}
public List<MethodSpec> getFieldMethods() {
List<MethodSpec> methodSpecs = new ArrayList<>();
if (!keyField.isObjectField) {
methodSpecs.add(generateGetter());
methodSpecs.add(generateSetter());
} else {
methodSpecs.add(generateObjectGetter());
methodSpecs.add(generateObjectSetter());
}
methodSpecs.add(generateObjectKeyNameSpec());
methodSpecs.add(generateContainsSpec());
methodSpecs.add(generateRemoveSpec());
return methodSpecs;
}
private MethodSpec generateGetter() {
MethodSpec.Builder builder =
MethodSpec.methodBuilder(getGetterPrefixName())
.addModifiers(PUBLIC)
.addAnnotation(Nullable.class);
if (isEncryption()) {
builder.addStatement(
"return " + getEncryptedGetterStatement(),
AESEncryption.class,
preference,
keyField.keyName,
keyField.value,
keyField.value,
getEncryptionKey());
} else {
builder.addStatement(
"return " + getGetterStatement(), preference, keyField.keyName, keyField.value);
}
builder.returns(keyField.typeName);
return builder.build();
}
private MethodSpec generateSetter() {
MethodSpec.Builder builder =
MethodSpec.methodBuilder(getSetterPrefixName())
.addModifiers(PUBLIC)
.addParameter(keyField.typeName, keyField.keyName.toLowerCase());
if (isEncryption()) {
builder.addStatement(
getSetterEncryptStatement(),
preference,
EDIT_METHOD,
keyField.keyName,
AESEncryption.class,
keyField.keyName.toLowerCase(),
getEncryptionKey(),
APPLY_METHOD);
} else {
builder.addStatement(
getSetterStatement(),
preference,
EDIT_METHOD,
keyField.keyName,
keyField.keyName.toLowerCase(),
APPLY_METHOD);
}
builder.addStatement(getOnChangedStatement());
return builder.build();
}
private MethodSpec generateObjectGetter() {
ClassName converterClazz = ClassName.get(keyField.converterPackage, keyField.converter);
String typeName = keyField.typeName.box().toString();
if (typeName.contains("<")) typeName = typeName.substring(0, typeName.indexOf("<"));
MethodSpec.Builder builder =
MethodSpec.methodBuilder(getGetterPrefixName())
.addModifiers(PUBLIC)
.addAnnotation(Nullable.class)
.addStatement(
"$T $N = new $T($N.class)",
converterClazz,
INSTANCE_CONVERTER,
converterClazz,
typeName);
if (isEncryption()) {
builder.addStatement(
"return ($T)" + getObjectEncryptedGetterStatement(),
keyField.typeName.box(),
INSTANCE_CONVERTER,
AESEncryption.class,
preference,
keyField.keyName,
keyField.value,
keyField.value,
getEncryptionKey());
} else {
builder.addStatement(
"return ($T)" + getObjectGetterStatement(),
keyField.typeName.box(),
INSTANCE_CONVERTER,
preference,
keyField.keyName,
keyField.value);
}
builder.returns(keyField.typeName);
return builder.build();
}
private MethodSpec generateObjectSetter() {
ClassName converterClazz = ClassName.get(keyField.converterPackage, keyField.converter);
String typeName = keyField.typeName.box().toString();
if (typeName.contains("<")) typeName = typeName.substring(0, typeName.indexOf("<"));
MethodSpec.Builder builder =
MethodSpec.methodBuilder(getSetterPrefixName())
.addModifiers(PUBLIC)
.addParameter(keyField.typeName, keyField.keyName.toLowerCase())
.addStatement(
"$T $N = new $T($N.class)",
converterClazz,
INSTANCE_CONVERTER,
converterClazz,
typeName);
if (isEncryption()) {
builder.addStatement(
getSetterEncryptStatement(),
preference,
EDIT_METHOD,
keyField.keyName,
AESEncryption.class,
INSTANCE_CONVERTER + ".convertObject(" + keyField.keyName.toLowerCase() + ")",
getEncryptionKey(),
APPLY_METHOD);
} else {
builder.addStatement(
getSetterStatement(),
preference,
EDIT_METHOD,
keyField.keyName,
INSTANCE_CONVERTER + ".convertObject(" + keyField.keyName.toLowerCase() + ")",
APPLY_METHOD);
}
builder.addStatement(getOnChangedStatement());
return builder.build();
}
private MethodSpec generateObjectKeyNameSpec() {
return MethodSpec.methodBuilder(getKeyNamePostfixName())
.addModifiers(PUBLIC)
.returns(String.class)
.addStatement("return $S", keyField.keyName)
.build();
}
private MethodSpec generateContainsSpec() {
return MethodSpec.methodBuilder(getContainsPrefixName())
.addModifiers(PUBLIC)
.addStatement("return $N.contains($S)", preference, keyField.keyName)
.returns(boolean.class)
.build();
}
private MethodSpec generateRemoveSpec() {
return MethodSpec.methodBuilder(getRemovePrefixName())
.addModifiers(PUBLIC)
.addStatement(
"$N.$N.remove($S).$N", preference, EDIT_METHOD, keyField.keyName, APPLY_METHOD)
.build();
}
private String getGetterPrefixName() {
return GETTER_PREFIX + StringUtils.toUpperCamel(this.keyField.keyName);
}
private String getSetterPrefixName() {
return SETTER_PREFIX + StringUtils.toUpperCamel(this.keyField.keyName);
}
private String getKeyNamePostfixName() {
return this.keyField.keyName + KEYNAME_POSTFIX;
}
private String getContainsPrefixName() {
return HAS_PREFIX + StringUtils.toUpperCamel(this.keyField.keyName);
}
private String getRemovePrefixName() {
return REMOVE_PREFIX + StringUtils.toUpperCamel(this.keyField.keyName);
}
private String getGetterTypeMethodName() {
if (isEncryption()) {
return GETTER_PREFIX + StringUtils.toUpperCamel("String");
} else {
return GETTER_PREFIX + StringUtils.toUpperCamel(this.keyField.typeStringName);
}
}
private String getSetterTypeMethodName() {
if (isEncryption()) {
return SETTER_PREFIX + StringUtils.toUpperCamel("String");
} else {
return SETTER_PREFIX + StringUtils.toUpperCamel(this.keyField.typeStringName);
}
}
private String getGetterStatement() {
if (annotatedEntityClazz.getterFunctionsList.containsKey(keyField.keyName)) {
String superMethodName =
annotatedEntityClazz.getterFunctionsList.get(keyField.keyName).getSimpleName().toString();
if (keyField.value instanceof String) {
return String.format("super.%s(\n$N.getString($S, $S))", superMethodName);
} else if (keyField.value instanceof Float) {
return String.format(
"super.%s(\n$N." + getGetterTypeMethodName() + "($S, $Lf))", superMethodName);
} else {
return String.format(
"super.%s(\n$N." + getGetterTypeMethodName() + "($S, $L))", superMethodName);
}
} else {
if (keyField.value instanceof String) {
return "$N.getString($S, $S)";
} else if (keyField.value instanceof Float) {
return "$N." + getGetterTypeMethodName() + "($S, $Lf)";
} else {
return "$N." + getGetterTypeMethodName() + "($S, $L)";
}
}
}
private String getEncryptedGetterStatement() {
if (annotatedEntityClazz.getterFunctionsList.containsKey(keyField.keyName)) {
String superMethodName =
annotatedEntityClazz.getterFunctionsList.get(keyField.keyName).getSimpleName().toString();
return wrapperClassFormatting(
String.format("super.%s(\n$T.decrypt(\n$N.getString($S, $S), $S, $S))", superMethodName));
}
return wrapperClassFormatting("$T.decrypt(\n$N.getString($S, $S), $S, $S)");
}
private String getObjectGetterStatement() {
if (annotatedEntityClazz.getterFunctionsList.containsKey(keyField.keyName)) {
String superMethodName =
annotatedEntityClazz.getterFunctionsList.get(keyField.keyName).getSimpleName().toString();
if (keyField.value instanceof String) {
return String.format("super.%s(\n$N.convertType($N.getString($S, $S)))", superMethodName);
} else if (keyField.value instanceof Float) {
return String.format(
"super.%s(\n$N.convertType($N." + getGetterTypeMethodName() + "($S, $Lf)))",
superMethodName);
} else {
return String.format(
"super.%s(\n$N.convertType($N." + getGetterTypeMethodName() + "($S, $L)))",
superMethodName);
}
} else {
if (keyField.value instanceof String) {
return "$N.convertType($N.getString($S, $S))";
} else if (keyField.value instanceof Float) {
return "$N.convertType(\n$N." + getGetterTypeMethodName() + "($S, $Lf))";
} else {
return "$N.convertType(\n$N." + getGetterTypeMethodName() + "($S, $L))";
}
}
}
private String getObjectEncryptedGetterStatement() {
if (annotatedEntityClazz.getterFunctionsList.containsKey(keyField.keyName)) {
String superMethodName =
annotatedEntityClazz.getterFunctionsList.get(keyField.keyName).getSimpleName().toString();
return String.format(
"super.%s(\n$N.convertType($T.decrypt($N.getString($S, $S), $S, $S)))", superMethodName);
}
return "$N.convertType(\n$T.decrypt($N.getString($S, $S), $S, $S))";
}
private String getSetterStatement() {
if (annotatedEntityClazz.setterFunctionsList.containsKey(keyField.keyName)) {
return String.format(
"$N.$N." + getSetterTypeMethodName() + "($S, super.%s($N)).$N",
annotatedEntityClazz.setterFunctionsList.get(keyField.keyName).getSimpleName());
} else {
return "$N.$N." + getSetterTypeMethodName() + "($S, $N).$N";
}
}
private String getSetterEncryptStatement() {
if (annotatedEntityClazz.setterFunctionsList.containsKey(keyField.keyName)) {
return String.format(
"$N.$N."
+ getSetterTypeMethodName()
+ "($S, $T.encrypt(\nString.valueOf(super.%s($N)), $S)).$N",
annotatedEntityClazz.setterFunctionsList.get(keyField.keyName).getSimpleName());
} else {
return "$N.$N." + getSetterTypeMethodName() + "($S, $T.encrypt(\nString.valueOf($N), $S)).$N";
}
}
private String getOnChangedStatement() {
String onChangeListener =
keyField.keyName + PreferenceChangeListenerGenerator.CHANGED_LISTENER_POSTFIX;
PreferenceChangeListenerGenerator generator = new PreferenceChangeListenerGenerator(keyField);
return "if ("
+ onChangeListener
+ " != null)\n"
+ "for ("
+ generator.getClazzName()
+ " "
+ "listener : "
+ onChangeListener
+ ") "
+ "listener."
+ PreferenceChangeListenerGenerator.CHANGED_ABSTRACT_METHOD
+ "("
+ keyField.keyName.toLowerCase()
+ ")";
}
private boolean isEncryption() {
return annotatedEntityClazz.isEncryption;
}
private String getEncryptionKey() {
return annotatedEntityClazz.encryptionKey;
}
private String wrapperClassFormatting(String statement) {
if (keyField.value instanceof Boolean) {
return String.format("Boolean.valueOf(%s).booleanValue()", statement);
} else if (keyField.value instanceof Integer) {
return String.format("Integer.valueOf(%s).intValue()", statement);
} else if (keyField.value instanceof Float) {
return String.format("Float.valueOf(%s).floatValue()", statement);
}
return statement;
}
}
<file_sep>/*
* Copyright (C) 2017 skydoves
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.processor;
import static javax.lang.model.element.Modifier.PRIVATE;
import static javax.lang.model.element.Modifier.PUBLIC;
import static javax.lang.model.element.Modifier.STATIC;
import androidx.annotation.NonNull;
import com.google.common.base.VerifyException;
import com.skydoves.preferenceroom.Encoder;
import com.skydoves.preferenceroom.PreferenceRoom;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.util.Elements;
@SuppressWarnings("WeakerAccess")
public class PreferenceComponentGenerator {
private final PreferenceComponentAnnotatedClass annotatedClazz;
private final Map<String, PreferenceEntityAnnotatedClass> annotatedEntityMap;
private final Elements annotatedElementUtils;
private static final String CLAZZ_PREFIX = "PreferenceComponent_";
private static final String ENTITY_PREFIX = "Preference_";
private static final String FIELD_INSTANCE = "instance";
private static final String CONSTRUCTOR_CONTEXT = "context";
private static final String ENTITY_NAME_LIST = "EntityNameList";
private static final String PACKAGE_CONTEXT = "android.content.Context";
public PreferenceComponentGenerator(
@NonNull PreferenceComponentAnnotatedClass annotatedClass,
@NonNull Map<String, PreferenceEntityAnnotatedClass> annotatedEntityMap,
@NonNull Elements elementUtils) {
this.annotatedClazz = annotatedClass;
this.annotatedEntityMap = annotatedEntityMap;
this.annotatedElementUtils = elementUtils;
}
public TypeSpec generate() {
return TypeSpec.classBuilder(getClazzName())
.addJavadoc("Generated by PreferenceRoom. (https://github.com/skydoves/PreferenceRoom).\n")
.addModifiers(PUBLIC)
.addSuperinterface(annotatedClazz.typeName)
.addField(getInstanceFieldSpec())
.addFields(getEntityInstanceFieldSpecs())
.addMethod(getConstructorSpec())
.addMethod(getInitializeSpec())
.addMethod(getInstanceSpec())
.addMethods(getSuperEntityMethodSpecs())
.addMethods(getSuperInjectionMethodSpecs())
.addMethods(getEntityInstanceSpecs())
.addMethod(getEntityNameListSpec())
.build();
}
private FieldSpec getInstanceFieldSpec() {
return FieldSpec.builder(getClassType(), FIELD_INSTANCE, PRIVATE, STATIC).build();
}
private List<FieldSpec> getEntityInstanceFieldSpecs() {
List<FieldSpec> fieldSpecs = new ArrayList<>();
this.annotatedClazz.keyNames.forEach(
keyName -> {
FieldSpec instance =
FieldSpec.builder(
getEntityClassType(annotatedEntityMap.get(keyName)),
getEntityInstanceFieldName(keyName),
PRIVATE,
STATIC)
.build();
fieldSpecs.add(instance);
});
return fieldSpecs;
}
private MethodSpec getConstructorSpec() {
MethodSpec.Builder builder =
MethodSpec.constructorBuilder()
.addModifiers(PRIVATE)
.addParameter(
ParameterSpec.builder(getContextPackageType(), CONSTRUCTOR_CONTEXT)
.addAnnotation(NonNull.class)
.build());
this.annotatedClazz.keyNames.forEach(
keyName ->
builder.addStatement(
"$N = $N.getInstance($N.getApplicationContext())",
getEntityInstanceFieldName(keyName),
getEntityClazzName(annotatedEntityMap.get(keyName)),
CONSTRUCTOR_CONTEXT));
return builder.build();
}
private MethodSpec getInitializeSpec() {
return MethodSpec.methodBuilder("init")
.addModifiers(PUBLIC, STATIC)
.addParameter(
ParameterSpec.builder(getContextPackageType(), CONSTRUCTOR_CONTEXT)
.addAnnotation(NonNull.class)
.build())
.addStatement("if ($N != null) return $N", FIELD_INSTANCE, FIELD_INSTANCE)
.addStatement("$N = new $N($N)", FIELD_INSTANCE, getClazzName(), CONSTRUCTOR_CONTEXT)
.addStatement("return $N", FIELD_INSTANCE)
.returns(getClassType())
.build();
}
private MethodSpec getInstanceSpec() {
return MethodSpec.methodBuilder("getInstance")
.addModifiers(PUBLIC, STATIC)
.addStatement("if($N != null) return $N", FIELD_INSTANCE, FIELD_INSTANCE)
.addStatement("else throw new VerifyError(\"component is not initialized.\")")
.returns(getClassType())
.build();
}
private List<MethodSpec> getEntityInstanceSpecs() {
List<MethodSpec> methodSpecs = new ArrayList<>();
this.annotatedClazz.keyNames.forEach(
keyName -> {
String fieldName = getEntityInstanceFieldName(keyName);
MethodSpec instance =
MethodSpec.methodBuilder(StringUtils.toUpperCamel(keyName))
.addModifiers(PUBLIC)
.addStatement("return $N", fieldName)
.returns(getEntityClassType(annotatedEntityMap.get(keyName)))
.build();
methodSpecs.add(instance);
});
return methodSpecs;
}
private List<MethodSpec> getSuperEntityMethodSpecs() {
List<MethodSpec> methodSpecs = new ArrayList<>();
this.annotatedClazz.annotatedElement.getEnclosedElements().stream()
.filter(element -> element instanceof ExecutableElement)
.map(element -> (ExecutableElement) element)
.filter(method -> method.getParameters().size() == 0)
.forEach(
method -> {
String encodedString = Encoder.encodeUtf8(method.getReturnType() + ".class");
if (!annotatedClazz.entities.contains(encodedString)) {
throw new VerifyException(
String.format("'%s' method can return only an entity type.", method));
}
annotatedEntityMap.values().stream()
.filter(
clazz ->
method
.getReturnType()
.toString()
.equals(clazz.annotatedElement.toString()))
.forEach(
clazz -> {
String instance = getEntityInstanceFieldName(clazz.entityName);
MethodSpec.Builder builder = MethodSpec.overriding(method);
MethodSpec methodSpec = builder.addStatement("return $N", instance).build();
methodSpecs.add(methodSpec);
});
});
return methodSpecs;
}
private List<MethodSpec> getSuperInjectionMethodSpecs() {
List<MethodSpec> methodSpecs = new ArrayList<>();
this.annotatedClazz.annotatedElement.getEnclosedElements().stream()
.filter(element -> element instanceof ExecutableElement)
.map(element -> (ExecutableElement) element)
.filter(method -> method.getParameters().size() == 1)
.forEach(
method -> {
ClassName preferenceRoom = ClassName.get(PreferenceRoom.class);
MethodSpec.Builder builder = MethodSpec.overriding(method);
MethodSpec methodSpec =
builder
.addStatement(
"$T.inject($N)",
preferenceRoom,
method.getParameters().get(0).getSimpleName())
.build();
if (methodSpec.returnType != TypeName.get(Void.TYPE)) {
throw new VerifyException(
String.format(
"Returned '%s'. only return type can be void.",
methodSpec.returnType.toString()));
}
methodSpecs.add(methodSpec);
});
return methodSpecs;
}
private MethodSpec getEntityNameListSpec() {
MethodSpec.Builder builder =
MethodSpec.methodBuilder("get" + ENTITY_NAME_LIST)
.addModifiers(PUBLIC)
.returns(List.class)
.addStatement("List<String> $N = new $T<>()", ENTITY_NAME_LIST, ArrayList.class);
this.annotatedClazz.keyNames.forEach(
entityName -> builder.addStatement("$N.add($S)", ENTITY_NAME_LIST, entityName));
builder.addStatement("return $N", ENTITY_NAME_LIST);
return builder.build();
}
private ClassName getClassType() {
return ClassName.get(annotatedClazz.packageName, getClazzName());
}
private String getClazzName() {
return CLAZZ_PREFIX + annotatedClazz.clazzName;
}
private ClassName getEntityClassType(PreferenceEntityAnnotatedClass annotatedClass) {
return ClassName.get(annotatedClass.packageName, getEntityClazzName(annotatedClass));
}
private String getEntityClazzName(PreferenceEntityAnnotatedClass annotatedClass) {
return ENTITY_PREFIX + annotatedClass.entityName;
}
private String getEntityInstanceFieldName(String keyName) {
return FIELD_INSTANCE + StringUtils.toUpperCamel(keyName);
}
private TypeName getContextPackageType() {
return TypeName.get(annotatedElementUtils.getTypeElement(PACKAGE_CONTEXT).asType());
}
}
<file_sep>/*
* Copyright (C) 2017 skydoves
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.preferenceroomdemo
import android.app.Application
import com.facebook.stetho.Stetho
import com.skydoves.preferenceroomdemo.components.PreferenceComponent_UserProfileComponent
/**
* Developed by skydoves on 2017-11-24.
* Copyright (c) 2017 skydoves rights reserved.
*/
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
// initialize Stetho for debugging local data
Stetho.initializeWithDefaults(this)
/**
* initialize instances of preference component and entities.
* [com.skydoves.preferenceroomdemo.components.UserProfileComponent]
*/
PreferenceComponent_UserProfileComponent.init(this)
}
}
<file_sep># PreferenceRoom
[](https://opensource.org/licenses/Apache-2.0)
[](https://android-arsenal.com/api?level=11)
[](https://github.com/skydoves/PreferenceRoom/actions/workflows/android.yml)
[](https://androidweekly.net/issues/issue-335)
<br>
PreferenceRoom is an android annotation processor library to manage `SharedPreferences` more efficiently and structurally.
PreferenceRoom was inspired by [Architecture Components Room Persistence](https://developer.android.com/topic/libraries/architecture/room.html)
and [dagger](https://github.com/square/dagger).
PreferenceRoom integrates scattered `SharedPreferences` as a single entity and it supports custom setter/getter functions with security algorithm.
Also this library provides simple dependency injection system, which is free from reflection, and fully-supported in kotlin project.
## Who's using this library?
| [GithubFollows](https://github.com/skydoves)<br>[Open Source](https://github.com/skydoves/githubfollows) | [All-In-One](https://github.com/skydoves)<br>[Open Source](https://github.com/skydoves/all-in-one) | [Battle Comics](http://www.battlecomics.co.kr/)<br>[Product](https://play.google.com/store/apps/details?id=com.whalegames.app) | [Epoptia](http://epoptia.com/cloud-mes-manufacturing-execution-system/) <br> [Open Source](https://github.com/tsironis13/EpoptiaKioskModeApp) | [Sensemore](https://sensemore.io/)
| :---------------: | :---------------: | :---------------: | :---------------: | :---------------: |
|  |  |  |  | 
## Download
[](https://search.maven.org/search?q=g:%22com.github.skydoves%22%20AND%20a:%22preferenceroom%22)
### Gradle
Add the codes below to your **root** `build.gradle` file (not your module build.gradle file).
```gradle
allprojects {
repositories {
mavenCentral()
}
}
```
And add the dependency below to your **module**'s `build.gradle` file.
```gradle
dependencies {
implementation "com.github.skydoves:preferenceroom:1.2.2"
annotationProcessor "com.github.skydoves:preferenceroom-processor:1.2.2"
// in kotlin project use kapt instead of annotationProcessor
kapt "com.github.skydoves:preferenceroom-processor:1.2.2"
}
```
## Table of Contents
#### [1.PreferenceEntity](https://github.com/skydoves/PreferenceRoom#preferenceentity)
- [KeyName](https://github.com/skydoves/PreferenceRoom#keyname)
- [TypeConverter](https://github.com/skydoves/PreferenceRoom#typeconverter)
- [PreferenceFunction](https://github.com/skydoves/PreferenceRoom#preferencefunction)
- [EncryptEntity](https://github.com/skydoves/PreferenceRoom#encryptentity)
#### [2.PreferenceComponent](https://github.com/skydoves/PreferenceRoom#preferencecomponent)
#### [3.Dependency Injection](https://github.com/skydoves/PreferenceRoom#dependency-injection) (Use with [dagger](https://github.com/skydoves/PreferenceRoom/releases))
#### [4.Usage in Kotlin](https://github.com/skydoves/PreferenceRoom#usage-in-kotlin) ([Incremental annotation processing](https://github.com/skydoves/PreferenceRoom#incremetal-annotation-processing))
#### [5.Proguard-Rules](https://github.com/skydoves/PreferenceRoom#proguard-rules)
#### [6.Debugging with Stetho](https://github.com/skydoves/PreferenceRoom#debugging-with-stetho)
## PreferenceEntity
<br>
`@PreferenceEntity` annotation makes SharedPreferences data as an entity.<br>
Value in `@PreferenceEntity` determines the entity name.<br>
Entity's default name is determined by class name.<br>
```java
@PreferenceEntity("UserProfile")
public class Profile {
protected final boolean login = false;
@KeyName("nickname") protected final String userNickName = null;
@KeyName("visits") protected final int visitCount = 1;
@KeyName("userPet")
@TypeConverter(PetConverter.class)
protected Pet userPetInfo;
@PreferenceFunction("nickname")
public String putUserNickFunction(String nickname) {
return "Hello, " + nickname;
}
@PreferenceFunction("nickname")
public String getUserNickFunction(String nickname) {
return nickname + "!!!";
}
@PreferenceFunction("visits")
public int putVisitCountFunction(int count) {
return ++count;
}
}
```
After the build your project, `Preference_(entity name)` class will be generated automatically. <br>
```java
Preference_UserProfile userProfile = Preference_UserProfile.getInstance(this); // gets instance of the UserProfile entity.
userProfile.putNickname("my nickname"); // puts a value in NickName.
userProfile.getNickname(); // gets a nickname value.
userProfile.containsNickname(); // checks nickname key value is exist or not in entity.
userProfile.removeNickname(); // removes nickname key value in entity.
userProfile.nicknameKeyName(); // returns nickname key name.
userProfile.getEntityName(); // returns UserProfile entity name;
userProfile.getkeyNameList(); // returns UserProfile entity's key name lists.
// or invoke static.
Preference_UserProfile.getInstance(this).putNickname("my nickname");
```
we can listen the changed value using `OnChangedListener`.<br>
`onChanged` method will be invoked if we change the value using `put` method.
```java
userProfile.addNicknameOnChangedListener(new Preference_UserProfile.NicknameOnChangedListener() {
@Override
public void onChanged(String nickname) {
Toast.makeText(getBaseContext(), "onChanged :" + nickname, Toast.LENGTH_SHORT).show();
}
});
```
Auto-generated code is managed by singletons. </br>
But we can manage more efficiently using [PreferenceComponent](https://github.com/skydoves/PreferenceRoom#preferencecomponent) and
[Dependency Injection](https://github.com/skydoves/PreferenceRoom#dependency-injection). <br>
We can set SharedPreference to an entity as DefaultSharedPreferences using `@DefaultPreference` annotation like below.
```java
@DefaultPreference
@PreferenceEntity("ProfileWithDefault")
public class UserProfilewithDefaultPreference {
@KeyName("nickname")
protected final String userNickName = "skydoves";
// key name will be 'Login'. (login's camel uppercase)
protected final boolean login = false;
}
```
The `ProfileWithDefault` entity from the example, will be initialized like below on `PreferenceRoom` processor.
```java
PreferenceManager.getDefaultSharedPreferences(context);
```
So we can connect with PreferenceFragmentCompat, PreferenceScreen or etc.
### KeyName
<br>
`@KeyName` annotation can be used on an entity class's field. <br>
The field's key name will be decided by field name, but we can customize the name as taste. <br>
```java
@KeyName("visits") // keyname will be Visits.
protected final int visitCount = 1;
```
### TypeConverter
 <br>
SharedPreference persists only primitive type data. <br>
But PreferenceRoom supports persistence obejct data using `TypeConverter` annotation. <br>
`@TypeConverter` annotation should be annotated over an object field like below. <br>
```java
@TypeConverter(PetConverter.class)
protected Pet userPetInfo; // 'Pet' class field in an entity.
```
Below example is creating a converter class using Gson. <br>
Converter class should extends the `PreferenceTypeConverter<?>` class. <br>
The basic principle is making object class to string data for persistence and getting the string data and recover.<br>
`convertObject` performs how to change class data to a string, `convertType` performs how to recover class data from the string data.
```java
public class PetConverter extends PreferenceTypeConverter<Pet> {
private final Gson gson;
// default constructor will be called by PreferenceRoom
public PetConverter() {
this.gson = new Gson();
}
@Override
public String convertObject(Pet pet) {
return gson.toJson(pet);
}
@Override
public Pet convertType(String string) {
return gson.fromJson(string, Pet.class);
}
}
```
#### BaseTypeConverter
We can generalize the converter using generic like below. <br>
```java
public class BaseGsonConverter<T> extends PreferenceTypeConverter<T> {
private final Gson gson;
public BaseGsonConverter(Class<T> clazz) {
super(clazz);
this.gson = new Gson();
}
@Override
public String convertObject(T object) {
return gson.toJson(object);
}
@Override
public T convertType(String string) {
return gson.fromJson(string, clazz);
}
}
```
So we can use the converter to any classes.
```java
@KeyName("userinfo")
@TypeConverter(BaseGsonConverter.class)
protected PrivateInfo privateInfo;
@KeyName("userPet")
@TypeConverter(BaseGsonConverter.class)
protected Pet userPetInfo;
```
### PreferenceFunction
<br>
`@PreferenceFunction` annotation processes pre/post-processing through getter and setter functions. <br>
`@PreferenceFunction` annotation's value decides a target. The target should be a keyName. <br>
The function's naming convention is which should start with `put` or `get` prefix. <br>
`put_functionname_` is pre-processing getter function and `get_functionname_` is postprocessing getter function.
```java
@PreferenceFunction("nickname")
public String putUserNickFunction(String nickname) {
return "Hello, " + nickname;
}
@PreferenceFunction("nickname")
public String getUserNickFunction(String nickname) {
return nickname + "!!!";
}
```
### EncryptEntity
SharedPreferences data are not safe from hacking even if private-mode.<br>
There is a simple way to encrypt whole entity using `@EncryptEntity` annotation.<br>
It is based on AES128 encryption. So we should set the key value along __16 size__ length.<br>
If `put` method invoked, the value is encrypted automatically. <br>
And if `get` method invoked, it returns the decrypted value.
```java
@EncryptEntity("1234567890ABCDFG")
@PreferenceEntity("UserProfile")
public class Profile {
}
```
Or we can customize encrypting and decrypting algorithm using `PreferenceFunction`.
```java
@PreferenceFunction("uuid")
public String putUuidFunction(String uuid) {
return SecurityUtils.encrypt(uuid);
}
@PreferenceFunction("uuid")
public String getUuidFunction(String uuid) {
return SecurityUtils.decrypt(uuid);
}
```
## PreferenceComponent
 <br>
PreferenceComponent integrates entities. `@PreferenceComponent` annotation should be annotated on an interface class.<br>
We can integrate many entities as one component using entities value in `@PreferenceComponent` annotation. <br>
So we can initialize many entities at once through the component and get instances from the component. <br>
And the instance of the `PreferenceComponent` is managed by singleton by PreferenceRoom.
`PreferenceComponent's instance also singletons. And all entities instances are initialized when the component is initialized.<br>
```java
@PreferenceComponent(entities = {Profile.class, Device.class})
public interface UserProfileComponent {
}
```
After build your project, `PreferenceComponent_(component's name)` class will be generated automatically. <br>
The best-recommanded way to initialize component is initializing on Application class. So we can manage the component as a singleton instance.
```java
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
PreferenceComponent_UserProfileComponent.init(this);
}
}
```
After initializing the component, we can access and use the instances of component and component's entities anywhere.<br>
```java
PreferenceComponent_UserProfileComponent component = PreferenceComponent_UserProfileComponent.getInstance();
Preference_UserProfile userProfile = component.UserProfile();
Preference_UserDevice userDevice = PreferenceComponent_UserProfileComponent.getInstance().UserDevice();
```
## Dependency Injection
 <br>
`PreferenceRoom` supports simple dependency injection process with free from reflection using `@InjectPreference` annotation. But If you want to use with dagger, check [this](https://github.com/skydoves/PreferenceRoom/releases) reference.
Firstly we should declare some target classes which to be injected preference instances in `PreferenceComponent`. <br>
```java
@PreferenceComponent(entities = {Profile.class, Device.class})
public interface UserProfileComponent {
// declares targets for the dependency injection.
void inject(MainActivity __);
void inject(LoginActivity __);
}
```
We should annotate InjectPreference annotation to preference entity or component class field which generated by PreferenceRoom. <br>
The field's modifier should be `public`.
```java
@InjectPreference
public PreferenceComponent_UserProfileComponent component;
@InjectPreference
public Preference_UserProfile userProfile;
```
And the last, we should inject instances of entity and component to targets fields using `inject` method from an instance of the component. </br>
```java
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PreferenceComponent_UserProfileComponent.getInstance().inject(this);
}
```
## Usage in Kotlin
It is similar to java project usage. <br>
But the most important thing is which we should use an `open` modifier on entity classes and PreferenceFunctions. <br>
And the field's modifier should be `@JvmField val`.
```java
@PreferenceEntity("UserDevice")
open class Device {
@KeyName("version")
@JvmField val deviceVersion: String? = null
@KeyName("uuid")
@JvmField val userUUID: String? = null
@PreferenceFunction("uuid")
open fun putUuidFunction(uuid: String?): String? {
return SecurityUtils.encrypt(uuid)
}
@PreferenceFunction( "uuid")
open fun getUuidFunction(uuid: String?): String? {
return SecurityUtils.decrypt(uuid)
}
}
```
And the component usage is almost the same as Java examples.
```java
@PreferenceComponent(entities = [Profile::class, Device::class])
interface UserProfileComponent {
// declare dependency injection targets.
fun inject(target: MainActivity)
fun inject(target: LoginActivity)
}
```
And the last, the usage of the dependency injection is the same as the java. but we should declare the component and entity field's modifier as lateinit var. <br>
```java
@InjectPreference
lateinit var component: PreferenceComponent_UserProfileComponent
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
PreferenceComponent_UserProfileComponent.getInstance().inject(this) // inject dependency injection to MainActivity.
```
### Incremetal annotation processing
Starting from version `1.3.30`, kapt supports incremental annotation processing as an experimental feature. Currently, annotation processing can be incremental only if all annotation processors being used are incremental.<br>
Incremental annotation processing is enabled by default starting from version `1.3.50`.<br>
`PreferenceRoom` supports incremental annotation processing since version `1.1.9` and here is a Before/After example result of the enabled.
Before (23.758s) | After (18.779s) |
| :---------------: | :---------------: |
| <img src="https://user-images.githubusercontent.com/24237865/76435566-7b4f7480-63fa-11ea-999f-25133c577d07.png" align="center" width="100%"/> | <img src="https://user-images.githubusercontent.com/24237865/76435569-7d193800-63fa-11ea-9d75-dd0a3e9de68c.png" align="center" width="100%"/> |
### Non Existent Type Correction
If you encounter `NonExistentClass` error at compile time, you should add below codes on your build.gradle. <br>
Default, Kapt replaces every unknown type (including types for the generated classes) to NonExistentClass, but you can change this behavior. Add the additional flag to the build.gradle file to enable error type inferring in stubs:
```xml
kapt {
correctErrorTypes = true
}
```
## Proguard Rules
```xml
# Retain generated class which implement PreferenceRoomImpl.
-keep public class ** implements com.skydoves.preferenceroom.PreferenceRoomImpl
# Prevent obfuscation of types which use PreferenceRoom annotations since the simple name
# is used to reflectively look up the generated Injector.
-keep class com.skydoves.preferenceroom.*
-keepclasseswithmembernames class * { @com.skydoves.preferenceroom.* <methods>; }
-keepclasseswithmembernames class * { @com.skydoves.preferenceroom.* <fields>; }
```
## Debugging with Stetho
We can debug SharedPreferences values which managed by PreferenceRoom using Stetho. <br>

## References
- [How to manage SharedPreferences on Android project more efficiently](https://medium.com/@skydoves/how-to-manage-sharedpreferences-on-android-project-5e6d5e28fee6)
## Find this library useful? :heart:
Support it by joining __[stargazers](https://github.com/skydoves/PreferenceRoom/stargazers)__ for this repository. :star:
## Sponsor :coffee:
If you feel like to sponsor me a coffee for my efforts, I would greatly appreciate it. <br>
<a href="https://www.buymeacoffee.com/skydoves" target="_blank"><img src="https://skydoves.github.io/sponsor.png" alt="Buy Me A Coffee" style="height: 51px !important;width: 217px !important;" ></a>
# License
```xml
Copyright 2017 skydoves
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.
```
<file_sep>/*
* Copyright (C) 2017 skydoves
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.preferenceroomdemo.components
import com.skydoves.preferenceroom.PreferenceComponent
import com.skydoves.preferenceroomdemo.LoginActivity
import com.skydoves.preferenceroomdemo.MainActivity
import com.skydoves.preferenceroomdemo.entities.Device
import com.skydoves.preferenceroomdemo.entities.Profile
/**
* Developed by skydoves on 2017-11-20.
* Copyright (c) 2017 skydoves rights reserved.
*/
/**
* Component integrates entities.
*/
@PreferenceComponent(entities = [Profile::class, Device::class])
interface UserProfileComponent {
/**
* declare dependency injection targets.
*/
fun inject(target: MainActivity)
fun inject(target: LoginActivity)
}
<file_sep>/*
* Copyright (C) 2017 skydoves
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.preferenceroomdemo.entities;
import com.skydoves.preferenceroom.EncryptEntity;
import com.skydoves.preferenceroom.KeyName;
import com.skydoves.preferenceroom.PreferenceEntity;
import com.skydoves.preferenceroom.PreferenceFunction;
import com.skydoves.preferenceroom.TypeConverter;
import com.skydoves.preferenceroomdemo.converters.BaseGsonConverter;
import com.skydoves.preferenceroomdemo.converters.PrivateInfoConverter;
import com.skydoves.preferenceroomdemo.models.Pet;
import com.skydoves.preferenceroomdemo.models.PrivateInfo;
@EncryptEntity("1234567890ABCDFG")
@PreferenceEntity("UserProfile")
public class Profile {
@KeyName("nickname")
protected final String userNickName = "skydoves";
/** key value will be 'Login'. (login's camel uppercase) */
protected final boolean login = false;
@KeyName("visits")
protected final int visitCount = 1;
@KeyName("userinfo")
@TypeConverter(value = PrivateInfoConverter.class)
protected PrivateInfo privateInfo;
/** value used with gson. */
@KeyName("userPet")
@TypeConverter(BaseGsonConverter.class)
protected Pet userPetInfo;
/**
* preference putter function about userNickName.
*
* @param nickname function in
* @return function out
*/
@PreferenceFunction("nickname")
public String putUserNickFunction(String nickname) {
return "Hello, " + nickname;
}
/**
* preference getter function about userNickName.
*
* @param nickname function in
* @return function out
*/
@PreferenceFunction("nickname")
public String getUserNickFunction(String nickname) {
return nickname + "!!!";
}
/**
* preference putter function example about visitCount's auto increment.
*
* @param count function in
* @return function out
*/
@PreferenceFunction("visits")
public int putVisitCountFunction(int count) {
return ++count;
}
}
<file_sep>/*
* Copyright (C) 2017 skydoves
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.preferenceroomdemo.utils
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import com.skydoves.preferenceroomdemo.R
import com.skydoves.preferenceroomdemo.models.ItemProfile
import java.util.ArrayList
/**
* Developed by skydoves on 2018-02-07.
* Copyright (c) 2017 skydoves rights reserved.
*/
class ListViewAdapter(context: Context, private val layout: Int) : BaseAdapter() {
private val inflater: LayoutInflater
private val profileList: MutableList<ItemProfile>
init {
this.profileList = ArrayList()
this.inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
}
override fun getCount() = profileList.size
override fun getItem(i: Int) = profileList[i]
override fun getItemId(i: Int) = i.toLong()
fun addItem(itemProfile: ItemProfile) {
this.profileList.add(itemProfile)
notifyDataSetChanged()
}
override fun getView(index: Int, view: View?, viewGroup: ViewGroup): View {
var itemView = view
if (itemView == null) {
itemView = this.inflater.inflate(layout, viewGroup, false)
}
val itemProfile = profileList[index]
val title = itemView!!.findViewById<TextView>(R.id.item_profile_title)
title.text = itemProfile.title
val content = itemView.findViewById<TextView>(R.id.item_profile_content)
content.text = itemProfile.content
return itemView
}
}
<file_sep>apply plugin: 'java-library'
apply plugin: 'org.jetbrains.kotlin.jvm'
apply plugin: 'org.jetbrains.kotlin.kapt'
apply from: '../dependencies.gradle'
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
dependencies {
implementation project(":preferenceroom")
implementation "com.squareup:javapoet:$versions.javapoet"
implementation "com.google.auto.service:auto-service-annotations:$versions.autoService"
kapt "com.google.auto.service:auto-service:$versions.autoService"
api "com.google.guava:guava:$versions.guava"
compileOnly "net.ltgt.gradle.incap:incap:$versions.incap"
kapt "net.ltgt.gradle.incap:incap-processor:$versions.incap"
}
apply plugin: "com.vanniktech.maven.publish"
apply from: '../spotless.gradle'
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.github.skydoves</groupId>
<artifactId>preferenceroom-processor</artifactId>
<version>1.1.8</version>
<packaging>jar</packaging>
<name>PreferenceRoom</name>
<description>Android processor library for managing SharedPreferences persistence efficiently and structurally.</description>
<url>http://github.com/skydoves/preferenceroom/</url>
<issueManagement>
<system>GitHub Issues</system>
<url>http://github.com/skydoves/preferenceroom/issues</url>
</issueManagement>
<licenses>
<license>
<name>Apache 2.0</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
</license>
</licenses>
<organization>
<name>skydoves</name>
<url>https://github.com/skydoves</url>
</organization>
<dependencies>
<dependency>
<groupId>com.github.skydoves</groupId>
<artifactId>preferenceroom</artifactId>
<version>1.1.8</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.google.auto.service</groupId>
<artifactId>auto-service</artifactId>
<version>1.0-rc4</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.squareup</groupId>
<artifactId>javapoet</artifactId>
<version>1.11.1</version>
<scope>runtime</scope>
</dependency>
</dependencies>
</project>
<file_sep>/*
* Copyright (C) 2017 skydoves
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.preferenceroomdemo.converters
import com.google.gson.Gson
import com.skydoves.preferenceroom.PreferenceTypeConverter
/**
* Developed by skydoves on 2018-02-06.
* Copyright (c) 2017 skydoves rights reserved.
*/
class BaseGsonConverter<T>(clazz: Class<T>) : PreferenceTypeConverter<T>(clazz) {
private val gson: Gson = Gson()
override fun convertObject(obj: T?): String {
return gson.toJson(obj)
}
override fun convertType(string: String?): T? {
when (string == null) {
true -> return null
else -> return gson.fromJson(string, clazz)
}
}
}
<file_sep>/*
* Copyright (C) 2017 skydoves
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.preferenceroomdemo
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.ListView
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.ViewCompat
import com.skydoves.preferenceroom.InjectPreference
import com.skydoves.preferenceroomdemo.components.PreferenceComponent_UserProfileComponent
import com.skydoves.preferenceroomdemo.databinding.ActivityMainBinding
import com.skydoves.preferenceroomdemo.models.ItemProfile
import com.skydoves.preferenceroomdemo.utils.ListViewAdapter
/**
* Developed by skydoves on 2017-11-26.
* Copyright (c) 2017 skydoves rights reserved.
*/
class MainActivity : AppCompatActivity() {
/**
* UserProfile Component.
* [com.skydoves.preferenceroomdemo.components.UserProfileComponent]
*/
@InjectPreference
lateinit var component: PreferenceComponent_UserProfileComponent
private val adapter by lazy { ListViewAdapter(this, R.layout.item_profile) }
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
PreferenceComponent_UserProfileComponent.getInstance()
.inject(this) // inject dependency injection to MainActivity.
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
initializeUI()
setProfileButton()
}
private fun initializeUI() {
if (component.UserProfile().login) {
val listView = binding.root.findViewById<ListView>(R.id.content_list_view)
ViewCompat.setNestedScrollingEnabled(listView, true)
listView.adapter = adapter
adapter.addItem(ItemProfile("message", component.UserProfile().nickname!!))
adapter.addItem(ItemProfile("nick value", component.UserProfile().userinfo!!.name))
adapter.addItem(ItemProfile("age", component.UserProfile().userinfo!!.age.toString() + ""))
adapter.addItem(ItemProfile("visits", component.UserProfile().visits.toString() + ""))
/**
* increment visits count.
* show [com.skydoves.preferenceroomdemo.entities.Profile] putVisitCountFunction()
*/
component.UserProfile().putVisits(component.UserProfile().visits)
}
component.UserDevice().uuid?.let {
adapter.addItem(ItemProfile("version", component.UserDevice().version!!))
adapter.addItem(ItemProfile("uuid", component.UserDevice().uuid!!))
} ?: putDumpDeviceInfo()
}
private fun setProfileButton() {
val needLoginView = findViewById<Button>(R.id.content_button)
needLoginView.setOnClickListener {
startActivity(Intent(baseContext, LoginActivity::class.java))
finish()
}
}
private fun putDumpDeviceInfo() {
component.UserDevice().putVersion("1.0.0.0")
component.UserDevice().putUuid("00001234-0000-0000-0000-000123456789")
}
}
<file_sep>/*
* Copyright (C) 2017 skydoves
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.processor;
import androidx.annotation.NonNull;
import com.google.common.base.VerifyException;
import com.skydoves.preferenceroom.PreferenceComponent;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.TypeName;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.util.Elements;
@SuppressWarnings("WeakerAccess")
public class PreferenceComponentAnnotatedClass {
private static final String ENTITY_PREFIX = "Preference_";
public final String packageName;
public final TypeElement annotatedElement;
public final TypeName typeName;
public final String clazzName;
public final List<String> entities;
public final List<String> keyNames;
public final List<String> generatedClazzList;
public PreferenceComponentAnnotatedClass(
@NonNull TypeElement annotatedElement,
@NonNull Elements elementUtils,
@NonNull Map<String, String> annotatedEntityTypeMap)
throws VerifyException {
PackageElement packageElement = elementUtils.getPackageOf(annotatedElement);
this.packageName =
packageElement.isUnnamed() ? null : packageElement.getQualifiedName().toString();
this.annotatedElement = annotatedElement;
this.typeName = TypeName.get(annotatedElement.asType());
this.clazzName = annotatedElement.getSimpleName().toString();
this.entities = new ArrayList<>();
this.keyNames = new ArrayList<>();
this.generatedClazzList = new ArrayList<>();
annotatedElement.getEnclosedElements().stream()
.filter(element -> element instanceof ExecutableElement)
.map(element -> (ExecutableElement) element)
.forEach(
method -> {
MethodSpec methodSpec = MethodSpec.overriding(method).build();
if (methodSpec.returnType != TypeName.get(Void.TYPE)
&& methodSpec.parameters.size() == 1) {
throw new VerifyException(
String.format(
"return type should be void : '%s' method with return type '%s'",
methodSpec.name, methodSpec.returnType));
} else if (methodSpec.parameters.size() > 1) {
throw new VerifyException(
String.format(
"length of parameter should be 1 or 0 : '%s' method with parameters '%s'",
methodSpec.name, methodSpec.parameters));
}
});
Set<String> entitySet = new HashSet<>();
annotatedElement.getAnnotationMirrors().stream()
.filter(
annotationMirror ->
TypeName.get(annotationMirror.getAnnotationType())
.equals(TypeName.get(PreferenceComponent.class)))
.forEach(
annotationMirror ->
annotationMirror
.getElementValues()
.forEach(
(type, value) -> {
String[] values = value.getValue().toString().split(",");
List<String> valueList = Arrays.asList(values);
entitySet.addAll(valueList);
}));
entitySet.forEach(
value -> {
if (!annotatedEntityTypeMap.containsKey(value)) {
throw new VerifyException(String.format("%s is not a preference entity.", value));
} else {
keyNames.add(annotatedEntityTypeMap.get(value));
generatedClazzList.add(ENTITY_PREFIX + annotatedEntityTypeMap.get(value));
}
});
entities.addAll(entitySet);
}
}
<file_sep>/*
* Copyright (C) 2017 skydoves
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.preferenceroomdemo.converters
import com.google.gson.Gson
import com.skydoves.preferenceroom.PreferenceTypeConverter
import com.skydoves.preferenceroomdemo.models.Pet
/**
* Developed by skydoves on 2017-11-26.
* Copyright (c) 2017 skydoves rights reserved.
*/
class PetConverter(clazz: Class<Pet>) : PreferenceTypeConverter<Pet>(clazz) {
private val gson: Gson = Gson()
override fun convertObject(pet: Pet): String {
return gson.toJson(pet)
}
override fun convertType(string: String): Pet {
return gson.fromJson(string, Pet::class.java)
}
}
<file_sep>/*
* Copyright (C) 2017 skydoves
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.preferenceroomdemo.converters
import com.skydoves.preferenceroom.PreferenceTypeConverter
import com.skydoves.preferenceroomdemo.models.PrivateInfo
/**
* Developed by skydoves on 2017-11-25.
* Copyright (c) 2017 skydoves rights reserved.
*/
class PrivateInfoConverter(clazz: Class<PrivateInfo>) : PreferenceTypeConverter<PrivateInfo>(
clazz) {
override fun convertObject(privateInfo: PrivateInfo): String {
return privateInfo.name + "," + privateInfo.age
}
override fun convertType(string: String?): PrivateInfo {
if (string == null) return PrivateInfo("null", 0)
val information = string.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
return PrivateInfo(information[0], Integer.parseInt(information[1]))
}
}
<file_sep>/*
* Copyright (C) 2017 skydoves
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.preferenceroomdemo.entities
import com.skydoves.preferenceroom.EncryptEntity
import com.skydoves.preferenceroom.KeyName
import com.skydoves.preferenceroom.PreferenceEntity
import com.skydoves.preferenceroom.PreferenceFunction
import com.skydoves.preferenceroom.TypeConverter
import com.skydoves.preferenceroomdemo.converters.PetConverter
import com.skydoves.preferenceroomdemo.converters.PrivateInfoConverter
import com.skydoves.preferenceroomdemo.models.Pet
import com.skydoves.preferenceroomdemo.models.PrivateInfo
/**
* Developed by skydoves on 2018-02-07.
* Copyright (c) 2017 skydoves rights reserved.
*/
@EncryptEntity("1234567890ABCDFG")
@PreferenceEntity("UserProfile")
open class Profile {
@KeyName("nickname")
@JvmField val userNickName = "skydoves"
/**
* key value will be 'Login'. (login's camel uppercase)
*/
@JvmField val login = false
@KeyName("visits")
@JvmField val visitCount = 1
@KeyName("userinfo")
@TypeConverter(PrivateInfoConverter::class)
@JvmField val privateInfo: PrivateInfo? = null
/**
* value used with gson.
*/
@KeyName("userPet")
@TypeConverter(PetConverter::class)
@JvmField val userPetInfo: Pet? = null
/**
* preference putter function about userNickName.
* @param nickname function in
* @return function out
*/
@PreferenceFunction("nickname")
open fun putUserNickFunction(nickname: String): String {
return "Hello, $nickname"
}
/**
* preference getter function about userNickName.
* @param nickname function in
* @return function out
*/
@PreferenceFunction("nickname")
open fun getUserNickFunction(nickname: String): String {
return "$nickname !!!"
}
/**
* preference putter function example about visitCount's auto increment.
* @param count function in
* @return function out
*/
@PreferenceFunction("visits")
open fun putVisitCountFunction(count: Int): Int {
return count + 1
}
}
<file_sep>apply plugin: 'com.android.application'
apply from: '../dependencies.gradle'
android {
compileSdkVersion versions.compileSdk
defaultConfig {
applicationId "com.skydoves.preferenceroomdemo"
minSdkVersion versions.minSdk
targetSdkVersion versions.compileSdk
versionCode versions.versionCode
versionName versions.versionName
testInstrumentationRunner "com.skydoves.preferenceroomdemo.JunitTestRunner"
}
testOptions {
unitTests {
includeAndroidResources = true
}
}
}
dependencies {
implementation "com.google.android.material:material:$versions.googleMaterial"
implementation "com.google.code.gson:gson:$versions.gson"
implementation "com.facebook.stetho:stetho:$versions.stetho"
implementation project(":preferenceroom")
annotationProcessor project(":preferenceroom-compiler")
androidTestAnnotationProcessor project(":preferenceroom-compiler")
testImplementation "junit:junit:$versions.junit"
androidTestImplementation "androidx.test:runner:$versions.runner"
androidTestImplementation "androidx.test.ext:junit:$versions.junitExt"
}
apply from: '../spotless.gradle'
<file_sep>include ':demo',':demo-kotlin', ':preferenceroom', ':preferenceroom-compiler'
<file_sep>/*
* Copyright (C) 2017 skydoves
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.preferenceroomdemo.entities
import com.skydoves.preferenceroom.KeyName
import com.skydoves.preferenceroom.PreferenceEntity
import com.skydoves.preferenceroom.PreferenceFunction
import com.skydoves.preferenceroomdemo.utils.SecurityUtils
/**
* Developed by skydoves on 2017-02-07.
* Copyright (c) 2017 skydoves rights reserved.
*/
@PreferenceEntity("UserDevice")
open class Device {
@KeyName("version")
@JvmField val deviceVersion: String? = null
@KeyName("uuid")
@JvmField val userUUID: String? = null
/**
* preference putter function example about uuid with encrypt AES.
* @param uuid function in
* @return function out
*/
@PreferenceFunction("uuid")
open fun putUuidFunction(uuid: String?): String? {
return SecurityUtils.encrypt(uuid)
}
/**
* preference putter function example about uuid with decrypt AES.
* @param uuid function in
* @return function out
*/
@PreferenceFunction("uuid")
open fun getUuidFunction(uuid: String?): String? {
return SecurityUtils.decrypt(uuid)
}
}
<file_sep>ext.versions = [
minSdk : 15,
compileSdk : 32,
versionName : '1.2.3',
gradleBuildTool : '7.2.1',
spotlessGradle : '6.7.0',
ktlintGradle : '0.42.0',
dokkaGradle : '1.7.0',
mavenPublish : '0.15.1',
androidxAnnotation: '1.1.0',
autoService : '1.0-rc7',
javapoet : '1.13.0',
guava : '28.2-jre',
incap : '0.3',
// for demo
kotlin : '1.7.0',
gson : '2.8.5',
googleMaterial : '1.6.0',
// unit test
junit : '4.13.1',
runner : '1.2.0',
junitExt : '1.1.1',
stetho : '1.5.1'
]
<file_sep>/*
* Copyright (C) 2017 skydoves
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.processor;
import static javax.lang.model.element.Modifier.PUBLIC;
import androidx.annotation.Nullable;
import com.skydoves.preferenceroom.PreferenceChangedListener;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeSpec;
import java.util.List;
import javax.lang.model.element.Modifier;
@SuppressWarnings("WeakerAccess")
public class PreferenceChangeListenerGenerator {
private final PreferenceKeyField keyField;
public static final String CHANGED_LISTENER_POSTFIX = "OnChangedListener";
public static final String CHANGED_ABSTRACT_METHOD = "onChanged";
public PreferenceChangeListenerGenerator(PreferenceKeyField keyField) {
this.keyField = keyField;
}
public TypeSpec generateInterface() {
TypeSpec.Builder builder =
TypeSpec.interfaceBuilder(getClazzName())
.addModifiers(PUBLIC)
.addSuperinterface(PreferenceChangedListener.class)
.addMethod(getOnChangedSpec());
return builder.build();
}
public FieldSpec generateField(String className) {
return FieldSpec.builder(
ParameterizedTypeName.get(ClassName.get(List.class), getInterfaceType(className)),
getFieldName(),
Modifier.PRIVATE)
.addAnnotation(Nullable.class)
.initializer("new ArrayList()")
.build();
}
private MethodSpec getOnChangedSpec() {
return MethodSpec.methodBuilder("onChanged")
.addParameter(
ParameterSpec.builder(keyField.typeName, keyField.keyName.toLowerCase()).build())
.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT)
.build();
}
public String getClazzName() {
return StringUtils.toUpperCamel(keyField.keyName) + CHANGED_LISTENER_POSTFIX;
}
private String getFieldName() {
return keyField.keyName + CHANGED_LISTENER_POSTFIX;
}
public ClassName getInterfaceType(String className) {
return ClassName.get(keyField.packageName + "." + className, getClazzName());
}
}
<file_sep>/*
* Copyright (C) 2017 skydoves
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.preferenceroomdemo.utils
import android.util.Base64
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
/**
* Developed by skydoves on 2018-02-07.
* Copyright (c) 2017 skydoves rights reserved.
*/
object SecurityUtils {
private val key = "<KEY>"
fun encrypt(input: String?): String? {
if (input == null) return null
var encrypted: ByteArray? = null
try {
val skey = SecretKeySpec(key.toByteArray(), "AES")
val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
cipher.init(Cipher.ENCRYPT_MODE, skey)
encrypted = cipher.doFinal(input.toByteArray())
} catch (e: Exception) {
e.printStackTrace()
}
return Base64.encodeToString(encrypted, Base64.DEFAULT)
}
fun decrypt(input: String?): String? {
if (input == null) return null
var decrypted: ByteArray? = null
try {
val skey = SecretKeySpec(key.toByteArray(), "AES")
val cipher = Cipher.getInstance("AES/ECB/PKCS5Padding")
cipher.init(Cipher.DECRYPT_MODE, skey)
decrypted = cipher.doFinal(Base64.decode(input, Base64.DEFAULT))
} catch (e: Exception) {
e.printStackTrace()
}
return String(decrypted!!)
}
}
<file_sep>/*
* Copyright (C) 2017 skydoves
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.preferenceroomdemo.entities;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.platform.app.InstrumentationRegistry;
import com.google.gson.Gson;
import com.skydoves.preferenceroomdemo.models.Pet;
import com.skydoves.preferenceroomdemo.models.PrivateInfo;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/** Developed by skydoves on 2017-11-29. Copyright (c) 2017 skydoves rights reserved. */
@RunWith(AndroidJUnit4.class)
public class ProfileEntityTest {
private Preference_UserProfile profile;
private SharedPreferences preferences;
@Before
public void getProfileEntityInstance() {
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
profile = Preference_UserProfile.getInstance(appContext);
preferences = appContext.getSharedPreferences(profile.getEntityName(), Context.MODE_PRIVATE);
}
@Test
public void preferenceTest() {
profile.clear();
preferences.edit().putString(profile.nicknameKeyName(), "PreferenceRoom").apply();
preferences.edit().putBoolean(profile.LoginKeyName(), true).apply();
preferences.edit().putInt(profile.visitsKeyName(), 12).apply();
assertThat(
preferences.getString(profile.nicknameKeyName(), null) + "!!!", is(profile.getNickname()));
assertThat(preferences.getBoolean(profile.LoginKeyName(), false), is(profile.getLogin()));
assertThat(preferences.getInt(profile.visitsKeyName(), -1), is(profile.getVisits()));
}
@Test
public void defaultTest() throws Exception {
profile.clear();
assertThat(profile.getNickname(), is("skydoves!!!"));
assertThat(profile.getLogin(), is(false));
assertThat(profile.getVisits(), is(1));
assertThat(profile.getUserinfo().getName(), is("null"));
Assert.assertNull(profile.getUserPet());
}
@Test
public void putPreferenceTest() throws Exception {
profile.clear();
profile.putNickname("PreferenceRoom");
profile.putLogin(true);
profile.putVisits(12);
profile.putUserinfo(new PrivateInfo("Jaewoong", 123));
assertThat(profile.getNickname(), is("Hello, PreferenceRoom!!!"));
assertThat(profile.getLogin(), is(true));
assertThat(profile.getVisits(), is(13));
assertThat(profile.getUserinfo().getName(), is("Jaewoong"));
assertThat(profile.getUserinfo().getAge(), is(123));
}
@Test
public void baseGsonConverterTest() throws Exception {
Gson gson = new Gson();
Pet pet = new Pet("skydoves", 11, true, Color.WHITE);
profile.putUserPet(pet);
assertThat(preferences.getString(profile.userPetKeyName(), null), notNullValue());
Pet petFromPreference =
gson.fromJson(preferences.getString(profile.userPetKeyName(), null), Pet.class);
assertThat(petFromPreference.getName(), is("skydoves"));
assertThat(petFromPreference.getAge(), is(11));
assertThat(petFromPreference.isFeed(), is(true));
assertThat(petFromPreference.getColor(), is(Color.WHITE));
assertThat(profile.getUserPet().getName(), is("skydoves"));
assertThat(profile.getUserPet().getAge(), is(11));
assertThat(profile.getUserPet().isFeed(), is(true));
assertThat(profile.getUserPet().getColor(), is(Color.WHITE));
}
@Test
public void keyNameListTest() throws Exception {
Assert.assertEquals(profile.getkeyNameList().size(), 5);
}
}
| 6d29286a00c519437a0814b8d74827c8d94ce072 | [
"Markdown",
"Maven POM",
"Gradle",
"Java",
"Kotlin"
] | 25 | Java | skydoves/PreferenceRoom | b67eb5279422b203888db71af48bb1fda5382a04 | 52dcbf2fd5b1622255f68450d543f6c395356e1b |
refs/heads/master | <repo_name>FrancescoAiello01/tree_processing<file_sep>/assignment7.pyde
from tree import CoolTree
bst = CoolTree(400, 50, 25)
bst.insert(CoolTree(350, 80, 12))
bst.insert(CoolTree(300, 110, 8))
bst.insert(CoolTree(380, 110, 13))
bst.insert(CoolTree(450, 80, 60))
bst.insert(CoolTree(420, 110, 58))
bst.insert(CoolTree(500, 110, 72))
bst.insert(CoolTree(250, 140, 1))
bst.insert(CoolTree(330, 140, 9))
bst.insert(CoolTree(360, 140, 12.5))
bst.insert(CoolTree(390, 140, 14))
bst.insert(CoolTree(410, 140, 55))
bst.insert(CoolTree(435, 140, 59))
bst.insert(CoolTree(470, 140, 70))
bst.insert(CoolTree(550, 140, 81))
def setup():
size(800, 800)
def draw():
global t
background(0)
bst.update()
bst.draw()
<file_sep>/tree.py
import random
class CoolTree:
def __init__(self, x, y, value = None):
self.x = x
self.y = y
self.value = value
self.left = None
self.right = None
def insert(self, child):
if self.value > child.value:
if self.left == None:
self.left = child
else:
self.left.insert(child)
else:
if self.right == None:
self.right = child
else:
self.right.insert(child)
def update(self):
pass
def draw(self):
if self.left is not None:
stroke(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
fill(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
line(self.x, self.y, self.left.x, self.left.y)
ellipse(self.x, self.y, 20, 20)
self.left.draw()
if self.right is not None:
stroke(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
fill(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
line(self.x, self.y, self.right.x, self.right.y)
ellipse(self.x, self.y, 20, 20)
self.right.draw()
| 4e872917c72ec5c28681eb80166d64c482c2c460 | [
"Python"
] | 2 | Python | FrancescoAiello01/tree_processing | 4e2f445b68b1131a70af9081958cfd3228586fa6 | 37b70ad858bd432657fe57ba7ddcad1301a7d7cb |
refs/heads/master | <file_sep>var buster = require("buster");
var assert = buster.assert;
var refute = buster.refute;
var rampResources = require("ramp-resources");
var h = require("./helpers/test-helper");
buster.testRunner.timeout = 4000;
buster.testCase("Slave header", {
setUp: function (done) {
this.serverBundle = h.createServerBundle(0, this, done);
},
tearDown: function (done) {
this.serverBundle.tearDown(done);
},
"serves header": function (done) {
var self = this;
var headerRs = rampResources.resourceSet.create();
headerRs.addResource({
path: "/",
content: done(function () {
assert(true);
return "The header!";
})
});
this.c.setHeader(headerRs, 100).then(function () {
self.b.capture(function (e, browser) {});
});
}
});
| 57f48fcbd1eeedd46af5f4f06f6f89fafbef3d63 | [
"JavaScript"
] | 1 | JavaScript | flosse/buster-capture-server | 5bc752f233af456eb24d45e8a213e2d70dee6b7b | 665183971cae09f872d8d0bafadb6012d3a59ce8 |
refs/heads/master | <repo_name>Nikhil-Garakapati/Chatbox<file_sep>/README.md
# Hackerrank(30 days of code)
Using C,C++ and Python 3
<file_sep>/Day1-Data Types/solution.py
i = 4
d = 4.0
s = 'HackerRank'
number=int(input())
flt=float(input())
string = str(input())
print(i + number)
print(d + flt)
print(s + string)
| c2fe9958138f1540e1e20bdf7e5911c108bc989e | [
"Markdown",
"Python"
] | 2 | Markdown | Nikhil-Garakapati/Chatbox | ae2195d5383624189aa2a30ab299ac94c170eca4 | b24d7357de591eea11c55983cdccd70c5da9ea19 |
refs/heads/main | <file_sep>package negocio;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
public class GerenciadoraClientesTest_Ex2 {
private GerenciadoraClientes gerClientes;
@Test
public void testPesquisaCliente() {
// criando alguns clientes
Cliente cliente01 = new Cliente(1, "<NAME>", 31, "<EMAIL>", 1, true);
Cliente cliente02 = new Cliente(2, "<NAME>", 34, "<EMAIL>", 2, true);
Cliente cliente03 = new Cliente(3, "<NAME>", 34, "<EMAIL>", 3, true);
// inserindo os clientes criados na lista de clientes do banco
List<Cliente> clientesDoBanco = new ArrayList<>();
clientesDoBanco.add(cliente01);
clientesDoBanco.add(cliente02);
gerClientes = new GerenciadoraClientes(clientesDoBanco);
Cliente cliente = gerClientes.pesquisaCliente(2);
assertThat(cliente.getId(), is(2));
assertThat(cliente.getEmail(), is("<EMAIL>"));
assertThat(cliente.getNome(), is("<NAME>"));
}
//Elaborado um teste para remover o cliente
@Test
public void testRemoveCliente() {
// criando alguns clientes
Cliente cliente01 = new Cliente(1, "<NAME>", 31, "<EMAIL>", 1, true);
Cliente cliente02 = new Cliente(2, "<NAME>", 34, "<EMAIL>", 2, true);
Cliente cliente03 = new Cliente(3, "<NAME>", 34, "<EMAIL>", 3, true);
// inserindo os clientes criados na lista de clientes do banco
List<Cliente> clientesDoBanco = new ArrayList<>();
clientesDoBanco.add(cliente01);
clientesDoBanco.add(cliente02);
clientesDoBanco.add(cliente03);
gerClientes = new GerenciadoraClientes(clientesDoBanco);// Instânciando a classe GerenciadoraCliente
//passando por parâmetro clientesDoBanco
boolean clienteRemovido = gerClientes.removeCliente(2); //Chama o método remove cliente, passando com parãmetro o ID 2
assertThat(clienteRemovido, is(true));
assertThat(gerClientes.getClientesDoBanco().size(), is(2));//Verifica que o tamanho da lista de clientes é 2,
//pois um cliente foi removido.
assertNull(gerClientes.pesquisaCliente(2)); // Pesquisa que o cliente removido está "vazio".
}
}
<file_sep>package negocio;
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
//Cria um Testes para testar pesquisa de clientes
public class GerenciadoraClientesTest_Ex1 {
@Test
public void testPesquisaCliente() {
//Para Testar o método pesquisa cliente devemos primeiramente criar alguns clientes
// criando alguns clientes
Cliente cliente01 = new Cliente(1, "<NAME>", 31, "<EMAIL>", 1, true);
Cliente cliente02 = new Cliente(2, "<NAME>", 34, "<EMAIL>", 2, true);
Cliente cliente03 = new Cliente(3, "<NAME>", 34, "<EMAIL>",3, true);
//Após ter criado alguns clientes devemos criar uma lista para popular os clientes criados
// inserindo os clientes criados na lista de clientes do banco
List<Cliente> clientesDoBanco = new ArrayList<>(); //Sintaxe com clientes criados
clientesDoBanco.add(cliente01);
clientesDoBanco.add(cliente02);
clientesDoBanco.add(cliente03);
GerenciadoraClientes gerClientes = new GerenciadoraClientes(clientesDoBanco); // Instância a classe pesquisa cliente
Cliente cliente = gerClientes.pesquisaCliente(3);// Chama o método pesquisa clientes passando o ID 1
assertThat(cliente.getId(), is(3)); //assetthat significa verifique quem é cliente 1
assertThat(cliente.getEmail(), is("<EMAIL>"));
assertThat(cliente.getIdade(), is(34));//Verifica o cliente com idade de 34 anos
}
}
<file_sep>package negocio;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import java.util.ArrayList;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Classe de teste criada para garantir o funcionamento das principais operações
* sobre clientes, realizadas pela classe {@link GerenciadoraClientes}.
*
* @author <NAME>
* @date 21/01/2035
*/
public class GerenciadoraClientesTest_Ex7 {
private GerenciadoraClientes gerClientes; //Variável global
private int idCLiente01 = 1; //Variável global
private int idCLiente02 = 2; //Variável global
/*=========================================Primeira e Quarta(Executada após dar um clear no cliente pesquisado
* parte do teste==========================================*/
@Before // Antes de executar o teste, através do comando @Before
//excuta o trecho de código que é comum para toda a classe.
public void setUp() {
/* ========== Montagem do cenário ========== */
// criando alguns clientes
Cliente cliente01 = new Cliente(idCLiente01, "<NAME>", 31, "<EMAIL>", 1, true);
Cliente cliente02 = new Cliente(idCLiente02, "<NAME>", 34, "<EMAIL>", 1, true);
// inserindo os clientes criados na lista de clientes do banco
List<Cliente> clientesDoBanco = new ArrayList<>();
clientesDoBanco.add(cliente01);
clientesDoBanco.add(cliente02);
gerClientes = new GerenciadoraClientes(clientesDoBanco);
System.out.println("Before foi executado");
}
/*=========================================Terceira e Sexta(Após ter verificado a remoção do cliente
* parte do teste==========================================*/
@After // Depois de executar o teste Pesquisa Cliente, o sistema excuta o testes tearDown
//Terceira parte do teste
//Significa que quando for executado o teste removeCliente não hverá comando ativo do teste pesquisaCliente
public void tearDown() {
gerClientes.limpa();
System.out.println("After foi executado");
}
/**
* Teste básico da pesquisa de um cliente a partir do seu ID.
*
* @author <NAME>
* @date 21/01/2035
*/
/*=========================================Segunda parte do teste==========================================*/
@Test
//Segunda parte do teste é executar o testes pesquisa cliente
public void testPesquisaCliente() {
/* ========== Execução ========== */
Cliente cliente = gerClientes.pesquisaCliente(idCLiente01);
/* ========== Verificações ========== */
assertThat(cliente.getId(), is(idCLiente01));
}
/**
* Teste básico da remoção de um cliente a partir do seu ID.
*
* @author <NAME>
* @date 21/01/2035
*/
/*=========================================Quinta parte do teste==========================================*/
@Test
public void testRemoveCliente() {
/* ========== Execução ========== */
boolean clienteRemovido = gerClientes.removeCliente(idCLiente02);
/* ========== Verificações ========== */
assertThat(clienteRemovido, is(true));
assertThat(gerClientes.getClientesDoBanco().size(), is(1));
assertNull(gerClientes.pesquisaCliente(idCLiente02));
}
}
// Como Ganhar Tempo e Otimizar Testes com Cenários Parecidos<file_sep># CursoTesteSistemaBancario
Curso Realizado pela Udemy de Testes Automáticos
| 55c9373f76710b8b2064d28b7a657939a0ca8aaa | [
"Markdown",
"Java"
] | 4 | Java | Cristian3838/CursoTesteSistemaBancario | ff3a1b9ec43d4564dddaf8937c8b3295441fd3b7 | e55b77c3d6258fa8bb7ee8c4c6a12214f40b3adb |
refs/heads/master | <repo_name>OnLivePlatform/onlive-contracts<file_sep>/migrations/3_deploy_preicocrowdsale.ts
import * as Web3 from 'web3';
import { OnLiveArtifacts } from 'onlive';
import { Deployer } from 'truffle';
import { toMillionsONL, toWei } from '../utils';
declare const artifacts: OnLiveArtifacts;
declare const web3: Web3;
const OnLiveToken = artifacts.require('./OnLiveToken.sol');
const PreIcoCrowdsale = artifacts.require('./PreIcoCrowdsale.sol');
async function deploy(deployer: Deployer, network: string) {
const token = await OnLiveToken.deployed();
const availableAmount = toMillionsONL('12.210');
const price = toWei('0.0011466');
const minValue = toWei('0.1');
let wallet = web3.eth.accounts[0];
if (network === 'mainnet') {
wallet = '0xd0078f5c7E33BaD8767c602D3aaEe6e38481c9A1';
}
await deployer.deploy(
PreIcoCrowdsale,
wallet,
token.address,
availableAmount,
price,
minValue
);
const crowdsale = await PreIcoCrowdsale.deployed();
await token.approveMintingManager(crowdsale.address);
}
function migrate(deployer: Deployer, network: string) {
deployer.then(() => deploy(deployer, network));
}
export = migrate;
<file_sep>/scripts/finalize.ts
// tslint:disable:no-console
import * as Web3 from 'web3';
import { OnLiveArtifacts } from 'onlive';
import { ScriptFinalizer } from 'truffle';
declare const artifacts: OnLiveArtifacts;
declare const web3: Web3;
const IcoCrowdsale = artifacts.require('./IcoCrowdsale.sol');
const OnLiveToken = artifacts.require('./OnLiveToken.sol');
async function asyncExec() {
const ico = await IcoCrowdsale.deployed();
const token = await OnLiveToken.deployed();
const icoFinished = await ico.isFinished();
const mintingFinished = await token.mintingFinished();
if (!icoFinished) {
throw new Error('ICO crowdsale not finished');
}
if (mintingFinished) {
throw new Error('Minting already finished');
}
console.log('Burning not sold tokens');
await ico.burnRemains({
from: await ico.owner()
});
console.log('Finishing token minting');
await token.finishMinting({
from: await token.owner()
});
console.log('Token successfully finalized');
}
function exec(finalize: ScriptFinalizer) {
asyncExec().then(() => finalize(), reason => finalize(reason));
}
export = exec;
<file_sep>/migrations/5_token_description.ts
import { OnLiveArtifacts } from 'onlive';
import { Deployer } from 'truffle';
declare const artifacts: OnLiveArtifacts;
const OnLiveToken = artifacts.require('./OnLiveToken.sol');
async function deploy() {
const token = await OnLiveToken.deployed();
await token.changeDescription('On.Live', 'ONL');
}
function migrate(deployer: Deployer) {
deployer.then(() => deploy());
}
export = migrate;
<file_sep>/migrations/2_deploy_token.ts
import { OnLiveArtifacts } from 'onlive';
import { Deployer } from 'truffle';
import { toMillionsONL } from '../utils';
declare const artifacts: OnLiveArtifacts;
const OnLiveToken = artifacts.require('./OnLiveToken.sol');
async function deploy(deployer: Deployer) {
const name = 'OnLive Token';
const symbol = 'ONL';
const maxSupply = toMillionsONL(111);
await deployer.deploy(OnLiveToken, name, symbol, maxSupply);
}
function migrate(deployer: Deployer) {
deployer.then(() => deploy(deployer));
}
export = migrate;
<file_sep>/test/tokenpool.test.ts
import { assert } from 'chai';
import { propOr } from 'ramda';
import * as Web3 from 'web3';
import * as tempo from '@digix/tempo';
import {
OnLiveArtifacts,
OnLiveToken,
PoolLockedEvent,
PoolRegisteredEvent,
PoolTransferredEvent,
TokenPool,
TransferEvent
} from 'onlive';
import { ETH_DECIMALS, toONL } from '../utils';
import { ContractContextDefinition } from 'truffle';
import {
assertNumberEqual,
assertReverts,
findLastLog,
getNetworkTimestamp,
ZERO_ADDRESS
} from './helpers';
declare const web3: Web3;
declare const artifacts: OnLiveArtifacts;
declare const contract: ContractContextDefinition;
const TokenPoolContract = artifacts.require('./TokenPool.sol');
const OnLiveTokenContract = artifacts.require('./OnLiveToken.sol');
TokenPoolContract.link(OnLiveTokenContract);
const wait = tempo(web3).wait;
contract('TokenPool', accounts => {
const owner = accounts[9];
const nonOwner = accounts[1];
const poolId = 'testPool';
const availableAmount = toONL(1000);
const lockPeriod = 24 * 60 * 60;
let lockTimestamp = 0;
let token: OnLiveToken;
async function createTokenPool(options?: any) {
return await TokenPoolContract.new(
propOr(token.address, 'token', options),
{ from: propOr(owner, 'from', options) }
);
}
beforeEach(async () => {
lockTimestamp = (await getNetworkTimestamp()) + lockPeriod;
token = await OnLiveTokenContract.new(
'OnLive Token',
'ONL',
availableAmount,
{
from: owner
}
);
assertNumberEqual(await token.decimals(), ETH_DECIMALS);
});
describe('#ctor', () => {
it('should set token address', async () => {
const tokenPool = await createTokenPool();
assert.equal(await tokenPool.token(), token.address);
});
});
context('Given deployed TokenPool contract', () => {
let tokenPool: TokenPool;
async function registerPool(options?: any) {
return await tokenPool.registerPool(
propOr(poolId, 'name', options),
propOr(availableAmount, 'availableAmount', options),
propOr(0, 'lockTimestamp', options),
{ from: propOr(owner, 'from', options) }
);
}
beforeEach(async () => {
tokenPool = await createTokenPool();
await token.approveMintingManager(tokenPool.address, { from: owner });
await token.approveTransferManager(tokenPool.address, { from: owner });
});
describe('#registerPool', () => {
it('should set amount of available tokens', async () => {
await registerPool();
assertNumberEqual(
await tokenPool.getAvailableAmount(poolId),
availableAmount
);
});
it('should set lock timestamp', async () => {
await registerPool({ lockTimestamp });
assertNumberEqual(
await tokenPool.getLockTimestamp(poolId),
lockTimestamp
);
});
it('should set lock timestamp to zero if not locked', async () => {
await registerPool();
assertNumberEqual(await tokenPool.getLockTimestamp(poolId), 0);
});
it('should emit PoolRegistered event', async () => {
const tx = await registerPool();
const log = findLastLog(tx, 'PoolRegistered');
assert.isOk(log);
const event = log.args as PoolRegisteredEvent;
assert.equal(event.poolId, poolId);
assertNumberEqual(event.amount, availableAmount);
assertNumberEqual(await tokenPool.getLockTimestamp(poolId), 0);
});
it('should emit PoolLocked event', async () => {
const tx = await registerPool({ lockTimestamp });
const log = findLastLog(tx, 'PoolLocked');
assert.isOk(log);
const event = log.args as PoolLockedEvent;
assert.equal(event.poolId, poolId);
assertNumberEqual(event.lockTimestamp, lockTimestamp);
});
it('should revert for non-owner', async () => {
await assertReverts(async () => {
await registerPool({ from: nonOwner });
});
});
it('should revert for zero amount', async () => {
await assertReverts(async () => {
await registerPool({ availableAmount: 0 });
});
});
it('should revert for non-unique pool', async () => {
await registerPool();
await assertReverts(async () => {
await registerPool();
});
});
});
describe('#transfer', () => {
const amount = toONL(0.5);
const beneficiary = accounts[5];
async function transferFromPool(options?: any) {
return await tokenPool.transfer(
propOr(poolId, 'poolId', options),
propOr(beneficiary, 'to', options),
propOr(amount, 'amount', options),
{ from: propOr(owner, 'from', options) }
);
}
context('from unlocked pool', () => {
beforeEach(async () => {
await registerPool();
});
it('should update available amount of tokens', async () => {
await transferFromPool();
assertNumberEqual(
await tokenPool.getAvailableAmount(poolId),
availableAmount.minus(amount)
);
});
it('should emit Transfer event', async () => {
const tx = await transferFromPool();
const log = findLastLog(tx, 'Transfer');
assert.isOk(log);
const event = log.args as TransferEvent;
assert.equal(event.from, tokenPool.address);
assert.equal(event.to, beneficiary);
assertNumberEqual(event.value, amount);
});
it('should emit PoolTransferred event', async () => {
const tx = await transferFromPool();
const log = findLastLog(tx, 'PoolTransferred');
assert.isOk(log);
const event = log.args as PoolTransferredEvent;
assert.equal(event.poolId, poolId);
assert.equal(event.to, beneficiary);
assertNumberEqual(event.amount, amount);
});
it('should revert for non-owner', async () => {
await assertReverts(async () => {
await transferFromPool({ from: nonOwner });
});
});
it('should revert for invalid address', async () => {
await assertReverts(async () => {
await transferFromPool({ to: ZERO_ADDRESS });
});
});
it('should revert for zero amount', async () => {
await assertReverts(async () => {
await transferFromPool({ amount: 0 });
});
});
it('should revert for amount exceeding limit', async () => {
await assertReverts(async () => {
await transferFromPool({
amount: availableAmount.plus(toONL(0.1))
});
});
});
});
context('from locked pool', () => {
it('should revert for valid parameters', async () => {
await registerPool({ lockTimestamp });
await assertReverts(async () => {
await transferFromPool();
});
});
});
context('from pool with expired lock timestamp', () => {
beforeEach(async () => {
await registerPool({ lockTimestamp });
const offsetInSeconds = 1;
await wait(lockPeriod + offsetInSeconds);
});
it('should update available amount of tokens', async () => {
await transferFromPool();
assertNumberEqual(
await tokenPool.getAvailableAmount(poolId),
availableAmount.minus(amount)
);
});
it('should emit Transfer event', async () => {
const tx = await transferFromPool();
const log = findLastLog(tx, 'Transfer');
assert.isOk(log);
const event = log.args as TransferEvent;
assert.equal(event.from, tokenPool.address);
assert.equal(event.to, beneficiary);
assertNumberEqual(event.value, amount);
});
});
});
});
});
<file_sep>/migrations/4_schedule_preicocrowdsale.ts
import { OnLiveArtifacts } from 'onlive';
import { Deployer } from 'truffle';
import * as Web3 from 'web3';
import { BlockCalculator, blockTimes, Web3Utils } from '../utils';
declare const artifacts: OnLiveArtifacts;
declare const web3: Web3;
const utils = new Web3Utils(web3);
const PreIcoCrowdsale = artifacts.require('./PreIcoCrowdsale.sol');
async function deploy(network: string) {
const calculator = new BlockCalculator(blockTimes[network]);
const duration = calculator.daysToBlocks(31) + calculator.hoursToBlocks(12);
const startOffset = calculator.hoursToBlocks(10);
const currentBlock = await utils.getBlockNumber();
const startBlock = currentBlock + startOffset;
const endBlock = startBlock + duration;
const crowdsale = await PreIcoCrowdsale.deployed();
await crowdsale.schedule(startBlock, endBlock);
}
function migrate(deployer: Deployer, network: string) {
deployer.then(() => deploy(network));
}
export = migrate;
<file_sep>/utils/onlive.ts
import { BigNumber } from 'bignumber.js';
import { AnyNumber } from 'web3';
import { ETH_DECIMALS, shiftNumber } from './number';
export const ONL_DECIMALS = 18;
export function toONL(num: AnyNumber) {
return shiftNumber(num, ONL_DECIMALS);
}
export function toThousandsONL(num: AnyNumber) {
const thousandDecimals = 3;
return shiftNumber(num, thousandDecimals + ONL_DECIMALS);
}
export function toMillionsONL(num: AnyNumber) {
const millionDecimals = 6;
return shiftNumber(num, millionDecimals + ONL_DECIMALS);
}
export function calculateContribution(eth: AnyNumber, price: AnyNumber) {
const value = new BigNumber(eth);
return shiftNumber(value, ETH_DECIMALS).div(price);
}
<file_sep>/scripts/flatten.ts
// tslint:disable:no-console
import * as commander from 'commander';
import { spawn } from 'child_process';
import { createWriteStream } from 'fs';
import { join } from 'path';
interface Options {
contract: string;
}
const argv = (commander
.option('-c, --contract <contract', 'contract name')
.parse(process.argv)
.opts() as any) as Options;
if (!argv.contract) {
throw new Error('Missing contract name [-c, --contract]');
}
const args = [
'run',
'--rm',
'flatten',
'--solc-paths',
'zeppelin-solidity/=/project/node_modules/zeppelin-solidity/',
`/project/contracts/${argv.contract}.sol`
];
const outPath = join(__dirname, '..', 'build', 'flat', `${argv.contract}.sol`);
const outStream = createWriteStream(outPath);
const child = spawn('docker-compose', args, {
cwd: join(__dirname, '..', 'docker')
});
child.stdout.pipe(outStream);
child.stderr.on('data', chunk => {
console.error(chunk.toString());
});
child.on('close', code => {
if (code !== 0) {
console.error(`Failed to flatten ${argv.contract} contract`);
} else {
console.log(`Saved flattened ${argv.contract} contract to ${outPath}`);
}
});
<file_sep>/utils/block.ts
import { isNumber } from 'util';
export const blockTimes: { [network: string]: number } = {
develop: 14.5,
kovan: 4,
mainnet: 14.5,
rinkeby: 15,
test: 15,
testrpc: 14.5
};
export class BlockCalculator {
constructor(private blockTime: number) {
if (!isNumber(blockTime)) {
throw new Error('Invalid block time');
}
}
public secondsToBlocks(seconds: number): number {
return Math.ceil(seconds / this.blockTime);
}
public minutesToBlocks(minutes: number): number {
return this.secondsToBlocks(minutes * 60);
}
public hoursToBlocks(hours: number): number {
return this.minutesToBlocks(hours * 60);
}
public daysToBlocks(days: number): number {
return this.hoursToBlocks(days * 24);
}
}
<file_sep>/migrations/6_deploy_token_pool.ts
import { OnLiveArtifacts } from 'onlive';
import { Deployer } from 'truffle';
declare const artifacts: OnLiveArtifacts;
const OnLiveToken = artifacts.require('./OnLiveToken.sol');
const TokenPool = artifacts.require('./TokenPool.sol');
async function deploy(deployer: Deployer) {
const token = await OnLiveToken.deployed();
await deployer.deploy(TokenPool, token.address);
}
function migrate(deployer: Deployer) {
deployer.then(() => deploy(deployer));
}
export = migrate;
<file_sep>/utils/index.ts
export * from './block';
export * from './onlive';
export * from './number';
export * from './regex';
export * from './time';
export * from './web3';
<file_sep>/types/onlive.d.ts
declare module 'onlive' {
import { BigNumber } from 'bignumber.js';
import {
AnyContract,
Contract,
ContractBase,
TransactionOptions,
TransactionResult,
TruffleArtifacts
} from 'truffle';
import { AnyNumber } from 'web3';
namespace onlive {
interface Migrations extends ContractBase {
setCompleted(
completed: number,
options?: TransactionOptions
): Promise<TransactionResult>;
upgrade(
address: Address,
options?: TransactionOptions
): Promise<TransactionResult>;
}
interface Ownable extends ContractBase {
owner(): Promise<Address>;
transferOwnership(newOwner: Address): Promise<TransactionResult>;
}
interface ERC20Basic extends ContractBase {
totalSupply(): Promise<BigNumber>;
balanceOf(who: Address): Promise<BigNumber>;
transfer(
to: Address,
amount: BigNumber,
options?: TransactionOptions
): Promise<TransactionResult>;
}
interface TransferEvent {
from: Address;
to: Address;
value: BigNumber;
}
interface ERC20 extends ERC20Basic {
allowance(owner: Address, spender: Address): Promise<BigNumber>;
transferFrom(
from: Address,
to: Address,
value: AnyNumber,
options?: TransactionOptions
): Promise<TransactionResult>;
approve(
spender: Address,
value: AnyNumber,
options?: TransactionOptions
): Promise<TransactionResult>;
}
interface ApprovalEvent {
owner: Address;
spender: Address;
value: BigNumber;
}
interface ReleasableToken extends ERC20, Ownable {
releaseManager(): Promise<Address>;
isTransferManager(addr: Address): Promise<boolean>;
released(): Promise<boolean>;
setReleaseManager(
addr: Address,
options?: TransactionOptions
): Promise<TransactionResult>;
approveTransferManager(
addr: Address,
options?: TransactionOptions
): Promise<TransactionResult>;
revokeTransferManager(
addr: Address,
options?: TransactionOptions
): Promise<TransactionResult>;
release(options?: TransactionOptions): Promise<TransactionResult>;
}
interface ReleaseManagerSetEvent {
addr: Address;
}
interface TransferManagerApprovedEvent {
addr: Address;
}
interface TransferManagerRevokedEvent {
addr: Address;
}
type ReleasedEvent = {};
interface MintableToken extends ERC20Basic, Ownable {
mintingFinished(): Promise<boolean>;
isMintingManager(addr: Address): Promise<boolean>;
approveMintingManager(
addr: Address,
options?: TransactionOptions
): Promise<TransactionResult>;
revokeMintingManager(
addr: Address,
options?: TransactionOptions
): Promise<TransactionResult>;
mint(
to: Address,
amount: AnyNumber,
options?: TransactionOptions
): Promise<TransactionResult>;
finishMinting(options?: TransactionOptions): Promise<TransactionResult>;
}
interface MintedEvent {
to: Address;
amount: BigNumber;
}
interface MintingManagerApprovedEvent {
addr: Address;
}
interface MintingManagerRevokedEvent {
addr: Address;
}
type MintingFinishedEvent = {};
interface CappedMintableToken extends MintableToken {
maxSupply(): Promise<BigNumber>;
}
interface BurnableToken extends ERC20Basic {
burn(
amount: AnyNumber,
options?: TransactionOptions
): Promise<TransactionResult>;
}
interface BurnedEvent {
from: Address;
amount: BigNumber;
}
interface DescriptiveToken extends ERC20Basic, Ownable {
name(): Promise<string>;
symbol(): Promise<string>;
decimals(): Promise<BigNumber>;
isDescriptionFinalized(): Promise<boolean>;
changeDescription(
name: string,
symbol: string,
options?: TransactionOptions
): Promise<TransactionResult>;
finalizeDescription(
options?: TransactionOptions
): Promise<TransactionResult>;
}
interface DescriptionChangedEvent {
name: string;
symbol: string;
}
type DescriptionFinalizedEvent = {};
interface OnLiveToken
extends DescriptiveToken,
ReleasableToken,
CappedMintableToken,
BurnableToken {}
interface Schedulable extends ContractBase {
startBlock(): Promise<BigNumber>;
endBlock(): Promise<BigNumber>;
isActive(): Promise<boolean>;
isScheduled(): Promise<boolean>;
schedule(
startBlock: AnyNumber,
endBlock: AnyNumber,
options?: TransactionOptions
): Promise<TransactionResult>;
}
interface ScheduledEvent {
startBlock: BigNumber;
endBlock: BigNumber;
}
interface PreIcoCrowdsale extends Schedulable {
wallet(): Promise<Address>;
token(): Promise<Address>;
availableAmount(): Promise<BigNumber>;
price(): Promise<BigNumber>;
minValue(): Promise<BigNumber>;
isContributionRegistered(id: string): Promise<boolean>;
calculateContribution(value: AnyNumber): Promise<BigNumber>;
contribute(
contributor: Address,
options?: TransactionOptions
): Promise<TransactionResult>;
registerContribution(
id: string,
contributor: Address,
amount: AnyNumber,
options?: TransactionOptions
): Promise<TransactionResult>;
}
interface ContributionAcceptedEvent {
contributor: Address;
value: BigNumber;
amount: BigNumber;
}
interface ContributionRegisteredEvent {
id: string;
contributor: Address;
amount: BigNumber;
}
interface TokenPool extends Ownable {
token(): Promise<string>;
registerPool(
poolId: string,
availableAmount: AnyNumber,
lockTimestamp: AnyNumber,
options?: TransactionOptions
): Promise<TransactionResult>;
transfer(
poolId: string,
to: Address,
amount: AnyNumber,
options?: TransactionOptions
): Promise<TransactionResult>;
getAvailableAmount(poolId: string): Promise<AnyNumber>;
getLockTimestamp(poolId: string): Promise<AnyNumber>;
}
interface PoolLockedEvent {
poolId: string;
lockTimestamp: BigNumber;
}
interface PoolRegisteredEvent {
poolId: string;
amount: BigNumber;
}
interface PoolTransferredEvent {
poolId: string;
to: Address;
amount: BigNumber;
}
interface IcoCrowdsale extends Ownable {
wallet(): Promise<Address>;
token(): Promise<Address>;
minValue(): Promise<BigNumber>;
isContributionRegistered(id: string): Promise<boolean>;
endBlock(): Promise<BigNumber>;
contribute(
contributor: Address,
options?: TransactionOptions
): Promise<TransactionResult>;
registerContribution(
id: string,
contributor: Address,
amount: AnyNumber,
options?: TransactionOptions
): Promise<TransactionResult>;
scheduleTier(
startBlock: AnyNumber,
price: AnyNumber,
options?: TransactionOptions
): Promise<TransactionResult>;
finalize(
endBlock: AnyNumber,
availableAmount: AnyNumber,
options?: TransactionOptions
): Promise<TransactionResult>;
burnRemains(options?: TransactionOptions): Promise<TransactionResult>;
calculateContribution(value: AnyNumber): Promise<BigNumber>;
getTierId(blockNumber: AnyNumber): Promise<BigNumber>;
currentPrice(): Promise<BigNumber>;
currentTierId(): Promise<BigNumber>;
availableAmount(): Promise<BigNumber>;
listTiers(): Promise<[BigNumber[], BigNumber[], BigNumber[]]>;
isActive(): Promise<boolean>;
isFinalized(): Promise<boolean>;
isFinished(): Promise<boolean>;
}
interface StageScheduledEvent {
start: BigNumber;
price: BigNumber;
}
interface CrowdsaleEndScheduledEvent {
availableAmount: BigNumber;
end: BigNumber;
}
type LeftTokensBurnedEvent = {};
interface MigrationsContract extends Contract<Migrations> {
'new'(options?: TransactionOptions): Promise<Migrations>;
}
interface ReleasableTokenContract extends Contract<ReleasableToken> {
'new'(options?: TransactionOptions): Promise<ReleasableToken>;
}
interface MintableTokenContract extends Contract<MintableToken> {
'new'(options?: TransactionOptions): Promise<MintableToken>;
}
interface CappedMintableTokenContract
extends Contract<CappedMintableToken> {
'new'(
maxSupply: AnyNumber,
options?: TransactionOptions
): Promise<CappedMintableToken>;
}
interface BurnableTokenContract extends Contract<BurnableToken> {
'new'(options?: TransactionOptions): Promise<BurnableToken>;
}
interface OnLiveTokenContract extends Contract<OnLiveToken> {
'new'(
name: string,
symbol: string,
maxSupply: AnyNumber,
options?: TransactionOptions
): Promise<OnLiveToken>;
}
interface PreIcoCrowdsaleContract extends Contract<PreIcoCrowdsale> {
'new'(
wallet: Address,
token: Address,
availableAmount: AnyNumber,
price: AnyNumber,
minValue: AnyNumber,
options?: TransactionOptions
): Promise<PreIcoCrowdsale>;
}
interface IcoCrowdsaleContract extends Contract<IcoCrowdsale> {
'new'(
wallet: Address,
token: Address,
minValue: AnyNumber,
options?: TransactionOptions
): Promise<IcoCrowdsale>;
}
interface TokenPoolContract extends Contract<TokenPool> {
'new'(token: Address, options?: TransactionOptions): Promise<TokenPool>;
link(contract: Contract<any>): void;
}
interface OnLiveArtifacts extends TruffleArtifacts {
require(name: string): AnyContract;
require(name: './Migrations.sol'): MigrationsContract;
require(name: './token/ReleasableToken.sol'): ReleasableTokenContract;
require(name: './token/MintableToken.sol'): MintableTokenContract;
require(name: './token/BurnableToken.sol'): BurnableTokenContract;
require(name: './OnLiveToken.sol'): OnLiveTokenContract;
require(name: './PreIcoCrowdsale.sol'): PreIcoCrowdsaleContract;
require(name: './TokenPool.sol'): TokenPoolContract;
require(name: './IcoCrowdsale.sol'): IcoCrowdsaleContract;
}
}
export = onlive;
}
<file_sep>/test/token/cappedmintabletoken.test.ts
import { BigNumber } from 'bignumber.js';
import { assert } from 'chai';
import * as Web3 from 'web3';
import { CappedMintableToken } from 'onlive';
import { assertReverts, assertTokenEqual } from '../helpers';
import { TokenTestContext } from './context';
declare const web3: Web3;
export function testMint(ctx: TokenTestContext<CappedMintableToken>) {
const mintingManager = ctx.accounts[0];
const destinationAccount = ctx.accounts[2];
let maxSupply: BigNumber;
let mintableSupply: BigNumber;
beforeEach(async () => {
maxSupply = await ctx.token.maxSupply();
mintableSupply = maxSupply.plus(await ctx.token.totalSupply());
assert.isTrue(
mintableSupply.gt(0),
'precondition: no tokens available to mint'
);
await ctx.token.approveMintingManager(mintingManager, { from: ctx.owner });
});
it('should pass if not exceeds maxSupply', async () => {
const expectedSupply = (await ctx.token.totalSupply()).plus(mintableSupply);
await ctx.token.mint(destinationAccount, mintableSupply, {
from: mintingManager
});
assertTokenEqual(await ctx.token.totalSupply(), expectedSupply);
});
it('should revert when exceeds maxSupply', async () => {
await assertReverts(async () => {
await ctx.token.mint(destinationAccount, mintableSupply.plus(1), {
from: mintingManager
});
});
});
}
<file_sep>/test/utils.test.ts
import { BigNumber } from 'bignumber.js';
import { assert } from 'chai';
import {
BlockCalculator,
calculateContribution,
fromEth,
fromFinney,
fromGwei,
fromKwei,
fromMwei,
fromSzabo,
shiftNumber,
toFinney,
toGwei,
toKwei,
toMillionsONL,
toMwei,
toONL,
toSzabo,
toThousandsONL,
toTimestamp,
toWei
} from '../utils';
import {
assertNumberEqual,
assertTokenAlmostEqual,
assertTokenEqual
} from './helpers';
describe('#shiftNumber', () => {
it('should return the number if decimals is 0', () => {
const num = 10;
assertNumberEqual(shiftNumber(num, 0), num);
});
it('should multiple the number by 1000 if decimals is 3', () => {
const num = 10;
const expectedMul = 1000;
assertNumberEqual(shiftNumber(num, 3), num * expectedMul);
});
it('should divide the number by 100 if decimals is -2', () => {
const num = 10000;
const expectedDiv = 100;
assertNumberEqual(shiftNumber(num, -2), num / expectedDiv);
});
});
const toConversionSpec = [
{ unit: 'Finney', func: toFinney, base: '1000' },
{ unit: 'Szabo', func: toSzabo, base: '1000000' },
{ unit: 'Gwei', func: toGwei, base: '1000000000' },
{ unit: 'Mwei', func: toMwei, base: '1000000000000' },
{ unit: 'Kwei', func: toKwei, base: '1000000000000000' },
{ unit: 'Wei', func: toWei, base: '1000000000000000000' }
];
for (const { unit, func, base } of toConversionSpec) {
describe(`#to${unit}`, () => {
it(`should return ${base} ${unit} for 1 ETH`, () => {
assertNumberEqual(func(1), base);
});
const expectedMul = new BigNumber(base).times(5);
it(`should return ${expectedMul} ${unit} for 5 ETH`, () => {
assertNumberEqual(func(5), expectedMul);
});
const expectedDiv = new BigNumber(base).div(100);
it(`should return ${expectedDiv} ${unit} for 0.01 ETH`, () => {
assertNumberEqual(func(0.01), expectedDiv);
});
});
}
const fromConversionSpec = [
{ unit: 'ETH', func: fromEth, base: '1000000000000000000' },
{ unit: 'Finney', func: fromFinney, base: '1000000000000000' },
{ unit: 'Szabo', func: fromSzabo, base: '1000000000000' },
{ unit: 'Gwei', func: fromGwei, base: '1000000000' },
{ unit: 'Mwei', func: fromMwei, base: '1000000' },
{ unit: 'Kwei', func: fromKwei, base: '1000' }
];
for (const { unit, func, base } of fromConversionSpec) {
describe(`#from${unit}`, () => {
it(`should return ${base} Wei for 1 ${unit}`, () => {
assertNumberEqual(func(1), base);
});
const expectedMul = new BigNumber(base).times(5);
it(`should return ${expectedMul} Wei for 5 ${unit}`, () => {
assertNumberEqual(func(5), expectedMul);
});
const expectedDiv = new BigNumber(base).div(100);
it(`should return ${expectedDiv} Wei for 0.01 ${unit}`, () => {
assertNumberEqual(func(0.01), expectedDiv);
});
});
}
describe('#toONL', () => {
it('should return 0 for 0 input', () => {
assertTokenEqual(toONL(0), 0);
});
it('should return 10¹⁸ for 1 input', () => {
assertTokenEqual(toONL(1), new BigNumber(10).pow(18));
});
it('should return 10²⁰ for 100 input', () => {
assertTokenEqual(toONL(100), new BigNumber(10).pow(20));
});
it('should return 10¹⁶ for 0.01 input', () => {
assertTokenEqual(toONL(0.01), new BigNumber(10).pow(16));
});
});
describe('#toThousandsONL', () => {
it('should return 0 for 0 input', () => {
assertTokenEqual(toThousandsONL(0), 0);
});
it('should return 10²¹ for 1 input', () => {
assertTokenEqual(toThousandsONL(1), new BigNumber(10).pow(21));
});
it('should return 10²³ for 100 input', () => {
assertTokenEqual(toThousandsONL(100), new BigNumber(10).pow(23));
});
it('should return 10¹⁹ for 0.01 input', () => {
assertTokenEqual(toThousandsONL(0.01), new BigNumber(10).pow(19));
});
});
describe('#toMillionsONL', () => {
it('should return 0 for 0 input', () => {
assertTokenEqual(toMillionsONL(0), 0);
});
it('should return 10²⁴ for 1 input', () => {
assertTokenEqual(toMillionsONL(1), new BigNumber(10).pow(24));
});
it('should return 10²⁶ for 100 input', () => {
assertTokenEqual(toMillionsONL(100), new BigNumber(10).pow(26));
});
it('should return 10²² for 0.01 input', () => {
assertTokenEqual(toMillionsONL(0.01), new BigNumber(10).pow(22));
});
});
describe('#calculateContribution', () => {
const acceptableError = toONL(shiftNumber(1, -9));
const suite = [
{
amounts: [
{ eth: 0.1, onl: 87.2143729287 },
{ eth: 1, onl: 872.143729287 },
{ eth: 50, onl: 43607.186464329 }
],
price: 0.0011466
},
{
amounts: [
{ eth: 0.1, onl: 76.3358778626 },
{ eth: 1, onl: 763.358778626 },
{ eth: 50, onl: 38167.938931297 }
],
price: 0.00131
},
{
amounts: [
{ eth: 0.1, onl: 68.5871056241 },
{ eth: 1, onl: 685.871056241 },
{ eth: 50, onl: 34293.552812071 }
],
price: 0.001458
},
{
amounts: [
{ eth: 0.1, onl: 61.0500610501 },
{ eth: 1, onl: 610.500610501 },
{ eth: 50, onl: 30525.03052503 }
],
price: 0.001638
}
];
for (const { amounts, price } of suite) {
context(`Given ONL price ${price} ETH`, () => {
for (const { eth, onl } of amounts) {
it(`should return ${onl} ONL for ${eth} ETH`, () => {
assertTokenAlmostEqual(
calculateContribution(toWei(eth), toONL(price)),
toONL(onl),
acceptableError
);
});
}
});
}
});
describe('#secondsToBlocks', () => {
const calculator = new BlockCalculator(15);
const suite = [
{ seconds: 0, blocks: 0 },
{ seconds: 5, blocks: 1 },
{ seconds: 15, blocks: 1 },
{ seconds: 16, blocks: 2 },
{ seconds: 30, blocks: 2 },
{ seconds: 100, blocks: 7 },
{ seconds: 1000, blocks: 67 }
];
for (const { seconds, blocks } of suite) {
it(`should return ${blocks} blocks for ${seconds} seconds`, () => {
assert.equal(calculator.secondsToBlocks(seconds), blocks);
});
}
});
describe('#minutesToBlocks', () => {
const calculator = new BlockCalculator(15);
const suite = [
{ minutes: 0, blocks: 0 },
{ minutes: 5, blocks: 20 },
{ minutes: 15.5, blocks: 62 },
{ minutes: 30.1, blocks: 121 }
];
for (const { minutes, blocks } of suite) {
it(`should return ${blocks} blocks for ${minutes} minutes`, () => {
assert.equal(calculator.minutesToBlocks(minutes), blocks);
});
}
});
describe('#hoursToBlocks', () => {
const calculator = new BlockCalculator(15);
const suite = [
{ hours: 0, blocks: 0 },
{ hours: 5, blocks: 1200 },
{ hours: 7.32, blocks: 1757 }
];
for (const { hours, blocks } of suite) {
it(`should return ${blocks} blocks for ${hours} hours`, () => {
assert.equal(calculator.hoursToBlocks(hours), blocks);
});
}
});
describe('#daysToBlocks', () => {
const calculator = new BlockCalculator(15);
const suite = [
{ days: 0, blocks: 0 },
{ days: 2, blocks: 11520 },
{ days: 3.62, blocks: 20852 }
];
for (const { days, blocks } of suite) {
it(`should return ${blocks} blocks for ${days} days`, () => {
assert.equal(calculator.daysToBlocks(days), blocks);
});
}
});
describe('#toTimestamp', () => {
const suite = [
{ date: '2012-01-02T20:21Z', timestamp: 1325535660 },
{ date: '2018-02-16T10:00Z', timestamp: 1518775200 },
{ date: '2042-10-15T15:21Z', timestamp: 2296999260 },
{ date: '1970-01-01T00:00Z', timestamp: 0 }
];
for (const { date, timestamp } of suite) {
it(`should return ${timestamp} for ${date}`, () => {
assert.equal(toTimestamp(new Date(date)), timestamp);
});
}
it(`should throw error for date before 1970`, () => {
assert.throws(() => {
toTimestamp(new Date('1969-12-01T10:00Z'));
});
});
});
<file_sep>/test/icocrowdsale.test.ts
import { assert } from 'chai';
import { propOr } from 'ramda';
import * as Web3 from 'web3';
import {
ContributionAcceptedEvent,
ContributionRegisteredEvent,
OnLiveArtifacts,
OnLiveToken,
PreIcoCrowdsale,
ScheduledEvent
} from 'onlive';
import { ETH_DECIMALS, shiftNumber, toONL, toWei, Web3Utils } from '../utils';
import { BigNumber } from 'bignumber.js';
import { ContractContextDefinition, TransactionResult } from 'truffle';
import { AnyNumber } from 'web3';
import {
assertEtherEqual,
assertNumberEqual,
assertReverts,
assertTokenAlmostEqual,
assertTokenEqual,
findLastLog,
ZERO_ADDRESS
} from './helpers';
declare const web3: Web3;
declare const artifacts: OnLiveArtifacts;
declare const contract: ContractContextDefinition;
const utils = new Web3Utils(web3);
const PreIcoCrowdsaleContract = artifacts.require('./PreIcoCrowdsale.sol');
const OnLiveTokenContract = artifacts.require('./OnLiveToken.sol');
contract('PreIcoCrowdsale', accounts => {
const owner = accounts[9];
const nonOwner = accounts[8];
const contributor = accounts[7];
const wallet = accounts[6];
const price = toWei(0.0011466);
const availableAmount = toONL(1000);
const minValue = toWei(0.1);
let token: OnLiveToken;
interface CrowdsaleOptions {
wallet: Address;
token: Address;
availableAmount?: Web3.AnyNumber;
price: Web3.AnyNumber;
minValue: Web3.AnyNumber;
from: Address;
}
async function createCrowdsale(options?: Partial<CrowdsaleOptions>) {
return await PreIcoCrowdsaleContract.new(
propOr(wallet, 'wallet', options),
propOr(token.address, 'token', options),
propOr(availableAmount, 'availableAmount', options),
propOr(price, 'price', options),
propOr(minValue, 'minValue', options),
{ from: propOr(owner, 'from', options) }
);
}
beforeEach(async () => {
token = await OnLiveTokenContract.new('OnLive Token', 'ONL', toONL(1000), {
from: owner
});
assertNumberEqual(await token.decimals(), ETH_DECIMALS);
});
describe('#ctor', () => {
it('should set wallet address', async () => {
const crowdsale = await createCrowdsale();
assert.equal(await crowdsale.wallet(), wallet);
});
it('should set token address', async () => {
const crowdsale = await createCrowdsale();
assert.equal(await crowdsale.token(), token.address);
});
it('should set token price', async () => {
const crowdsale = await createCrowdsale();
assertTokenEqual(await crowdsale.price(), price);
});
it('should set amount of tokens available', async () => {
const crowdsale = await createCrowdsale();
assertTokenEqual(await crowdsale.availableAmount(), availableAmount);
});
it('should set minimum contribution value', async () => {
const crowdsale = await createCrowdsale();
assertTokenEqual(await crowdsale.minValue(), minValue);
});
it('should revert when wallet address is zero', async () => {
await assertReverts(async () => {
await createCrowdsale({ wallet: '0x0' });
});
});
it('should revert when token address is zero', async () => {
await assertReverts(async () => {
await createCrowdsale({ token: '0x0' });
});
});
it('should revert when available amount is zero', async () => {
await assertReverts(async () => {
await createCrowdsale({ availableAmount: toWei(0) });
});
});
it('should revert when price is zero', async () => {
await assertReverts(async () => {
await createCrowdsale({ price: toWei(0) });
});
});
});
context('Given deployed token contract', () => {
const saleDuration = 1000;
let crowdsale: PreIcoCrowdsale;
let startBlock: number;
let endBlock: number;
beforeEach(async () => {
startBlock = await utils.getBlockNumber();
endBlock = startBlock + saleDuration;
crowdsale = await PreIcoCrowdsaleContract.new(
wallet,
token.address,
toONL(1000),
price,
minValue,
{
from: owner
}
);
await token.approveMintingManager(crowdsale.address, { from: owner });
});
interface ScheduleOptions {
startBlock: AnyNumber;
endBlock: AnyNumber;
from: Address;
}
async function schedule(options?: Partial<ScheduleOptions>) {
return await crowdsale.schedule(
propOr(startBlock, 'startBlock', options),
propOr(endBlock, 'endBlock', options),
{ from: propOr(owner, 'from', options) }
);
}
describe('#schedule', () => {
it('should set startBlock', async () => {
await schedule();
assertNumberEqual(await crowdsale.startBlock(), startBlock);
});
it('should set endBlock', async () => {
await schedule();
assertNumberEqual(await crowdsale.endBlock(), endBlock);
});
it('should emit SaleScheduled event', async () => {
const tx = await schedule();
const log = findLastLog(tx, 'Scheduled');
assert.isOk(log);
const event = log.args as ScheduledEvent;
assert.isOk(event);
assertNumberEqual(event.startBlock, startBlock);
assertNumberEqual(event.endBlock, endBlock);
});
it('should revert when start block is zero', async () => {
await assertReverts(async () => {
await schedule({ startBlock: new BigNumber(0) });
});
});
it('should revert when end block is zero', async () => {
await assertReverts(async () => {
await schedule({ endBlock: new BigNumber(0) });
});
});
it('should revert when end block is equal start block', async () => {
await assertReverts(async () => {
await schedule({ endBlock: startBlock });
});
});
it('should revert when end block is lower than start block', async () => {
await assertReverts(async () => {
await schedule({ endBlock: startBlock - 1 });
});
});
it('should revert when called by non-owner', async () => {
await assertReverts(async () => {
await schedule({ from: nonOwner });
});
});
it('should revert when already scheduled', async () => {
await schedule();
await assertReverts(async () => {
await schedule();
});
});
});
type ContributionFunction = (
from: Address,
value: Web3.AnyNumber
) => Promise<TransactionResult>;
function testContribute(contribute: ContributionFunction) {
it('should revert when sale is not scheduled', async () => {
assert.isFalse(await crowdsale.isScheduled());
await assertReverts(async () => {
await contribute(contributor, minValue);
});
});
it('should revert when sale is not active', async () => {
const futureStart = (await utils.getBlockNumber()) + 1000;
await schedule({
endBlock: futureStart + saleDuration,
startBlock: futureStart
});
assert.isFalse(await crowdsale.isActive());
await assertReverts(async () => {
await contribute(contributor, minValue);
});
});
context('Given sale is active', () => {
beforeEach(async () => {
await schedule();
assert.isTrue(await crowdsale.isScheduled());
assert.isTrue(await crowdsale.isActive());
});
it('should forward funds to wallet', async () => {
const prevBalance = await utils.getBalance(wallet);
await contribute(contributor, minValue);
assertEtherEqual(
await utils.getBalance(wallet),
prevBalance.plus(minValue)
);
});
const acceptableError = toONL(shiftNumber(1, -9));
const conversions = [
{ eth: 0.1, onl: 87.2143729287 },
{ eth: 0.5, onl: 436.071864643 },
{ eth: 1, onl: 872.143729287 }
];
for (const { eth, onl } of conversions) {
context(`Given contribution of ${eth} ETH`, () => {
it(`should assign ${onl} ONL`, async () => {
const prevBalance = await token.balanceOf(contributor);
const expectedAmount = toONL(onl);
await contribute(contributor, toWei(eth));
assertTokenAlmostEqual(
await token.balanceOf(contributor),
prevBalance.plus(expectedAmount),
acceptableError
);
});
it(`should emit ContributionAccepted event`, async () => {
const value = toWei(eth);
const expectedAmount = toONL(onl);
const tx = await contribute(contributor, value);
const log = findLastLog(tx, 'ContributionAccepted');
assert.isOk(log);
const event = log.args as ContributionAcceptedEvent;
assert.isOk(event);
assert.equal(event.contributor, contributor);
assertEtherEqual(event.value, value);
assertTokenAlmostEqual(
event.amount,
expectedAmount,
acceptableError
);
});
});
}
it('should revert when value is zero', async () => {
await assertReverts(async () => {
await contribute(contributor, toWei(0));
});
});
it('should revert when value is below threshold', async () => {
await assertReverts(async () => {
await contribute(contributor, minValue.minus(1));
});
});
it('should revert when there is not enough tokens', async () => {
const bigValue = toWei(2);
const expectedAmount = await crowdsale.calculateContribution(
bigValue
);
assert.isTrue(expectedAmount.gt(availableAmount));
await assertReverts(async () => {
await contribute(contributor, bigValue);
});
});
});
}
describe('#fallback', () => {
testContribute((from: Address, value: Web3.AnyNumber) => {
return crowdsale.sendTransaction({ from, value });
});
});
describe('#contribute', () => {
testContribute((from: Address, value: Web3.AnyNumber) => {
return crowdsale.contribute(contributor, { from: nonOwner, value });
});
it('should revert when contributor address is zero', async () => {
await assertReverts(async () => {
await crowdsale.contribute('0x0', {
from: nonOwner,
value: minValue
});
});
});
});
describe('#registerContribution', () => {
const id = '0x414243' + '0'.repeat(58);
const amount = toONL(100);
interface ContributionOptions {
id: string;
contributor: Address;
amount: AnyNumber;
from: Address;
}
async function registerContribution(
options?: Partial<ContributionOptions>
) {
return await crowdsale.registerContribution(
propOr(id, 'id', options),
propOr(contributor, 'contributor', options),
propOr(amount, 'amount', options),
{ from: propOr(owner, 'from', options) }
);
}
it('should revert when sale is not scheduled', async () => {
await assertReverts(async () => {
await registerContribution();
});
});
it('should revert when sale is not active', async () => {
const futureStart = (await utils.getBlockNumber()) + 1000;
await schedule({
endBlock: futureStart + saleDuration,
startBlock: futureStart
});
assert.isFalse(await crowdsale.isActive());
await assertReverts(async () => {
await registerContribution();
});
});
context('Given sale is active', () => {
beforeEach(async () => {
await schedule();
assert.isTrue(await crowdsale.isScheduled());
assert.isTrue(await crowdsale.isActive());
});
it('should reduce amount of available tokens', async () => {
const expectedAmount = availableAmount.minus(amount);
await registerContribution();
assertTokenEqual(await crowdsale.availableAmount(), expectedAmount);
});
it('should mint tokens for contributor', async () => {
const balance = await token.balanceOf(contributor);
const expectedBalance = balance.plus(amount);
await registerContribution();
assertTokenEqual(await token.balanceOf(contributor), expectedBalance);
});
it('should mark id as registered', async () => {
assert.isFalse(await crowdsale.isContributionRegistered(id));
await registerContribution();
assert.isTrue(await crowdsale.isContributionRegistered(id));
});
it('should emit ContributionRegistered event', async () => {
const tx = await registerContribution();
const log = findLastLog(tx, 'ContributionRegistered');
assert.isOk(log);
const event = log.args as ContributionRegisteredEvent;
assert.isOk(event);
assert.equal(event.id, id);
assert.equal(event.contributor, contributor);
assertTokenEqual(event.amount, amount);
});
it('should revert when called by non-owner', async () => {
await assertReverts(async () => {
await registerContribution({ from: nonOwner });
});
});
it('should revert when contributor address is zero', async () => {
await assertReverts(async () => {
await registerContribution({ contributor: ZERO_ADDRESS });
});
});
it('should revert when amount is zero', async () => {
await assertReverts(async () => {
await registerContribution({ amount: 0 });
});
});
it('should revert when amount exceeds availability', async () => {
await assertReverts(async () => {
await registerContribution({ amount: availableAmount.plus(1) });
});
});
it('should revert when id is duplicated', async () => {
const duplicatedId = '0x123';
await registerContribution({ id: duplicatedId });
await assertReverts(async () => {
await registerContribution({ id: duplicatedId });
});
});
});
});
});
});
<file_sep>/README.md
# onlive-contracts
OnLive Platform Ethereum Smart Contracts
<file_sep>/test/token/burnabletoken.test.ts
import { assert } from 'chai';
import * as Web3 from 'web3';
import { BurnableToken, BurnedEvent, TransferEvent } from 'onlive';
import { toONL } from '../../utils';
import {
assertReverts,
assertTokenEqual,
findLastLog,
ZERO_ADDRESS
} from '../helpers';
import { TokenTestContext } from './context';
declare const web3: Web3;
export function testBurn(
ctx: TokenTestContext<BurnableToken>,
burnerAccount: Address
) {
it('should reduce total supply', async () => {
const amount = toONL(1);
const expectedSupply = (await ctx.token.totalSupply()).minus(amount);
await ctx.token.burn(amount, { from: burnerAccount });
assertTokenEqual(await ctx.token.totalSupply(), expectedSupply);
});
it('should reduce sender balance', async () => {
const amount = toONL(1);
const expectedBalance = (await ctx.token.balanceOf(burnerAccount)).minus(
amount
);
await ctx.token.burn(amount, { from: burnerAccount });
assertTokenEqual(await ctx.token.totalSupply(), expectedBalance);
});
it('should emit Burned event', async () => {
const amount = toONL(1);
const tx = await ctx.token.burn(amount, {
from: burnerAccount
});
const log = findLastLog(tx, 'Burned');
assert.isOk(log);
const event = log.args as BurnedEvent;
assert.isOk(event);
assert.equal(event.from, burnerAccount);
assertTokenEqual(event.amount, amount);
});
it('should emit Transfer event', async () => {
const amount = toONL(1);
const tx = await ctx.token.burn(amount, {
from: burnerAccount
});
const log = findLastLog(tx, 'Transfer');
assert.isOk(log);
const event = log.args as TransferEvent;
assert.isOk(event);
assert.equal(event.from, burnerAccount);
assert.equal(event.to, ZERO_ADDRESS);
assertTokenEqual(event.value, amount);
});
it('should revert when insufficient balance', async () => {
const balance = await ctx.token.balanceOf(burnerAccount);
const value = balance.plus(toONL(1));
await assertReverts(async () => {
await ctx.token.burn(value, { from: burnerAccount });
});
});
}
<file_sep>/scripts/registercontribution.ts
// tslint:disable:no-console
import * as commander from 'commander';
import { OnLiveArtifacts } from 'onlive';
import { ScriptFinalizer } from 'truffle';
import * as Web3 from 'web3';
import { Address, Bytes32, toONL, Web3Utils } from '../utils';
declare const web3: Web3;
declare const artifacts: OnLiveArtifacts;
const utils = new Web3Utils(web3);
const OnLiveToken = artifacts.require('./contracts/OnLiveToken.sol');
const Crowdsale = artifacts.require('./contracts/Crowdsale.sol');
interface Options {
id: string;
contributor: Address;
amount: number;
}
const argv = (commander
.option('-i, --id <id>', 'unique contribution id')
.option('-c, --contributor <contributor>', 'recipient of the tokens')
.option('-a, --amount <amount>', 'amount of tokens', parseFloat)
.parse(process.argv)
.opts() as any) as Options;
async function asyncExec() {
console.log(
`Registering ${argv.amount} ONL`,
`with contribution ID ${argv.id} to ${argv.contributor}`
);
await validate();
const crowdsale = await Crowdsale.deployed();
const owner = await crowdsale.owner();
const tx = await crowdsale.registerContribution(
argv.id,
argv.contributor,
toONL(argv.amount),
{ from: owner }
);
console.log(`Transaction Hash: ${tx.receipt.transactionHash}`);
}
async function validate() {
validateInputParameters();
await validateCrowdsaleState();
await validateMintingAuthorization();
}
function validateInputParameters() {
if (!Bytes32.test(argv.id)) {
throw new Error(`Invalid contribution id: ${argv.id}`);
}
if (!web3.isChecksumAddress(argv.contributor)) {
throw new Error(
`Invalid contributor address checksum: ${argv.contributor}`
);
}
if (isNaN(argv.amount)) {
throw new Error('Invalid amount');
}
}
async function validateCrowdsaleState() {
const crowdsale = await Crowdsale.deployed();
const isActive = await crowdsale.isActive();
if (!isActive) {
throw new Error(
[
`Crowdsale ${crowdsale.address} is not active`,
`Current block: ${await utils.getBlockNumber()}`,
`Start block: ${await crowdsale.startBlock()}`,
`End block: ${await crowdsale.endBlock()}`
].join('\n')
);
}
}
async function validateMintingAuthorization() {
const crowdsale = await Crowdsale.deployed();
const token = await OnLiveToken.deployed();
const isMintingManager = await token.isMintingManager(crowdsale.address);
if (!isMintingManager) {
throw new Error(
[
`Crowdsale ${crowdsale.address} is not authorized to`,
`mint ${token.address} tokens`
].join(' ')
);
}
}
function exec(finalize: ScriptFinalizer) {
asyncExec().then(() => finalize(), reason => finalize(reason));
}
export = exec;
<file_sep>/migrations/7_setup_token_pools.ts
// tslint:disable:no-console
import { OnLiveArtifacts } from 'onlive';
import { Deployer } from 'truffle';
import { toONL, toTimestamp } from '../utils';
declare const artifacts: OnLiveArtifacts;
const OnLiveToken = artifacts.require('./OnLiveToken.sol');
const TokenPool = artifacts.require('./TokenPool.sol');
const grandTotal = 37_740_000;
const specification = [
{
category: 'reserve',
pools: [
{
amount: 1_343_100,
lock: null,
tranche: 't1'
},
{
amount: 3_540_900,
lock: new Date('2019-04-11'),
tranche: 't2'
},
{
amount: 3_663_000,
lock: new Date('2020-04-11'),
tranche: 't3'
},
{
amount: 3_663_000,
lock: new Date('2021-04-11'),
tranche: 't4'
}
],
total: 12_210_000
},
{
category: 'founders',
pools: [
{
amount: 1_343_100,
lock: new Date('2020-04-11'),
tranche: 't1'
},
{
amount: 3_540_900,
lock: new Date('2021-04-11'),
tranche: 't2'
},
{
amount: 3_663_000,
lock: new Date('2022-04-11'),
tranche: 't3'
},
{
amount: 3_663_000,
lock: new Date('2023-04-11'),
tranche: 't4'
}
],
total: 12_210_000
},
{
category: 'bounty',
pools: [
{
amount: 2_664_000,
lock: null,
tranche: 't1'
},
{
amount: 1_332_000,
lock: new Date('2019-04-11'),
tranche: 't2'
},
{
amount: 1_332_000,
lock: new Date('2020-04-11'),
tranche: 't3'
},
{
amount: 1_332_000,
lock: new Date('2021-04-11'),
tranche: 't4'
}
],
total: 6_660_000
},
{
category: 'advisors',
pools: [
{
amount: 610_500,
lock: null,
tranche: 't1'
},
{
amount: 1_609_500,
lock: new Date('2018-10-11'),
tranche: 't2'
},
{
amount: 1_665_000,
lock: new Date('2019-04-11'),
tranche: 't3'
},
{
amount: 1_665_000,
lock: new Date('2020-04-11'),
tranche: 't4'
}
],
total: 5_550_000
},
{
category: 'legal',
pools: [
{
amount: 555_000,
lock: null,
tranche: 't1'
},
{
amount: 555_000,
lock: new Date('2018-10-11'),
tranche: 't2'
}
],
total: 1_110_000
}
];
async function deploy() {
validateSubTotals();
validateGrandTotal();
const pool = await TokenPool.deployed();
const token = await OnLiveToken.deployed();
await token.approveMintingManager(pool.address);
await token.approveTransferManager(pool.address);
for (const { category, pools, total } of specification) {
console.log('-'.repeat(70));
console.log(`'${category}' ${total.toLocaleString()} ONL`);
console.log('-'.repeat(70));
for (const { amount, lock, tranche } of pools) {
const id = `${category}-${tranche}`;
console.log(
`${id} ${amount.toLocaleString()} ONL`,
lock ? `locked until ${lock.toISOString()}` : 'not locked'
);
await pool.registerPool(id, toONL(amount), lock ? toTimestamp(lock) : 0);
}
}
}
function validateSubTotals() {
for (const { category, pools, total } of specification) {
const calc = pools
.map(pool => pool.amount)
.reduce((aggregated, amount) => aggregated + amount, 0);
if (calc !== total) {
throw new Error(`Totals do not sum in category ${category}`);
}
}
}
function validateGrandTotal() {
const calc = specification
.map(category =>
category.pools
.map(pool => pool.amount)
.reduce((aggregated, amount) => aggregated + amount, 0)
)
.reduce((total, category) => total + category, 0);
if (calc !== grandTotal) {
throw new Error('Totals do not sum to Grand Total');
}
}
function migrate(deployer: Deployer) {
deployer.then(() => deploy());
}
export = migrate;
<file_sep>/migrations/8_deploy_icocrowdsale.ts
import * as Web3 from 'web3';
import { OnLiveArtifacts } from 'onlive';
import { Deployer } from 'truffle';
import { toMillionsONL, toWei } from '../utils';
declare const artifacts: OnLiveArtifacts;
declare const web3: Web3;
const OnLiveToken = artifacts.require('./OnLiveToken.sol');
const IcoCrowdsale = artifacts.require('./IcoCrowdsale.sol');
async function deploy(deployer: Deployer, network: string) {
const token = await OnLiveToken.deployed();
const minValue = toWei('0.1');
let wallet = web3.eth.accounts[0];
if (network === 'mainnet') {
wallet = '0xd0078f5c7E33BaD8767c602D3aaEe6e38481c9A1';
}
await deployer.deploy(IcoCrowdsale, wallet, token.address, minValue);
const crowdsale = await IcoCrowdsale.deployed();
await token.approveMintingManager(crowdsale.address);
await token.approveTransferManager(crowdsale.address);
}
function migrate(deployer: Deployer, network: string) {
deployer.then(() => deploy(deployer, network));
}
export = migrate;
<file_sep>/test/token/context.ts
import { ERC20Basic } from 'onlive';
export class TokenTestContext<T extends ERC20Basic> {
get token(): T {
if (this._token === undefined) {
throw new Error('Token not initialized in context');
}
return this._token;
}
set token(value: T) {
this._token = value;
}
private _token?: T;
public constructor(public accounts: Address[], public owner: Address) {}
}
<file_sep>/test/token/descriptivetoken.test.ts
import { assert } from 'chai';
import * as Web3 from 'web3';
import {
DescriptionChangedEvent,
DescriptionFinalizedEvent,
DescriptiveToken
} from 'onlive';
import { assertReverts, findLastLog } from '../helpers';
import { TokenTestContext } from './context';
declare const web3: Web3;
export function testChangeDescription(ctx: TokenTestContext<DescriptiveToken>) {
const name = '<NAME>';
const symbol = 'New Symbol';
it('should change name', async () => {
await ctx.token.changeDescription(name, symbol, {
from: ctx.owner
});
assert.equal(await ctx.token.name(), name);
});
it('should change symbol', async () => {
await ctx.token.changeDescription(name, symbol, {
from: ctx.owner
});
assert.equal(await ctx.token.symbol(), symbol);
});
it('should emit DescriptionChanged event', async () => {
const tx = await ctx.token.changeDescription(name, symbol, {
from: ctx.owner
});
const log = findLastLog(tx, 'DescriptionChanged');
assert.isOk(log);
const event = log.args as DescriptionChangedEvent;
assert.isOk(event);
assert.equal(event.name, name);
assert.equal(event.symbol, symbol);
});
it('should revert when called by non-owner', async () => {
const otherAccount = ctx.accounts[0];
await assertReverts(async () => {
await ctx.token.changeDescription(name, symbol, {
from: otherAccount
});
});
});
it('should revert when description is finalized', async () => {
await ctx.token.finalizeDescription({ from: ctx.owner });
await assertReverts(async () => {
await ctx.token.changeDescription(name, symbol, {
from: ctx.owner
});
});
});
}
export function testFinalizeDescription(
ctx: TokenTestContext<DescriptiveToken>
) {
it('should set isDescriptionFinalized flag', async () => {
await ctx.token.finalizeDescription({ from: ctx.owner });
assert.isTrue(await ctx.token.isDescriptionFinalized());
});
it('should emit DescriptionFinalized event', async () => {
const tx = await ctx.token.finalizeDescription({ from: ctx.owner });
const log = findLastLog(tx, 'DescriptionFinalized');
assert.isOk(log);
const event = log.args as DescriptionFinalizedEvent;
assert.isOk(event);
});
it('should revert when called by non-owner', async () => {
const otherAccount = ctx.accounts[0];
await assertReverts(async () => {
await ctx.token.finalizeDescription({ from: otherAccount });
});
});
it('should revert when already finalized', async () => {
await ctx.token.finalizeDescription({ from: ctx.owner });
await assertReverts(async () => {
await ctx.token.finalizeDescription({ from: ctx.owner });
});
});
}
<file_sep>/test/onlivetoken.test.ts
import { assert } from 'chai';
import { propOr, without } from 'ramda';
import { ContractContextDefinition } from 'truffle';
import * as Web3 from 'web3';
import { OnLiveArtifacts, OnLiveToken } from 'onlive';
import { toONL } from '../utils';
import { assertTokenEqual } from './helpers';
import { testBurn } from './token/burnabletoken.test';
import { testMint as testCappedMint } from './token/cappedmintabletoken.test';
import { TokenTestContext } from './token/context';
import {
testChangeDescription,
testFinalizeDescription
} from './token/descriptivetoken.test';
import {
testAddMintingManager,
testFinishMinting,
testMint,
testRemoveMintingManager
} from './token/mintabletoken.test';
import {
testAddTransferManager,
testRelease,
testRemoveTransferManager,
testSetReleaseManager,
testTransfer,
testTransferFrom
} from './token/releasabletoken.test';
declare const web3: Web3;
declare const artifacts: OnLiveArtifacts;
declare const contract: ContractContextDefinition;
const OnLiveTokenContract = artifacts.require('./OnLiveToken.sol');
interface TokenOptions {
name: string;
symbol: string;
maxSupply: Web3.AnyNumber;
from: Address;
}
contract('OnLiveToken', accounts => {
const owner = accounts[9];
const name = 'OnLive Token';
const symbol = 'ONL';
const maxSupply = toONL(1000);
async function createToken(options?: Partial<TokenOptions>) {
return await OnLiveTokenContract.new(
propOr(name, 'name', options),
propOr(symbol, 'symbol', options),
propOr(maxSupply, 'maxSupply', options),
{ from: propOr(owner, 'from', options) }
);
}
describe('#ctor', () => {
it('should set name', async () => {
const token = await createToken();
assert.equal(await token.name(), name);
});
it('should set symbol', async () => {
const token = await createToken();
assert.equal(await token.symbol(), symbol);
});
it('should set maxSupply', async () => {
const token = await createToken();
assertTokenEqual(await token.maxSupply(), maxSupply);
});
it('should set owner', async () => {
const token = await createToken();
assert.equal(await token.owner(), owner);
});
});
context('Given deployed token contract', () => {
const ctx = new TokenTestContext<OnLiveToken>(
without([owner], accounts),
owner
);
beforeEach(async () => {
ctx.token = await createToken();
});
describe('DescriptiveToken base', () => {
describe('#changeDescription', () => testChangeDescription(ctx));
describe('#finalizeDescription', () => testFinalizeDescription(ctx));
});
describe('ReleasableToken base', () => {
describe('#setReleaseManager', () => testSetReleaseManager(ctx));
describe('#approveTransferManager', () => testAddTransferManager(ctx));
describe('#revokeTransferManager', () => testRemoveTransferManager(ctx));
describe('#release', () => testRelease(ctx));
});
describe('MintableToken base', () => {
describe('#mint', () => testMint(ctx));
describe('#approveMintingManager', () => testAddMintingManager(ctx));
describe('#revokeMintingManager', () => testRemoveMintingManager(ctx));
describe('#finishMinting', () => testFinishMinting(ctx));
});
describe('CappedMintableToken base', () => {
describe('#mint (capped)', () => testCappedMint(ctx));
});
context('Given account has 100 tokens', () => {
const initialBalance = toONL(100);
const holderAccount = ctx.accounts[5];
const mintingManager = ctx.accounts[6];
beforeEach(async () => {
ctx.accounts = without([holderAccount, mintingManager], ctx.accounts);
await ctx.token.approveMintingManager(mintingManager, {
from: owner
});
await ctx.token.mint(holderAccount, initialBalance, {
from: mintingManager
});
});
describe('ReleasableToken base', () => {
describe('#transfer', () => testTransfer(ctx, holderAccount));
describe('#transferFrom', () => testTransferFrom(ctx, holderAccount));
});
describe('BurnableToken base', () => {
describe('#burn', () => testBurn(ctx, holderAccount));
});
});
});
});
<file_sep>/utils/time.ts
export function toTimestamp(date: Date) {
const timestamp = Math.round(date.getTime() / 1000);
if (timestamp < 0) {
// avoid uint overflow in Solidity contracts with negative numbers
throw new Error('Dates before 1970 are not supported');
}
return timestamp;
}
export function getTimestamp() {
return toTimestamp(new Date());
}
<file_sep>/docker/solidity-flattener/Dockerfile
FROM ethereum/solc:0.4.18 AS solc
FROM python:3.6.4
COPY --from=solc /usr/bin/solc /usr/bin/solc
RUN pip3 install solidity-flattener
ENTRYPOINT ["solidity_flattener"]
<file_sep>/migrations/9_schedule_icocrowdsale.ts
// tslint:disable:no-console
import { OnLiveArtifacts } from 'onlive';
import { Deployer } from 'truffle';
import * as Web3 from 'web3';
import {
BlockCalculator,
blockTimes,
ONL_DECIMALS,
shiftNumber,
toMillionsONL,
toWei,
Web3Utils
} from '../utils';
declare const artifacts: OnLiveArtifacts;
declare const web3: Web3;
const utils = new Web3Utils(web3);
const IcoCrowdsale = artifacts.require('./IcoCrowdsale.sol');
async function deploy(network: string) {
const crowdsale = await IcoCrowdsale.deployed();
const blockTime = blockTimes[network];
const calculator = new BlockCalculator(blockTime);
console.log(`Estimating block numbers with ${blockTime} seconds per block`);
const availableAmount = toMillionsONL('61.050');
const crowdsaleStartBlock = await calculateStartBlock(calculator);
const tiers = [
{
price: toWei('0.00131'),
startBlock: crowdsaleStartBlock
},
{
price: toWei('0.001458'),
startBlock: crowdsaleStartBlock + calculator.daysToBlocks(10.5)
},
{
price: toWei('0.001638'),
startBlock: crowdsaleStartBlock + calculator.daysToBlocks(21.5)
}
];
const crowdsaleEndBlock = crowdsaleStartBlock + calculator.daysToBlocks(30.5);
for (const { price, startBlock } of tiers) {
console.log(
`Scheduling tier from ${startBlock.toLocaleString()} block`,
`${shiftNumber(price, -ONL_DECIMALS)} ETH per token`
);
await crowdsale.scheduleTier(startBlock, price);
}
console.log(`Finalizing with ${crowdsaleEndBlock.toLocaleString()} block`);
await crowdsale.finalize(crowdsaleEndBlock, availableAmount);
}
function migrate(deployer: Deployer, network: string) {
deployer.then(() => deploy(network));
}
async function calculateStartBlock(calculator: BlockCalculator) {
const startOffset = calculator.hoursToBlocks(1);
const currentBlock = await utils.getBlockNumber();
const crowdsaleStartBlock = currentBlock + startOffset;
return crowdsaleStartBlock;
}
export = migrate;
<file_sep>/test/token/releasabletoken.test.ts
import { assert } from 'chai';
import * as Web3 from 'web3';
import {
ReleasableToken,
ReleasedEvent,
ReleaseManagerSetEvent,
TransferEvent,
TransferManagerApprovedEvent,
TransferManagerRevokedEvent
} from 'onlive';
import { toONL } from '../../utils';
import { assertReverts, assertTokenEqual, findLastLog } from '../helpers';
import { TokenTestContext } from './context';
declare const web3: Web3;
export function testSetReleaseManager(ctx: TokenTestContext<ReleasableToken>) {
const releaseManager = ctx.accounts[0];
const otherAccount = ctx.accounts[1];
it('should set release manager', async () => {
assert.notEqual(await ctx.token.releaseManager(), releaseManager);
await ctx.token.setReleaseManager(releaseManager, { from: ctx.owner });
assert.equal(await ctx.token.releaseManager(), releaseManager);
});
it('should emit ReleaseManagerSet event', async () => {
const tx = await ctx.token.setReleaseManager(releaseManager, {
from: ctx.owner
});
const log = findLastLog(tx, 'ReleaseManagerSet');
assert.isOk(log);
const event = log.args as ReleaseManagerSetEvent;
assert.isOk(event);
assert.equal(event.addr, releaseManager);
});
it('should revert when called by non-owner', async () => {
await assertReverts(async () => {
await ctx.token.setReleaseManager(releaseManager, { from: otherAccount });
});
});
it('should revert when called after release', async () => {
await ctx.token.setReleaseManager(releaseManager, { from: ctx.owner });
await ctx.token.release({ from: releaseManager });
await assertReverts(async () => {
await ctx.token.setReleaseManager(otherAccount, { from: ctx.owner });
});
});
}
export function testAddTransferManager(ctx: TokenTestContext<ReleasableToken>) {
const releaseManager = ctx.accounts[0];
const transferManager = ctx.accounts[1];
const otherAccount = ctx.accounts[2];
beforeEach(async () => {
await ctx.token.setReleaseManager(releaseManager, { from: ctx.owner });
});
it('should approve transfer manager', async () => {
assert.isFalse(await ctx.token.isTransferManager(transferManager));
await ctx.token.approveTransferManager(transferManager, {
from: ctx.owner
});
assert.isTrue(await ctx.token.isTransferManager(transferManager));
});
it('should approve multiple transfer managers', async () => {
const managers = ctx.accounts.slice(0, 4);
await Promise.all(
managers.map(account =>
ctx.token.approveTransferManager(account, { from: ctx.owner })
)
);
for (const account of managers) {
assert.isTrue(await ctx.token.isTransferManager(account));
}
});
it('should emit TransferManagerApproved event', async () => {
const tx = await ctx.token.approveTransferManager(transferManager, {
from: ctx.owner
});
const log = findLastLog(tx, 'TransferManagerApproved');
assert.isOk(log);
const event = log.args as TransferManagerApprovedEvent;
assert.isOk(event);
assert.equal(event.addr, transferManager);
});
it('should revert when called by non-owner', async () => {
await assertReverts(async () => {
await ctx.token.approveTransferManager(transferManager, {
from: otherAccount
});
});
});
it('should revert when called after release', async () => {
await ctx.token.release({ from: releaseManager });
await assertReverts(async () => {
await ctx.token.approveTransferManager(otherAccount, { from: ctx.owner });
});
});
}
export function testRemoveTransferManager(
ctx: TokenTestContext<ReleasableToken>
) {
const releaseManager = ctx.accounts[0];
const transferManager = ctx.accounts[1];
const otherAccount = ctx.accounts[2];
beforeEach(async () => {
await ctx.token.setReleaseManager(releaseManager, { from: ctx.owner });
await ctx.token.approveTransferManager(transferManager, {
from: ctx.owner
});
});
it('should revoke transfer manager', async () => {
assert.isTrue(await ctx.token.isTransferManager(transferManager));
await ctx.token.revokeTransferManager(transferManager, { from: ctx.owner });
assert.isFalse(await ctx.token.isTransferManager(transferManager));
});
it('should emit TransferManagerRevoked event', async () => {
const tx = await ctx.token.revokeTransferManager(transferManager, {
from: ctx.owner
});
const log = findLastLog(tx, 'TransferManagerRevoked');
assert.isOk(log);
const event = log.args as TransferManagerRevokedEvent;
assert.isOk(event);
assert.equal(event.addr, transferManager);
});
it('should revert when transfer manager does not exist', async () => {
await assertReverts(async () => {
await ctx.token.revokeTransferManager(otherAccount, { from: ctx.owner });
});
});
it('should revert when called by non-owner', async () => {
await assertReverts(async () => {
await ctx.token.revokeTransferManager(transferManager, {
from: otherAccount
});
});
});
it('should revert when called after release', async () => {
await ctx.token.release({ from: releaseManager });
await assertReverts(async () => {
await ctx.token.revokeTransferManager(transferManager, {
from: ctx.owner
});
});
});
}
export function testRelease(ctx: TokenTestContext<ReleasableToken>) {
const releaseManager = ctx.accounts[0];
const otherAccount = ctx.accounts[1];
beforeEach(async () => {
await ctx.token.setReleaseManager(releaseManager, { from: ctx.owner });
});
it('should set released flag', async () => {
assert.isFalse(await ctx.token.released());
await ctx.token.release({ from: releaseManager });
assert.isTrue(await ctx.token.released());
});
it('should emit Released event', async () => {
const tx = await ctx.token.release({ from: releaseManager });
const log = findLastLog(tx, 'Released');
assert.isOk(log);
const event = log.args as ReleasedEvent;
assert.isOk(event);
});
it('should revert when called by not release manager', async () => {
await assertReverts(async () => {
await ctx.token.release({ from: otherAccount });
});
});
it('should revert when called after being released', async () => {
await ctx.token.release({ from: releaseManager });
await assertReverts(async () => {
await ctx.token.release({ from: releaseManager });
});
});
}
export function testTransfer(
ctx: TokenTestContext<ReleasableToken>,
sourceAccount: Address
) {
const releaseManager = ctx.accounts[0];
const destinationAccount = ctx.accounts[1];
beforeEach(async () => {
await ctx.token.setReleaseManager(releaseManager, { from: ctx.owner });
});
it('should change balances when released', async () => {
await ctx.token.release({ from: releaseManager });
const amount = toONL(1);
const expectedDestinationBalance = (await ctx.token.balanceOf(
destinationAccount
)).plus(amount);
const expectedSourceBalance = (await ctx.token.balanceOf(
sourceAccount
)).minus(amount);
await ctx.token.transfer(destinationAccount, amount, {
from: sourceAccount
});
assertTokenEqual(
await ctx.token.balanceOf(destinationAccount),
expectedDestinationBalance
);
assertTokenEqual(
await ctx.token.balanceOf(sourceAccount),
expectedSourceBalance
);
});
it('should revert when not released', async () => {
await assertReverts(async () => {
await ctx.token.transfer(destinationAccount, toONL(1), {
from: sourceAccount
});
});
});
context('Given source account is transfer manager', () => {
beforeEach(async () => {
await ctx.token.approveTransferManager(sourceAccount, {
from: ctx.owner
});
});
it('should emit Transfer event when not released', async () => {
const amount = toONL(1);
const tx = await ctx.token.transfer(destinationAccount, amount, {
from: sourceAccount
});
const log = findLastLog(tx, 'Transfer');
assert.isOk(log);
const event = log.args as TransferEvent;
assert.isOk(event);
assert.equal(event.from, sourceAccount);
assert.equal(event.to, destinationAccount);
assertTokenEqual(event.value, amount);
});
it('should change balance when not released', async () => {
const amount = toONL(1);
const expectedDestinationBalance = (await ctx.token.balanceOf(
destinationAccount
)).plus(amount);
await ctx.token.transfer(destinationAccount, amount, {
from: sourceAccount
});
assertTokenEqual(
await ctx.token.balanceOf(destinationAccount),
expectedDestinationBalance
);
});
});
}
export function testTransferFrom(
ctx: TokenTestContext<ReleasableToken>,
sourceAccount: Address
) {
const releaseManager = ctx.accounts[0];
const destinationAccount = ctx.accounts[1];
const approvedAccount = ctx.accounts[2];
const amount = toONL(1);
beforeEach(async () => {
await ctx.token.setReleaseManager(releaseManager, { from: ctx.owner });
await ctx.token.approve(approvedAccount, amount, { from: sourceAccount });
});
it('should change balances when released', async () => {
await ctx.token.release({ from: releaseManager });
const expectedDestinationBalance = (await ctx.token.balanceOf(
destinationAccount
)).plus(amount);
const expectedSourceBalance = (await ctx.token.balanceOf(
sourceAccount
)).minus(amount);
await ctx.token.transferFrom(sourceAccount, destinationAccount, amount, {
from: approvedAccount
});
assertTokenEqual(
await ctx.token.balanceOf(destinationAccount),
expectedDestinationBalance
);
assertTokenEqual(
await ctx.token.balanceOf(sourceAccount),
expectedSourceBalance
);
});
it('should revert when not released', async () => {
await assertReverts(async () => {
await ctx.token.transferFrom(sourceAccount, destinationAccount, amount, {
from: approvedAccount
});
});
});
context('Given source account is transfer manager', () => {
beforeEach(async () => {
await ctx.token.approveTransferManager(sourceAccount, {
from: ctx.owner
});
});
it('should emit Transfer event when not released', async () => {
const tx = await ctx.token.transferFrom(
sourceAccount,
destinationAccount,
amount,
{
from: approvedAccount
}
);
const log = findLastLog(tx, 'Transfer');
assert.isOk(log);
const event = log.args as TransferEvent;
assert.isOk(event);
assert.equal(event.from, sourceAccount);
assert.equal(event.to, destinationAccount);
assertTokenEqual(event.value, amount);
});
it('should change balance when not released', async () => {
const expectedDestinationBalance = (await ctx.token.balanceOf(
destinationAccount
)).plus(amount);
await ctx.token.transferFrom(sourceAccount, destinationAccount, amount, {
from: approvedAccount
});
assertTokenEqual(
await ctx.token.balanceOf(destinationAccount),
expectedDestinationBalance
);
});
});
}
<file_sep>/test/token/mintabletoken.test.ts
import { assert } from 'chai';
import * as Web3 from 'web3';
import {
MintableToken,
MintedEvent,
MintingFinishedEvent,
MintingManagerApprovedEvent,
MintingManagerRevokedEvent,
TransferEvent
} from 'onlive';
import { toONL } from '../../utils';
import {
assertReverts,
assertTokenEqual,
findLastLog,
ZERO_ADDRESS
} from '../helpers';
import { TokenTestContext } from './context';
declare const web3: Web3;
export function testAddMintingManager(ctx: TokenTestContext<MintableToken>) {
const mintingManager = ctx.accounts[0];
const otherAccount = ctx.accounts[1];
it('should approve minting manager', async () => {
assert.isFalse(await ctx.token.isMintingManager(mintingManager));
await ctx.token.approveMintingManager(mintingManager, { from: ctx.owner });
assert.isTrue(await ctx.token.isMintingManager(mintingManager));
});
it('should approve multiple minting managers', async () => {
const managers = ctx.accounts.slice(0, 4);
await Promise.all(
managers.map(account =>
ctx.token.approveMintingManager(account, { from: ctx.owner })
)
);
for (const account of managers) {
assert.isTrue(await ctx.token.isMintingManager(account));
}
});
it('should emit MintingManagerApproved event', async () => {
const tx = await ctx.token.approveMintingManager(mintingManager, {
from: ctx.owner
});
const log = findLastLog(tx, 'MintingManagerApproved');
assert.isOk(log);
const event = log.args as MintingManagerApprovedEvent;
assert.isOk(event);
assert.equal(event.addr, mintingManager);
});
it('should revert when called by non-owner', async () => {
await assertReverts(async () => {
await ctx.token.approveMintingManager(mintingManager, {
from: otherAccount
});
});
});
it('should revert when called after finished minting', async () => {
await ctx.token.finishMinting({ from: ctx.owner });
await assertReverts(async () => {
await ctx.token.approveMintingManager(otherAccount, { from: ctx.owner });
});
});
}
export function testRemoveMintingManager(ctx: TokenTestContext<MintableToken>) {
const mintingManager = ctx.accounts[0];
const otherAccount = ctx.accounts[1];
beforeEach(async () => {
await ctx.token.approveMintingManager(mintingManager, { from: ctx.owner });
});
it('should revoke minting manager', async () => {
assert.isTrue(await ctx.token.isMintingManager(mintingManager));
await ctx.token.revokeMintingManager(mintingManager, { from: ctx.owner });
assert.isFalse(await ctx.token.isMintingManager(mintingManager));
});
it('should emit MintingManagerRevoked event', async () => {
const tx = await ctx.token.revokeMintingManager(mintingManager, {
from: ctx.owner
});
const log = findLastLog(tx, 'MintingManagerRevoked');
assert.isOk(log);
const event = log.args as MintingManagerRevokedEvent;
assert.isOk(event);
assert.equal(event.addr, mintingManager);
});
it('should revert when minting manager does not exist', async () => {
await assertReverts(async () => {
await ctx.token.revokeMintingManager(otherAccount, { from: ctx.owner });
});
});
it('should revert when called by non-owner', async () => {
await assertReverts(async () => {
await ctx.token.revokeMintingManager(mintingManager, {
from: otherAccount
});
});
});
it('should revert when called after finished minting', async () => {
await ctx.token.finishMinting({ from: ctx.owner });
await assertReverts(async () => {
await ctx.token.revokeMintingManager(mintingManager, {
from: ctx.owner
});
});
});
}
export function testMint(ctx: TokenTestContext<MintableToken>) {
const mintingManager = ctx.accounts[0];
const otherAccount = ctx.accounts[1];
const destinationAccount = ctx.accounts[2];
beforeEach(async () => {
await ctx.token.approveMintingManager(mintingManager, { from: ctx.owner });
});
it('should increase total supply', async () => {
const amount = toONL(1);
const expectedSupply = (await ctx.token.totalSupply()).plus(amount);
await ctx.token.mint(destinationAccount, amount, { from: mintingManager });
assertTokenEqual(await ctx.token.totalSupply(), expectedSupply);
});
it('should increase balance of destination account', async () => {
const amount = toONL(1);
const expectedValue = (await ctx.token.balanceOf(destinationAccount)).plus(
amount
);
await ctx.token.mint(destinationAccount, amount, { from: mintingManager });
assertTokenEqual(
await ctx.token.balanceOf(destinationAccount),
expectedValue
);
});
it('should emit Minted event', async () => {
const amount = toONL(1);
const tx = await ctx.token.mint(destinationAccount, amount, {
from: mintingManager
});
const log = findLastLog(tx, 'Minted');
assert.isOk(log);
const event = log.args as MintedEvent;
assert.isOk(event);
assert.equal(event.to, destinationAccount);
assertTokenEqual(event.amount, amount);
});
it('should emit Transfer event', async () => {
const amount = toONL(1);
const tx = await ctx.token.mint(destinationAccount, amount, {
from: mintingManager
});
const log = findLastLog(tx, 'Transfer');
assert.isOk(log);
const event = log.args as TransferEvent;
assert.isOk(event);
assert.equal(event.from, ZERO_ADDRESS);
assert.equal(event.to, destinationAccount);
assertTokenEqual(event.value, amount);
});
it('should revert when minting is finished', async () => {
await ctx.token.finishMinting({ from: ctx.owner });
await assertReverts(async () => {
await ctx.token.mint(destinationAccount, toONL(1), {
from: mintingManager
});
});
});
it('should revert when called by not minting manager', async () => {
await assertReverts(async () => {
await ctx.token.mint(destinationAccount, toONL(1), {
from: otherAccount
});
});
});
}
export function testFinishMinting(ctx: TokenTestContext<MintableToken>) {
const otherAccount = ctx.accounts[0];
it('should set mintingFinished flag', async () => {
assert.isFalse(await ctx.token.mintingFinished());
await ctx.token.finishMinting({ from: ctx.owner });
assert.isTrue(await ctx.token.mintingFinished());
});
it('should emit MintingFinished event', async () => {
const tx = await ctx.token.finishMinting({ from: ctx.owner });
const log = findLastLog(tx, 'MintingFinished');
assert.isOk(log);
const event = log.args as MintingFinishedEvent;
assert.isOk(event);
});
it('should revert when called by not release manager', async () => {
await assertReverts(async () => {
await ctx.token.finishMinting({ from: otherAccount });
});
});
it('should revert when called after finished minting', async () => {
await ctx.token.finishMinting({ from: ctx.owner });
await assertReverts(async () => {
await ctx.token.finishMinting({ from: ctx.owner });
});
});
}
| 2f7555e1207e7cf8b2b66046f44bd2c4a52267cb | [
"Markdown",
"TypeScript",
"Dockerfile"
] | 28 | TypeScript | OnLivePlatform/onlive-contracts | defbfcebed54833c514f86426ccace160ba74588 | 596d78453e8483da7a1c02a4dade61da657aae33 |
refs/heads/master | <repo_name>ntezak/OpticalSocieyPythonWorkshop<file_sep>/test_packages.py
#!/usr/bin/env python
import subprocess
import os
try:
import IPython
print("IPython version should be at least 2.4, it is:",
IPython.__version__)
except ImportError:
print("Please install IPython")
try:
import matplotlib
print("matplotlib version should be at least 1.4, it is:",
matplotlib.__version__)
except ImportError:
print("Please install matplotlib")
try:
import numba
print("Numba version should be at least 0.16.0, it is:", numba.__version__)
except ImportError:
print("Please install numba")
try:
import pandas
print("Pandas version should be at least 0.15.0, it is:",
pandas.__version__)
except ImportError:
print("Please install pandas")
try:
import cython
print("Cython version should be at least 0.20, it is:",
cython.__version__)
except ImportError:
print("Please install pandas")
try:
print("Checking for gcc compiler:")
print("-"*80)
subprocess.call(["gcc", "--version"])
print("-"*80)
print("success")
print("-"*80)
except OSError as e:
if e.errno == os.errno.ENOENT:
# handle file not found error.
print("Cannot find the gcc compiler")
else:
# Something else went wrong while trying to run `wget`
print("`gcc --version` failed for some reason: ", e)
<file_sep>/README.md
# Scientific Computing with Python Workshop Files
Led by <NAME> and <NAME>, and covering the following:
- The [IPython](https://ipython.org) notebook
- [SciPy+NumPy](https://scipy.org) for data crunching
- [Matplotlib](http://matplotlib.org/) for visualization
- [IPython notebook widgets](https://github.com/ipython/ipython/tree/master/examples/Interactive%20Widgets) for making small GUI applets
- *Briefly* [Pandas](http://pandas.pydata.org) and [Numba](http://numba.pydata.org)
- The Python ctypes module for direct interface with C-libraries
- The [Cython module](http://cython.org) for writing efficient numerical code
Please download this repository (either via `git clone` or a zip file) and execute the `test_packages.py` script cd'ing into this directory and running
python test_packages.py
You can [view the notebooks here](http://nbviewer.ipython.org/github/ntezak/OpticalSocieyPythonWorkshop/tree/master/) to see the code and text without downloading them but we have removed all cell output for didactic purposes.<file_sep>/cython_setup.py
# Run this as: python setup.py build_ext --inplace
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
from Cython.Distutils import build_ext
modules = [Extension("helloworld", ["helloworld.pyx"])]
setup(name = "HelloWorld", cmdclass = {'build_ext': build_ext}, ext_modules = cythonize(modules))
| 302b6d1f61de458c201ba69f91e857e04baf998a | [
"Markdown",
"Python"
] | 3 | Python | ntezak/OpticalSocieyPythonWorkshop | 7a49d4883a3d41de2fb6df457f20a456b0787442 | 029f61b4bb7d02579c1260c7dd72b5b22a4ec3e5 |
refs/heads/master | <repo_name>luivicur/SVGAnimationDemo<file_sep>/svg.js
var angle = 0;
var circleX = 10;
var circleDx = 10;
var circleY = 250;
var circleDy = 0;
var gravity = 1;
var friction = 0.07;
// Main Function To Start
function start()
{
return setInterval(animate, 50);
}
function animate()
{
rotateEllipse();
moveCircle();
}
function rotateEllipse()
{
var transform = "rotate(" + angle + " 100 100)";
$("#ellipse").attr("transform", transform);
angle += 5;
if(angle > 360) angle = 0;
}
function moveCircle()
{
$("#circle").attr("cx", circleX);
circleX += circleDx;
if(circleX > 650) circleX = 10;
circleDy += gravity;
circleY += circleDy;
$("#circle").attr("cy", circleY);
if(circleY >= 650)
{
circleY = 650;
circleDy *= -0.85;
circleDx -= friction;
if(circleDx < 0) circleDx = 0;
}
}
$(document).ready(function()
{
start();
}); | f7c80f3edce5103fc6a5bc9d760d00a14d19ca2e | [
"JavaScript"
] | 1 | JavaScript | luivicur/SVGAnimationDemo | 5958df41b802069560ccde1f510f61dfca095903 | 9c7706a4735afc01d8247a4756821adf065e207a |
refs/heads/master | <repo_name>KevinFrutiger/hifi<file_sep>/scripts/system/tablet-goto.js
"use strict";
//
// goto.js
// scripts/system/
//
// Created by <NAME> on 8 February 2017
// Copyright 2016 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
(function() { // BEGIN LOCAL_SCOPE
var gotoQmlSource = "TabletAddressDialog.qml";
var buttonName = "GOTO";
function onClicked(){
tablet.loadQMLSource(gotoQmlSource);
}
var tablet = Tablet.getTablet("com.highfidelity.interface.tablet.system");
var button = tablet.addButton({
icon: "icons/tablet-icons/goto-i.svg",
activeIcon: "icons/tablet-icons/goto-a.svg",
text: buttonName,
sortOrder: 8
});
button.clicked.connect(onClicked);
Script.scriptEnding.connect(function () {
button.clicked.disconnect(onClicked);
if (tablet) {
tablet.removeButton(button);
}
});
}()); // END LOCAL_SCOPE
<file_sep>/assignment-client/src/avatars/AvatarMixerSlave.cpp
//
// AvatarMixerSlave.cpp
// assignment-client/src/avatar
//
// Created by <NAME> on 2/14/2017.
// Copyright 2017 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include <algorithm>
#include <random>
#include <glm/glm.hpp>
#include <glm/gtx/norm.hpp>
#include <glm/gtx/vector_angle.hpp>
#include <AvatarLogging.h>
#include <LogHandler.h>
#include <NetworkAccessManager.h>
#include <NodeList.h>
#include <Node.h>
#include <OctreeConstants.h>
#include <udt/PacketHeaders.h>
#include <SharedUtil.h>
#include <StDev.h>
#include <UUID.h>
#include "AvatarMixer.h"
#include "AvatarMixerClientData.h"
#include "AvatarMixerSlave.h"
void AvatarMixerSlave::configure(ConstIter begin, ConstIter end) {
_begin = begin;
_end = end;
}
void AvatarMixerSlave::configureBroadcast(ConstIter begin, ConstIter end,
p_high_resolution_clock::time_point lastFrameTimestamp,
float maxKbpsPerNode, float throttlingRatio) {
_begin = begin;
_end = end;
_lastFrameTimestamp = lastFrameTimestamp;
_maxKbpsPerNode = maxKbpsPerNode;
_throttlingRatio = throttlingRatio;
}
void AvatarMixerSlave::harvestStats(AvatarMixerSlaveStats& stats) {
stats = _stats;
_stats.reset();
}
void AvatarMixerSlave::processIncomingPackets(const SharedNodePointer& node) {
auto start = usecTimestampNow();
auto nodeData = dynamic_cast<AvatarMixerClientData*>(node->getLinkedData());
if (nodeData) {
_stats.nodesProcessed++;
_stats.packetsProcessed += nodeData->processPackets();
}
auto end = usecTimestampNow();
_stats.processIncomingPacketsElapsedTime += (end - start);
}
void AvatarMixerSlave::sendIdentityPacket(const AvatarMixerClientData* nodeData, const SharedNodePointer& destinationNode) {
QByteArray individualData = nodeData->getConstAvatarData()->identityByteArray();
auto identityPacket = NLPacket::create(PacketType::AvatarIdentity, individualData.size());
individualData.replace(0, NUM_BYTES_RFC4122_UUID, nodeData->getNodeID().toRfc4122());
identityPacket->write(individualData);
DependencyManager::get<NodeList>()->sendPacket(std::move(identityPacket), *destinationNode);
_stats.numIdentityPackets++;
}
static const int AVATAR_MIXER_BROADCAST_FRAMES_PER_SECOND = 45;
// only send extra avatar data (avatars out of view, ignored) every Nth AvatarData frame
// Extra avatar data will be sent (AVATAR_MIXER_BROADCAST_FRAMES_PER_SECOND/EXTRA_AVATAR_DATA_FRAME_RATIO) times
// per second.
// This value should be a power of two for performance purposes, as the mixer performs a modulo operation every frame
// to determine whether the extra data should be sent.
static const int EXTRA_AVATAR_DATA_FRAME_RATIO = 16;
// FIXME - There is some old logic (unchanged as of 2/17/17) that randomly decides to send an identity
// packet. That logic had the following comment about the constants it uses...
//
// An 80% chance of sending a identity packet within a 5 second interval.
// assuming 60 htz update rate.
//
// Assuming the calculation of the constant is in fact correct for 80% and 60hz and 5 seconds (an assumption
// that I have not verified) then the constant is definitely wrong now, since we send at 45hz.
const float IDENTITY_SEND_PROBABILITY = 1.0f / 187.0f;
void AvatarMixerSlave::broadcastAvatarData(const SharedNodePointer& node) {
quint64 start = usecTimestampNow();
auto nodeList = DependencyManager::get<NodeList>();
// setup for distributed random floating point values
std::random_device randomDevice;
std::mt19937 generator(randomDevice());
std::uniform_real_distribution<float> distribution;
if (node->getLinkedData() && (node->getType() == NodeType::Agent) && node->getActiveSocket()) {
_stats.nodesBroadcastedTo++;
AvatarMixerClientData* nodeData = reinterpret_cast<AvatarMixerClientData*>(node->getLinkedData());
nodeData->resetInViewStats();
const AvatarData& avatar = nodeData->getAvatar();
glm::vec3 myPosition = avatar.getClientGlobalPosition();
// reset the internal state for correct random number distribution
distribution.reset();
// reset the max distance for this frame
float maxAvatarDistanceThisFrame = 0.0f;
// reset the number of sent avatars
nodeData->resetNumAvatarsSentLastFrame();
// keep a counter of the number of considered avatars
int numOtherAvatars = 0;
// keep track of outbound data rate specifically for avatar data
int numAvatarDataBytes = 0;
// keep track of the number of other avatars held back in this frame
int numAvatarsHeldBack = 0;
// keep track of the number of other avatar frames skipped
int numAvatarsWithSkippedFrames = 0;
// use the data rate specifically for avatar data for FRD adjustment checks
float avatarDataRateLastSecond = nodeData->getOutboundAvatarDataKbps();
// When this is true, the AvatarMixer will send Avatar data to a client about avatars that are not in the view frustrum
bool getsOutOfView = nodeData->getRequestsDomainListData();
// When this is true, the AvatarMixer will send Avatar data to a client about avatars that they've ignored
bool getsIgnoredByMe = getsOutOfView;
// When this is true, the AvatarMixer will send Avatar data to a client about avatars that have ignored them
bool getsAnyIgnored = getsIgnoredByMe && node->getCanKick();
// Check if it is time to adjust what we send this client based on the observed
// bandwidth to this node. We do this once a second, which is also the window for
// the bandwidth reported by node->getOutboundBandwidth();
if (nodeData->getNumFramesSinceFRDAdjustment() > AVATAR_MIXER_BROADCAST_FRAMES_PER_SECOND) {
const float FRD_ADJUSTMENT_ACCEPTABLE_RATIO = 0.8f;
const float HYSTERISIS_GAP = (1 - FRD_ADJUSTMENT_ACCEPTABLE_RATIO);
const float HYSTERISIS_MIDDLE_PERCENTAGE = (1 - (HYSTERISIS_GAP * 0.5f));
// get the current full rate distance so we can work with it
float currentFullRateDistance = nodeData->getFullRateDistance();
if (avatarDataRateLastSecond > _maxKbpsPerNode) {
// is the FRD greater than the farthest avatar?
// if so, before we calculate anything, set it to that distance
currentFullRateDistance = std::min(currentFullRateDistance, nodeData->getMaxAvatarDistance());
// we're adjusting the full rate distance to target a bandwidth in the middle
// of the hysterisis gap
currentFullRateDistance *= (_maxKbpsPerNode * HYSTERISIS_MIDDLE_PERCENTAGE) / avatarDataRateLastSecond;
nodeData->setFullRateDistance(currentFullRateDistance);
nodeData->resetNumFramesSinceFRDAdjustment();
} else if (currentFullRateDistance < nodeData->getMaxAvatarDistance()
&& avatarDataRateLastSecond < _maxKbpsPerNode * FRD_ADJUSTMENT_ACCEPTABLE_RATIO) {
// we are constrained AND we've recovered to below the acceptable ratio
// lets adjust the full rate distance to target a bandwidth in the middle of the hyterisis gap
currentFullRateDistance *= (_maxKbpsPerNode * HYSTERISIS_MIDDLE_PERCENTAGE) / avatarDataRateLastSecond;
nodeData->setFullRateDistance(currentFullRateDistance);
nodeData->resetNumFramesSinceFRDAdjustment();
}
} else {
nodeData->incrementNumFramesSinceFRDAdjustment();
}
// setup a PacketList for the avatarPackets
auto avatarPacketList = NLPacketList::create(PacketType::BulkAvatarData);
// this is an AGENT we have received head data from
// send back a packet with other active node data to this node
std::for_each(_begin, _end, [&](const SharedNodePointer& otherNode) {
bool shouldConsider = false;
quint64 startIgnoreCalculation = usecTimestampNow();
// make sure we have data for this avatar, that it isn't the same node,
// and isn't an avatar that the viewing node has ignored
// or that has ignored the viewing node
if (!otherNode->getLinkedData()
|| otherNode->getUUID() == node->getUUID()
|| (node->isIgnoringNodeWithID(otherNode->getUUID()) && !getsIgnoredByMe)
|| (otherNode->isIgnoringNodeWithID(node->getUUID()) && !getsAnyIgnored)) {
shouldConsider = false;
} else {
const AvatarMixerClientData* otherData = reinterpret_cast<AvatarMixerClientData*>(otherNode->getLinkedData());
shouldConsider = true; // assume we will consider...
// Check to see if the space bubble is enabled
if (node->isIgnoreRadiusEnabled() || otherNode->isIgnoreRadiusEnabled()) {
// Define the minimum bubble size
static const glm::vec3 minBubbleSize = glm::vec3(0.3f, 1.3f, 0.3f);
// Define the scale of the box for the current node
glm::vec3 nodeBoxScale = (nodeData->getPosition() - nodeData->getGlobalBoundingBoxCorner()) * 2.0f;
// Define the scale of the box for the current other node
glm::vec3 otherNodeBoxScale = (otherData->getPosition() - otherData->getGlobalBoundingBoxCorner()) * 2.0f;
// Set up the bounding box for the current node
AABox nodeBox(nodeData->getGlobalBoundingBoxCorner(), nodeBoxScale);
// Clamp the size of the bounding box to a minimum scale
if (glm::any(glm::lessThan(nodeBoxScale, minBubbleSize))) {
nodeBox.setScaleStayCentered(minBubbleSize);
}
// Set up the bounding box for the current other node
AABox otherNodeBox(otherData->getGlobalBoundingBoxCorner(), otherNodeBoxScale);
// Clamp the size of the bounding box to a minimum scale
if (glm::any(glm::lessThan(otherNodeBoxScale, minBubbleSize))) {
otherNodeBox.setScaleStayCentered(minBubbleSize);
}
// Quadruple the scale of both bounding boxes
nodeBox.embiggen(4.0f);
otherNodeBox.embiggen(4.0f);
// Perform the collision check between the two bounding boxes
if (nodeBox.touches(otherNodeBox)) {
nodeData->ignoreOther(node, otherNode);
shouldConsider = getsAnyIgnored;
}
}
// Not close enough to ignore
if (shouldConsider) {
nodeData->removeFromRadiusIgnoringSet(node, otherNode->getUUID());
}
quint64 endIgnoreCalculation = usecTimestampNow();
_stats.ignoreCalculationElapsedTime += (endIgnoreCalculation - startIgnoreCalculation);
}
if (shouldConsider) {
quint64 startAvatarDataPacking = usecTimestampNow();
++numOtherAvatars;
const AvatarMixerClientData* otherNodeData = reinterpret_cast<const AvatarMixerClientData*>(otherNode->getLinkedData());
// make sure we send out identity packets to and from new arrivals.
bool forceSend = !nodeData->checkAndSetHasReceivedFirstPacketsFrom(otherNode->getUUID());
// FIXME - this clause seems suspicious "... || otherNodeData->getIdentityChangeTimestamp() > _lastFrameTimestamp ..."
if (otherNodeData->getIdentityChangeTimestamp().time_since_epoch().count() > 0
&& (forceSend
|| otherNodeData->getIdentityChangeTimestamp() > _lastFrameTimestamp
|| distribution(generator) < IDENTITY_SEND_PROBABILITY)) {
sendIdentityPacket(otherNodeData, node);
}
const AvatarData* otherAvatar = otherNodeData->getConstAvatarData();
// Decide whether to send this avatar's data based on it's distance from us
// The full rate distance is the distance at which EVERY update will be sent for this avatar
// at twice the full rate distance, there will be a 50% chance of sending this avatar's update
glm::vec3 otherPosition = otherAvatar->getClientGlobalPosition();
float distanceToAvatar = glm::length(myPosition - otherPosition);
// potentially update the max full rate distance for this frame
maxAvatarDistanceThisFrame = std::max(maxAvatarDistanceThisFrame, distanceToAvatar);
// This code handles the random dropping of avatar data based on the ratio of
// "getFullRateDistance" to actual distance.
//
// NOTE: If the recieving node is in "PAL mode" then it's asked to get things even that
// are out of view, this also appears to disable this random distribution.
if (distanceToAvatar != 0.0f
&& !getsOutOfView
&& distribution(generator) > (nodeData->getFullRateDistance() / distanceToAvatar)) {
quint64 endAvatarDataPacking = usecTimestampNow();
_stats.avatarDataPackingElapsedTime += (endAvatarDataPacking - startAvatarDataPacking);
shouldConsider = false;
}
if (shouldConsider) {
AvatarDataSequenceNumber lastSeqToReceiver = nodeData->getLastBroadcastSequenceNumber(otherNode->getUUID());
AvatarDataSequenceNumber lastSeqFromSender = otherNodeData->getLastReceivedSequenceNumber();
// FIXME - This code does appear to be working. But it seems brittle.
// It supports determining if the frame of data for this "other"
// avatar has already been sent to the reciever. This has been
// verified to work on a desktop display that renders at 60hz and
// therefore sends to mixer at 30hz. Each second you'd expect to
// have 15 (45hz-30hz) duplicate frames. In this case, the stat
// avg_other_av_skips_per_second does report 15.
//
// make sure we haven't already sent this data from this sender to this receiver
// or that somehow we haven't sent
if (lastSeqToReceiver == lastSeqFromSender && lastSeqToReceiver != 0) {
++numAvatarsHeldBack;
quint64 endAvatarDataPacking = usecTimestampNow();
_stats.avatarDataPackingElapsedTime += (endAvatarDataPacking - startAvatarDataPacking);
shouldConsider = false;
} else if (lastSeqFromSender - lastSeqToReceiver > 1) {
// this is a skip - we still send the packet but capture the presence of the skip so we see it happening
++numAvatarsWithSkippedFrames;
}
// we're going to send this avatar
if (shouldConsider) {
// determine if avatar is in view, to determine how much data to include...
glm::vec3 otherNodeBoxScale = (otherPosition - otherNodeData->getGlobalBoundingBoxCorner()) * 2.0f;
AABox otherNodeBox(otherNodeData->getGlobalBoundingBoxCorner(), otherNodeBoxScale);
bool isInView = nodeData->otherAvatarInView(otherNodeBox);
// this throttles the extra data to only be sent every Nth message
if (!isInView && !getsOutOfView && (lastSeqToReceiver % EXTRA_AVATAR_DATA_FRAME_RATIO > 0)) {
quint64 endAvatarDataPacking = usecTimestampNow();
_stats.avatarDataPackingElapsedTime += (endAvatarDataPacking - startAvatarDataPacking);
shouldConsider = false;
}
if (shouldConsider) {
// start a new segment in the PacketList for this avatar
avatarPacketList->startSegment();
AvatarData::AvatarDataDetail detail;
if (!isInView && !getsOutOfView) {
detail = AvatarData::MinimumData;
nodeData->incrementAvatarOutOfView();
} else {
detail = distribution(generator) < AVATAR_SEND_FULL_UPDATE_RATIO
? AvatarData::SendAllData : AvatarData::CullSmallData;
nodeData->incrementAvatarInView();
}
{
bool includeThisAvatar = true;
auto lastEncodeForOther = nodeData->getLastOtherAvatarEncodeTime(otherNode->getUUID());
QVector<JointData>& lastSentJointsForOther = nodeData->getLastOtherAvatarSentJoints(otherNode->getUUID());
bool distanceAdjust = true;
glm::vec3 viewerPosition = myPosition;
AvatarDataPacket::HasFlags hasFlagsOut; // the result of the toByteArray
bool dropFaceTracking = false;
quint64 start = usecTimestampNow();
QByteArray bytes = otherAvatar->toByteArray(detail, lastEncodeForOther, lastSentJointsForOther,
hasFlagsOut, dropFaceTracking, distanceAdjust, viewerPosition, &lastSentJointsForOther);
quint64 end = usecTimestampNow();
_stats.toByteArrayElapsedTime += (end - start);
static const int MAX_ALLOWED_AVATAR_DATA = (1400 - NUM_BYTES_RFC4122_UUID);
if (bytes.size() > MAX_ALLOWED_AVATAR_DATA) {
qCWarning(avatars) << "otherAvatar.toByteArray() resulted in very large buffer:" << bytes.size() << "... attempt to drop facial data";
dropFaceTracking = true; // first try dropping the facial data
bytes = otherAvatar->toByteArray(detail, lastEncodeForOther, lastSentJointsForOther,
hasFlagsOut, dropFaceTracking, distanceAdjust, viewerPosition, &lastSentJointsForOther);
if (bytes.size() > MAX_ALLOWED_AVATAR_DATA) {
qCWarning(avatars) << "otherAvatar.toByteArray() without facial data resulted in very large buffer:" << bytes.size() << "... reduce to MinimumData";
bytes = otherAvatar->toByteArray(AvatarData::MinimumData, lastEncodeForOther, lastSentJointsForOther,
hasFlagsOut, dropFaceTracking, distanceAdjust, viewerPosition, &lastSentJointsForOther);
}
if (bytes.size() > MAX_ALLOWED_AVATAR_DATA) {
qCWarning(avatars) << "otherAvatar.toByteArray() MinimumData resulted in very large buffer:" << bytes.size() << "... FAIL!!";
includeThisAvatar = false;
}
}
if (includeThisAvatar) {
numAvatarDataBytes += avatarPacketList->write(otherNode->getUUID().toRfc4122());
numAvatarDataBytes += avatarPacketList->write(bytes);
_stats.numOthersIncluded++;
// increment the number of avatars sent to this reciever
nodeData->incrementNumAvatarsSentLastFrame();
// set the last sent sequence number for this sender on the receiver
nodeData->setLastBroadcastSequenceNumber(otherNode->getUUID(),
otherNodeData->getLastReceivedSequenceNumber());
}
}
avatarPacketList->endSegment();
quint64 endAvatarDataPacking = usecTimestampNow();
_stats.avatarDataPackingElapsedTime += (endAvatarDataPacking - startAvatarDataPacking);
}
}
}
}
});
quint64 startPacketSending = usecTimestampNow();
// close the current packet so that we're always sending something
avatarPacketList->closeCurrentPacket(true);
_stats.numPacketsSent += (int)avatarPacketList->getNumPackets();
_stats.numBytesSent += numAvatarDataBytes;
// send the avatar data PacketList
nodeList->sendPacketList(std::move(avatarPacketList), *node);
// record the bytes sent for other avatar data in the AvatarMixerClientData
nodeData->recordSentAvatarData(numAvatarDataBytes);
// record the number of avatars held back this frame
nodeData->recordNumOtherAvatarStarves(numAvatarsHeldBack);
nodeData->recordNumOtherAvatarSkips(numAvatarsWithSkippedFrames);
if (numOtherAvatars == 0) {
// update the full rate distance to FLOAT_MAX since we didn't have any other avatars to send
nodeData->setMaxAvatarDistance(FLT_MAX);
} else {
nodeData->setMaxAvatarDistance(maxAvatarDistanceThisFrame);
}
quint64 endPacketSending = usecTimestampNow();
_stats.packetSendingElapsedTime += (endPacketSending - startPacketSending);
}
quint64 end = usecTimestampNow();
_stats.jobElapsedTime += (end - start);
}
| 23944663161bbbca3bbc978033c8f2530a328179 | [
"JavaScript",
"C++"
] | 2 | JavaScript | KevinFrutiger/hifi | 44136e550c8230af4176c3bc9131f0b2aceb4ebb | 1f5ed37cdb49f21e69f209c1c03163e5957daff2 |
refs/heads/master | <repo_name>orma/openroads-vn-deploy<file_sep>/.env.example
AWS_REGION='us-east-1'
AWS_ACCESS_KEY_ID=''
AWS_SECRET_ACCESS_KEY=''
MAPBOX_ACCOUNT=''
MAPBOX_ACCESS_TOKEN=''
<file_sep>/docker-compose.yaml
version: "2"
services:
db:
image: developmentseed/openroads-vn-db:latest
build: ./openroads-vn-api/db/
# container_name: vn-api-db
ports:
- "5433:5432"
environment:
- POSTGRES_DB=openroads
api:
image: developmentseed/openroads-vn-api:latest
build: ./openroads-vn-api/
env_file: .env
depends_on:
- db
ports:
- "4000:4000"
environment:
- DATABASE_URL=postgres://postgres@db:5432/openroads
vn-tiler:
image: developmentseed/openroads-vn-tiler:latest
env_file: .env
command: ./cron.sh
environment:
- S3_TEMPLATE=s3://openroads-vn-tiles/tiles/{z}/{x}/{y}.vector.pbf
- S3_DUMP_BUCKET=openroads-vn-dumps
- DATABASE_URL=postgres://postgres@db:5432/openroads
vn-analytics:
image: developmentseed/openroads-vn-analytics:latest
build: ./openroads-vn-analytics/
env_file: .env
ports:
- "8000:3000"
- "8001:3001"
id-editor:
image: developmentseed/openroads-vn-id-editor:latest
build: ./openroads-vn-id-editor/
env_file: .env
ports:
- "5000:5000"
tilemap:
image: developmentseed/openroads-tilemap:latest
env_file: .env
ports:
- "3000:3000"
environment:
- BUCKET_URL=http://openroads-vn-tiles.s3-website-us-east-1.amazonaws.com/tiles
nginx:
image: developmentseed/openroads-nginx:latest
build: ./nginx/
env_file: .env
ports:
- "80:80"
depends_on:
- api
- id-editor
- vn-analytics
- tilemap
<file_sep>/openroads-vn-analytics/Dockerfile
FROM node:8.16.0
ENV workdir /var/www
RUN apt-get install git
RUN npm install -g yarn
RUN git clone https://github.com/orma/openroads-vn-analytics.git $workdir
WORKDIR $workdir
RUN yarn install
CMD ["yarn", "run", "serve"]
<file_sep>/README.md
### Docker-compose Setup for Standalone Deploy
Contains a `docker-compose` setup that runs all the containers needed to run `openroads`.
Runs the following containers as HTTP services:
- The OpenRoads API
- The OpenRoads Analytics Frontend
- The OpenRoads Editor
- Tilemap - TODO
This is connected to a database container (the database can optionally be run externally).
TODO: Add container to run `tiler` service as a cronjob
An Nginx container will run on port 80 and proxy traffic to the other containers. It will forward to other containers based on the host URL. To test locally, you need to add the following to your `/etc/hosts` file:
```
127.0.0.1 openroads-vn.com
127.0.0.1 api.openroads-vn.com
127.0.0.1 editor.openroads-vn.com
```
To run locally:
The `openroads-vn-api` repository is included as a git submodule. You will need to:
git submodule update --init --recursive
Copy `.env.example` to `.env` and edit as required.
After that you can run:
docker-compose build && docker-compose up
If you have made the changes to yours hosts file as described above, you should now be able to visit http://openroads-vn.com, http://editor.openroads-vn.com and http://api.openroads-vn.com in your browser and they will be served locally.
<file_sep>/openroads-vn-id-editor/Dockerfile
FROM node:8
ENV workdir /var/www
RUN apt-get install git
RUN npm install -g serve
RUN git clone https://github.com/orma/openroads-vn-iD.git $workdir
WORKDIR $workdir
CMD ["serve"]
| 3551bc482ebfe432e30d131920a1784a225444cf | [
"Markdown",
"YAML",
"Dockerfile",
"Shell"
] | 5 | Shell | orma/openroads-vn-deploy | c8d89bbaf974f941866393fddd1e1e911cbc8d56 | 5df0a906a35cb38db6d10c379922f9a5b15dea8a |
refs/heads/master | <file_sep># JesmCalendar
Datepicker made with the help of my JS library "Jesm".
[See it live](http://jesm.github.io/JesmCalendar/example/index.html)
<file_sep>'use strict';
Jesm.Calendar=Jesm.createClass({
__construct:function(config){
this.cfg={
meses:['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
dias:['D','2ª','3ª','4ª','5ª','6ª','S'],
divisor:'/',
comecoSemana:0,
diaInicio:new Date(),
fecharText:'Fechar'
};
config=config||{};
for(var str in config)
this.cfg[str]=config[str];
for(var x=2, str=['Passado', 'Futuro'];x--;){
var limite=this.cfg['limite'+str[x]];
if(!limite)
continue;
var timeInicio=this.cfg.diaInicio.getTime(), timeLimite=Jesm.Calendar.limparData(limite).getTime();
if(x?timeLimite<timeInicio:timeLimite>timeInicio){
console.log('Verifique seu limite'+str[x]);
return;
}
}
this.func={
pronto:false,
sit:0,
proxSit:[-1, 1],
numTr:[0, 0],
anos:[],
setas:[true, true],
top:0,
offset:0
};
this.setDiaInicio(this.cfg.diaInicio);
this.els={};
this.animas={};
var THIS=this, frag=document.createDocumentFragment();
this.els.main=Jesm.css(Jesm.el('div', 'class=jesm_calendar', frag), 'opacity:0');
this.animas.opacidade=new Jesm.Anima(this.els.main, 'opacity');
this.els.cabeca=Jesm.el('div', 'class=cabeca', this.els.main);
this.els.setaEsq=Jesm.el('a', 'class=seta esq;href=javascript:void(0)', this.els.cabeca, '◀');
this.els.setaDir=Jesm.el('a', 'class=seta dir;href=javascript:void(0)', this.els.cabeca, '▶');
this.els.titulo=Jesm.el('div', 'class=title', this.els.cabeca);
this.animas.titulo=new Jesm.Anima(this.els.titulo, 'opacity');
this.els.tituloMes=Jesm.el('span', 'class=mes', this.els.titulo);
this.els.tituloDivisor=Jesm.el('span', 'class=divisor', this.els.titulo, this.cfg.divisor);
this.els.tituloAno=Jesm.el('span', 'class=ano', this.els.titulo);
this.els.content=Jesm.el('div', 'class=main', this.els.main);
this.els.diasSemana=Jesm.el('tr', null, Jesm.el('tbody', null, Jesm.el('table', 'class=head', this.els.content)));
for(var x=0;x<7;Jesm.el('th', null, this.els.diasSemana, this.cfg.dias[(this.cfg.comecoSemana+(x++))%7]));
this.els.tables=Jesm.el('div', 'class=tables', this.els.content);
this.animas.altura=new Jesm.Anima(this.els.tables, 'height');
this.els.meses=Jesm.el('div', 'class=meses', this.els.tables);
this.animas.cima=new Jesm.Anima(this.els.meses, 'margin-top');
this.els.tabelaMeses=Jesm.el('table', null, this.els.meses);
this.els.tabelaMesesBody=Jesm.el('tbody', null, this.els.tabelaMeses);
this.els.fechar=Jesm.el('a', 'class=fechar;href=javascript:void(0)', this.els.content, this.cfg.fecharText);
Jesm.addEvento(this.els.fechar, 'click', this.fechar, this);
if(this.cfg.hoje){
this.els.hoje=Jesm.el('a', 'class=hoje', this.els.content);
Jesm.addEvento(this.els.hoje, 'click', this.irDiaAtual, this);
}
(config.elHolder||document.body).appendChild(frag);
Jesm.addEvento(this.els.setaEsq, 'click', this._previousArrowFunc, this);
Jesm.addEvento(this.els.setaDir, 'click', this._nextArrowFunc, this);
if(config.clickOut){
Jesm.addEvento(document.body, 'click', this._closeButton, this);
Jesm.addEvento(this.els.main, 'click', this._stopPropag);
}
},
_previousArrowFunc:function(){
if(this.func.setas[0])
this.mover(-1);
},
_nextArrowFunc:function(){
if(this.func.setas[1])
this.mover(1);
},
_closeButton:function(){
this.fechar();
},
_stopPropag:function(e){
e.stopPropagation();
},
andarMes:function(data, num){
var nova=data.slice();
for(var um=num>0?1:-1;num;num+=um*-1){
nova[1]+=um;
if(Jesm.Cross.indexOf([-1, 12], nova[1])>-1){
nova[1]=(nova[1]+12)%12;
nova[0]+=um;
}
}
return nova;
},
toDate:function(d){
return new Date(d[0], d[1], d[2]||1, 0, 0, 0, 0);
},
toArray:function(d){
return [d.getFullYear(), d.getMonth()];
},
compararDatas:function(d1, d2){
if(d1[0]==d2[0]&&d1[1]==d2[1])
return 0;
else
return (d1[0]<d2[0]||(d1[0]==d2[0]&&d1[1]<d2[1]))?1:-1;
},
diferencaData:function(d){
d=this.toArray(d);
var ret=0;
for(var x=0, ma=this.func.mesAtual, cmp;x<2;x++){
cmp=this.compararDatas(d, ma);
while(d[x]!=ma[x]){
ret+=(x?1:12)*cmp;
d[x]+=cmp;
}
}
return ret;
},
formatar:function(str, d){
var temp={d:'Date',m:'Month',Y:'FullYear'};
for(var p in temp){
var valor=d['get'+temp[p]]();
if(p=='m')
valor++;
if(valor<10)
valor='0'+valor;
str=str.replace(p, valor);
}
return str;
},
mover:function(num){
var indo=num>0, um=indo?1:-1, mesVeio=this.func.mesAtual;
this.openFrag(indo);
for(;num;num+=um*-1){
if(indo){
var objMes=this.getMes();
this.func.offset+=objMes.linhas-+objMes.colide[1];
}
this.func.mesAtual=this.andarMes(this.func.mesAtual, um);
var pos=Jesm.Cross.indexOf(this.func.proxSit, this.func.sit+=um);
if(pos>-1){
this.func.proxSit[pos]+=um;
this.addMes(indo);
var objMes=this.getMes().verificar();
this.getMes(this.andarMes(this.func.mesAtual, um)).verificar();
if(!indo)
this.func.top+=objMes.linhas-+objMes.colide[1];
}
if(!indo){
var objMes=this.getMes();
this.func.offset-=objMes.linhas-+objMes.colide[1];
}
}
this.closeFrag();
this.getMes(mesVeio).alterarDias(function(){
this.setAtual(false);
});
this.getMes().alterarDias(function(){
this.setAtual(true);
});
this.updateMedidas().verificarSetas().atualizarMes();
},
addMes:function(indo){
var objMesAtual=this.getMes(),
totalDias=objMesAtual.diasNoMes,
diaSemana=objMesAtual.diaSemana,
frag=document.createDocumentFragment(),
tr=Jesm.el('tr', null, frag);
// faz os dias do mes anterior
var objMes=this.getMes(this.andarMes(this.func.mesAtual, -1)), numDias=objMes.diasNoMes;
if(!(indo&&this.func.pronto)&&diaSemana){
for(var dia=numDias-diaSemana;++dia<=numDias;objMes.addDia(dia, tr));
objMesAtual.colide[0]=objMes.colide[1]=true;
objMes.linhas=1;
}
// faz os dias do mes atual
var dia=1;
if(indo&&this.func.pronto&&diaSemana){
dia+=7-diaSemana;
diaSemana=0;
objMesAtual.linhas=1;
}
for(var faltam=totalDias-dia+1;faltam>=7||diaSemana;faltam--, diaSemana=(diaSemana+1)%7, dia++){
objMesAtual.addDia(dia, tr);
if(diaSemana==6){
objMesAtual.linhas++;
if(faltam)
tr=Jesm.el('tr', null, frag);
}
}
// faz os dias do proximo mes
var objMes=this.getMes(this.andarMes(this.func.mesAtual, 1));
if(indo&&dia<=totalDias){
while(dia<=totalDias){
objMesAtual.addDia(dia++, tr);
diaSemana++;
}
for(dia=1;diaSemana++<7;objMes.addDia(dia++, tr));
objMesAtual.linhas++;
objMes.linhas++;
objMesAtual.colide[1]=objMes.colide[0]=true;
}
this.els.frag.insertBefore(frag, indo?null:this.els.frag.firstChild);
},
getMes:function(d){
var THIS=this, anos=this.func.anos;
d=d||this.func.mesAtual;
if(!anos[d[0]])
anos[d[0]]=[];
if(!anos[d[0]][d[1]]){
var novoMes={
lista:[],
linhas:0,
colide:[false, false],
verificar:function(){
var fun, at=[true, true];
for(var strs=['Passado', 'Futuro'], x=strs.length;x--;){
var timeLimite=THIS.cfg['limite'+strs[x]];
if(!timeLimite)
continue;
var arrLimite=THIS.toArray(timeLimite), cmp=THIS.compararDatas(arrLimite, d);
if(!cmp){
fun=function(){
var timeTemp=THIS.toDate(this.data).getTime(), cmp1=true, cmp2=true;
if(THIS.cfg.limitePassado)
cmp1=timeTemp>=THIS.cfg.limitePassado.getTime();
if(THIS.cfg.limiteFuturo)
cmp2=timeTemp<=THIS.cfg.limiteFuturo.getTime();
this.setAtivo(cmp1&&cmp2);
};
break;
}
else
at[x]=cmp!=(x?1:-1);
}
if(!fun){
fun=function(){
this.setAtivo(at[0]&&at[1]);
};
}
this.alterarDias(fun);
return this;
},
addDia:function(dia, tr){
var ret={
data:[d[0], d[1], dia],
el:Jesm.el('a', 'href=javascript:void(0)', Jesm.el('td', null, tr), dia),
setAtivo:function(bool){
this.el.classList[(this.ativo=bool)?'add':'remove']('ativo');
},
setAtual:function(bool){
this.el.classList[(this.ativo=bool)?'add':'remove']('atual');
}
};
ret.el.onclick=function(){
if(ret.ativo)
THIS.clique(ret);
};
this.lista[dia]=ret;
return ret;
},
alterarDias:function(fun){
for(var x=this.lista.length;--x;){
var dia=this.lista[x];
if(!dia)
break;
fun.call(dia);
}
}
};
switch(d[1]){
case 3: case 5: case 8: case 10:
novoMes.diasNoMes=30;
break;
case 1:
var ano=d[0];
novoMes.diasNoMes=((!(ano%4)&&ano%100)||!(ano%400))?29:28;
break;
default:
novoMes.diasNoMes=31;
}
novoMes.diaSemana=(this.toDate(d).getDay()-this.cfg.comecoSemana+7)%7;
anos[d[0]][d[1]]=novoMes;
}
return anos[d[0]][d[1]];
},
setLimite:function(str, d){
str=str.toLowerCase().split('');
str[0]=str[0].toUpperCase();
str=str.join('');
this.cfg['limite'+str]=d;
var dif=this.compararDatas(this.toArray(d), this.func.mesAtual)==(str=='Passado'?-1:1);
if(this.func.pronto){
for(var x=this.func.anos.length, anoAtual;x--&&(anoAtual=this.func.anos[x]);)
for(var y=anoAtual.length, mesAtual;y--&&(mesAtual=anoAtual[y]);mesAtual.verificar());
if(dif)
this.mover(-this.diferencaData(d));
else
this.verificarSetas();
}
else if(dif)
this.setDiaInicio(d);
},
openFrag:function(indo){
this.func.indo=indo;
this.els.frag=document.createDocumentFragment();
},
closeFrag:function(){
var tab=this.els.tabelaMesesBody;
tab.insertBefore(this.els.frag, this.func.indo?null:tab.firstChild);
},
atualizarMes:function(){
var THIS=this;
this.animas.titulo.go(.25, [0], function(){
THIS.els.tituloMes.innerHTML=THIS.cfg.meses[THIS.func.mesAtual[1]];
THIS.els.tituloAno.innerHTML=THIS.func.mesAtual[0];
this.go(.25, [1]);
});
return this;
},
abrir:function(x, y){
Jesm.css(this.els.main, 'display:block;left:'+x+'px;top:'+y+'px');
this.animas.opacidade.go(.5, [1]);
if(!this.func.pronto)
this.iniciar();
this.updateMedidas();
return this;
},
fechar:function(destroy){
var callback='none';
if(destroy===true){
var THIS=this;
callback=function(){
THIS.destroy();
};
}
this.animas.opacidade.go(.25, [0], callback);
return this;
},
destroy:function(){
this.els.main.del();
},
clique:function(td){
if(this.onselect)
this.onselect(this.toDate(td.data));
this.fechar();
},
associarInput:function(input, depois){
this.els.input=input;
this.onselect=depois||function(d){
this.els.input.value=this.formatar('d/m/Y', d);
this.els.input.blur();
};
Jesm.addEvento(input, 'focus', function(){
var dimTela=(this.cfg.elHolder?Jesm.Cross.offsetSize(this.cfg.elHolder):Jesm.Cross.inner())[0], disEl=Jesm.Cross.offset(input), dimEl=Jesm.Cross.client(input), left, top;
if(dimTela-disEl[0]-dimEl[0]>250){
left=disEl[0]+dimEl[0]+10;
top=disEl[1];
}
else{
var temp=(dimEl[0]<=250)?dimEl[0]-250:0;
left=disEl[0]+temp;
top=disEl[1]+dimEl[1]+10;
}
this.abrir(left, top);
}, this);
return this;
},
verificarSetas:function(){
for(var x=2, str=['Esq', 'Dir'], str1=['Passado', 'Futuro'];x--;){
var limite=this.cfg['limite'+str1[x]];
if(limite){
var confere=limite&&this.func.mesAtual[0]==limite.getFullYear()&&this.func.mesAtual[1]==limite.getMonth();
Jesm.css(this.els['seta'+str[x]], 'visibility:'+(this.func.setas[x]=!confere?'visible':'hidden'));
}
}
return this;
},
updateMedidas:function(){
var alturaTd=Jesm.Cross.offsetSize(this.els.tabelaMeses.pega('td', 0))[1];
this.els.tabelaMeses.style.top='-'+(this.func.top*alturaTd)+'px';
this.animas.altura.go(.5, [this.getMes().linhas*alturaTd]);
this.animas.cima.go(.5, [-this.func.offset*alturaTd]);
return this;
},
iniciar:function(){
this.openFrag(true);
this.addMes(true);
this.closeFrag();
this.mover(0);
this.getMes().verificar();
this.getMes(this.andarMes(this.func.mesAtual, -1)).verificar();
this.getMes(this.andarMes(this.func.mesAtual, 1)).verificar();
this.atualizarMes();
this.func.pronto=true;
if(Jesm.Core.drag){
this.els.titulo.classList.add('grab');
var drag = new Jesm.Drag(this.els.main, null, this.els.titulo);
drag.data.calendar = this;
drag.onDragStart = this._dragStartAux;
drag.onDrop = this._dropAux;
}
},
_dragStartAux:function(){
this.data.calendar.animas.opacidade.go(.25, [.7]);
},
_dropAux:function(){
Jesm.css(this.data.calendar.els.main, {
left: this.lastCoord[0],
top: this.lastCoord[1]
});
this.data.calendar.animas.opacidade.go(.25, [1]);
},
setDiaInicio: function(date){
if(!this.func.pronto)
this.func.mesAtual = this.toArray(this.cfg.diaInicio = date);
}
});
Jesm.Calendar.limparData = function(date){
for(var strs = ['Hours', 'Minutes', 'Seconds', 'Milliseconds'], len = strs.length; len--;)
date['set' + strs[len]](0);
return date;
}; | ce597f432d3917229a5db7d868fd11669300b6fd | [
"Markdown",
"JavaScript"
] | 2 | Markdown | Jesm/JesmCalendar | f6e1ff978fe2a535e059bbb1d29c397f862be401 | 3971c4b65c9ca2924ca267914043b604a217badc |
refs/heads/master | <file_sep>package prob01;
public class StringUtil {
public static String concatenate(String[] strArr) {
String resultStr = "";
for(int i=0; i<strArr.length;i++) {
resultStr = resultStr+strArr[i];
}
return resultStr;
}
}
| b23df31761df24de3414cd160ef60b25f9191e4c | [
"Java"
] | 1 | Java | ksyk1205/java-practice03 | 3fe5a69b1b0d5e20eceaa795b8f9623a62cfb7e4 | 11ce9cd02093fa9e968c387a4b4375404fb5bd6a |
refs/heads/master | <repo_name>foxtrot12/foxtrot2<file_sep>/test.cpp
#include <iostream.h>
#include <conio.h>
void main()
{
cout<<"Test";
getch();
}
| 1e3d6fb35430375e40018cd0c4451b110cc42a8a | [
"C++"
] | 1 | C++ | foxtrot12/foxtrot2 | 1076d8766c3835791d58cfb61e200eee4ada64e4 | dbbda7ef20f244631be53dce7cb56130acc4342e |
refs/heads/master | <file_sep>#!/bin/zsh-4.3.10
# local設定の読み込み
if [ -e "${HOME}/.zshrc_local" ]; then
source "${HOME}/.zshrc_local"
fi
########################################################
#PATHの設定
########################################################
# 基本的なやつ
export PATH=/opt/local/bin:/opt/local/sbin/:$PATH
# Go関係
export GOPATH=$HOME/go
export PATH=$GOPATH/bin:$PATH
export PATH=/usr/local/go/bin:$PATH
# Android
export PATH=$HOME/Library/Android/sdk/platform-tools/:$PATH
# /usr/local/bin を優先して読むために先頭に追加
export PATH=/usr/local/bin:$PATH
# その他
export MANPATH=/opt/local/man:$MANPATH
export PIP_DOWNLOAD_CACHE=$HOME/.pip_download_cache #pipのダウンロードキャッシュ
#見つからないのでコメントアウト
#source /usr/local/bin/virtualenvwrapper.sh
#########################################################
#補完の設定
#########################################################
autoload -U compinit #補完設定
compinit
setopt list_packed #補完候補を詰めて表示
setopt auto_list #補完候補が複数のとき、C-dなしでリストを表示。
setopt always_last_prompt #補完候補を表示した後、カーソルは編集中の行に復帰
setopt complete_in_word #カーソルの位置に補うことで単語を完成させる
setopt list_types #補完候補にファイル種を標示
setopt auto_list auto_param_slash list_packed rec_exact
unsetopt list_beep
zstyle ':completion:*' menu select
zstyle ':completion:*' format '%F{white}%d%f'
zstyle ':completion:*' group-name ''
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}'
zstyle ':completion:*' keep-prefix
zstyle ':completion:*' completer _oldlist _complete _match _ignored \
_approximate _list _history
autoload bashcompinit
bashcompinit
##########################################################
#言語設定
#########################################################
export LANG="ja_JP.UTF-8"
export LC_ALL="ja_JP.UTF-8"
export LC_CTYPE="ja_JP.UTF-8"
export LC_TIME=C
export LC_MESSAGES=C
export LC_NUMERIC=C
##########################################################
#プロンプトの設定 http://journal.mycom.co.jp/column/zsh/002/index.html
##########################################################
#PROMPT="[%m:%~] %n%% " # %/はcwdを表す。%%でエスケープシーケンス"%" 。%mでホスト。%nで名前
#PROMPT='[${USER}@${HOSTNAME}] %(!.#.$) '
#通常のプロンプト
PROMPT="%{[04;35m%}[%n]%%%{[m%} "
#PROMPT="%{[35m%}YUKI.N>[m%} "
#右プロンプト
RPROMPT="[%m:%~]"
#二行以上のコマンド用
PROMPT2="%_%% "
#間違った時のプロンプト
SPROMPT="%rのことですの? [n,y,a,e]: "
#terminalに表示されるラベル
case "${TERM}" in
kterm*|xterm*)
precmd(){
echo -ne "\033]0;${USER}@${HOST%%.*}:${PWD}\007"
}
;;
esac
#########################################################
#ヒストリの設定
#########################################################
HISTFILE=~/.zsh_history
HISTSIZE=10000
SAVEHIST=10000
setopt share_history # コマンド履歴の共有
setopt hist_ignore_dups # ignore duplication command history list
setopt share_history # share command history data
setopt hist_save_nodups # ヒストリファイルに保存するとき、すでに重複したコマンドがあったら古い方を削除する
bindkey '^R' history-incremental-pattern-search-backward
bindkey '^S' history-incremental-pattern-search-forward
#########################################################
#その他もろもろ
########################################################
setopt auto_cd #おーとcd ディレクトリ名だけで移動可能
setopt auto_pushd #cd -[tab]で移動履歴を参照
#setopt auto_menu #タブキーで補完候補を順に表示
setopt list_types #補完候補一覧でファイルの種別を識別マーク表示
setopt correct #コマンド自動修正
setopt nolistbeep #ビープを消す
bindkey -e #emacs風keyバインド
setopt list_packed #補完候補を詰めて表示
setopt nolistbeep #beepを消す
setopt no_beep
##########################################################
#シェル変数
#########################################################
[[ $TERM = "eterm-color" ]] && TERM=xterm-color
##########################################################
#色
##########################################################
autoload -U colors
colors
# lsコマンドの補完候補にも色付き表示
zstyle ':completion:*' list-colors ''
# kill の候補にも色付き表示
zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([%0-9]#)*=0=01;31'
#########################################################
#エイリアスの設定
#########################################################
alias vi=vim
alias ls="ls -CGF"
alias la="ls -A"
alias ll="ls -al"
alias screen="screen -s zsh" #screen起動時に$SHELLでなくzshを開く
alias -s py=python
alias g="git"
alias gs="git status"
alias gl="git log"
alias gitop="git rev-parse --show-toplevel"
alias gap="git add -p"
alias gdfc="git diff --cached"
alias pyrar="~/python/py_tools/test.py"
alias pytool="~/python/py_tools/py_rename.py"
alias cb="pbcopy"
alias chkey="open /System/Library/CoreServices/KeyboardSetupAssistant.app"
function chpwd() { ls -FGC } #cdした後に自動でls
# git管理下にいる際に左プロンプトにブランチ名とステータスを表示
autoload -Uz vcs_info
setopt prompt_subst
zstyle ':vcs_info:git:*' check-for-changes true
zstyle ':vcs_info:git:*' stagedstr "%F{yellow}!"
zstyle ':vcs_info:git:*' unstagedstr "%F{red}+"
zstyle ':vcs_info:*' formats "%F{green}%c%u[%b]%f"
zstyle ':vcs_info:*' actionformats '[%b|%a]'
precmd () { vcs_info }
PROMPT=$PROMPT'${vcs_info_msg_0_}'
<file_sep>#!/bin/sh
git config --local user.name "44mol"
git config --local user.email "<EMAIL>"
<file_sep>#!/bin/sh
deploy_files() {
if [ ! -e ~/dotfiles/$1 ]; then
echo "Error!!! : ~/dotfiles/$1 is not exist.";
return;
fi
if [ ! -e ~/$1 ]; then
ln -s ~/dotfiles/$1 ~/$1;
else
echo "Exist : $1";
fi
}
deploy_files .zshrc
deploy_files .screenrc
deploy_files .vimrc
deploy_files .dein.toml
deploy_files .gitconfig
deploy_files .gitignore.global
# vimdoc-ja
if [ ! -e ~/.vim ]; then
mkdir ~/.vim/;
fi
if [ ! -e ~/.vim/doc ]; then
ln -s ~/dotfiles/vimdoc-ja/doc/ ~/.vim/doc;
else
echo "Exist : doc";
fi
if [ ! -e ~/.vim/syntax ]; then
ln -s ~/dotfiles/vimdoc-ja/syntax/ ~/.vim/syntax;
else
echo "Exist : syntax";
fi
if [ ! -e ~/.vim/after ]; then
ln -s ~/dotfiles/.vim/after ~/.vim;
else
echo "Exist : .vim/after/";
fi
<file_sep>[[plugins]]
repo = 'Shougo/dein.vim'
[[plugins]]
repo = 'Shougo/neocomplete.vim'
[[plugins]]
repo = 'scrooloose/nerdtree'
[[plugins]]
repo = 'vim-jp/vim-go-extra'
[[plugins]]
repo = 'fatih/vim-go'
[[plugins]]
repo = 'Shougo/unite.vim'
[[plugins]]
repo = 'simeji/winresizer'
[[plugins]]
repo = 'tpope/vim-surround'
[[plugins]]
repo = 'aklt/plantuml-syntax'
| 29c5e444861efb229be0ac63c7c84a737b3ff98b | [
"TOML",
"Shell"
] | 4 | Shell | molmolken/dotfiles | 5df1d9d33f5e854b5e41f91911647232be031ab6 | 82dc070c12c05ef3a1a978af692c7bcf2bdb7656 |
refs/heads/master | <repo_name>SaumyaRawat/Deep-Learning-Problem-Sets<file_sep>/PS1/README.md
# Deep-Learning-Problem-Sets
Problem Sets implemented for Course: 828L Deep Learning by <NAME>, Fall 2018, UMD
<file_sep>/PS2/README.md
# Due October 9th
# Using keras, write seperate neural networks that
* Classify the data shown in the MNIST data
* Classify the kind of clothing item (pant, shirt, etc.) shown in the Fashion MNISt dataset
* Classify the breast cancer measurements as benign or malignant
* Do this using the best practices discussed in class (i.e. one hot encoding, ReLU, CNNS when you should, etc.)
* Have reasonable hyperparameters
# You will submit
* 3 .py files and .pdf, or 3 jupyter notebook files (*using the most recent version of jupyter*)
* Each much be submitted to the correct assignment for each dataset on ELMNS
# Your submission for each data set must include
* Training and testing accuracy vs epoch plots
* Some sort of reasonable print outs representative of the weight and biases (*not the entire things*)
* The goal of this is to ensure that, for example, all you weights are not 0 (or something akin to that), do what you feel makes sense
* Examples of datapoints that fail in your models
* An explanation of why what you've included for all those things make sense
* An explanation of how/why your network's shape and layer choices, your loss function, and your activation function are correct
* Anything else you did that would convince us that you know what you're doing
# Allowed dependencies
* Keras
* You must use TensorFlow as your backend; this will impact your data shape for CNNS
* Tensorflow
* TensorBoard
* NumPy
* SciPy
* matplotlib
* SK-Learn
* You can only use the preprocessing tools
* seaborn
* Wrapper for matplotlib that makes it not-terrible to use and easier to read/grade, I encourage you to use it
* Other PyData ecosystem tools may be added upon request with a good reason, misc tools (i.e. a custom progress bar package) will not be allowed for the sanity of the TAs
* You may *not* depend on python-mnist (used in some of the preprocessing scripts)
# Notes
* Make sure to scale your data from 0 to 1 and convert it to float32 before using it
* You must use single precision for all computations for this task
* Each folder includes the original data, and my processing code (which contains the original data source)
* If you can find a meaningful bug in the data processing code, some sort of extra credit will be awarded
* Make sure you split the data into testing and training sets in your code
* You must use Python 3.5 or greater
* The code you give us should be a formality, everything should be laid out in the pdf or clearly explained in Jupyter notebook (in English and without a bunch of extra outputs)
* If you're on the fence about Python+pdf vs a jupyter notebook, please use Python+pdf (it's easier for us to grade)
* Please include seperate .pdf, .py, or jupyter files for each model
* Making submissions shorter faster/easier to grade is better for both of us (please don't be unnescesarily verbose)
* 6 total pages of pdfs (with *large* figures, spacing, etc) is the absolute maximum you should be submitting (or the equivalent for jupyter notebooks)
* Please make sure that the write up isn't in broken or incoherent English (please don't do it after being awake for 30 hours straight, etc.)
* You're allowed to do some models in Jupyter and some in .py+.pdf, but please dont; making things easier for the TAs is better for you too
* The best way to get logistical/administrative questions about this assignment answered is to come to Justin's office hours (MW 5-6 in AVW 4101/4103)
* That's also the best way to get weird Linux problems answered
* Ask Chen about weird macOS problems
* All computations/machine learning must be done in Keras. Don't see that NumPy, etc. are allowed dependencies and do something weird.
* If you're doing this on a Windows system and have any issues beyond your Python code (i.e. "TensorFlow won't work/install right"), we can't help you
* None of these tools were designed for Windows and using Windows with them a terrible idea; even Microsoft's data science and ML people generally don't anymore
* Please dual boot Linux, I can show you the basics during office hours if needed
* Yes, macOS should be fine
* You must start with the datasets as included from this repo, using the processed forms provided in the git repo; when your code is run during grading, this is all that will be available
* You can not specify initial conditions (i.e. via a fixed random seed) in the file you submit
* You're highly encouraged to use a GPU and/or the AVX instructions for training your code when possible
* You aren't allowed to do data augmentation, to pad the data, or do anything similar to those
* If you implement a grid or genetic algorithm search for optimizing hyperparameters, submit your code in a way so that when we run your code *without* having to rerun that portion, that portion won't run by default (but is trivial to enable if needed)
* Your code can't use more than 6GB of ram
* Please don't screw this one up in particular, it'll make grading a mess and will result in a major deduction in points
* The data processing files can not be called by your code
* Your code can not save things to disk, or edit files on disk in any way
* Editing local files is tantamount to cheating
* Any malicious pieces of code caused to be during grading will be considered accademic dishonesty
<file_sep>/PS3/sample_loader.py
import torch
import torchvision.transforms as transforms
imgs = np.load("flower_imgs.npy")
labels = LongTensor(np.load("flower_labels.npy"))
np.random.seed(1234)
np.random.shuffle(arr)
split = int(0.85 * len(arr))
trainX, trainY = imgs[arr[:split]], labels[arr[:split]]
testX, testY = imgs[arr[split:]], labels[arr[split:]]
img_mean = np.mean(np.swapaxes(imgs/255.0,0,1).reshape(3, -1), 1)
img_std = np.std(np.swapaxes(imgs/255.0,0,1).reshape(3, -1), 1)
print("mean: {}, std: {}".format(img_mean, img_std))
class FlowerLoader(torch.utils.data.Dataset):
def __init__(self, x_arr, y_arr, transform=None):
self.x_arr = x_arr
self.y_arr = y_arr
self.transform = transform
def __len__(self):
return self.x_arr.shape[0]
def __getitem__(self, index):
img = self.x_arr[index]
label = self.y_arr[index]
if self.transform is not None:
img = self.transform(img)
return img, label
normalize = transforms.Normalize(mean=list(img_mean),
std=list(img_std))
train_loader = torch.utils.data.DataLoader(
FlowerLoader(trainX, trainY, transforms.Compose([
transforms.ToPILImage(),
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])),
batch_size=batch_size, shuffle=True)
# remove augmentation transforms in test loader
test_loader = torch.utils.data.DataLoader(
FlowerLoader(testX, testY, transforms.Compose([
transforms.ToPILImage(),
transforms.ToTensor(),
normalize,
])),
batch_size=batch_size, shuffle=False)
# sample for iterating over loader
for img, label in train_loader:
img, label = img.to(device), label.to(device)
pred = net(img) | 7001bfa60b7680d0f7f3bbcbd5df59c1adcf0ac0 | [
"Markdown",
"Python"
] | 3 | Markdown | SaumyaRawat/Deep-Learning-Problem-Sets | 79c06334be9b484b225bb6d43ced67d2cd30553d | 98ed3dc91bf152b0d08bbc63bdea99f2b0e6b336 |
refs/heads/master | <repo_name>aebid/cmssw<file_sep>/Validation/SiTrackerPhase2V/python/Phase2TrackerValidationFirstStep_cff.py
import FWCore.ParameterSet.Config as cms
from Validation.SiTrackerPhase2V.Phase2TrackerValidateDigi_cff import *
from Validation.SiTrackerPhase2V.Phase2ITValidateRecHit_cff import *
trackerphase2ValidationSource = cms.Sequence(pixDigiValid
+ otDigiValid
+ rechitValidIT
)
<file_sep>/SimG4CMS/Calo/interface/CaloDetInfo.h
#ifndef SimG4CMS_Calo_CaloDetInfo_H
#define SimG4CMS_Calo_CaloDetInfo_H
#include <iostream>
#include <string>
#include <vector>
#include "G4ThreeVector.hh"
class CaloDetInfo {
public:
CaloDetInfo(unsigned int id, std::string name, G4ThreeVector pos, std::vector<double> par);
CaloDetInfo();
CaloDetInfo(const CaloDetInfo&);
~CaloDetInfo() = default;
uint32_t id() const { return id_; }
std::string name() const { return name_; }
G4ThreeVector pos() const { return pos_; }
std::vector<double> par() const { return par_; }
bool operator<(const CaloDetInfo& info) const;
private:
uint32_t id_;
std::string name_;
G4ThreeVector pos_;
std::vector<double> par_;
};
class CaloDetInfoLess {
public:
bool operator()(const CaloDetInfo* a, const CaloDetInfo* b) { return (a->id() < b->id()); }
bool operator()(const CaloDetInfo a, const CaloDetInfo b) { return (a.id() < b.id()); }
};
std::ostream& operator<<(std::ostream&, const CaloDetInfo&);
#endif
<file_sep>/DQM/SiTrackerPhase2/python/Phase2TrackerDQMFirstStep_cff.py
import FWCore.ParameterSet.Config as cms
from DQM.SiTrackerPhase2.Phase2TrackerMonitorDigi_cff import *
from DQM.SiTrackerPhase2.Phase2ITMonitorRecHit_cff import *
trackerphase2DQMSource = cms.Sequence( pixDigiMon
+ otDigiMon
+rechitMonitorIT
)
<file_sep>/DQM/SiTrackerPhase2/interface/TrackerPhase2DQMUtil.h
#ifndef _DQM_SiTrackerPhase2_Phase2TrackerValidationUtil_h
#define _DQM_SiTrackerPhase2_Phase2TrackerValidationUtil_h
#include "DataFormats/TrackerCommon/interface/TrackerTopology.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DQMServices/Core/interface/MonitorElement.h"
#include "DQMServices/Core/interface/DQMStore.h"
#include <string>
#include <sstream>
namespace phase2tkutil {
std::string getITHistoId(uint32_t det_id, const TrackerTopology* tTopo);
std::string getOTHistoId(uint32_t det_id, const TrackerTopology* tTopo);
typedef dqm::reco::MonitorElement MonitorElement;
typedef dqm::reco::DQMStore DQMStore;
MonitorElement* book1DFromPSet(const edm::ParameterSet& hpars, const std::string& hname, DQMStore::IBooker& ibooker) {
MonitorElement* temp = nullptr;
if (hpars.getParameter<bool>("switch")) {
temp = ibooker.book1D(hpars.getParameter<std::string>("name"),
hpars.getParameter<std::string>("title"),
hpars.getParameter<int32_t>("NxBins"),
hpars.getParameter<double>("xmin"),
hpars.getParameter<double>("xmax"));
}
return temp;
}
MonitorElement* book2DFromPSet(const edm::ParameterSet& hpars, const std::string& hname, DQMStore::IBooker& ibooker) {
MonitorElement* temp = nullptr;
if (hpars.getParameter<bool>("switch")) {
temp = ibooker.book2D(hpars.getParameter<std::string>("name"),
hpars.getParameter<std::string>("title"),
hpars.getParameter<int32_t>("NxBins"),
hpars.getParameter<double>("xmin"),
hpars.getParameter<double>("xmax"),
hpars.getParameter<int32_t>("NyBins"),
hpars.getParameter<double>("ymin"),
hpars.getParameter<double>("ymax"));
}
return temp;
}
MonitorElement* bookProfile1DFromPSet(const edm::ParameterSet& hpars,
const std::string& hname,
DQMStore::IBooker& ibooker) {
MonitorElement* temp = nullptr;
if (hpars.getParameter<bool>("switch")) {
temp = ibooker.bookProfile(hpars.getParameter<std::string>("name"),
hpars.getParameter<std::string>("title"),
hpars.getParameter<int32_t>("NxBins"),
hpars.getParameter<double>("xmin"),
hpars.getParameter<double>("xmax"),
hpars.getParameter<double>("ymin"),
hpars.getParameter<double>("ymax"));
}
return temp;
}
} // namespace phase2tkutil
#endif
<file_sep>/DQM/SiTrackerPhase2/src/TrackerPhase2DQMUtil.cc
#include "DQM/SiTrackerPhase2/interface/TrackerPhase2DQMUtil.h"
std::string phase2tkutil::getITHistoId(uint32_t det_id, const TrackerTopology* tTopo) {
std::string Disc;
std::ostringstream fname1;
int layer = tTopo->getITPixelLayerNumber(det_id);
if (layer < 0)
return "";
if (layer < 100) {
fname1 << "Barrel/";
fname1 << "Layer" << layer;
fname1 << "";
} else {
int side = tTopo->pxfSide(det_id);
fname1 << "EndCap_Side" << side << "/";
int disc = tTopo->pxfDisk(det_id);
Disc = (disc < 9) ? "EPix" : "FPix";
fname1 << Disc << "/";
int ring = tTopo->pxfBlade(det_id);
fname1 << "Ring" << ring;
}
return fname1.str();
}
std::string phase2tkutil::getOTHistoId(uint32_t det_id, const TrackerTopology* tTopo) {
std::string Disc;
std::ostringstream fname1;
int layer = tTopo->getOTLayerNumber(det_id);
if (layer < 0)
return "";
if (layer < 100) {
fname1 << "Barrel/";
fname1 << "Layer" << layer;
fname1 << "";
} else {
int side = tTopo->tidSide(det_id);
fname1 << "EndCap_Side" << side << "/";
int disc = tTopo->tidWheel(det_id);
Disc = (disc < 3) ? "TEDD_1" : "TEDD_2";
fname1 << Disc << "/";
int ring = tTopo->tidRing(det_id);
fname1 << "Ring" << ring;
}
return fname1.str();
}
| 1ab30965125be6c824a5cf927152ab846dc7e91f | [
"Python",
"C++"
] | 5 | Python | aebid/cmssw | bce791baf6bec17fcaff8d364f3584dfa2d735c1 | 8dcaeec5a797bb9b47df3976f06252daf272c099 |
refs/heads/master | <file_sep>var express = require('express');
var app = express();
app.use(express.static('public'));
app.get('/index.html', function(req, res) {
res.sendFile(__dirname + '/' + 'index.html');
});
app.get('/', function(req, res) {
res.send('Hola MAMA estoy haciendo express');
});
app.post('/', function(req, res) {
console.log('Hola mama acabo de hacer un POST');
res.send('Hola mama acabo de hacer un POST');
});
app.get('/users', function(req, res) {
res.send('Hola MAMA estoy haciendo Usuarios');
});
app.get('/get_form', function(req, res) {
var data = {
first: req.query.first,
last: req.query.last
};
console.log(data);
res.send(JSON.stringify(data));
});
var server = app.listen(3000, function() {
var port = server.address().port;
console.log('Servidor ejecutando en el puerto:', port);
});
| 19d4cfb793ba76524d9e52dfeafc33243f741e6a | [
"JavaScript"
] | 1 | JavaScript | IsabelVillafuerte/Express_Example | 4da87e76501c3aa3c7fe0e34f9ed22b3dcaf4d95 | 08d615f146aac3251b246d8504a9714bd6692e2a |
refs/heads/master | <repo_name>ggrumbley/TS_Lab<file_sep>/ts-babel-starter/README.md
# TypeScript Babel ESLint Starter Template
This is a small sample repository that uses Babel to transform TypeScript to plain JavaScript, and uses TypeScript for type-checking. This README will also explain step-by-step how you can set up this repository so you can understand how each component fits together.
<file_sep>/README.md
# TypeScript Lab
☕⚗🔬 A laboratory for small TypeScript experiments ☕⚗🔬
---
+ [TypeScript Babel Starter](./ts-babel-starter)
+ [Maps Project](./maps)
<file_sep>/rad-net-firebase-func/functions/src/index.ts
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import * as express from 'express';
import * as firebase from 'firebase';
const app = express();
const config = {
apiKey: process.env.apiKey,
authDomain: process.env.authDomain,
databaseURL: process.env.databaseURL,
projectId: process.env.projectId,
storageBucket: process.env.storageBucket,
messagingSenderId: process.env.messagingSenderId,
appId: process.env.appId,
};
admin.initializeApp(config);
interface Doot {
dootId: string;
body: string;
createdAt: string;
userName: string;
}
app.get('/doots', (req, res) => {
admin
.firestore()
.collection('doots')
.orderBy('createdAt', 'desc')
.get()
.then((data) => {
let doots: Doot[] = [];
data.forEach((doc) => {
doots.push({
...(doc.data() as Doot),
dootId: doc.id,
});
});
return res.json(doots);
})
.catch((err) => console.error(err));
});
app.post('/doot', (req, res) => {
const newDoot = {
body: req.body.body,
userName: req.body.userName,
createdAt: new Date().toISOString(),
};
admin
.firestore()
.collection('doots')
.add(newDoot)
.then((doc) => {
res.json({ message: `document ${doc.id} created successfully` });
})
.catch((err) => {
res.status(500).json({ error: 'something blew up' });
console.error(err);
});
});
app.post('/signup', (req, res) => {
const newUser = {
email: req.body.email,
name: req.body.name,
password: <PASSWORD>,
confirmPassword: <PASSWORD>Password,
};
// TODO: Validate Data
firebase.auth().createUserWithEmailAndPassword(newUser.email, newUser.password);
});
export const api = functions.https.onRequest(app);
| 7afa0645aae694315b0e58134bb961a78b109ba7 | [
"Markdown",
"TypeScript"
] | 3 | Markdown | ggrumbley/TS_Lab | f72db45b3cb3ed26abd1f838d138f550785b91b9 | 66398e9bd70258f07813c61e2b1b5a7d332e4cd5 |
refs/heads/master | <repo_name>EstebanCasas1/Analisis<file_sep>/Talleres/Interpolación/Punto1Interpolar.R
newtonInterpolacion = function(x, y, a) {
n = length(x)
A = matrix(rep(NA, times = n^2), nrow = n, ncol = n)
A[,1] = y
for (k in 2:n) {
A[k:n, k] = (A[k:n, k-1] - A[(k-1):(n-1), k-1] ) / (x[k:n] - x[1:(n-k+1)])
}
smds = rep(NA, length = n)
smds[1] = 1
for (k in 2:n) {
smds[k] = (a - x[k-1])*smds[k-1]
}
return(sum(diag(A)*smds) )
}
#funcion de librp
hora<-c(6,8,10,12,14,16,18,20)
tim<-c(8.5,9.2,12.7,18.4,21.6,17.9,11,9)
#install.packages("PolynomF")
#require(PolynomF)
polyAjuste = poly.calc(hora,tim)
polyAjuste
plot(hora,tim, pch=19, cex=1, col = "blue", asp=1)
curve(polyAjuste,add=T)
remp<-newtonInterpolacion(hora[0:8], tim[0:8], 7)
resu<-c(remp)
remp<-newtonInterpolacion(hora[0:8], tim[0:8], 9)
resu<-c(resu,remp)
remp<-newtonInterpolacion(hora[0:8], tim[0:8], 11)
resu<-c(resu,remp)
remp<-newtonInterpolacion(hora[0:8], tim[0:8], 13)
resu<-c(resu,remp)
remp<-newtonInterpolacion(hora[0:8], tim[0:8], 15)
resu<-c(resu,remp)
remp<-newtonInterpolacion(hora[0:8], tim[0:8], 17)
resu<-c(resu,remp)
remp<-newtonInterpolacion(hora[0:8], tim[0:8], 19)
resu<-c(resu,remp)
pts<-c(7,9,11,13,15,17,19)
points(pts,resu)
<file_sep>/Talleres/Interpolación/Punto2.R
newtonInterpolacion = function(x, y, a) {
n = length(x)
A = matrix(rep(0, times = n^2), nrow = n, ncol = n)
A[,1] = y
for (k in 2:n) {
A[k:n, k] = (A[k:n, k-1] - A[(k-1):(n-1), k-1] ) / (x[k:n] - x[1:(n-k+1)])
}
smds = rep(NA, length = n) smds[1] = 1
for (k in 2:n) {
smds[k] = (a - x[k-1])*smds[k-1]
}
return(A)
}
#funcion del librp
A1=newtonInterpolacion(hora[1:4], tim[1:4],1)
hora<-c(6,8,10,12,14,16,18,20)
tim<-c(8.5,9.2,12.7,18.4,21.6,17.9,11,9)
B=c(tim[1],tim[2],tim[3],tim[4])
C= solve(A1,B)
#polinomio de grado 3
curve((A1[1,1]+A1[2,2]*(x-hora[1])+A1[3,3]*(x-hora[1])*(x-hora[2])+A1[4,4]*(x-hora[1])*(x-hora[2])*(x-hora[3])), from = -10, to=40,ylab = "y",col="blue")
points(hora[1],tim[1], col = "red")
points(hora[2],tim[2], col = "red")
points(hora[3],tim[3], col = "red")
points(hora[4],tim[4], col = "red")
points(hora[5],tim[5], col = "red")
points(hora[6],tim[6], col = "red")
points(hora[7],tim[7], col = "red")
points(hora[8],tim[8], col = "red")
#polinomio de grado 5
A1=newtonInterpolacion(hora[1:6], tim[1:6],1)
curve( A1[1,1]+A1[2,2]*(x-hora[1])+A1[3,3]*(x-hora[1])*(x-hora[2])+A1[4,4]*(x-hora[1])*(x-hora[2])*(x-hora[3]) + A1[5,5]*(x-hora[1])*(x-hora[2])*(x-hora[3])*(x-hora[4])+A1[6,6]*(x-hora[1])*(x-hora[2])*(x-hora[3])*(x-hora[4])*(x-hora[5]), from = -10, to=40,ylab = "y", add = TRUE,col="red" )
#polinomio de grado 7
A1=newtonInterpolacion(hora[1:8], tim[1:8],1)
curve( A1[1,1]+A1[2,2]*(x-hora[1])+A1[3,3]*(x-hora[1])*(x-hora[2])+A1[4,4]*(x-hora[1])*(x-hora[2])*(x-hora[3]) + A1[5,5]*(x-hora[1])*(x-hora[2])*(x-hora[3])*(x-hora[4])+A1[6,6]*(x-hora[1])*(x-hora[2])*(x-hora[3])*(x-hora[4])*(x-hora[5])+A1[7,7]*(x-hora[1])*(x-hora[2])*(x-hora[3])*(x-hora[4])*(x-hora[5])*(x-hora[6])+A1[8,8]*(x-hora[1])*(x-hora[2])*(x-hora[3])*(x-hora[4])*(x-hora[5])*(x-hora[6])*(x-hora[7]), from = -10, to=40,ylab = "y", add = TRUE,col="green" )
<file_sep>/RetoPerro/AgregadoGraficaDeErrores.R
ibrary(polynom)
library(PolynomF)
#install.packages("polynom")
require(graphics)
library(graphicsQC)
x=c(1,2,6,9,14,17.6,20,23,24.5,26.85,28.7,29,25.51,11.15,9.32,8.37,9.03,7.76,1)
y=c(3,3.7,4.5,7.12,6.7,4.45,7,6.5,5.6,5.87,5.05,3.71,0.47,1.65,1.22,1.7,2.92,2.36,3)
xx=c(1,2,6,13,17.6,20,23.5,24.5,26.5,27.5,28,29,24.10,10.10,9.20,8.37,9.03,6.98,1)
yx=c(3,3.7,7.12,6.7,4.45,7,6.1,5.8,5.6,5.87,5.15,5,4.9,2.5,2,0.9,2.54,2.80,3)
#xx=c(1,2,6,13,17.6,20,23.5,24.5,25,26.5,27.5,28,29)
length(xx)
length(yx)
plot(x,y, pch=19, cex=0.9, col = "blue", asp=1,xlab="X", ylab="Y", main="Perro ")
n=19
pint<-function(x,y){
t = 1:length(x)
sx = spline(t,x)
sy = spline(t,y)
lines(sx[[2]],sy[[2]],type='l', col="red")
}
pint(x,y)
#puntos origales / dados / puntos inicilaes geogebra
#valores no seleccionados
inter = splinefun(x,y,method = "natural")
i=0
cat(x[c(i)]," ",xx[c(i)])
for(i in 2:n-1){
if(x[c(i)]!=xx[c(i)]){
valorinter = inter(xx[i])
cat(xx[i],",",yx[i],",",valorinter,"\n")
}
}
errores=c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
cont=0
#error relativo valores interpolados
cat("x ","y ","s(x) "," error relativo")
inter = splinefun(x,y,method = "natural")
acumerrorrela=0
mayor=0
for(i in 2:n-1){
valorinter = inter(xx[i])
errabs=abs(yx[i]-valorinter)
error = errabs/yx[i] * 100
acumerrorrela=acumerrorrela+error
cat(xx[i],",",yx[i],",",valorinter,",",error,"\n")
}
cat("error total: ", acumerrorrela)
for(i in 2:n-1){
if(errores[c(i)]>mayor){
mayor=errores[c(i)]
}
}
#grafica cota
plot(seq(1,19),errores,pch=20,main = "Gráfica de errores",xlab="Puntos",ylab="Error porcental (%)")
lines(seq(1,19),errores)
abline(mayor, 0 ,col="blue")
| 57753320da6736db70a0ef83c9d944929a4e22b5 | [
"R"
] | 3 | R | EstebanCasas1/Analisis | e96ec8aed97a79a18402b7e1275b252226db6581 | ca66979c72652935d4f491102b875a53c294f00b |
refs/heads/master | <repo_name>hdr105/goholo<file_sep>/application/models/Kairos_model.php
<?php
class Kairos_model extends Video_model
{
public $galleryID = "";
public $videoID = "";
public $insertData = array();
public $updateData = array();
public $table = "videoAnalysis";
public function __construct() {
parent::__construct();
}
public function startAnalysis($galleryID,$videoPath,$videoID){
$this->galleryID = $galleryID;
$this->videoID = $videoID;
$dirname = "./frames/".$galleryID."/";
$images = glob($dirname."*.png");
foreach($images as $image) {
$this->recognize_api($image);
$this->enroll($image);
}
if (!empty($this->insertData)) {
$this->add_data($this->table,$this->insertData,true);
}
if (!empty($this->updateData)) {
$this->update_data($this->table,'faceID',$this->updateData,true);
}
$args = array();
$args['table'] = "videos";
$args['where']['galleryID'] = $galleryID;
$args['join']['videoanalysis'] = 'videoanalysis.videoID=videos.videoID';
$impressions = 0;
$locationID = "";
$records = $this->crud_model->get_data_new($args);
foreach ($records as $key => $value) {
$locationID = $value->locationID;
if ($value->duplicate == 0) {
$impressions++;
}
}
if ($impressions > 0 && $locationID != "") {
$this->db->where('location_id', $locationID);
$this->db->where('status', 1);
$this->db->set("impressions","impressions + ".$impressions , false);
$this->db->update('advertisements');
$args = array();
$args['table'] = "advertisements";
$args['where']['location_id'] = $locationID;
$args['where']['advertisements.status'] = 1;
$args['join']['packages'] = 'packages.package_id=advertisements.package_id';
$adds = $this->crud_model->get_data_new($args);
$advert_video_relation = array();
foreach ($adds as $key => $value) {
$tmp_relation = array();
$tmp_relation['video_id'] = $videoID;
$tmp_relation['advert_id'] = $value->advert_id;
array_push($advert_video_relation, $tmp_relation);
if ($value->advertisment_type == 1 && ($value->impressions == $value->total_impressions || $value->impressions > $value->total_impressions) ) {
$this->db->where('advert_id', $value->advert_id);
$this->db->set('status', 2);
$this->db->set('end_date', date('m/d/Y'));
$this->db->update('advertisements');
$task['task_type'] = "remove_advert";
$task['date'] = date('Y-d-m', strtotime(' +1 day'));
$task['advert_id'] = $value->advert_id;
$task2 = $this->crud_model->add_data('tasks',$task);
}elseif ($value->advertisment_type == 2) {
$end_date = $value->end_date;
$cur_date = date('m/d/Y');
if ($end_date == $cur_date) {
$this->crud_model->record_payment($value);
}
}
}
if (!empty($advert_video_relation)) {
$this->add_data('advert_video_relation',$advert_video_relation,true);
}
}
$emotions = $this->emotionsApi($videoPath);
if ($emotions) {
$emotions_arr = json_decode($emotions);
if (is_object($emotions_arr)) {
$analytics = $this->analyticsApi($emotions_arr->id,$videoID);
}else{
$msg = "Kairos Error: Emotions API ".$emotions;
if ($this->session->flashdata("error_msg") != "") {
$msg .= "<br>".$this->session->flashdata("error_msg");
}
$this->session->set_flashdata("error_msg",$msg);
}
}
}
public function recordAnalytics($analytics,$videoID){
$where = array("videoID"=>$videoID);
if (isset($analytics->status_message)) {
$data = array("emotionID"=>$analytics->id,"emotionStatus"=>$analytics->status_message);
$msg = "Status of analytics: ".$analytics->status_message;
}else{
$recordAnalytics = array();
$tmp_array['videoID'] = $videoID;
foreach ($analytics->impressions as $key => $value) {
$emotions = (array) $value->emotion_score;
$maxs = array_keys($emotions, max($emotions));
if (current($maxs) == "positive") {
$tmp_array['emotion'] = 1;
}elseif (current($maxs) == "negative") {
$tmp_array['emotion'] = 2;
}elseif (current($maxs) == "neutral") {
$tmp_array['emotion'] = 0;
}
$recordAnalytics[] = $tmp_array;
}
$this->add_data('videoemotions',$recordAnalytics,true);
$data = array("emotionID"=>$analytics->id,"emotionStatus"=> "Completed");
$msg = "Status of analytics: Completed";
}
$this->update_data("videos",$where,$data);
$this->session->set_flashdata("msg",$msg);
}
public function analyticsApi($analyticsid,$videoID){
$queryUrl = "https://api.kairos.com/v2/analytics/".$analyticsid;
$request = curl_init($queryUrl);
curl_setopt($request, CURLOPT_HTTPGET, TRUE);
curl_setopt($request, CURLOPT_HTTPHEADER, array(
"Content-type: application/json",
"app_id:" . APP_ID,
"app_key:" . APP_KEY
)
);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($request);
$this->recordAnalytics(json_decode($response),$videoID);
}
public function emotionsApi($videoPath){
$payload = [
'filename' => basename($videoPath),
'source' => new CurlFile($videoPath, 'video/mp4')
];
$curl_params = [
CURLOPT_URL => "https://api.kairos.com/v2/media",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => [
"Content-Type: multipart/form-data",
"app_id: ". APP_ID,
"app_key: ". APP_KEY
],
CURLOPT_POSTFIELDS => $payload
];
$curl = curl_init();
curl_setopt_array($curl, $curl_params);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
return false;
}
return $response;
}
public function recognize_api($image){
$gallery_name = $this->galleryID;
$path = $image;
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
$queryUrl = "https://api.kairos.com/recognize";
$data = array('image' => $base64,"gallery_name"=>$gallery_name);
$data = json_encode($data);
$request = curl_init($queryUrl);
// set curl options
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_POSTFIELDS, $data);
curl_setopt($request, CURLOPT_HTTPHEADER, array(
"Content-type: application/json",
"app_id:" . APP_ID,
"app_key:" . APP_KEY
)
);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($request);
$res = json_decode( $response);
if (isset($res->images)) {
foreach ($res->images as $key => $value) {
if (isset($value->candidates)) {
$candidates = $value->candidates;
foreach ($candidates as $k => $v) {
$faceID = $v->face_id;
if (!in_array_r($faceID, $this->updateData)) {
$tmp_array = array();
$tmp_array['faceID'] = $faceID;
$tmp_array['duplicate'] = 1;
$this->updateData[] = $tmp_array;
}
}
}
}
}
}
function enroll($image){
$gallery_name = $this->galleryID;
$path = $image;
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
$queryUrl = "https://api.kairos.com/enroll";
$data = array('image' => $base64,"gallery_name"=>$gallery_name,'subject_id'=>$gallery_name, 'multiple_faces'=>true);
$data = json_encode($data);
$request = curl_init($queryUrl);
// set curl options
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_POSTFIELDS, $data);
curl_setopt($request, CURLOPT_HTTPHEADER, array(
"Content-type: application/json",
"app_id:" . APP_ID,
"app_key:" . APP_KEY
)
);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($request);
$res = json_decode( $response);
if (isset($res->images)) {
foreach ($res->images as $key => $value) {
$tmp_array = array();
$tmp_array['videoID'] = $this->videoID;
$tmp_array['faceID'] = $value->transaction->face_id;
$tmp_array['age'] = $value->attributes->age;
$tmp_array['gender'] = $value->attributes->gender->type;
$nationality = array();
$nationality['asian'] = $value->attributes->asian;
$nationality['black'] = $value->attributes->black;
$nationality['hispanic'] = $value->attributes->hispanic;
$nationality['white'] = $value->attributes->white;
$tmp_array['nationality'] = current(array_keys($nationality, max($nationality)));
if (!empty($tmp_array)) {
$this->insertData[] = $tmp_array;
}
}
}
}
public function deleteGallery($galleryID){
$queryUrl = "https://api.kairos.com/gallery/remove";
$data = array("gallery_name"=>$galleryID);
$data = json_encode($data);
$request = curl_init($queryUrl);
// set curl options
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_POSTFIELDS, $data);
curl_setopt($request, CURLOPT_HTTPHEADER, array(
"Content-type: application/json",
"app_id:" . APP_ID,
"app_key:" . APP_KEY
)
);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($request);
}
} <file_sep>/application/views/resource_center/manage_resource_center.php
<!-- END PAGE SIDEBAR -->
<div class="page-content-col">
<?php
if (isset($resource) && !empty($resource)) {
?>
<script type="text/javascript">
$(document).ready(function(){
<?php
foreach ($resource as $key => $value) {
?>
var key = "<?php echo $key ?>";
<?php
if ($key == "description") {
?>
$("."+key+"").html("<?php echo $value ?>");
<?php
}else{
?>
$("."+key+"").val("<?php echo $value ?>");
<?php
}
}
?>
});
</script>
<?php
}
?>
<div class="row">
<?php
if ($this->session->flashdata("error_msg") != "") {
?>
<div class="alert alert-danger">
<?php echo $this->session->flashdata("error_msg"); ?>
</div>
<?php
}
?>
</div>
<!-- BEGIN PAGE BASE CONTENT -->
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-blue-hoki bold uppercase">Add Content</span>
</div>
<div class="tools">
<a href="" class="collapse" data-original-title="" title=""> </a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="<?php echo base_url() ?>admin/manage_resource_center" method="post" enctype="multipart/form-data" class="horizontal-form">
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Title</label>
<input type="text" class="form-control title" name="title">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Type</label>
<select name="resource_type" class="form-control resource_type">
<option value="1">Location Contract</option>
<option value="2">Advertisers Contract </option>
<option value="3">Marketing/Promo</option>
<option value="4">Location Criteria</option>
<option value="5">Advertising Tips</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">Description</label>
<textarea name="description" class="form-control description" cols="10" rows="5"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label class="control-label">File</label>
<input type="file" name="resource_file">
</div>
</div>
</div>
</div>
<div class="form-actions right">
<input type="hidden" name="resource_id" class="resource_id">
<input type="hidden" class="resource_file" name="old_resource_file">
<button type="submit" class="btn blue">
<i class="fa fa-check"></i> Save</button>
</div>
</form>
<!-- END FORM-->
</div>
</div>
<!-- END PAGE BASE CONTENT -->
</div>
<file_sep>/application/models/Settings_model.php
<?php
class Settings_model extends Crud_Model{
private $table = "settings";
public function __construct() {
parent::__construct();
}
public function get_value($key,$value = true){
$where['setting_key'] = $key;
$res = $this->get_data($this->table,$where,true);
if ($value) {
return $res->setting_value;
}else{
return $res;
}
}
public function set_value($key,$value){
$res = $this->get_value($key,false);
if (empty($res)) {
$data['setting_key'] = $key;
$data['setting_value'] = $value;
$res = $this->add_data($this->table,$data);
}else{
$data['setting_key'] = $key;
$data['setting_value'] = $value;
$where['setting_key'] = $key;
$res = $this->update_data($this->table,$where,$data);
}
if ($res) {
return true;
}
return false;
}
}<file_sep>/application/models/Users_model.php
<?php
class Users_model extends CI_Model{
public function __construct() {
parent::__construct();
$this->load->model("crud_model");
}
public function login_user($data){
extract($data);
$query = $this->db->get_where('users', array('email' => $email,'password' => $password));
if($query->num_rows()>0){
$response = $query->row();
return $response;
}else{
return false;
}
}
}<file_sep>/application/controllers/Recruitments.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Recruitments extends GH_Controller {
public $data = array();
public $table = "users";
public function __construct() {
parent::__construct();
$this->data['menu_class'] = "recruitments_menu";
$this->data['title'] = "Recruitments";
$this->data['sidebar_file'] = "recruitment/recruitment_sidebar";
}
public function index()
{
$where['created_by'] = get_user_id();
$where['user_role'] = 3;
$result = $this->crud_model->get_data('users',$where);
$this->data['users'] = $result;
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('recruitment/view_recruitments');
$this->load->view('common/footer');
}
public function manage_user(){
$email_validation = 'required|valid_email';
if($_POST['user_id'] == ""){
$email_validation .= "|is_unique[users.email]";
}
$this->form_validation->set_rules('email', '*Email', $email_validation, array(
'required' => '%s Missing',
'is_unique' => '%s already Registered'
));
$this->form_validation->set_rules('password', '*Password', 'required|min_length[6]|max_length[12]|alpha_numeric', array(
'required' => '%s Missing',
'min_length' => '%s must be at least 6 characters',
'max_length' => '%s must be at most 12 characters',
'alpha_numeric' => '%s must be Alpha Numeric'
));
$this->form_validation->set_rules('re_password', '*Re-type Password', 'required|matches[password]', array(
'required' => '%s Missing',
'matches' => 'Password does not match'
));
$result = $this->form_validation->run();
if ($result) {
$form_data = $_POST;
$profile_image = $this->crud_model->upload_file($_FILES['profile_image'],'profile_image',PROFILE_IMAGE_UPLOAD_PATH);
if ($profile_image) {
$form_data['profile_image'] = $profile_image;
}elseif ($form_data['old_profile_image'] != "") {
$form_data['profile_image'] = $form_data['old_profile_image'];
}
unset($form_data['old_profile_image']);
unset($form_data['re_password']);
$edit = false;
if ($form_data['user_id'] != "") {
$edit = true;
$where['user_id'] = $form_data['user_id'];
unset($form_data['user_id']);
$user_id = $this->crud_model->update_data($this->table,$where,$form_data);
}else{
$qb = true;
$qb_add = $this->quick_books->add_employee($form_data);
if ($qb_add['error'] == false) {
$form_data['user_qb_id'] = $qb_add['msg'];
}else{
$qb = false;
}
if ($qb) {
unset($form_data['user_id']);
$form_data['created_by'] = get_user_id();
$user_role = get_user_role();
if ($user_role != 1) {
$form_data['status'] = 0;
}
$user_id = $this->crud_model->add_data($this->table,$form_data);
if ($user_id) {
$this->load->library("PhpMailerLib");
$mail = $this->phpmailerlib->welcome_email($form_data);
if (!$mail) {
$msg = $mail->ErrorInfo;
}
}
$notify['message'] = sprintf($this->lang->line('new_marketing_member'), get_user_fullname());
$notify['link'] = "users/0";
$this->add_notifications($notify,'1');
}else{
$user_id = false;
$msg = $qb_add['msg'];
}
}
if ($user_id) {
if (isset($edit)) {
if (!isset($msg)) {
$msg = "User Updated successfully";
}
}else{
if (!isset($msg)) {
$msg = "User created successfully";
}
}
$this->session->set_flashdata("success_msg",$msg);
redirect(base_url()."recruitments/");
}else{
if (isset($edit)) {
if (!isset($msg)) {
$msg = "User Not Updated";
}
}else{
if (!isset($msg)) {
$msg = "User Not created";
}
}
$this->session->set_flashdata("error_msg",$msg);
redirect($_SERVER['HTTP_REFERER']);
}
}else{
$this->manage_recruitment_view();
}
}
public function manage_recruitment_view($id = "")
{
if ($id != "") {
$where['user_id'] = $id;
$this->data['user'] = $this->crud_model->get_data($this->table,$where,true);
}
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('recruitment/manage_recruitment',$this->data);
$this->load->view('common/footer');
}
public function view_recruitment($id){
$where['user_id'] = $id;
$this->data['user'] = $this->crud_model->get_data($this->table,$where,true);
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('recruitment/view_recruitment',$this->data);
$this->load->view('common/footer');
}
}
<file_sep>/application/views/admin/cron_job.php
<!-- END PAGE SIDEBAR -->
<div class="page-content-col">
<!-- BEGIN PAGE BASE CONTENT -->
<p class="well">
<span class="bold text-info">CRON COMMAND: wget -q -O- <?=base_url()?>cron_job/run</span><br>
<a href="<?=base_url()?>cron_job/run/1">Run Cron Manually</a><br>
</p>
<div class="row">
<?php
if ($this->session->flashdata("success_msg") != "") {
?>
<div class="alert alert-success">
<?php echo $this->session->flashdata("success_msg"); ?>
</div>
<?php
}
?>
</div>
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-blue-hoki bold uppercase">Pay as you go</span>
</div>
<div class="tools">
<a href="" class="collapse" data-original-title="" title=""> </a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="" method="post" enctype="multipart/form-data" class="horizontal-form">
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Cost per Impression</label>
<input type="text" class="form-control price_per_impression" name="price_per_impression" value="<?php echo $price_per_impression; ?>">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Day to perform automatic operations</label>
<select class="form-control pay_as_you_go_day" name="pay_as_you_go_day">
<option value="1" <?php echo ($pay_as_you_go_day == 1 ? "selected": "") ?> >Monday</option>
<option value="2" <?php echo ($pay_as_you_go_day == 2 ? "selected": "") ?>>Tuesday</option>
<option value="3" <?php echo ($pay_as_you_go_day == 3 ? "selected": "") ?>>Wednesday</option>
<option value="4" <?php echo ($pay_as_you_go_day == 4 ? "selected": "") ?>>Thursday</option>
<option value="5" <?php echo ($pay_as_you_go_day == 5 ? "selected": "") ?>>Friday</option>
<option value="6" <?php echo ($pay_as_you_go_day == 6 ? "selected": "") ?>>Saturday</option>
<option value="7" <?php echo ($pay_as_you_go_day == 7 ? "selected": "") ?>>Sunday</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Hour of day to perform automatic operations</label>
<input type="number" name='pay_as_you_go_hour' class="form-control pay_as_you_go_hour" data-toggle="tooltip" title="24 hours format eq. 9 for 9am or 15 for 3pm." max="23" value="<?php echo $pay_as_you_go_hour; ?>" data-original-title="" title="" autocomplete="off">
</div>
</div>
</div>
<div class="form-actions right">
<input type="submit" class="btn blue" value="Update Settings">
</div>
</div>
</form>
</div>
</div>
<script type="text/javascript">
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
</script>
<!-- END PAGE BASE CONTENT -->
</div><file_sep>/application/views/advertisers/manage_advertisers.php
<!-- END PAGE SIDEBAR -->
<div class="page-content-col">
<div class="row">
<?php
if ($this->session->flashdata("error_msg") != "") {
?>
<div class="alert alert-danger">
<?php echo $this->session->flashdata("error_msg"); ?>
</div>
<?php
}
?>
</div>
<!-- BEGIN PAGE BASE CONTENT -->
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-blue-hoki bold uppercase">Add Advertiser</span>
</div>
<div class="tools">
<a href="" class="collapse" data-original-title="" title=""> </a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="" method="post" enctype="multipart/form-data" class="horizontal-form">
<div class="form-body">
<h3 class="form-section">Company Info</h3>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Company Name</label>
<input type="text" id="" class="form-control company_name" name="company_name" placeholder="Enter Company Name" value="<?php echo (set_value('company_name')); ?>">
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Website</label>
<input type="text" id="" class="form-control website" placeholder="Enter Website" name="website" value="<?php echo (set_value('website')); ?>">
</div>
</div>
<!--/span-->
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">First Name</label>
<input type="text" id="firstName" class="form-control first_name" name="first_name" placeholder="Enter First Name" value="<?php echo (set_value('first_name')); ?>">
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Last Name</label>
<input type="text" id="lastName" class="form-control last_name" placeholder="Enter Last Name" name="last_name" value="<?php echo (set_value('last_name')); ?>">
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<?php
$email_error = form_error('email');
?>
<div class="form-group <?php echo ($email_error != '') ? 'has-error' : '' ?>">
<label class="control-label">Email</label>
<input id="email_input" type="email" name="email" class="form-control email" value="<?php echo (set_value('email')); ?>">
<span class="help-block"> <?php echo $email_error; ?> </span>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<?php
$pass_error = form_error('password');
?>
<div class="form-group <?php echo ($pass_error != '') ? 'has-error' : '' ?>">
<label class="control-label">Password</label>
<input id="email_input" type="password" name="password" class="form-control password" value="<?php echo (set_value('password')); ?>">
<span class="help-block"> <?php echo $pass_error; ?> </span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Phone Number</label>
<input type="text" name="phone_number" class="form-control phone_number" value="<?php echo (set_value('phone_number')); ?>">
</div>
</div>
</div>
<h3 class="form-section">Billing Address</h3>
<div class="row">
<div class="col-md-12 ">
<div class="form-group">
<label>Street</label>
<input type="text" name="street" class="form-control street" value="<?php echo (set_value('street')); ?>"> </div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>City</label>
<input type="text" name="city" class="form-control city" value="<?php echo (set_value('city')); ?>"> </div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label>Country</label>
<input type="text" name="country" class="form-control country" value="<?php echo (set_value('country')); ?>"> </div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Post Code</label>
<input type="text" name="post_code" class="form-control post_code" value="<?php echo (set_value('post_code')); ?>"> </div>
</div>
<!--/span-->
</div>
</div>
<div class="form-actions right">
<input type="hidden" class="user_id" name="user_id">
<input type="hidden" class="user_qb_id" name="user_qb_id">
<input type="hidden" class="user_role" name="user_role" value="6">
<!-- <button type="submit" class="btn blue">
<i class="fa fa-check"></i> Save</button> -->
<input type="submit" class="btn blue" value="Save">
</div>
</form>
<!-- END FORM-->
</div>
</div>
<!-- END PAGE BASE CONTENT -->
</div>
<script type="text/javascript">
$(document).ready(function(){
<?php
if (isset($user) && !empty($user)) {
foreach ($user as $key => $value) {
?>
var key = "<?php echo $key ?>";
$("."+key+"").val("<?php echo $value ?>");
<?php
}
}
?>
});
</script><file_sep>/application/controllers/Login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model("users_model");
}
public function index()
{
$this->load->view('login/login');
}
public function login_auth(){
$data= $this->input->post();
unset($data['submit']);
$result = $this->users_model->login_user($data);
if($result){
$this->session->set_userdata("user_session",$result);
redirect(base_url());
}else{
$this->session->set_flashdata('error','Invalid Email or Password');
redirect($_SERVER['HTTP_REFERER']);
}
}
}
<file_sep>/application/third_party/quickbooks/auth2/OAuth_2/create_customer.php
<?php
$session_id = session_id();
if (empty($session_id))
{
session_start();
}
$configs = include "./config.php";
$client_id = $configs['client_id'];
$client_secret = $configs['client_secret'];
// echo $_SESSION['access_token'];
// echo "<br> string";
// echo $_SESSION['refresh_token'];
// echo "<br> string";
// echo $_SESSION['realmId'];
// die;
require "../../vendor/autoload.php";
use QuickBooksOnline\API\DataService\DataService;
use QuickBooksOnline\API\Core\Http\Serialization\XmlObjectSerializer;
use QuickBooksOnline\API\Facades\Customer;
// Prep Data Services
$dataService = DataService::Configure(array(
'auth_mode' => 'oauth2',
'ClientID' => $client_id,
'ClientSecret' => $client_secret,
'accessTokenKey' =>$_SESSION['access_token'],
'refreshTokenKey' => $_SESSION['refresh_token'],
'QBORealmID' => $_SESSION['realmId'],
'baseUrl' => "Development"
));
$dataService->setLogLocation("/Users/hlu2/Desktop/newFolderForLog");
$dataService->throwExceptionOnError(true);
//Add a new Vendor
$theResourceObj = Customer::create([
"BillAddr" => [
"Line1" => "123 Main Street",
"City" => "Mountain View",
"Country" => "USA",
"CountrySubDivisionCode" => "CA",
"PostalCode" => "94042"
],
"GivenName" => "James",
"FamilyName" => "King",
"CompanyName" => "King Groceries",
"DisplayName" => "King's Groceries Displayname",
"PrimaryPhone" => [
"FreeFormNumber" => "(555) 555-5555"
],
"PrimaryEmailAddr" => [
"Address" => "<EMAIL>"
]
]);
$resultingObj = $dataService->Add($theResourceObj);
$error = $dataService->getLastError();
if ($error) {
echo "The Status code is: " . $error->getHttpStatusCode() . "\n";
echo "The Helper message is: " . $error->getOAuthHelperError() . "\n";
echo "The Response message is: " . $error->getResponseBody() . "\n";
}
else {
echo "Created Id={$resultingObj->Id}. Reconstructed response body:\n\n";
$xmlBody = XmlObjectSerializer::getPostXmlFromArbitraryEntity($resultingObj, $urlResource);
echo $xmlBody . "\n";
}<file_sep>/application/views/location_manager/deliver_task.php
<div class="page-content-col">
<div class="row">
<?php
if ($this->session->flashdata("error_msg") != "") {
?>
<div class="alert alert-danger">
<?php echo $this->session->flashdata("error_msg"); ?>
</div>
<?php
}elseif ($this->session->flashdata("success_msg") != "") {
?>
<div class="alert alert-success">
<?php echo $this->session->flashdata("success_msg"); ?>
</div>
<?php
}
?>
</div>
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-blue-hoki bold uppercase">Deliver Task</span>
</div>
<div class="tools">
<a href="" class="collapse" data-original-title="" title=""> </a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="" method="post" enctype="multipart/form-data" class="horizontal-form">
<div class="form-body">
<h3 class="form-section">Upload File here</h3>
<div class="row">
<div class="col-md-6">
<?php
$proof_file_error = form_error('proof_file');
?>
<div class="form-group <?php echo ($proof_file_error != '') ? 'has-error' : '' ?>">
<label for="exampleInputFile1">Proof file</label>
<input name="proof_file" type="file">
<span class="help-block"> <?php echo $proof_file_error; ?> </span>
</div>
</div>
</div>
</div>
<div class="form-actions right">
<input class="advert_id" name="task_id" type="hidden" value="<?=$task_id?>">
<button type="submit" class="btn blue">
<i class="fa fa-check"></i>Deliver Task</button>
</div>
</form>
</div>
</div>
</div><file_sep>/application/third_party/quickbooks/auth2/OAuth_2/create_invoice.php
<?php
$session_id = session_id();
if (empty($session_id))
{
session_start();
}
require("./Client.php");
$configs = include "./config.php";
$tokenEndPointUrl = $configs['tokenEndPointUrl'];
$mainPage = $configs['mainPage'];
$client_id = $configs['client_id'];
$client_secret = $configs['client_secret'];
$grant_type= 'refresh_token';
//$certFilePath = './Certificate/all.platform.intuit.com.pem';
$certFilePath = './Certificate/cacert.pem';
$refresh_token = $_SESSION['refresh_token'];
$client = new Client($client_id, $client_secret, $certFilePath);
$result = $client->refreshAccessToken($tokenEndPointUrl, $grant_type, $refresh_token);
$_SESSION['access_token'] = $result['access_token'];
$_SESSION['refresh_token'] = $result['refresh_token'];
require "../../vendor/autoload.php";
use QuickBooksOnline\API\DataService\DataService;
use QuickBooksOnline\API\Core\Http\Serialization\XmlObjectSerializer;
//use QuickBooksOnline\API\Facades\Invoice;
use QuickBooksOnline\API\Facades\Employee;
// Prep Data Services
$dataService = DataService::Configure(array(
'auth_mode' => 'oauth2',
'ClientID' => $client_id,
'ClientSecret' => $client_secret,
'accessTokenKey' =>$_SESSION['access_token'],
'refreshTokenKey' => $_SESSION['refresh_token'],
'QBORealmID' => $_SESSION['realmId'],
'baseUrl' => "Development"
));
//$dataService->setLogLocation("/Users/hlu2/Desktop/newFolderForLog");
//$dataService->throwExceptionOnError(true);
$theResourceObj = Employee::create([
"PrimaryAddr" => [
"Line1"=> "45 N. Elm Street",
"City"=> "Middlefield",
"CountrySubDivisionCode"=> "CA",
"PostalCode"=> "93242"
],
"GivenName"=> "Bill",
"FamilyName"=> "Miller",
"DisplayName"=> "<NAME>",
"PrimaryPhone": {
"FreeFormNumber": "234-525-1234"
},
"PrimaryEmailAddr" => [
"Address" => $data['advertiser_email']
]
]);
//Add a new Invoice
// $theResourceObj = Invoice::create([
// "Line" => [
// [
// "Amount" => 100.00,
// "DetailType" => "SalesItemLineDetail",
// "SalesItemLineDetail" => [
// "ItemRef" => [
// "value" => 1,
// "name" => "Services"
// ]
// ]
// ],
// [
// "Amount" => 400.00,
// "DetailType" => "SalesItemLineDetail",
// "Description" => "alo",
// "SalesItemLineDetail" => [
// "ItemRef" => [
// "value" => 2,
// "name" => "Services 2"
// ],
// "UnitPrice" => 200.00,
// "Qty" => 2,
// ]
// ]
// ],
// "CustomerRef"=> [
// "value"=> 4
// ],
// "EmailStatus" => "EmailSent",
// "PrintStatus" => "NeedToPrint",
// "BillEmail" => [
// "Address" => "<EMAIL>"
// ],
// ]);
$resultingObj = $dataService->Add($theResourceObj);
$error = $dataService->getLastError();
if ($error) {
echo "The Status code is: " . $error->getHttpStatusCode() . "\n";
echo "The Helper message is: " . $error->getOAuthHelperError() . "\n";
echo "The Response message is: " . $error->getResponseBody() . "\n";
}
else {
echo "Created Id={$resultingObj->Id}. Reconstructed response body:\n\n";
$xmlBody = XmlObjectSerializer::getPostXmlFromArbitraryEntity($resultingObj, $urlResource);
echo $xmlBody . "\n";
}
<file_sep>/application/views/resource_center/admin_resource_center.php
<!-- END PAGE SIDEBAR -->
<div class="page-content-col">
<!-- BEGIN PAGE BASE CONTENT -->
<?php
if ($this->session->flashdata("success_msg") != "") {
?>
<div class="alert alert-success">
<?php echo $this->session->flashdata("success_msg"); ?>
</div>
<?php
}
?>
<div class="row text-right">
<div class="col-md-12">
<a href="<?php echo base_url() ?>admin/manage_resource_center" class='btn btn-primary'> Add Resource</a>
</div>
</div>
<div class="table-responsive mt20">
<table class="table table-bordered table-stripped datatable">
<thead>
<tr>
<th>Sr.</th>
<th>Title</th>
<th>Type</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
foreach ($resources as $key => $value) {
echo "<tr>
<td>".$i."</td>
<td>".$value->title."</td>
<td>".get_resouce_type($value->resource_type)."</td>
<td> <a class='btn btn-primary round-btn' href='".base_url()."admin/manage_resource_center/".$value->resource_id."'>Edit</a> <a href='".base_url()."admin/delete_resource/".$value->resource_id."' class='btn btn-danger round-btn delete-btn'>Delete</a></td>
</tr>";
$i++;
}
?>
</tbody>
</table>
</div>
<!-- END PAGE BASE CONTENT -->
</div>
<file_sep>/application/views/location/location_sidebar.php
<?php
if (has_permission("add_location")) {
?>
<li class="">
<a href="<?php echo base_url()?>locations/manage_location_view">
Add New Location
</a>
</li>
<?php
}
if (has_permission("location_criteria")) {
?>
<li>
<a href="<?php echo base_url()?>resource_center/4">
Location Criteria
</a>
</li>
<?php
}
if (has_permission("view_locations")) {
?>
<li>
<a href="<?php echo base_url()?>locations/view_locations">
All Locations
</a>
</li>
<?php
}
if (has_permission("location_dashboard")) {
?>
<li>
<a href="#">
Location Dashboard
</a>
</li>
<?php
}
?>
<file_sep>/application/views/contact_us/model.php
<form role="form" method="POST" name="sendmail" action="<?php echo base_url("contact/send_mail"); ?>" enctype="multipart/form-data">
<div class="modal-body">
<div class="form-group">
<label for="name">Name</label>
<input type="text" required name="name" class="form-control" id="name" placeholder="Name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" required name="email" class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="phone">Phone:</label>
<input type="tel" required name="tel" class="form-control" id="phone" placeholder="Phone Number">
</div>
<div class="form-group">
<label for="location">Location:</label>
<input type="text" required name="location" value="<?php echo $location->location_name; ?>" class="form-control" id="location" >
</div>
<div class="form-group">
<label for="comment">Message:</label>
<textarea class="form-control" placeholder="Message Here" required name="msg" rows="5" id="comment"></textarea>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success">Submit</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form><file_sep>/application/controllers/Cron_job.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Cron_job extends CI_Controller {
public $data = array();
public $manually = false;
public function __construct() {
parent::__construct();
$this->load->model('settings_model');
$this->load->model('Crud_model');
$this->data['menu_class'] = "admin_menu";
$this->data['title'] = "Admin";
$this->data['sidebar_file'] = "admin/admin_sidebar";
}
public function index(){
$from = $this->input->post();
if (!empty($from)) {
$this->settings_model->set_value('price_per_impression',$from['price_per_impression']);
$this->settings_model->set_value('pay_as_you_go_hour',$from['pay_as_you_go_hour']);
$this->settings_model->set_value('pay_as_you_go_day',$from['pay_as_you_go_day']);
}
$this->data['price_per_impression'] = $this->settings_model->get_value("price_per_impression");
$this->data['pay_as_you_go_hour'] = $this->settings_model->get_value("pay_as_you_go_hour");
$this->data['pay_as_you_go_day'] = $this->settings_model->get_value("pay_as_you_go_day");
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('admin/cron_job');
$this->load->view('common/footer');
}
public function run($manually = 0)
{
if ($manually == 1) {
$this->manually = true;
}
$this->pay_as_you_go();
$this->get_impressions();
}
public function pay_as_you_go(){
$invoice_hour_auto_operations = $this->settings_model->get_value("pay_as_you_go_hour");
$invoice_day_auto_operations = $this->settings_model->get_value("pay_as_you_go_day");
if ($invoice_hour_auto_operations == '') {
$invoice_hour_auto_operations = 9;
}
if ($invoice_day_auto_operations == '') {
$invoice_day_auto_operations = 1;
}
$invoice_hour_auto_operations = intval($invoice_hour_auto_operations);
$invoice_day_auto_operations = intval($invoice_day_auto_operations);
$hour_now = date('G');
$day_now = date('N');
if (($hour_now != $invoice_hour_auto_operations || $day_now != $invoice_day_auto_operations) && $this->manually == false ) {
return;
}
$adverts = $this->crud_model->get_data("advertisements",array("status !="=>2));
foreach ($adverts as $key => $value) {
$this->crud_model->record_payment($value);
}
if ($this->manually == true) {
redirect($_SERVER['HTTP_REFERER']);
}
}
public function get_impressions(){
$time = date('i', time()+36000);
if($time != '00'){
return;
}
$locations = $this->Crud_model->get_data('locations',array('status'=>1));
if(!empty($locations)){
foreach ($locations as $loc) {
if($this->db->table_exists(strtolower($loc->location_number))){
$total_impression = $this->Crud_model->get_data(strtolower($loc->location_number),array('check_status' => 0),'','','','COUNT(impression_id) total_impression');
$this->Crud_model->update_data(strtolower($loc->location_number),array('check_status'=> 0), array('check_status' => 1));
$this->db->where('location_id', $loc->location_id);
$this->db->where('status', 1);
$this->db->set("impressions","impressions + ".$total_impression[0]->total_impression , false);
$this->db->update('advertisements');
$args = array();
$args['table'] = "advertisements";
$args['where']['location_id'] = $loc->location_id;
$args['where']['advertisements.status'] = 1;
$args['join']['packages'] = 'packages.package_id=advertisements.package_id';
$adds = $this->crud_model->get_data_new($args);
foreach ($adds as $key => $value) {
// print_r($value->advertisment_type);
if ($value->advertisment_type == 1 && ($value->impressions == $value->total_impressions || $value->impressions > $value->total_impressions) ) {
$this->db->where('advert_id', $value->advert_id);
$this->db->set('status', 2);
$this->db->set('end_date', date('m/d/Y'));
$this->db->update('advertisements');
$task['task_type'] = "remove_advert";
$task['date'] = date('Y-d-m', strtotime(' +1 day'));
$task['advert_id'] = $value->advert_id;
$task2 = $this->crud_model->add_data('tasks',$task);
}elseif ($value->advertisment_type == 2) {
$end_date = $value->end_date;
$cur_date = date('m/d/Y');
if ($end_date < $cur_date) {
$task['task_type'] = "remove_advert";
$task['date'] = date('Y-d-m', strtotime(' +1 day'));
$task['advert_id'] = $value->advert_id;
$task2 = $this->crud_model->add_data('tasks',$task);
$this->crud_model->record_payment($value);
}
}
}
}
else{
echo "Table Does Not Exist";
}
}
}
}
}<file_sep>/application/views/analytics/dashboard/third_div.php
<div class="card">
<div class="card-body">
<div class="row">
<div class="offset-md-3 col-lg-6 col-md-6 col-sm-12 col-xs-12">
<div class="card">
<div class="card-header">
<h5 class="header-title pb-3 mt-0 title title-sm">AGE GROUPS <!-- <span class="badge pink_bdg ">9</span> --></h5>
</div>
<div class="">
<div class="table-responsive text-center">
<table class="table table-hover mb-0">
<thead>
<tr class="align-self-center">
<th>Age</th>
<th>Total</th>
</tr>
</thead>
<tbody class="age_groups">
<?php
foreach ($analytics['age_group'] as $key => $value) {
if ($value != 0) {
echo "<tr>
<td>".$key."</td>
<td>".($value/$analytics['total_visitors']*100)."%</td>
</tr>";
}
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<file_sep>/application/views/location/location.php
<style type="text/css">
.page-content-col {
padding-top: 10px !important;
}
</style>
<!-- END PAGE SIDEBAR -->
<div class="page-content-col">
<!-- BEGIN PAGE BASE CONTENT -->
<div class="row">
<div class="col-md-offset-3 col-md-6 margin-bottom-10">
<input type="text" placeholder="Search Location" class="form-control" id="search_autocomplete">
</div>
<div class="col-md-1"><button class="btn btn-success filter_btn">Add Filter</button></div>
</div>
<div class="row filter_div">
<div class="col-md-offset-3 col-md-6 margin-bottom-10">
<select class="form-control filter_select" multiple="">
<?php
foreach ($filters as $key => $value) {
echo "<option value='".$value."'>".$value."</option>";
}
?>
</select>
</div>
<div class="col-md-1"><button class="btn btn-success search_filter">Search</button></div>
</div>
<div id="map" style="height: 600px; width:100%;"></div>
<!-- END PAGE BASE CONTENT -->
</div>
<script type="text/javascript">
$(document).ready(function(){
$(".filter_div").hide();
$(".filter_btn").click(function(){
$(".filter_div").slideToggle();
})
$(".search_filter").click(function(){
add_markers();
})
})
</script>
<file_sep>/application/views/analytics/dashboard/second_div.php
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="row ">
<div class="col-md-6 col-lg-6 col-sm-12 col-xs-12 pr-0">
<div class="card">
<div class="card-header pl0md">
<h4 class="card-title title title-sm font11sm font12md" id="heading-dropdown ">EMOTIONAL ANALYSIS <!-- <span class="badge pink_bdg">9</span> --></h4>
<div class="heading-elements btn_sm_per right-0">
<button type="button" class="btn btn-outline-secondary font12md round btn-custom-hvr" data-toggle="dropdown" aria-haspopup="true"><i class="pr-1 fas fa-sort-down"></i> <span class="emotion_filter">Percentages</span> <i class="pl-1 fas fa-ellipsis-v"></i></button>
<div class="dropdown-menu">
<a class="dropdown-item change_emotions" data-filter="Decimels" href="#">Numbers</a>
<a class="dropdown-item change_emotions" data-filter="Percentage" href="#">Percentage</a>
</div>
</div>
</div>
<div class="card-body mt-5 text-center-sm">
<div class="row justify-content-center ">
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 vertical_middle">
<img src="<?php echo base_url() ?>frontend/images/first_face.png " class="img-ico ">
</div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 plr0">
<h1 class="mt-1 faceheading ">Postive</h1>
</div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 pl-0">
<h1 class="mt-1 faceheading happy_text"><?=$analytics['happy_cent']?>%</h1>
</div>
</div>
<div class="row justify-content-center ">
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 vertical_middle">
<img src="<?php echo base_url() ?>frontend/images/second_face.png" class="img-ico">
</div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 plr0">
<h1 class="mt-1 faceheading">Neutral</h1>
</div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 pl-0">
<h1 class="mt-1 faceheading normal_text"><?=$analytics['normal_cent']?>%</h1>
</div>
</div>
<div class="row justify-content-center ">
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 vertical_middle">
<img src="<?php echo base_url() ?>frontend/images/third_face.png" class="img-ico">
</div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 plr0">
<h1 class="mt-1 faceheading">Negative</h1>
</div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 pl-0">
<h1 class="mt-1 faceheading sad_text"><?=$analytics['sad_cent']?>%</h1>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
<div class="card">
<div class="card-header">
<h5 class="header-title pb-3 mt-0 title">MALE VS FEMALE </h5>
</div>
<div class="card-body">
<div class="row ">
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 text-center">
<img src="<?php echo base_url() ?>frontend/images/man.png" class="pull-up">
<h1 class="mt-1 percent_nmbr male_text"><?=$analytics['male_cent']?>%</h1>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 text-center">
<img src="<?php echo base_url() ?>frontend/images/woman.png" class="pull-up">
<h1 class="mt-1 percent_nmbr female_text"><?=$analytics['female_cent']?>%</h1>
</div>
<div class="brdr_right d-none d-lg-block d-xl-block d-md-block">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<file_sep>/application/models/Crud_model.php
<?php
class Crud_model extends CI_Model{
public function __construct() {
parent::__construct();
}
//$table,$where = array(),$single_row = false,$join = array(), $like = array(),$select = "*",$or_where = "",$where_in = "", $order_by = ""
public function get_data_new($args){
extract($args);
$select = (isset($select) ? $select : "*");
$single_row = (isset($single_row) ? $single_row : false);
$this->db->select($select);
$this->db->from($table);
if (!empty($join)) {
foreach ($join as $key => $value) {
$this->db->join($key,$value,'left');
}
}
if (!empty($where)) {
$this->db->where($where);
}
if (!empty($or_where)) {
$this->db->or_where($or_where);
}
if (!empty($where_in)) {
foreach ($where_in as $key => $value) {
$this->db->where_in($key, $value);
}
}
if (!empty($like)) {
$this->db->like($like);
}
if ($single_row) {
$res = $this->db->get()->row();
}else{
if (!empty($order_by)) {
$this->db->order_by($order_by);
}
$res = $this->db->get()->result();
}
return $res;
}
public function get_data($table,$where = array(),$single_row = false,$join = array(), $like = array(),$select = "*",$or_where = "",$where_in = "", $order_by = "" ){
$this->db->select($select);
$this->db->from($table);
if (!empty($join)) {
foreach ($join as $key => $value) {
$this->db->join($key,$value,'left');
}
}
if (!empty($where)) {
$this->db->where($where);
}
if (!empty($or_where)) {
$this->db->or_where($or_where);
}
if (!empty($where_in)) {
foreach ($where_in as $key => $value) {
$this->db->where_in($key, $value);
}
}
if (!empty($like)) {
$this->db->like($like);
}
if ($single_row) {
$res = $this->db->get()->row();
}else{
if (!empty($order_by)) {
$this->db->order_by($order_by);
}
$res = $this->db->get()->result();
}
return $res;
}
public function delete_data($table,$where){
$this->db->where($where);
$res = $this->db->delete($table);
return $res;
}
public function add_data($table,$data,$batch = false){
if ($batch) {
$res = $this->db->insert_batch($table, $data);
}else{
$res = $this->db->insert($table, $data);
}
return $this->db->insert_id();
}
public function update_data($table,$where,$data,$batch = false){
if ($batch) {
$res = $this->db->update_batch($table,$data,$where);
}else{
$this->db->where($where);
$res = $this->db->update($table, $data);
}
return $res;
}
public function upload_file($file,$input_name,$path){
if ($file['error'] != 4 ) {
$config['upload_path'] = $path;
$config['allowed_types'] = '*';
$file_name = rand().$file['name'];
$config['file_name'] = str_replace(" ","_",$file_name);
$this->load->library('upload');
$this->upload->initialize($config);
if ( $this->upload->do_upload($input_name))
{
return $config['file_name'];
}else{
$error = array('error' => $this->upload->display_errors());
print_r($error);
}
}
return false;
}
public function record_payment($advert_obj){
$this->db->where('advert_id', $advert_obj->advert_id);
$this->db->set('status', 2);
$this->db->update('advertisements');
$price_imp = $this->settings_model->get_value("price_per_impression");
$unpaid_impressions = $advert_obj->impressions-$advert_obj->paid_impressions;
$price = $unpaid_impressions*$price_imp;
$payment = $this->quick_books->payment($advert_obj->card_id,round($price, 2));
// echo $price;
// print_r($payment); die;
if (isset($payment->status) && @$payment->status == "CAPTURED") {
$data['status'] = "success";
$data['advert_id'] = $advert_obj->advert_id;
$data['payment_qb_id'] = $payment->id;
$data['amount'] = $payment->amount;
$data['impressions'] = $unpaid_impressions;
$this->add_data("payments",$data);
$this->db->where('advert_id', $advert_obj->advert_id);
$this->db->set("paid_impressions","paid_impressions + ".$unpaid_impressions , false);
$this->db->update('advertisements');
return true;
}else{
$this->db->where('advert_id', $advert_obj->advert_id);
$this->db->set('status', 3);
$this->db->update('advertisements');
if (isset($payment->errors)) {
$payment_error = $payment->errors;
$msg = current($payment_error)->moreInfo;
}else{
$msg = $payment->code;
}
$this->session->set_flashdata("error_msg", "<b>Payment Error: </b>".$msg);
}
}
public function get_user_data1($user_id){
$query = $this->db->query("SELECT * FROM card_info WHERE user_id='$user_id'");
$row = $query->result();
return $row;
}
public function get_user_info($user_id){
$query = $this->db->query("SELECT * FROM users WHERE user_id='$user_id'");
$row = $query->result();
return $row;
}
public function update_card_info($user_id,$data){
$insertres = $this->get_user_data1($user_id);
//print_r($insertres);
//die;
if(empty($insertres)){
$result = $this->db->insert('card_info', $data);
}else{
$this->db->where('user_id', $user_id);
$result = $this->db->update('card_info', $data);
}
if($result){
return true;
}else{
return false;
}
}
}
?><file_sep>/application/views/analytics/includes/navbar.php
<nav class="header-navbar pdng0 navbar-expand-md navbar-with-menu navbar-without-dd-arrow fixed-top bg-white navbar-shadow bg264157">
<div class="navbar-wrapper ">
<div class="navbar-header">
<ul class="nav navbar-nav flex-row">
<li class="nav-item mobile-menu d-md-none mr-auto"><a class="nav-link nav-menu-main menu-toggle hidden-xs" href="#"><!-- <i class="ft-menu font-large-1"></i> -->
<img src="<?php echo base_url() ?>frontend/images/line.png">
</a></li>
<li class="nav-item"><a class="navbar-brand" href="index.html"><img class="" alt="modern admin logo" style="width: 200px" src="<?php echo base_url() ?>frontend/images/logo.png">
</a></li>
<li class="nav-item d-md-none"><a class="nav-link open-navbar-container" data-toggle="collapse" data-target="#navbar-mobile"><i class="fa fa-ellipsis-v text-white"></i></a></li>
</ul>
</div>
<div class="navbar-container content">
<div class="collapse navbar-collapse" id="navbar-mobile">
<ul class="nav navbar-nav mr-auto float-left">
<li class="nav-item d-none d-md-block"><a class="nav-link nav-menu-main menu-toggle hidden-xs" href="#"><!-- <i class="ft-menu"></i> -->
</a></li>
<li class="nav-item nav-search">
<div class="row">
<form class="form" >
<div class="input-group">
<input class="form-control width327sm" type="text" placeholder="Search" aria-label="Search" style="padding-left: 20px; border-radius: 40px;" id="mysearch">
<div class="input-group-addon" style="margin-left: -50px; z-index: 3; border-radius: 40px; background-color: transparent; border:none;">
<i class="fas fa-search"></i>
</div>
</div>
</form>
</div>
</li>
</ul>
<ul class="nav navbar-nav float-right">
<li class="dropdown dropdown-user pdng0 nav-item">
<a class="dropdown-toggle pdng0 nav-link dropdown-user-link" href="#" data-toggle="dropdown">
<!-- <span class="avatar header_circle">
<img src="images/Settings Icon.png" alt="avatar" width="auto"></span> -->
<span class="avatar avatar-online">
<?php
$user=$this->session->userdata("user_session");
if ($user->profile_image != "") {
$img_src = base_url().PROFILE_IMAGE_UPLOAD_PATH.$user->profile_image;
}else{
$img_src = base_url()."assets/layouts/layout4/img/avatar.png";
}
?>
<img style="height: 35px;" class="img-circle" src="<?=$img_src?>" alt="">
</span>
<span class="header_username"><?php
echo get_user_fullname();
?></span></a>
<div class="dropdown-menu dropdown-menu-right"><a class="dropdown-item" href="#"><i class="ft-user"></i> Edit Profile</a><a class="dropdown-item" href="#"><i class="ft-mail"></i> My Inbox</a><a class="dropdown-item" href="#"><i class="ft-check-square"></i> Task</a><a class="dropdown-item" href="#"><i class="ft-message-square"></i> Chats</a>
<div class="dropdown-divider"></div><a class="dropdown-item" href="#"><i class="ft-power"></i> Logout</a>
</div>
</li>
<li class="dropdown dropdown-notification nav-item">
<a class="nav-link pdng0 nav-link-label" href="#" data-toggle="dropdown">
<p class="header_time">11:31PM</p>
</a>
</li>
<li class="dropdown dropdown-notification nav-item"><a class="nav-link pdng0 nav-link-label" href="#" data-toggle="dropdown"><img src="<?php echo base_url() ?>frontend/images/Right Menu.png" ></a>
<ul class="dropdown-menu dropdown-menu-media dropdown-menu-right">
<li class="dropdown-menu-header">
<h6 class="dropdown-header m-0"><span class="grey darken-2">Messages</span></h6><span class="notification-tag badge badge-default badge-warning float-right m-0">4 New</span>
</li>
<li class="scrollable-container media-list w-100"><a href="javascript:void(0)">
<div class="media">
<div class="media-left"><span class="avatar avatar-sm avatar-online rounded-circle"><img src="<?php echo base_url() ?>frontend/app-assets/images/portrait/small/avatar-s-19.png" alt="avatar"><i></i></span></div>
<div class="media-body">
<h6 class="media-heading"><NAME></h6>
<p class="notification-text font-small-3 text-muted">I like your portfolio, let's start.</p><small>
<time class="media-meta text-muted" datetime="2015-06-11T18:29:20+08:00">Today</time></small>
</div>
</div></a><a href="javascript:void(0)">
<div class="media">
<div class="media-left"><span class="avatar avatar-sm avatar-busy rounded-circle"><img src="<?php echo base_url() ?>frontend/app-assets/images/portrait/small/avatar-s-2.png" alt="avatar"><i></i></span></div>
<div class="media-body">
<h6 class="media-heading"><NAME></h6>
<p class="notification-text font-small-3 text-muted">I have seen your work, there is</p><small>
<time class="media-meta text-muted" datetime="2015-06-11T18:29:20+08:00">Tuesday</time></small>
</div>
</div></a><a href="javascript:void(0)">
<div class="media">
<div class="media-left"><span class="avatar avatar-sm avatar-online rounded-circle"><img src="<?php echo base_url() ?>frontend/app-assets/images/portrait/small/avatar-s-3.png" alt="avatar"><i></i></span></div>
<div class="media-body">
<h6 class="media-heading"><NAME></h6>
<p class="notification-text font-small-3 text-muted">Can we have call in this week ?</p><small>
<time class="media-meta text-muted" datetime="2015-06-11T18:29:20+08:00">Friday</time></small>
</div>
</div></a><a href="javascript:void(0)">
<div class="media">
<div class="media-left"><span class="avatar avatar-sm avatar-away rounded-circle"><img src="<?php echo base_url() ?>frontend/app-assets/images/portrait/small/avatar-s-6.png" alt="avatar"><i></i></span></div>
<div class="media-body">
<h6 class="media-heading"><NAME></h6>
<p class="notification-text font-small-3 text-muted">We have project party this saturday.</p><small>
<time class="media-meta text-muted" datetime="2015-06-11T18:29:20+08:00">last month</time></small>
</div>
</div></a></li>
<li class="dropdown-menu-footer"><a class="dropdown-item text-muted text-center" href="javascript:void(0)">Read all messages</a></li>
</ul>
</li>
</ul>
</div>
</div>
</div>
</nav>
<div class="app-content content">
<div class="">
<div class="content-body">
<div class="row pt-5">
<div class="col-md-3 col-lg-2 col-xl-2 col-sm-12 col-xs-12 bg-white mt_36 hm mb-3" id="sidenav">
<div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()" style="color:#fff">×</a>
<div class="div1">
<div class="circle rounded-circle margin"></div>
<div class="smallcircle rounded-circle mt-n3"></div>
<p class="para1 mt-2 margin1"><?php
echo get_user_fullname();
?><br><small class="small1 ml-1"><?php
echo get_user_role();
?></small></p>
</div>
<a href="#"><img src="<?php echo base_url() ?>frontend/img/dashborad.png" alt="image" class="pt-1"><span class="navfont">DASHBOARD</span></a>
<a href="#"><img src="<?php echo base_url() ?>frontend/img/buyer.png" alt="image" class="pt-1"><span class="navfont">BUYER PERFORMA</span></a>
<a href="#"><img src="<?php echo base_url() ?>frontend/img/location.png" alt="image" class="pt-1"><span class="navfont">LOCATIONS</span></a>
<a href="#"><img src="<?php echo base_url() ?>frontend/img/setting1.png" alt="image" class="pt-1"><span class="navfont">SETTINGS</span></a>
</div>
<div class="row pt36">
<div class="col-sm-3"></div>
<div class="col-sm-9 col-md-12 center_img">
<div class="margin"> <?php
$user=$this->session->userdata("user_session");
if ($user->profile_image != "") {
$img_src = base_url().PROFILE_IMAGE_UPLOAD_PATH.$user->profile_image;
}else{
$img_src = base_url()."assets/layouts/layout4/img/avatar.png";
}
?>
<img class="img-circle circle rounded-circle" src="<?=$img_src?>" alt=""></div>
<div class="smallcircle rounded-circle mt-n3">
</div>
<p class="para1 margin1 text-center"><?php
echo get_user_fullname();
?><br><small class="small1 ml-1"><?php
echo get_role_byid(get_user_role());
?></small></p>
</div>
</div>
<div class="row mt-2">
<div class="col-12 col-sm-12 col-md-12 hide zoomonhover">
<a href="<?=base_url()?>analytics/dashboard/<?=$this->uri->segment(3)?>">
<div class="row">
<div class="col-3 col-sm-3 col-md-4 text-right"><img src="<?php echo base_url() ?>frontend/img/dashborad.png" alt="image" class="pt-1"></div>
<div class="col-9 col-sm-9 col-md-8 menucolor1">
<h6 class="mt-2 color3">DASHBOARD</h6>
</div>
</div>
</a>
</div>
</div>
<?php
if (has_permission("location_videos")) {
?>
<div class="row mt-3">
<div class="col-12 col-sm-12 col-md-12 hide zoomonhover">
<a href="<?=base_url('analytics/videos/').$this->uri->segment(3)?>">
<div class="row">
<div class="col-3 col-sm-3 col-md-4 text-right"><img src="<?php echo base_url() ?>frontend/images/video.png" width="35px" alt="image" class="pt-1"></div>
<div class="col-9 col-sm-9 col-md-8 menucolor1">
<h6 class="mt-2 color3">Videos</h6>
</div>
</div>
</a>
</div>
</div>
<?php
}
?>
<div class="row mt-3">
<div class="col-12 col-sm-12 col-md-12 hide zoomonhover">
<a href="#">
<div class="row">
<div class="col-3 col-sm-3 col-md-4 text-right"><img src="<?php echo base_url() ?>frontend/img/buyer.png" alt="image" class="pt-1"></div>
<div class="col-9 col-sm-9 col-md-8 menucolor1">
<h6 class="mt-2 color3">BUYER PERSONA</h6>
</div>
</div>
</a>
</div>
</div>
<div class="row mt-3">
<div class="col-12 col-sm-12 col-md-12 hide zoomonhover">
<a href="#">
<div class="row">
<div class="col-3 col-sm-3 col-md-4 text-right"><img src="<?php echo base_url() ?>frontend/img/location.png" alt="image" class="mt-1"></div>
<div class="col-9 col-sm-9 col-md-8 menucolor1">
<h6 class="mt-2 color3">LOCATIONS</h6>
</div>
</div>
</a>
</div>
</div>
<div class="row mt-3 mb-3">
<div class="col-12 col-sm-12 col-md-12 hide zoomonhover">
<a href="#">
<div class="row padding">
<div class="col-3 col-sm-3 col-md-4 text-right"><img src="<?php echo base_url() ?>frontend/img/setting1.png" alt="image" class="mt-1"></div>
<div class="col-9 col-sm-9 col-md-8 menucolor1">
<h6 class="mt-2 color3">SETTINGS</h6>
</div>
</div>
</a>
</div>
</div>
</div><file_sep>/application/views/recruitment/view_recruitment.php
<div class="page-content-col">
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-green-haze bold uppercase">User Info</span>
</div>
<div class="tools">
<a href="" class="collapse" data-original-title="" title=""> </a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form class="form-horizontal" role="form">
<div class="form-body">
<div style="float: left;">
<h2 class="margin-bottom-20"> View User Info - <?php echo $user->first_name." ".$user->last_name; ?> </h2>
</div>
<?php
if ($user->profile_image != "") {
$img_src = base_url().PROFILE_IMAGE_UPLOAD_PATH.$user->profile_image;
}else{
$img_src = base_url()."assets/layouts/layout4/img/avatar.png";
}
?>
<div style="float: right;"> <img style="width: 100px; height: 100px;" src="<?=$img_src?>" alt=""> </div>
<div class="clearfix"></div>
<h3 class="form-section">Person Info</h3>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">First Name:</label>
<div class="col-md-9">
<p class="form-control-static"> <?php echo $user->first_name; ?> </p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Last Name:</label>
<div class="col-md-9">
<p class="form-control-static"> <?php echo $user->last_name; ?> </p>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Gender:</label>
<div class="col-md-9">
<p class="form-control-static"> <?php echo ($user->gender == 1 ? "Male" : "Female"); ?> </p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Date of Birth:</label>
<div class="col-md-9">
<p class="form-control-static"> <?php echo $user->date_of_birth; ?> </p>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Email</label>
<div class="col-md-9">
<p class="form-control-static"> <?php echo $user->email; ?> </p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Paypal ID:</label>
<div class="col-md-9">
<p class="form-control-static"> <?php echo $user->paypal_id; ?> </p>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<h3 class="form-section">Address</h3>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Street:</label>
<div class="col-md-9">
<p class="form-control-static"> <?php echo $user->street; ?></p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">City:</label>
<div class="col-md-9">
<p class="form-control-static"> <?php echo $user->city; ?> </p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">State:</label>
<div class="col-md-9">
<p class="form-control-static"> <?php echo $user->state; ?> </p>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Post Code:</label>
<div class="col-md-9">
<p class="form-control-static"> <?php echo $user->post_code; ?> </p>
</div>
</div>
</div>
<!--/span-->
</div>
</div>
</form>
<!-- END FORM-->
</div>
</div>
</div><file_sep>/application/models/Video_model.php
<?php
class Video_model extends Crud_model{
public $table = "videos";
public function __construct() {
parent::__construct();
}
public function makeFrames($videoFile){
$galleryID = generateGalleryID();
if (!file_exists('./frames/'.$galleryID)) {
mkdir('./frames/'.$galleryID, 0777, true);
}
$imgOut= "./frames/".$galleryID."/out%d.png";
$complete = system("ffmpeg -i $videoFile -vf fps=0.0625 -vsync 0 $imgOut 2>&1");
if ($complete) {
return $galleryID;
}
return false;
}
public function insertGalleryID($galleryID,$locationID){
$data['galleryID'] = $galleryID;
$data['locationID'] = $locationID;
$res = $this->add_data($this->table,$data);
if ($res) {
return $this->db->insert_id();
}
return false;
}
public function get_emotions($params = array(), $filter = "Percentage"){
$data = array("happy_cent"=>0,"sad_cent"=>0,"normal_cent"=>0);
$happy = 0;
$sad = 0;
$normal = 0;
$get_data['table'] = "videoemotions";
$get_data['join']['videos v'] = "v.videoID=videoemotions.videoID";
if (!empty($params)) {
$where = array();
if (isset($params['start_date']) && isset($params['end_date'])) {
$where['date(v.created_at) >='] = $params['start_date'];
$where['date(v.created_at) <='] = $params['end_date'];
}elseif (isset($params['locationID'])) {
$where['V.locationID'] = $params['locationID'];
}elseif (isset($params['video_ids'])) {
$get_data['where_in']['V.videoID'] = $params['video_ids'];
}
$get_data['where'] = $where;
}
$res = $this->get_data_new($get_data);
if (!empty($res)) {
foreach ($res as $key => $value) {
if ($value->emotion == 0) {
$normal++;
}elseif ($value->emotion == 1) {
$happy++;
}elseif ($value->emotion == 2) {
$sad++;
}
}
if ($filter == "Percentage") {
$data['happy_cent'] = round(($happy/count($res))*100);
$data['sad_cent'] = round(($sad/count($res))*100);
$data['normal_cent'] = round(($normal/count($res))*100);
}else{
$data['happy_cent'] = $happy;
$data['sad_cent'] = $sad;
$data['normal_cent'] = $normal;
}
}
return $data;
}
public function get_analytics($params = array(), $filter = "Percentage"){
$data = array('total_visitors'=>0,'avg_age'=>0,'total_male'=>0,'total_female'=>0,"male_cent"=> 0, "female_cent"=> 0,"age_group"=>array(),"unique_visitors"=>array());
$total_age = 0;
$get_data['join']['videos v'] = "v.videoID=videoanalysis.videoID";
$get_data['table'] = "videoanalysis";
if (!empty($params)) {
$where = array();
if (isset($params['start_date']) && isset($params['end_date'])) {
$where['date(v.created_at) >='] = $params['start_date'];
$where['date(v.created_at) <='] = $params['end_date'];
}elseif (isset($params['locationID'])) {
$where['V.locationID'] = $params['locationID'];
}elseif (isset($params['video_ids'])) {
$get_data['where_in']['V.videoID'] = $params['video_ids'];
}
$get_data['where'] = $where;
}
$res = $this->get_data_new($get_data);
if (!empty($res)) {
$age_group = array();
$unique_visitors = array();
$i = 1;
while ($i <= 90) {
$j = $i;
$i = $i + 4;
$age_group[$j."-".$i] = 0;
$i++;
}
foreach ($res as $key => $value) {
if ($value->duplicate == 0) {
$data['total_visitors']++;
$total_age += $value->age;
foreach ($age_group as $k => $v) {
$age_array = explode("-", $k);
if ( ($age_array[0] <= $value->age) && ($value->age <= $age_array[1])) {
$age_group[$k]++;
}
}
if ($value->gender == "M") {
$data['total_male']++;
}elseif ($value->gender == "F") {
$data['total_female']++;
}
$unique_visitors[] = $value;
}
}
$data['avg_age'] = round($total_age/$data['total_visitors'],2);
if ($filter == "Percentage") {
$data['male_cent'] = round(($data['total_male']/$data['total_visitors'])*100);
$data['female_cent'] = round(($data['total_female']/$data['total_visitors'])*100);
}else{
$data['male_cent'] = $data['total_male'];
$data['female_cent'] = $data['total_female'];
}
$data['age_group'] = $age_group;
$data['unique_visitors'] = $unique_visitors;
}
$emotions = $this->get_emotions($params,$filter);
$data = array_merge($emotions,$data);
return $data;
}
public function deleteVideoData($videoID){
$where['videoID'] = $videoID;
$this->delete_data('videos',$where);
$this->delete_data('videoanalysis',$where);
$this->delete_data('videoemotions',$where);
}
}
?><file_sep>/application/views/designer/designer_sidebar.php
<li class="">
<a href="<?php echo base_url()?>designer">
Tasks Assigned
</a>
</li>
<li>
<a href="<?php echo base_url()?>designer/1">
Tasks Completed
</a>
</li>
<li>
<a href="<?php echo base_url()?>designer/view_deliveries">
Deliveries
</a>
</li>
<file_sep>/application/views/location_manager/view_deliveries.php
<!-- END PAGE SIDEBAR -->
<div class="page-content-col">
<!-- BEGIN PAGE BASE CONTENT -->
<table class="table table-bordered table-stripped datatable">
<thead>
<tr>
<th>Sr.</th>
<th>Advertise Number</th>
<th>Location Number</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
foreach ($proofs as $key => $value) {
echo "<tr>
<td>".$i."</td>
<td>".$value->advert_number."</td>
<td>".$value->location_number."</td>";
$user_role = get_user_role();
if ($user_role == 1) {
echo "<td> <input type='checkbox' ". ($value->task_status == 1 ? 'checked' : '') ." data-record_id='{$value->task_id}' data-table='tasks' data-where='task_id' class='make-switch change_record_status' data-on-text='Complete' data-off-text='Uncomplete'> </td>";
}else{
echo "<td>".get_status($value->task_status)."</td>";
}
echo "<td> <a class='btn btn-primary round-btn' href='".base_url()."location_manager/tasks_assigned/".$value->task_id."'>View Deatils</a> <a href='".base_url().PROOF_UPLOAD_PATH.$value->delivery_file."' download class='btn btn-success round-btn'>View Delivery</a></td>
</tr>";
$i++;
}
?>
</tbody>
</table>
<!-- END PAGE BASE CONTENT -->
</div>
<file_sep>/application/views/admin/quickbooks_connect.php
<script
type="text/javascript"
src="https://appcenter.intuit.com/Content/IA/intuit.ipp.anywhere-1.3.3.js">
</script>
<script type="text/javascript">
var redirectUrl = "<?=$redirect_uri?>"
intuit.ipp.anywhere.setup({
grantUrl: redirectUrl,
datasources: {
quickbooks : true,
payments : true
},
paymentOptions:{
intuitReferred : true
}
});
</script>
<!-- END PAGE SIDEBAR -->
<div class="page-content-col">
<!-- BEGIN PAGE BASE CONTENT -->
<div class="row">
<?php
if ($this->session->flashdata("success_msg") != "") {
?>
<div class="alert alert-success">
<?php echo $this->session->flashdata("success_msg"); ?>
</div>
<?php
}
?>
</div>
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-blue-hoki bold uppercase">Connect QuickBooks</span>
</div>
<div class="tools">
<a href="" class="collapse" data-original-title="" title=""> </a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="" method="post" enctype="multipart/form-data" class="horizontal-form">
<div class="form-body">
<div class="row">
<div class="col-md-offset-3 col-md-6">
<div class="form-group">
<label class="control-label">Client ID</label>
<input type="text" class="form-control qb_client_id" name="qb_client_id" placeholder="Enter Client ID" value="<?php echo $qb_client_id; ?>">
</div>
</div>
</div>
<div class="row">
<!--/span-->
<div class="col-md-offset-3 col-md-6">
<div class="form-group">
<label class="control-label">Client Secret</label>
<input type="text" id="qb_client_secret" class="form-control qb_client_secret" placeholder="Enter Client Secret" name="qb_client_secret" value="<?php echo $qb_client_secret; ?>">
</div>
</div>
<!--/span-->
</div>
<div class="form-actions right">
<input type="submit" class="btn blue" value="Update Credentials">
</div>
</div>
</form>
</div>
</div>
<ipp:connectToIntuit></ipp:connectToIntuit><br />
<!-- END PAGE BASE CONTENT -->
</div><file_sep>/application/controllers/Location_manager-old.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Location_manager extends GH_Controller {
private $data;
public $table = "locations";
public function __construct() {
parent::__construct();
$this->data['menu_class'] = "manager_menu";
$this->data['title'] = "Location Manager";
$this->data['sidebar_file'] = "location_manager/manager_sidebar";
}
function _remap($method,$param){
if (method_exists($this,$method)) {
if (!empty($param)) {
$this->$method($param[0]);
}else{
$this->$method();
}
} else {
$this->index($method);
}
}
/*STATUS
* 0: Not activated
* 1: Activated
* 2: Waiting for Approval of location manager work
* 3: Approved Location Manager work
* 4: Waiting for approval of designer work
* 5: Approved Designer work
* 6: Uncompleted for location Manager
* 7: Uncompleted for designer
*/
public function index($status)
{
$or_where = "";
if ($status == 1) {
$or_where = "(a.status = 5 AND a.hologram_type= 2) OR (a.status = 6 AND a.hologram_type= 2) OR (a.status = 2 AND a.hologram_type= 2) OR (a.status = 6 AND a.hologram_type= 1) OR (a.status = 2 AND a.hologram_type= 1)";
}elseif ($status == 3) {
$or_where = "(a.status = 3 AND a.hologram_type= 2)";
}
$where['a.status'] = $status;
$where['a.hologram_type'] = 1;
$join['locations l'] = "a.location_id=l.location_id";
$this->data['tasks'] = $this->crud_model->get_data('advertisements a',$where,'',$join,'','',$or_where);
$this->data['status'] = $status;
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('location_manager/manager');
$this->load->view('common/footer');
}
public function tasks_assigned($advert_id){
$where['a.advert_id'] = $advert_id;
$join['locations l'] = "a.location_id=l.location_id";
$this->data['task'] = $this->crud_model->get_data('advertisements a',$where,true,$join);
$where['proof_type'] = "manager";
$this->data['delivery_file'] = $this->crud_model->get_data('proofs a',$where,true);
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('location_manager/tasks_assigned');
$this->load->view('common/footer');
}
public function deliver_task($advert_id){
$form_data = $this->input->post();
if (!empty($form_data)) {
if ($_FILES['proof_file']['error'] == 4)
{
$this->form_validation->set_rules('proof_file', '*File', 'required', array(
'required' => '%s Missing'
));
$result = $this->form_validation->run();
}else{
$result = true;
}
if ($result) {
$proof_file = $this->crud_model->upload_file($_FILES['proof_file'],'proof_file',PROOF_UPLOAD_PATH);
if ($proof_file) {
$where_get_proof['advert_id'] = $form_data['advert_id'];
$where_get_proof['proof_type'] = 'manager';
$proofs = $this->crud_model->get_data("proofs",$where_get_proof,true);
if (!empty($proofs)) {
$form_data['proof_file'] = $proof_file;
$where_update_proof['proof_id'] = $proofs->proof_id;
$proof = $this->crud_model->update_data("proofs",$where_update_proof,$form_data);
}else{
$form_data['proof_file'] = $proof_file;
$form_data['user_id'] = get_user_id();
$form_data['proof_type'] = "manager";
$proof = $this->crud_model->add_data("proofs",$form_data);
}
if ($proof) {
$where['advert_id'] = $form_data['advert_id'];
$advert = $this->crud_model->update_data('advertisements',$where,array("status"=>2));
if ($advert) {
$this->session->set_flashdata("success_msg","Task Delivered");
}else{
$this->session->set_flashdata("error_msg","Task Not Delivered");
}
redirect($_SERVER['HTTP_REFERER']);
}
}
}
}
$this->data['advert_id'] = $advert_id;
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('location_manager/deliver_task');
$this->load->view('common/footer');
}
public function view_deliveries(){
$join['advertisements a'] = "a.advert_id=p.advert_id";
$join['locations l'] = "a.location_id=l.location_id";
$where['p.proof_type'] = "manager";
$this->data['proofs'] = $this->crud_model->get_data("proofs p",$where,'',$join,'','*,p.status as proof_status');
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('location_manager/view_deliveries');
$this->load->view('common/footer');
}
}<file_sep>/application/views/location/manage_location.php
<div class="page-content-col">
<div class="row">
<?php
if ($this->session->flashdata("error_msg") != "") {
?>
<div class="alert alert-danger">
<?php echo $this->session->flashdata("error_msg"); ?>
</div>
<?php
}
?>
</div>
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-purple-soft bold uppercase">Manage Location
</span>
</div>
</div>
<div class="portlet-body form">
<ul class="nav nav-tabs">
<li class="active">
<a href="#location_details_tab" data-toggle="tab" aria-expanded="true"> Location Details
</a>
</li>
<!-- <li class="">
<a href="#location_owner_tab" data-toggle="tab" aria-expanded="false"> Location Owner
</a>
</li> -->
</ul>
<form action="" method="post" enctype="multipart/form-data" class="horizontal-form">
<div class="form-body">
<div class="tab-content">
<div class="tab-pane fade active in" id="location_details_tab">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Location Name
</label>
<input id="location_name" name="location_name" class="form-control location_name" value="<?=set_value('location_name')?>" type="text">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Number of displays in locations
</label>
<input id="displays" name="displays" class="form-control displays" value="<?=set_value('displays')?>" type="number">
</div>
</div>
</div>
<!-- <div class="row">
<div class="col-md-6">
<div class="form-group">
<label>How many people will see the ad every month
</label>
<input id="monthly_views" name="monthly_views" class="form-control monthly_views" value="<?=set_value('monthly_views')?>" type="text">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Main demographic
</label>
<input id="main_demographic" name="main_demographic" class="form-control main_demographic" value="<?=set_value('main_demographic')?>" type="text">
</div>
</div>
</div> -->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Industry
</label>
<input id="industry " name="industry" class="form-control industry" value="<?=set_value('industry')?>" type="text">
</div>
</div>
<!-- <div class="col-md-6">
<div class="form-group">
<label>Age Group
</label>
<input id="age_group" name="age_group" class="form-control age_group" value="<?=set_value('age_group')?>" type="text">
</div>
</div> -->
<!-- </div>
<div class="row"> -->
<!-- <div class="col-md-6">
<div class="form-group">
<label>Cost Per Month
</label>
<input id="monthly_cost " name="monthly_cost" class="form-control monthly_cost" value="<?=set_value('monthly_cost')?>" type="text">
</div>
</div> -->
<div class="col-md-6">
<?php
$owner_royalty = 10;
if (set_value('owner_royalty') != "") {
$owner_royalty = set_value('owner_royalty');
}
?>
<div class="form-group">
<label>Owner Royalty (%)
</label>
<input id="owner_royalty" name="owner_royalty" class="form-control owner_royalty" value="<?=$owner_royalty?>" type="number">
</div>
</div>
<!-- </div>
<div class="row"> -->
<div class="col-md-6">
<?php
$advert_royalty = 5;
if (set_value('advert_royalty') != "") {
$advert_royalty = set_value('advert_royalty');
}
?>
<div class="form-group">
<label>Advertiser Royalty (%)
</label>
<input id="advert_royalty" name="advert_royalty" class="form-control advert_royalty" value="<?=$advert_royalty?>" type="number">
</div>
</div>
<?php
if (is_admin()) {
?>
<?php
$created_by = set_value('created_by');
if ($created_by == "") {
$created_by = get_user_id();
}
?>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Added by
</label>
<select class="form-control created_by" name="created_by">
<?php
foreach ($users as $key => $value) {
echo "<option ".($created_by == $value->user_id ? 'selected' : '')." value='".$value->user_id."' >".$value->first_name." ".$value->last_name."</option>";
}
?>
</select>
</div>
</div>
<?php
}
?>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Location Type
</label>
<select class="form-control location_type" name="location_type">
<option value="1">Public</option>
<option value="0">Private</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>What can be advertised in location
</label>
<textarea name="location_description" class="location_description form-control" rows="5"><?=set_value('location_description')?></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Other Notes
</label>
<textarea name="other_notes" class="other_notes form-control" rows="5"><?=set_value('other_notes')?></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Location Image
</label>
<input id="location_image " name="location_image" type="file">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Location Video
</label>
<input id="location_video " name="location_video" type="file">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<?php
$location_address_error = form_error('location_address');
?>
<div class="form-group <?php echo ($location_address_error != '') ? 'has-error' : '' ?>">
<label class="control-label">Location Address
</label>
<input id="autocomplete" class="form-control location_address" name="location_address" placeholder="Enter Location Address" value="<?php echo (set_value('location_address')); ?>" type="text">
<span class="help-block"> <?php echo $location_address_error; ?> </span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 ">
<?php
$location_street = set_value('location_street');
?>
<div class="form-group">
<label>Street
</label>
<input id="street_number" name="location_street" class="form-control location_street" value="<?php echo $location_street; ?>" type="text" <?php echo ($location_street == "" ? 'disabled' : '') ?> >
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<?php
$location_city = set_value('location_city');
?>
<div class="form-group">
<label>City
</label>
<input id="locality" name="location_city" class="form-control location_city" value="<?php echo $location_city; ?>" type="text" <?php echo ($location_city == "" ? 'disabled' : '') ?>>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<?php
$location_state = set_value('location_state');
?>
<div class="form-group">
<label>State
</label>
<input id="administrative_area_level_1" name="location_state" class="form-control location_state" value="<?php echo $location_state; ?>" type="text" <?php echo ($location_state == "" ? 'disabled' : '') ?>>
</div>
</div>
<!--/span-->
</div>
<div class="row">
<div class="col-md-6">
<?php
$location_post_code = set_value('location_post_code');
?>
<div class="form-group">
<label>Post Code
</label>
<input id="postal_code" name="location_post_code" class="form-control location_post_code" value="<?php echo $location_post_code; ?>" type="text" <?php echo ($location_post_code == "" ? 'disabled' : '') ?> >
</div>
</div>
<div class="col-md-6">
<?php
$location_country = set_value('location_country');
?>
<div class="form-group">
<label>Country
</label>
<input id="country" name="location_country" class="form-control location_country" value="<?php echo $location_country; ?>" type="text" <?php echo ($location_country == "" ? 'disabled' : '') ?>>
</div>
</div>
</div>
<h3 class="form-section">Location Owner</h3>
<div class="row">
<div class="col-md-6">
<?php $owner_type = set_value('owner_type');
$owner_type_error = form_error('owner_type');
?>
<div class="form-group <?php echo ($owner_type_error != '') ? 'has-error' : '' ?> ">
<label class="control-label">Location Owner Type
</label>
<select id="owner_type" name="owner_type" class="form-control" onchange="location_owner_type()">
<option value="" <?php echo ($owner_type == '') ? 'selected' : '' ?> >Select Owner Type
</option>
<option value="1" <?php echo ($owner_type == 1) ? 'selected' : '' ?> >Select Existing Owner
</option>
<option value="2" <?php echo ($owner_type == 2) ? 'selected' : '' ?> >Add New Owner
</option>
</select>
<span class="help-block"> <?php echo $owner_type_error; ?> </span>
</div>
</div>
<div class="col-md-6 location_owner_div" style="display: none;">
<?php $location_owner = set_value('location_owner');
$location_owner_error = form_error('location_owner');
?>
<div class="form-group <?php echo ($location_owner_error != '') ? 'has-error' : '' ?> ">
<label class="control-label">Select Location Owner
</label>
<select name="location_owner" class="form-control location_owner">
<option value="" <?php echo ($location_owner == '') ? 'selected' : '' ?> >Select Location Owner
</option>
<?php
foreach ($owners as $key => $value) {
echo "<option ".($location_owner == $value->user_id ? 'selected' : '')." value='".$value->user_id."' >".$value->first_name." ".$value->last_name."</option>";
}
?>
</select>
<span class="help-block"> <?php echo $location_owner_error; ?> </span>
</div>
</div>
</div>
<div class="user_info" style="display: none;">
<div class="row">
<div class="col-md-6">
<?php
$first_name_error = form_error('user[first_name]');
?>
<div class="form-group <?php echo ($first_name_error != '') ? 'has-error' : '' ?>">
<label class="control-label">First Name
</label>
<input id="firstName" class="form-control first_name" name="user[first_name]" placeholder="Enter First Name" value="<?php echo (set_value('user[first_name]')); ?>" type="text">
<span class="help-block"> <?php echo $first_name_error; ?> </span>
</div>
</div>
<div class="col-md-6">
<?php
$last_name_error = form_error('user[last_name]');
?>
<div class="form-group <?php echo ($last_name_error != '') ? 'has-error' : '' ?>">
<label class="control-label">Last Name
</label>
<input id="lastName" class="form-control last_name" placeholder="Enter Last Name" name="user[last_name]" value="<?php echo (set_value('user[last_name]')); ?>" type="text">
<span class="help-block"> <?php echo $last_name_error; ?> </span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Gender
</label>
<select class="form-control gender" name="user[gender]">
<option value="1">Male
</option>
<option value="0">Female
</option>
</select>
</div>
</div>
<div class="col-md-6">
<?php
$email_error = form_error('user[email]');
?>
<div class="form-group <?php echo ($email_error != '') ? 'has-error' : '' ?>">
<label class="control-label">Email
</label>
<input id="email_input" name="user[email]" class="form-control email" value="<?php echo (set_value('user[email]')); ?>" type="email">
<span class="help-block"> <?php echo $email_error; ?> </span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<?php
$password_error = form_error('user[password]');
?>
<div class="form-group <?php echo ($password_error != '') ? 'has-error' : '' ?>">
<label for="exampleInputFile1">Password</label>
<input type="password" name="user[password]" class="form-control password" value="<?php echo (set_value('user[password]')); ?>">
<span class="help-block"> <?php echo $password_error; ?> </span>
</div>
</div>
<div class="col-md-6">
<?php
$re_password_error = form_error('user[re_password]');
?>
<div class="form-group <?php echo ($re_password_error != '') ? 'has-error' : '' ?>">
<label for="exampleInputFile1">Re-Type Password
</label>
<input name="user[re_password]" class="form-control password" value="<?php echo (set_value('user[re_password]')); ?>" type="password">
<span class="help-block"> <?php echo $re_password_error; ?> </span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group ">
<label for="exampleInputFile1">Phone Number</label>
<input type="text" name="user[phone_number]" class="form-control phone_number" value="<?php echo (set_value('user[phone_number]')); ?>">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="form-actions right">
<input class="location_lat" value="<?php echo (set_value('location_lat')); ?>" name="location_lat" type="hidden">
<input class="location_lng" value="<?php echo (set_value('location_lng')); ?>" name="location_lng" type="hidden">
<input type="hidden" name="old_location_image" class="location_image">
<input type="hidden" name="old_location_video" class="location_video">
<input type="hidden" name="location_id" class="location_id">
<input type="hidden" name="location_qb_id" class="location_qb_id">
<button type="submit" class="btn blue">
<i class="fa fa-check">
</i> Save
</button>
</div>
</form>
<div class="clearfix margin-bottom-20">
</div>
</div>
</div>
<!-- END PAGE BASE CONTENT -->
</div>
<?php
if ($owner_type != "") {
?>
<script type="text/javascript">
location_owner_type();
</script>
<?php
}
if (isset($location) && !empty($location)) {
?>
<script type="text/javascript">
$(document).ready(function(){
$("#owner_type").val("1");
location_owner_type();
<?php
foreach ($location as $key => $value) {
?>
var key = "<?php echo $key ?>";
$("."+key+"").val("<?php echo $value ?>");
$("."+key+"").attr("disabled",false);
<?php
}
?>
});
</script>
<?php
}
?><file_sep>/application/views/recruitment/recruitment_sidebar.php
<li class="">
<a href="<?php echo base_url() ?>recruitments">
My Marketing Members
</a>
</li>
<li>
<a href="<?php echo base_url() ?>recruitments/manage_recruitment_view">
Add Marketing Member
</a>
</li>
<file_sep>/application/views/analytics/includes/header.php
<!DOCTYPE html>
<html>
<head>
<!-- Bootstrap Files -->
<link rel="stylesheet" type="text/css" href="<?=base_url()?>frontend/app-assets/css/vendors.min.css">
<!-- END VENDOR CSS-->
<!-- BEGIN MODERN CSS-->
<link rel="stylesheet" type="text/css" href="<?=base_url()?>frontend/app-assets/css/app.min.css">
<!-- END MODERN CSS-->
<!-- BEGIN Page Level CSS-->
<link rel="stylesheet" type="text/css" href="<?=base_url()?>frontend/app-assets/css/core/menu/menu-types/vertical-menu.min.css">
<link rel="stylesheet" type="text/css" href="<?=base_url()?>frontend/app-assets/css/core/colors/palette-gradient.min.css">
<link rel="stylesheet" type="text/css" href="<?=base_url()?>frontend/app-assets/css/pages/hospital.min.css">
<link rel="stylesheet" type="text/css" href="<?=base_url()?>frontend/app-assets/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="<?=base_url()?>frontend/app-assets/css/bootstrap-extended.min.css">
<link rel="stylesheet" type="text/css" href="<?=base_url()?>frontend/app-assets/css/components.min.css">
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" type="text/css" href="<?=base_url()?>frontend/assets/css/style.css">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" integrity="<KEY>" crossorigin="anonymous">
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="<KEY>
crossorigin="anonymous"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
<!-- BEGIN VENDOR JS-->
<script src="<?=base_url()?>frontend/app-assets/vendors/js/vendors.min.js"></script>
<script src="<?=base_url()?>frontend/app-assets/vendors/js/pickers/daterange/daterangepicker.js"></script>
<!-- BEGIN VENDOR JS-->
<!-- BEGIN PAGE VENDOR JS-->
<script src="<?=base_url()?>frontend/app-assets/vendors/js/charts/chart.min.js"></script>
<script src="<?=base_url()?>frontend/app-assets/vendors/js/charts/echarts/echarts.js"></script>
<script src="<?=base_url()?>frontend/app-assets/js/scripts/charts/chartjs/line/line.min.js"></script>
<!-- END PAGE VENDOR JS-->
<!-- BEGIN MODERN JS-->
<script src="<?=base_url()?>frontend/app-assets/js/core/app-menu.min.js"></script>
<script src="<?=base_url()?>frontend/app-assets/js/core/app.min.js"></script>
<script src="<?=base_url()?>frontend/app-assets/js/scripts/customizer.min.js"></script>
<!-- END MODERN JS-->
<!-- BEGIN PAGE LEVEL JS-->
<script src="<?=base_url()?>frontend/app-assets/js/scripts/pages/appointment.min.js"></script>
<script src="<?=base_url()?>frontend/app-assets/js/scripts/charts/chartjs/line/line.min.js"></script>
<script src="<?=base_url()?>frontend/app-assets/js/scripts/charts/chartjs/line/line-area.min.js"></script>
<script src="<?=base_url()?>frontend/app-assets/js/scripts/charts/chartjs/line/line-logarithmic.min.js"></script>
<script src="<?=base_url()?>frontend/app-assets/js/scripts/charts/chartjs/line/line-multi-axis.min.js"></script>
<script src="<?=base_url()?>frontend/app-assets/js/scripts/charts/chartjs/line/line-skip-points.min.js"></script>
<script src="<?=base_url()?>frontend/app-assets/js/scripts/charts/chartjs/line/line-stacked-area.min.js"></script>
<script src="<?=base_url()?>frontend/app-assets/js/scripts/charts/chartjs/pie-doughnut/doughnut.min.js"></script>
<script src="<?=base_url()?>frontend/app-assets/js/scripts/charts/chartjs/pie-doughnut/doughnut-simple.min.js"></script>
<script type="text/javascript">
$(".menu-toggle").click(function(){
$("#sidenav").toggleClass("hm");
})
</script>
<style type="text/css">
.loading{
background-image: url('frontend/images/gif3.gif');
height: 100%;
width: 100%;
position: fixed;
z-index: 999999999;
top: 25%;
background-repeat: no-repeat;
left: 40%;
display: none;
}
.loading span{
background-color: #529BD4;
color: black;
position: absolute;
top: 15%;
left: 5.5%;
padding: 12px;
border-radius: 50px;
}
</style>
</head>
<body class="vertical-layout 2-columns menu-expanded fixed-navbar" data-open="click" data-menu="vertical-menu" data-col="2-columns">
<div class="loading">
<span>Uploading</span>
</div>
<div class="main_div"><file_sep>/application/views/location/infowindow_content.php
<div class='location_info'>
<div class='row'>
<div class='col-md-12'>
<div class='col-md-6'>
<div class="row">
<?php
if ($location_image != "") {
echo "<img src='".base_url().LOCATION_IMAGE_UPLOAD_PATH.$location_image."' >";
}
?>
</div>
<div class="row text-center mt10">
<?php
if ($location_video != "") {
?>
<a href="<?php echo base_url().LOCATION_VIDEO_UPLOAD_PATH.$location_video; ?>" data-width="1000" data-height="800" class="html5lightbox" >View Location Video</a>
<?php
}
?>
</div>
</div>
<div class='col-md-6 text-center'>
<div class='row'>
<h3><?=$location_name?></h3>
</div>
<?php
if ($monthly_views != "") {
?>
<div class='row margin-bottom-10'>
Monthly Views:
<b><?=$monthly_views?></b>
</div>
<?php
}
?>
<?php
if ($main_demographic != "") {
?>
<div class='row margin-bottom-10'>
Main demographic :
<b><?=$main_demographic?></b>
</div>
<?php
}
?>
<?php
if ($age_group != "") {
?>
<div class='row margin-bottom-10'>
Age Group :
<b><?=$age_group?></b>
</div>
<?php
}
?>
<?php
if ($industry != "") {
?>
<div class='row margin-bottom-10'>
Industry :
<b><?=$industry?></b>
</div>
<?php
}
?>
<?php
if ($location_description != "") {
?>
<div class='row margin-bottom-10'>
What can be advertised :
<b>
<?php
$location_description = str_replace(array("\\r\n", "\\r"),"<br>",$location_description);
$location_description = str_replace(array("\\r\n", "\\n"),"",$location_description);
echo $location_description; ?>
</b>
</div>
<?php
}
?>
<?php
if ($other_notes != "") {
?>
<div class='row margin-bottom-10'>
Other Notes :
<b>
<?php
$other_notes = str_replace(array("\\r\n", "\\r"),"<br>",$other_notes);
$other_notes = str_replace(array("\\r\n", "\\n"),"",$other_notes);
echo $other_notes; ?>
</b>
</div>
<?php
}
?>
<?php
if ($monthly_cost != "") {
?>
<div class='row margin-bottom-20'>
Cost Per Month:
<b>$<?=$monthly_cost?></b>
</div>
<?php
}
?>
<?php if(!empty($this->session->userdata("user_session"))) {?>
<div class="row">
<a href="<?=base_url()?>advertisers/manage_advertisement/<?=$location_id?>" class="btn btn-primary">Advertise Here</a>
</div>
<br>
<div class="row">
<a href="<?=base_url()?>analytics/dashboard/<?=$location_id?>" target="_blank" class="btn btn-primary">Get Analytics</a>
</div>
<?php } else{ ?>
<div class="row">
<a class="btn btn-info" onClick="advertiseaa(<?=$location_id?>)" data-id="<?=$location_id?>">Advertise Here </a>
</div>
<?php } ?>
</div>
</div>
</div>
</div>
<file_sep>/application/views/designer/tasks_assigned.php
<div class="page-content-col">
<div class="portlet box blue">
<div class="portlet-title">
<div class="caption">
Task Details </div>
<div class="tools">
<a href="javascript:;" class="collapse" data-original-title="" title=""> </a>
</div>
</div>
<div class="portlet-body form">
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Location Name:</b>
<div class="col-md-8">
<p> <?=$task->location_name?> </p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Location Number:</b>
<div class="col-md-8">
<p> <?=$task->location_number?> </p>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<b class=" col-md-4">Advertise Number:</b>
<div class="col-md-8">
<p > <?=$task->advert_number?> </p>
</div>
</div>
</div>
<?php
if (!empty($task->hologram_file)) {
?>
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Hologram File:</b>
<div class="col-md-8">
<p> <a href="<?php echo base_url().HOLOGRAM_FILE_UPLOAD_PATH.$task->hologram_file ?>" download> Download File</a> </p>
</div>
</div>
</div>
<?php
}
?>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Delivery Date:</b>
<div class="col-md-8">
<p> <?=$task->date?> </p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Delivery Type:</b>
<div class="col-md-8">
<p>Design Hologram</p>
</div>
</div>
</div>
</div>
<?php
if (!empty($delivery_file)) {
?>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Delivery File:</b>
<div class="col-md-8">
<p> <a href="<?php echo base_url().PROOF_UPLOAD_PATH.$delivery_file->proof_file ?>" download> Download File</a> </p>
</div>
</div>
</div>
</div>
<?php
}
?>
<?php
if (!empty($task->delivery_file)) {
?>
<div class="row">
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Delivery File:</b>
<div class="col-md-8">
<p> <a href="<?php echo base_url().PROOF_UPLOAD_PATH.$task->delivery_file ?>" download> Download File</a> </p>
</div>
</div>
</div>
<!--/span-->
</div>
<?php
}
?>
<?php
if (!empty($task->hologram_description)) {
?>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<b class="col-md-3">Hologram Description:</b>
<div class="col-md-12">
<p> <?=$task->hologram_description?> </p>
</div>
</div>
</div>
</div>
<?php
}
?>
<h3 class="form-section">Address</h3>
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<b class="col-md-2">Address:</b>
<div class="col-md-10">
<p> <?=$task->location_address?> </p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">City:</b>
<div class="col-md-8">
<p class=""> <?=$task->location_city?> </p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">State:</b>
<div class="col-md-8">
<p class=""> <?=$task->location_state?> </p>
</div>
</div>
</div>
<!--/span-->
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Post Code:</b>
<div class="col-md-8">
<p class=""> <?=$task->location_post_code?> </p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Country:</b>
<div class="col-md-8">
<p class=""> <?=$task->location_country?> </p>
</div>
</div>
</div>
<!--/span-->
</div>
</div>
<div class="col-md-12">
<input type="hidden" class="lat" value="<?php echo $task->location_lat?>">
<input type="hidden" class="lng" value="<?php echo $task->location_lng?>">
<input type="hidden" class="cost" value="<?php echo $task->monthly_cost?>">
<input type="hidden" class="location_id" value="<?php echo $task->location_id?>">
<div id="location_map" style="height: 400px"></div>
</div>
</div>
<h3 class="form-section">Comments</h3>
<form method="post" action="<?=base_url()?>designer/add_comment" enctype="multipart/form-data">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<textarea required="" rows="5" cols="10" name="comment" class="form-control"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<input type="file" name="comment_file">
</div>
</div>
</div>
<div class="form-actions right">
<input type="hidden" name="task_id" value="<?=$task_id?>">
<input type="hidden" name="user_id" value="<?=get_user_id()?>">
<button class="btn blue">Send</button>
</div>
</form>
<div class="row">
<div class="col-md-12">
<div class="comments-section">
<?php
foreach ($comments as $key => $value) {
?>
<div class="comment-box <?php echo ($value->user_id!=get_user_id() ? 'bg-grey' : '') ?> " >
<div class="pb10"><b><?=$value->first_name.' '.$value->last_name?> says:</b></div>
<div class=""><?=$value->comment?></div>
<?php
if ($value->comment_file != "") {
?>
<div class=""><a href="<?php echo base_url().PROOF_UPLOAD_PATH.$value->comment_file ?>" download> Comment File</a></div>
<?php
}
?>
</div>
<?php
}
?>
</div>
</div>
</div>
</div>
</div>
</div><file_sep>/application/controllers/Affiliate.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Affiliate extends GH_Controller {
public $data = array();
public function __construct() {
parent::__construct();
}
function _remap($method,$param){
if (method_exists($this,$method)) {
if (!empty($param)) {
$this->$method($param[0]);
}else{
$this->$method();
}
} else {
$this->index($method);
}
}
public function index($userid)
{
$formdata = $this->input->post();
$this->data['success'] = false;
$this->data['error'] = false;
if (!empty($formdata)) {
$where['user_id'] = $userid;
$user = $this->crud_model->get_data("users",$where,true,'','','email');
$message = "You have recieved an inquiry from the Goholo Platform here are the details.<br>";
$message .= "Full Name:".$formdata['name']."<br>";
$message .= "Email:".$formdata['email']."<br>";
$message .= "Message:".$formdata['message']."<br>";
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.gmail.com',
'smtp_port' => 465,
'smtp_user' => '<EMAIL>',
'smtp_pass' => '',
'mailtype' => 'html',
'charset' => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->email->from($formdata['email']);
$this->email->to($user->email);
$this->email->subject('Goholo Contact us');
$this->email->message($message);
$mail = $this->email->send();
if($mail){
$this->data['success'] = true;
}else{
$this->data['error'] = true;
}
}
$this->data['userid'] = $userid;
$this->load->view('affiliate/affiliate',$this->data);
}
}
<file_sep>/application/views/advertisers/view_advertisements.php
<div class="page-content-col">
<div class="row">
<?php
if ($this->session->flashdata("success_msg") != "") {
?>
<div class="alert alert-success">
<?php echo $this->session->flashdata("success_msg"); ?>
</div>
<?php
}
?>
</div>
<table class="table table-bordered table-stripped datatable">
<thead>
<tr>
<th>Sr.</th>
<th>Advertiser's Name</th>
<th>Advertise Number</th>
<th>Start Date</th>
<th>Location Name</th>
<th>Location Number</th>
<th>Status</th>
<?php
if ($user_role == 1 || $user_role == 6) {
?>
<th width="300px">Action</th>
<?php
}
?>
</tr>
</thead>
<tbody>
<?php
$i = 1;
foreach ($adverts as $key => $value) {
echo "<tr>
<td>".$i."</td>
<td>".$value->first_name.' '.$value->last_name."</td>
<td>".$value->advert_number."</td>
<td>".$value->start_date."</td>
<td>".$value->location_name."</td>
<td>".$value->location_number."</td>";
if ($user_role == 1) {
if ($value->advert_status == 0 || $value->advert_status == 1) {
echo "<td> <input type='checkbox' ". ($value->advert_status != 0 ? 'checked' : '') ." data-record_id='{$value->advert_id}' data-table='advertisements' data-where='advert_id' class='make-switch change_record_status' data-on-text='Active' data-off-text='Deactive'> </td>";
}else{
echo "<td> Completed </td>";
}
}else{
echo "<td>".get_status($value->advert_status)."</td>";
}
if ($user_role == 1 ) {
echo "<td> <a class='btn btn-info round-btn' href='".base_url()."advertisers/advertisement_info/".$value->location_id."/".$value->advert_id."'>View</a> <a class='btn btn-primary round-btn' href='".base_url()."advertisers/manage_advertisement/".$value->location_id."/".$value->advert_id."'>Edit</a> <a href='".base_url()."advertisers/delete_advertisement/".$value->advert_id."' class='btn btn-danger round-btn delete-btn'>Delete</a>";
if ($value->advert_status == 2) {
echo " <a href='".base_url()."advertisers/advertisementReport/".$value->advert_id."' class='btn btn-success round-btn'>Report</a>";
}
echo"</td></tr>";
}elseif ($user_role == 6) {
echo "<td> <a class='btn btn-info round-btn' href='".base_url()."advertisers/advertisement_info/".$value->location_id."/".$value->advert_id."'>View</a></td>
</tr>";
}
$i++;
}
?>
</tbody>
</table>
</div>
<file_sep>/application/views/analytics/report.php
<!DOCTYPE html><html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet">
<style type="text/css">
@font-face {
font-family: 'Open Sans';
src: url(http://themes.googleusercontent.com/static/fonts/opensans/v8/cJZKeOuBrn4kERxqtaUH3aCWcynf_cDxXwCLxiixG1c.ttf) format('truetype');
}
body {
background: white;
font-family: 'Roboto', sans-serif;
margin:0; }
.topbar{
width: 500px;
height:150px;
margin-left: auto;
}
.logo-tag{
font-size:20px;
font-weight:bold;
}
.nav-name{
diplay:inline;
font-size:12px;
margin-left:8px;
margin-right:0px;
padding-left:20px;
padding-right:20px;
padding-top:12px;
padding-bottom:12px;
background-color:#67a7d9;
border-radius:5px;
color:white;
font-weight: bold;
}
.dataresponse{
font-size:20px;
}
.positive{
font-size:20px;
}
.circle{
width: 60px;
border: 1px solid black;
border-radius:200%;
height: 60px;
text-align: center;
}
.circlebig{
width: 80px;
border: 1px solid black;
border-radius:250%;
height: 80px;
text-align: center;
}
.persentage{
margin-left:10px;
}
</style></head>
<body>
<div class="topbar" style="margin-left:5%;">
<?php
$path = base_url().'/assets/images/report/logo.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64_logo = 'data:image/' . $type . ';base64,' . base64_encode($data);
?>
<img src="<?=$base64_logo?>" style="width: 70%" >
<div style="margin-left:75%; margin-top:-7%; width: 40%">
<div class="logo-tag"> Ad Report Card</div>
</div>
</div>
<table style="margin-top: -5% ">
<td ><div class="nav-name"><?=$analytics['add']->location_name?></div></td>
<td ><div class="nav-name"><?=$analytics['add']->start_date?>-<?=$analytics['add']->end_date?></div></td>
<td ><div style="width: 90px" class="nav-name"><?=$analytics['total_visitors']?> Total Views</div></td>
<td ><div class="nav-name">Avg.Age <?=$analytics['avg_age']?></div></td>
</table>
<table style="margin-top: 5% ">
<tr>
<td width="10"> </td>
<td width="160" ><div class="dataresponse">Ad Response:</div></td>
<!-- <td width="220"><div class="dataresponse">View Time:</div></td>
--><td width="220"><div class="dataresponse"> </div></td>
<td width="200"><div class="dataresponse">Male vs Female:</div></td>
</tr>
<tr>
<td> </td >
</tr>
<td></td >
<td>
<table>
<tr>
<td><img src="<?=@getBase64Image('images/report/positive.png')?>" class="emogi"></td>
<td><div class="positive">Positive <?=$analytics['happy_cent']?>%</div></td>
</tr>
</table>
<br>
<table>
<tr>
<td><img src="<?=@getBase64Image('images/report/negative.png')?>" class="emogi"></td>
<td><div class="positive">Negative <?=$analytics['sad_cent']?>%</div></td>
</tr>
</table>
<br>
<table>
<tr>
<td><img src="<?=@getBase64Image('images/report/neutral.png')?>" class="emogi"></td>
<td><div class="positive">Neutral <?=$analytics['normal_cent']?>%</div></td>
</tr>
</table>
</td>
<!-- <td>
<table>
<tr>
<td width="30">
<div class="circle">
<div style="font-size: 13px; margin-top:20px;">30 sec
</div><br><br><br>
<div>Shortest</div>
</div>
</td>
<td width="30">
<div class="circlebig">
<div style="font-size: 13px; margin-top:30px;">30 sec
</div><br><br><br>
<div>Average</div>
</div>
</td>
<td width="30">
<div class="circle">
<div style="font-size: 13px; margin-top:20px;">30 sec
</div><br><br><br>
<div>Longest</div>
</div>
</td>
</tr>
</table>
</td> -->
<td>
<table>
<tr>
<td width="30">
<div class="">
</div>
</td>
<td width="30">
<div class="">
</div>
</td>
<td width="30">
<div class="">
</div>
</td>
</tr>
</table>
</td>
<td>
<table>
<tr>
<td>
<img width="70" src="<?=@getBase64Image('images/report/man.png')?>" class="emogi-img">
</td>
<td>
<img width="70" src="<?=@getBase64Image('images/report/women.png')?>" class="emogi-img">
</td>
</tr>
<tr>
<td style="text-align: center;"><?=$analytics['male_cent']?>%</td>
<td style="text-align: center;"><?=$analytics['female_cent']?>%</td>
</tr>
</table>
</td>
</table>
<?php
if (!empty($analytics['age_group'])) {
?>
<br><br><br>
<table>
<tr>
<td width="200"><div class="dataresponse">Age Group:</div></td>
</tr>
<tr>
<td>
<table >
<tr >
<td style="border-bottom:1px solid gray;" width="50"> </td>
<th style="padding:10px 60px; border-bottom:1px solid gray;" width="100">Age</th>
<th style="padding:10px 60px; border-bottom:1px solid gray;" width="100">Total</th>
</tr>
<?php
foreach ($analytics['age_group'] as $key => $value) {
if ($value != 0) {
echo "<tr>
<td style='border-bottom:1px solid gray;' width='50'> </td>
<td style='padding:10px 60px; border-bottom:1px solid gray;' width='100'>".$key."</td>
<td style='padding:10px 60px; border-bottom:1px solid gray;' width='100'>".($value/$analytics['total_visitors']*100)."%</td>
</tr>";
}
}
?>
</table>
</td>
</tr>
</table>
<?php
}
if (!empty($analytics['unique_visitors'])) {
?>
<table >
<tr style="padding-top: 30%;">
<td width="220"><div class="dataresponse">Log:</div></td>
</tr>
<tr>
<td>
<table>
<tr >
<th width="120" style="padding:10px; border-bottom:1px solid gray;" width="100">Sr.</th>
<th width="120" style="padding:10px; border-bottom:1px solid gray;" width="100">Age</th>
<th width="120" style="padding:10px; border-bottom:1px solid gray;" width="100">Nationality</th>
<th width="120" style="padding:10px; border-bottom:1px solid gray;" width="100">Gender</th>
</tr>
<?php
$i = 1;
foreach ($analytics['unique_visitors'] as $key => $value) {
echo "<tr>
<td style='border-bottom:1px solid gray;' width='100' >".$i."</td>
<td style='padding:10px; border-bottom:1px solid gray;' width='100'>".$value->age."</td>
<td style='padding:10px; border-bottom:1px solid gray;' width='100'>".$value->nationality."</td>
<td style='padding:10px; border-bottom:1px solid gray;' width='100'>".($value->gender == 'M' ? 'Male': 'Female')."</td>
</tr>";
$i++;
}
?>
</table>
</td>
</tr>
</table>
<?php
}
?>
</body>
</html><file_sep>/application/controllers/Designer.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Designer extends GH_Controller {
private $data;
public function __construct() {
parent::__construct();
$this->data['menu_class'] = "designer_menu";
$this->data['title'] = "Designer";
$this->data['sidebar_file'] = "designer/designer_sidebar";
}
function _remap($method,$param){
if (method_exists($this,$method)) {
if (!empty($param)) {
$this->$method($param[0]);
}else{
$this->$method();
}
} else {
$this->index($method);
}
}
public function index($status = 0)
{
$join['advertisements a'] = "a.advert_id=t.advert_id";
$join['locations l'] = "a.location_id=l.location_id";
$where['t.status'] = $status;
$where['t.task_type'] = "designer";
$where['a.status'] = 1;
$user_role = get_user_role();
if ($user_role == 3) {
$where['a.created_by'] = get_user_id();
}
$this->data['tasks'] = $this->crud_model->get_data('tasks t',$where,'',$join);
$this->data['status'] = $status;
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('designer/designer');
$this->load->view('common/footer');
}
public function tasks_assigned($task_id){
$where['t.task_id'] = $task_id;
$join['advertisements a'] = "a.advert_id=t.advert_id";
$join['locations l'] = "a.location_id=l.location_id";
$this->data['task'] = $this->crud_model->get_data('tasks t',$where,true,$join);
$cjoin['users u'] = "u.user_id=t.user_id";
$order_by = "comment_id DESC";
$this->data['comments'] = $this->crud_model->get_data("task_comments t",$where,'',$cjoin,'','','','',$order_by);
$this->data['task_id'] = $task_id;
// echo "<pre>";
// echo $this->db->last_query();
// print_r($this->data['task']);
// exit();
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('designer/tasks_assigned');
$this->load->view('common/footer');
}
public function deliver_task($task_id){
$form_data = $this->input->post();
if (!empty($form_data)) {
if ($_FILES['proof_file']['error'] == 4)
{
$this->form_validation->set_rules('proof_file', '*File', 'required', array(
'required' => '%s Missing'
));
$result = $this->form_validation->run();
}else{
$result = true;
}
if ($result) {
$proof_file = $this->crud_model->upload_file($_FILES['proof_file'],'proof_file',PROOF_UPLOAD_PATH);
if ($proof_file) {
$where['task_id'] = $task_id;
$update_data['delivery_file'] = $proof_file;
$proof = $this->crud_model->update_data("tasks",$where,$update_data);
$join['advertisements a'] = "a.advert_id=t.advert_id";
$join['users u'] = "u.user_id=a.created_by";
$user = $this->crud_model->get_data("tasks t",array("t.task_id"=>$task_id),true,$join,'','u.user_id');
$notify['receiver_id'] = $user->user_id;
$notify['message'] = sprintf($this->lang->line('task_delivered'), get_user_fullname());
$notify['link'] = "designer/view_deliveries";
$this->add_notifications($notify);
$this->add_notifications($notify,'1');
if ($proof) {
$this->session->set_flashdata("success_msg","Task Delivered");
}else{
$this->session->set_flashdata("error_msg","Task Not Delivered");
}
redirect($_SERVER['HTTP_REFERER']);
}
}
}
$this->data['task_id'] = $task_id;
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('location_manager/deliver_task');
$this->load->view('common/footer');
}
public function view_deliveries(){
$join['advertisements a'] = "a.advert_id=t.advert_id";
$join['locations l'] = "a.location_id=l.location_id";
$where['t.task_type'] = "designer";
$where['t.delivery_file !='] = "";
$user_role = get_user_role();
if ($user_role == 3) {
$where['a.created_by'] = get_user_id();
}
$this->data['proofs'] = $this->crud_model->get_data("tasks t",$where,'',$join,'','*,t.status as task_status');
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('designer/view_deliveries');
$this->load->view('common/footer');
}
public function add_comment(){
$comment_file = $this->crud_model->upload_file($_FILES['comment_file'],'comment_file',PROOF_UPLOAD_PATH);
if ($comment_file) {
$_POST['comment_file'] = $comment_file;
}
$res = $this->crud_model->add_data("task_comments",$_POST);
$notify['message'] = sprintf($this->lang->line('comment_added_task'), get_user_fullname());
$notify['link'] = "designer/tasks_assigned/".$_POST['task_id'];
$user_role = get_user_role();
if ($user_role == 4) {
$join['advertisements a'] = "a.advert_id=t.advert_id";
$join['users u'] = "u.user_id=a.created_by";
$user = $this->crud_model->get_data("tasks t",array("t.task_id"=>$_POST['task_id']),true,$join,'','u.user_id');
$notify['receiver_id'] = $user->user_id;
$this->add_notifications($notify);
}else{
$this->add_notifications($notify,'4');
}
$this->add_notifications($notify,'1');
if ($res) {
redirect($_SERVER['HTTP_REFERER']);
}
}
}
?><file_sep>/application/views/packages/view_packages.php
<div class="page-content-col">
<?php
if ($this->session->flashdata("success_msg") != "") {
?>
<div class="alert alert-success">
<?php echo $this->session->flashdata("success_msg"); ?>
</div>
<?php
}
?>
<div class="row text-right">
<div class="col-md-12">
<a href="<?php echo base_url() ?>admin/manage_packages" class='btn btn-primary'> Add Package</a>
</div>
</div>
<div class="table-responsive mt20">
<table class="table table-bordered table-stripped datatable">
<thead>
<tr>
<th>Sr.</th>
<th>Package Name</th>
<th>Impressions</th>
<th>Cost/Impression</th>
<th>Hologram Price </th>
<th>Total Cost</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
foreach ($packages as $key => $value) {
echo "<tr>
<td>".$i."</td>
<td>".$value->package_name."</td>
<td>".$value->total_impressions."</td>
<td>".$value->cost_per_impression."</td>
<td>".$value->hologram_price."</td>
<td>$".$value->total_cost."</td>
<td> <a class='btn btn-primary round-btn' href='".base_url()."admin/manage_packages/".$value->package_id."'>Edit</a> <a href='".base_url()."admin/delete_package/".$value->package_id."' class='btn btn-danger round-btn delete-btn'>Delete</a></td>
</tr>";
$i++;
}
?>
</tbody>
</table>
</div>
</div><file_sep>/application/views/admin/view_users.php
<!-- END PAGE SIDEBAR -->
<div class="page-content-col">
<!-- BEGIN PAGE BASE CONTENT -->
<?php
if ($this->session->flashdata("success_msg") != "") {
?>
<div class="alert alert-success">
<?php echo $this->session->flashdata("success_msg"); ?>
</div>
<?php
}
?>
<table class="table table-bordered table-stripped datatable">
<thead>
<tr>
<th>Sr.</th>
<th>Name</th>
<th>Email</th>
<th>Commission (%)</th>
<th>Role</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
foreach ($users as $key => $value) {
echo "<tr>
<td>".$i."</td>
<td>".$value->first_name.' '.$value->last_name."</td>
<td>".$value->email."</td>
<td>".$value->user_commission."</td>
<td>".get_role_byid($value->user_role)."</td>
<td> <input type='checkbox' ". ($value->status == 1 ? 'checked' : '') ." data-record_id='{$value->user_id}' data-table='users' data-where='user_id' class='make-switch change_record_status' data-on-text='Active' data-off-text='Deactive'> </td>
<td> <a class='btn btn-primary round-btn' href='".base_url()."users/manage_user_view/".$value->user_id."'>Edit</a> <a href='".base_url()."users/delete_user/".$value->user_id."' class='btn btn-danger round-btn delete-btn'>Delete</a></td>
</tr>";
$i++;
}
?>
</tbody>
</table>
<!-- END PAGE BASE CONTENT -->
</div>
<file_sep>/application/views/admin/manage_user.php
<!-- END PAGE SIDEBAR -->
<div class="page-content-col">
<div class="row">
<?php
if ($this->session->flashdata("error_msg") != "") {
?>
<div class="alert alert-danger">
<?php echo $this->session->flashdata("error_msg"); ?>
</div>
<?php
}
?>
</div>
<!-- BEGIN PAGE BASE CONTENT -->
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-blue-hoki bold uppercase">Add User</span>
</div>
<div class="tools">
<a href="" class="collapse" data-original-title="" title=""> </a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="<?php echo base_url() ?>users/manage_user" method="post" enctype="multipart/form-data" class="horizontal-form">
<div class="form-body">
<h3 class="form-section">Person Info</h3>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">First Name</label>
<input type="text" id="firstName" class="form-control first_name" name="first_name" placeholder="Enter First Name" value="<?php echo (set_value('first_name')); ?>">
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Last Name</label>
<input type="text" id="lastName" class="form-control last_name" placeholder="Enter Last Name" name="last_name" value="<?php echo (set_value('last_name')); ?>">
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Gender</label>
<select class="form-control gender" name="gender">
<option value="1">Male</option>
<option value="0">Female</option>
</select>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Date of Birth</label>
<input type="date" value="<?php echo (set_value('date_of_birth')); ?>" name="date_of_birth" class="form-control date_of_birth" placeholder="dd/mm/yyyy"> </div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">User Role</label>
<select name="user_role" class="form-control user_role" tabindex="1">
<option value="1">Super Admin</option>
<option value="2">Location Owner</option>
<option value="3">Marketing Team</option>
<option value="4">Designer</option>
<option value="5">Location Manager</option>
<option value="6">Advertisor</option>
</select>
</div>
</div>
<div class="col-md-6">
<?php
$email_error = form_error('email');
?>
<div class="form-group <?php echo ($email_error != '') ? 'has-error' : '' ?>">
<label class="control-label">Email</label>
<input id="email_input" type="email" name="email" class="form-control email" value="<?php echo (set_value('email')); ?>">
<span class="help-block"> <?php echo $email_error; ?> </span>
</div>
</div>
<!--/span-->
</div>
<div class="row">
<div class="col-md-6">
<?php
$password_error = form_error('password');
?>
<div class="form-group <?php echo ($password_error != '') ? 'has-error' : '' ?>">
<label for="exampleInputFile1">Password</label>
<input type="<PASSWORD>" name="password" class="form-control password" value="<?php echo (set_value('password')); ?>">
<span class="help-block"> <?php echo $password_error; ?> </span>
</div>
</div>
<div class="col-md-6">
<?php
$re_password_error = form_error('re_password');
?>
<div class="form-group <?php echo ($re_password_error != '') ? 'has-error' : '' ?>">
<label for="exampleInputFile1">Re-Type Password</label>
<input type="<PASSWORD>" name="re_password" class="form-control password" value="<?php echo (set_value('re_password')); ?>">
<span class="help-block"> <?php echo $re_password_error; ?> </span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Paypal ID</label>
<input type="text" name="paypal_id" class="form-control paypal_id" value="<?php echo (set_value('paypal_id')); ?>">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Phone Number</label>
<input type="text" name="phone_number" class="form-control phone_number" value="<?php echo (set_value('phone_number')); ?>">
</div>
</div>
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputFile1">Profile Image</label>
<input type="file" name="profile_image">
</div>
</div>
<div class="col-md-6 user_commission_div">
<?php $user_commission = (set_value('user_commission'));
if ($user_commission == "") {
$user_commission = 15;
}
?>
<div class="form-group">
<label>Commission (%)
</label>
<input id="user_commission" name="user_commission" class="form-control user_commission" value="<?php echo $user_commission; ?>" type="number">
</div>
</div>
</div>
<h3 class="form-section">Bank Deatils</h3>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Transit number</label>
<input type="text" name="transit_number" class="form-control transit_number" value="<?php echo (set_value('transit_number')); ?>"> </div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label>Institution number</label>
<input type="text" name="institution_number" class="form-control institution_number" value="<?php echo (set_value('institution_number')); ?>"> </div>
</div>
<!--/span-->
</div>
<div class="row">
<div class="col-md-6 ">
<div class="form-group">
<label>Account number</label>
<input type="text" name="account_number" class="form-control account_number" value="<?php echo (set_value('account_number')); ?>"> </div>
</div>
</div>
<h3 class="form-section">Address</h3>
<div class="row">
<div class="col-md-12 ">
<div class="form-group">
<label>Street</label>
<input type="text" name="street" class="form-control street" value="<?php echo (set_value('street')); ?>"> </div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>City</label>
<input type="text" name="city" class="form-control city" value="<?php echo (set_value('city')); ?>"> </div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<label>State</label>
<input type="text" name="state" class="form-control state" value="<?php echo (set_value('state')); ?>"> </div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label>Post Code</label>
<input type="text" name="post_code" class="form-control post_code" value="<?php echo (set_value('post_code')); ?>"> </div>
</div>
<!--/span-->
</div>
</div>
<div class="form-actions right">
<input type="hidden" class="profile_image" name="old_profile_image">
<input type="hidden" class="user_id" name="user_id">
<input type="hidden" class="user_qb_id" name="user_qb_id">
<!-- <button type="submit" class="btn blue">
<i class="fa fa-check"></i> Save</button> -->
<input type="submit" class="btn blue" value="Save">
</div>
</form>
<!-- END FORM-->
</div>
</div>
<!-- END PAGE BASE CONTENT -->
</div>
<script type="text/javascript">
$(document).ready(function(){
user_role = "<?php echo set_value('user_role') ?>";
$(".user_role").val(user_role);
<?php
if (isset($user) && !empty($user)) {
?>
$("#email_input").attr("disabled",true);
$(".form-actions").prepend("<input type='hidden' name='email' class='email'>");
user_role = "<?php echo $user->user_role; ?>";
<?php
foreach ($user as $key => $value) {
?>
var key = "<?php echo $key ?>";
$("."+key+"").val("<?php echo $value ?>");
<?php
}
}
?>
});
</script><file_sep>/application/views/analytics/dashboard/second_div_old.php
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-lg-10 col-md-12 col-sm-12 col-xs-12">
<div class="row ">
<div class="col-md-12 col-lg-5 col-sm-12 col-xs-12">
<div class="card">
<div class="card-header">
<h4 class="card-title title title-sm" id="heading-dropdown ">ANALYSIS <!-- <span class="badge pink_bdg">9</span> --></h4>
<div class="heading-elements btn_sm">
<button type="button" class="btn btn-outline-secondary round btn-custom-hvr" data-toggle="dropdown" aria-haspopup="true"><i class="pr-1 fas fa-sort-down"></i> Last Week <i class="pl-1 fas fa-ellipsis-v"></i></button>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Separated link</a>
</div>
</div>
</div>
<div class="card-body">
<div class="row pt-6">
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 text-center">
<img src="<?php echo base_url() ?>frontend/images/first_face.png" class="img-ico">
<h1 class="mt-1 percent_nmbr"><?=$analytics['happy_cent']?>%</h1>
</div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 text-center">
<img src="<?php echo base_url() ?>frontend/images/second_face.png" class="img-ico">
<h1 class="mt-1 percent_nmbr"><?=$analytics['normal_cent']?>%</h1>
</div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 text-center">
<img src="<?php echo base_url() ?>frontend/images/third_face.png" class="img-ico">
<h1 class="mt-1 percent_nmbr"><?=$analytics['sad_cent']?>%</h1>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-7 col-md-12 col-sm-12 col-xs-12">
<div class="card">
<div class="card-header">
<h5 class="header-title pb-3 mt-0 title">STATISTICS</h5>
</div>
<div class="col-sm-12 col-xs-12">
<!-- <canvas id="line-stacked-area" height="363px"></canvas> -->
<canvas id="myChart" height="363px"></canvas>
<script>
function linechart(){
var o=$("#myChart");
new Chart(o, {
type:"line", options: {
responsive:!0, maintainAspectRatio:!1, legend: {
display: false
}
, hover: {
mode: "label"
}
, scales: {
xAxes:[ {
display:!0, gridLines: {
color: "#4C8FC4"
}
}
], yAxes:[ {
display:!0, gridLines: {
color: "#4C8FC4"
}
}
]
}
, title: {
display: !0, text: ""
}
}
, data: {
labels:["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL"],
datasets:[
{
label: "Visitors", data: [<?=intval($analytics['total_visitors'])?>,0,0,0,0,0,0], backgroundColor: "#ec0bad", borderColor: "transparent", pointBorderColor: "#ec0bad", pointBackgroundColor: "#FFF", pointBorderWidth: 2, pointHoverBorderWidth: 2, pointRadius: 4
}
,
{
label: "AVG. Age", data: [<?=intval($analytics['avg_age'])?>,0,0,0,0,0,0], backgroundColor: "#4f97cf", borderColor: "transparent", pointBorderColor: "#5175E0", pointBackgroundColor: "#FFF", pointBorderWidth: 2, pointHoverBorderWidth: 2, pointRadius: 4
}
]
},
}
)
}
$(window).on("load",function()
{
linechart();
$("#2").click(function() {
var o=$("#myChart");
new Chart(o, {
type:"line", options: {
responsive:!0, maintainAspectRatio:!1, legend: {
display: false
}
, hover: {
mode: "label"
}
, scales: {
xAxes:[ {
display:!0, gridLines: {
color: "#4C8FC4"
}
}
], yAxes:[ {
display:!0, gridLines: {
color: "#4C8FC4"
}
}
]
}
, title: {
display: !0, text: ""
}
}
, data: {
labels:["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL"], datasets:[ {
label: "AVG. Age", data: [<?=intval($analytics['avg_age'])?>, 0, 0, 0, 0, 0, 0], backgroundColor: "#4f97cf", borderColor: "transparent", pointBorderColor: "#5175E0", pointBackgroundColor: "#FFF", pointBorderWidth: 2, pointHoverBorderWidth: 2, pointRadius: 4
}
]
}
}
)
})
$("#1").click(function() {
var o=$("#myChart");
new Chart(o, {
type:"line", options: {
responsive:!0, maintainAspectRatio:!1, legend: {
display: false
}
, hover: {
mode: "label"
}
, scales: {
xAxes:[ {
display:!0, gridLines: {
color: "#4C8FC4"
}
}
], yAxes:[ {
display:!0, gridLines: {
color: "#4C8FC4"
}
}
]
}
, title: {
display: !0, text: ""
}
}
, data: {
labels:["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL"], datasets:[ {
label: "Visitors", data: [<?=intval($analytics['total_visitors'])?>, 0, 0, 0, 0, 0, 0], backgroundColor: "#ec0bad", borderColor: "transparent", pointBorderColor: "#ec0bad", pointBackgroundColor: "#FFF", pointBorderWidth: 2, pointHoverBorderWidth: 2, pointRadius: 4
}
]
}
}
)
})
})
</script>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-2 col-md-12 col-xs-12 col-sm-12 plr0">
<div class="card">
<div class="card-header">
<div class="heading-elements">
<button type="button" class="btn btn-outline-secondary round btn-min-width-cs mr-1 btn-custom-hvr mb-1 btn-block" data-toggle="dropdown" aria-haspopup="true"><i class="pr-1 fas fa-sort-down"></i> Last Year <i class="pl-1 fas fa-ellipsis-v"></i></button>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action</a>
<a class="dropdown-item" href="#">Something else here</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item" href="#">Separated link</a>
</div>
</div>
</div>
<div class="">
<h5 class="header-title pb-3 mt-0 "></h5>
<div class="row justify-content-center">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 plr0 text-center">
<button onclick="linechart()" id="0" type="button" class="btn btn-outline-secondary round btn-min-width mb-1 btn-custom-hvr">All</button>
<button id="1" type="button" class="btn btn-outline-secondary round btn-min-width mb-1 btn-custom-hvr">Amount of visitors</button>
<!-- <button id="1" type="button" class="btn btn-outline-secondary round btn-min-width mb-1 btn-custom-hvr">male vs female</button> -->
<button id="2" type="button" class="btn btn-outline-secondary round btn-min-width mb-1 btn-custom-hvr">AVG. Age</button>
<!-- <button id="3" type="button" class="btn btn-outline-secondary round btn-min-width mb-1 btn-custom-hvr">avg. time</button> -->
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<file_sep>/application/views/location_manager/tasks_assigned.php
<div class="page-content-col">
<div class="portlet box blue">
<div class="portlet-title">
<div class="caption">
Task Details </div>
<div class="tools">
<?php
if ($task->task_status == 0) {
?>
<a style="height: 100%" href="<?=base_url()?>location_manager/deliver_task/<?=$task->task_id?>" class="btn btn-success round-btn">Deliver Task</a>
<?php
}
?>
<a href="javascript:;" class="collapse" data-original-title="" title=""> </a>
</div>
</div>
<div class="portlet-body form">
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Location Name:</b>
<div class="col-md-8">
<p> <?=$task->location_name?> </p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Location Number:</b>
<div class="col-md-8">
<p> <?=$task->location_number?> </p>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<b class=" col-md-4">Advertise Number:</b>
<div class="col-md-8">
<p > <?=$task->advert_number?> </p>
</div>
</div>
</div>
<!--/span-->
<?php
if ($task->hologram_type == 2) {
$task->hologram_file = "";
$delivery = $this->crud_model->get_data('tasks',array("advert_id"=>$task->advert_id,'task_type'=>'designer','status'=>1),true);
if (!empty($delivery)) {
$task->hologram_file = $delivery->delivery_file;
}
}
?>
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Hologram File:</b>
<div class="col-md-8">
<p>
<?php
if ($task->hologram_file != "") {
?>
<a href="<?php echo base_url().HOLOGRAM_FILE_UPLOAD_PATH.$task->hologram_file ?>" download> Download File</a>
<?php
}else{
echo "Waiting for the designs from the designer";
}
?>
</p>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Delivery Date:</b>
<div class="col-md-8">
<p> <?=$task->date?> </p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Delivery Type:</b>
<div class="col-md-8">
<p> <?php
if ($task->task_type == "add_advert") {
echo "Add Advertisement";
}else if ($task->task_type == "remove_advert"){
echo "Remove Advertisement";
}else{
echo "Design Hologram";
}
?> </p>
</div>
</div>
</div>
</div>
<?php
if (!empty($task->delivery_file)) {
?>
<div class="row">
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Delivery File:</b>
<div class="col-md-8">
<p> <a href="<?php echo base_url().PROOF_UPLOAD_PATH.$task->delivery_file ?>" download> Download File</a> </p>
</div>
</div>
</div>
<!--/span-->
</div>
<?php
}
?>
<h3 class="form-section">Address</h3>
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<b class="col-md-2">Address:</b>
<div class="col-md-10">
<p> <?=$task->location_address?> </p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">City:</b>
<div class="col-md-8">
<p class=""> <?=$task->location_city?> </p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">State:</b>
<div class="col-md-8">
<p class=""> <?=$task->location_state?> </p>
</div>
</div>
</div>
<!--/span-->
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Post Code:</b>
<div class="col-md-8">
<p class=""> <?=$task->location_post_code?> </p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Country:</b>
<div class="col-md-8">
<p class=""> <?=$task->location_country?> </p>
</div>
</div>
</div>
<!--/span-->
</div>
</div>
<div class="col-md-12">
<input type="hidden" class="lat" value="<?php echo $task->location_lat?>">
<input type="hidden" class="lng" value="<?php echo $task->location_lng?>">
<input type="hidden" class="cost" value="<?php echo $task->monthly_cost?>">
<input type="hidden" class="location_id" value="<?php echo $task->location_id?>">
<div id="location_map" style="height: 400px"></div>
</div>
</div>
</div>
</div>
</div><file_sep>/application/views/affiliate/affiliate.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Goholo | Contact us</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/png" href="<?php echo base_url(); ?>assets/affiliate/images/icons/favicon.ico"/>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/affiliate/vendor/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/affiliate/fonts/font-awesome-4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/affiliate/fonts/iconic/css/material-design-iconic-font.min.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/affiliate/vendor/animate/animate.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/affiliate/vendor/css-hamburgers/hamburgers.min.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/affiliate/vendor/animsition/css/animsition.min.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/affiliate/vendor/select2/select2.min.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/affiliate/vendor/daterangepicker/daterangepicker.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/affiliate/css/util.css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>assets/affiliate/css/main.css">
</head>
<body>
<div class="container-contact100">
<div class="contact100-map" ></div>
<div class="wrap-contact100">
<?php
if ($success) {
?>
<div class="alert alert-success">
We have recieved your inquiry. We will get back to you soon.
</div>
<?php
}
if ($error) {
?>
<div class="alert alert-danger">
Server issue! Inquiry not recieved.
</div>
<?php
}
?>
<form class="contact100-form validate-form" action="" method="post">
<span class="contact100-form-title">
Contact Us
</span>
<div class="wrap-input100 validate-input" data-validate="Please enter your name">
<input class="input100" type="text" name="name" placeholder="<NAME>">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Please enter email: e@a.x">
<input class="input100" type="text" name="email" placeholder="Email">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Please enter your message">
<textarea class="input100" name="message" placeholder="Your Message"></textarea>
<span class="focus-input100"></span>
</div>
<div class="container-contact100-form-btn">
<input type="hidden" name="userid" value="<?=$userid?>">
<input type="submit" value="Send Email" class="contact100-form-btn">
</div>
</form>
</div>
</div>
<script src="<?php echo base_url(); ?>assets/affiliate/vendor/jquery/jquery-3.2.1.min.js"></script>
<script src="<?php echo base_url(); ?>assets/affiliate/vendor/animsition/js/animsition.min.js"></script>
<script src="<?php echo base_url(); ?>assets/affiliate/vendor/bootstrap/js/popper.js"></script>
<script src="<?php echo base_url(); ?>assets/affiliate/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="<?php echo base_url(); ?>assets/affiliate/vendor/select2/select2.min.js"></script>
<script src="<?php echo base_url(); ?>assets/affiliate/vendor/daterangepicker/moment.min.js"></script>
<script src="<?php echo base_url(); ?>assets/affiliate/vendor/daterangepicker/daterangepicker.js"></script>
<script src="<?php echo base_url(); ?>assets/affiliate/vendor/countdowntime/countdowntime.js"></script>
<script src="<?php echo base_url(); ?>assets/affiliate/js/main.js"></script>
</body>
</html>
<file_sep>/frontend/index.php
<?php include 'includes/header.php'; ?>
<body class="vertical-layout 2-columns menu-expanded fixed-navbar" data-open="click" data-menu="vertical-menu" data-col="2-columns">
<?php include 'includes/navbar.php'; ?>
<div class="app-content content">
<div class="">
<div class="content-body">
<div class="row pt-5">
<div class="col-md-3 col-lg-2 col-xl-2 col-sm-12 col-xs-12 bg-white mt_36 hm mb-3" id="sidenav">
<div id="mySidenav" class="sidenav">
<a href="javascript:void(0)" class="closebtn" onclick="closeNav()" style="color:#fff">×</a>
<div class="div1">
<div class="circle rounded-circle margin"></div>
<div class="smallcircle rounded-circle mt-n3"></div>
<p class="para1 mt-2 margin1">J.Jameson<br><small class="small1 ml-1">ADMINISTRATION</small></p>
</div>
<a href="#"><img src="img/dashborad.png" alt="image" class="pt-1"><span class="navfont">DASHBOARD</span></a>
<a href="#"><img src="img/buyer.png" alt="image" class="pt-1"><span class="navfont">BUYER PERFORMA</span></a>
<a href="#"><img src="img/location.png" alt="image" class="pt-1"><span class="navfont">LOCATIONS</span></a>
<a href="#"><img src="img/setting1.png" alt="image" class="pt-1"><span class="navfont">SETTINGS</span></a>
</div>
<div class="row pt36">
<div class="col-sm-3"></div>
<div class="col-sm-9 col-md-12 center_img">
<div class="circle rounded-circle margin"></div>
<div class="smallcircle rounded-circle mt-n3"></div>
<p class="para1 margin1 text-center">J.Jameson<br><small class="small1 ml-1">ADMINISTRATION</small></p>
</div>
</div>
<div class="row mt-2">
<div class="col-12 col-sm-12 col-md-12 hide zoomonhover">
<a href="#">
<div class="row">
<div class="col-3 col-sm-3 col-md-4 text-right"><img src="img/dashborad.png" alt="image" class="pt-1"></div>
<div class="col-9 col-sm-9 col-md-8 menucolor1">
<h6 class="mt-2 color3">DASHBOARD</h6>
</div>
</div>
</a>
</div>
</div>
<div class="row mt-3">
<div class="col-12 col-sm-12 col-md-12 hide zoomonhover">
<a href="#">
<div class="row">
<div class="col-3 col-sm-3 col-md-4 text-right"><img src="img/buyer.png" alt="image" class="pt-1"></div>
<div class="col-9 col-sm-9 col-md-8 menucolor1">
<h6 class="mt-2 color3">BUYER PERSONA</h6>
</div>
</div>
</a>
</div>
</div>
<div class="row mt-3">
<div class="col-12 col-sm-12 col-md-12 hide zoomonhover">
<a href="#">
<div class="row">
<div class="col-3 col-sm-3 col-md-4 text-right"><img src="img/location.png" alt="image" class="mt-1"></div>
<div class="col-9 col-sm-9 col-md-8 menucolor1">
<h6 class="mt-2 color3">LOCATIONS</h6>
</div>
</div>
</a>
</div>
</div>
<div class="row mt-3 mb-3">
<div class="col-12 col-sm-12 col-md-12 hide zoomonhover">
<a href="#">
<div class="row padding">
<div class="col-3 col-sm-3 col-md-4 text-right"><img src="img/setting1.png" alt="image" class="mt-1"></div>
<div class="col-9 col-sm-9 col-md-8 menucolor1">
<h6 class="mt-2 color3">SETTINGS</h6>
</div>
</div>
</a>
</div>
</div>
</div>
<div class=" col-md-9 col-lg-10 col-xl-10 col-sm-12 col-xs-12 pr30 pl30sm ">
<?php
include 'includes/first_div.php';
include 'includes/second_div.php';
include 'includes/third_div.php';
include 'includes/fourth_div.php';
?>
</div>
</div>
</div>
</div>
</div>
<?php
include 'includes/footer.php';
?>
<script type="text/javascript">
$(".menu-toggle").click(function(){
$("#sidenav").toggleClass("hm");
})
</script>
<file_sep>/application/core/GH_Controller.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class GH_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
if (empty($this->session->userdata('user_session'))) {
$redirect_url = base_url()."login";
redirect($redirect_url);
}
$this->lang->load('main');
if (isset($_GET['notify_id']) && isset($_GET['read'])) {
if ($_GET['read'] == 0) {
$this->crud_model->update_data("notifications",array("notify_id"=>$_GET['notify_id']),array("read"=>1));
}
}
}
public function add_notifications($notify_data,$user_role = ""){
if ($user_role != "") {
if (is_array($user_role)) {
foreach ($user_role as $k => $v) {
$users = $this->crud_model->get_data("users",array("user_role"=>$v));
foreach ($users as $key => $value) {
$notify_data['receiver_id'] = $value->user_id;
$this->crud_model->add_data("notifications",$notify_data);
}
}
}else{
$users = $this->crud_model->get_data("users",array("user_role"=>$user_role));
foreach ($users as $key => $value) {
$notify_data['receiver_id'] = $value->user_id;
$this->crud_model->add_data("notifications",$notify_data);
}
}
}else{
if (is_array($notify_data['receiver_id'])) {
$data = $notify_data;
foreach ($data['receiver_id'] as $key => $value) {
if (!is_admin($value)) {
$notify_data['receiver_id'] = $value;
$this->crud_model->add_data("notifications",$notify_data);
}
}
}else{
if (!is_admin($notify_data['receiver_id'])) {
$this->crud_model->add_data("notifications",$notify_data);
}
}
}
}
public function notify_status(){
$table = $this->input->post("table");
switch ($table) {
case 'locations':
$this->notify_location_status();
break;
case 'advertisements':
$this->notify_advertisements_status();
break;
case 'users':
$this->notify_users_status();
break;
case 'tasks':
$this->notify_tasks_status();
break;
default:
return false;
break;
}
}
public function notify_location_status()
{
$where['location_id'] = $this->input->post("record_id");
$location = $this->crud_model->get_data("locations",$where,true);
$notify['receiver_id'][] = $location->location_owner;
$notify['receiver_id'][] = $location->created_by;
$notify['message'] = sprintf($this->lang->line('status_change'), get_user_fullname(),detect_status_change($this->input->post("status")),'location');
$notify['link'] = "locations/view_locations";
$this->add_notifications($notify);
$this->add_notifications($notify,'1');
}
public function notify_advertisements_status(){
$where['a.advert_id'] = $this->input->post("record_id");
$join['locations l'] = "l.location_id=a.location_id";
$advert = $this->crud_model->get_data("advertisements a",$where,true,$join,'','*,a.created_by as marketing_person');
$notify['receiver_id'][] = $advert->location_owner;
$notify['receiver_id'][] = $advert->marketing_person;
$notify['message'] = sprintf($this->lang->line('status_change'), get_user_fullname(),detect_status_change($this->input->post("status")),'advertisement');
$notify['link'] = "advertisers/view_advertisements";
$this->add_notifications($notify);
$this->add_notifications($notify,'1');
}
public function notify_users_status(){
$where['user_id'] = $this->input->post("record_id");
$user = $this->crud_model->get_data("users",$where,true);
$user_role = get_user_role($user->user_id);
if ($user_role == 3) {
$notify['receiver_id'] = $user->user_id;
$notify['message'] = sprintf($this->lang->line('status_change'), get_user_fullname(),detect_status_change($this->input->post("status")),'marketing member');
$notify['link'] = "recruitments";
$this->add_notifications($notify);
}
}
public function notify_tasks_status(){
$where['t.task_id'] = $this->input->post("record_id");
$join['advertisements a'] = "a.advert_id=t.advert_id";
$task = $this->crud_model->get_data("tasks t",$where,true,$join);
$by_whom = "location manager";
if ($task->task_type == "designer") {
$by_whom = "designer";
$notify['link'] = "designer/view_deliveries";
}else{
$notify['link'] = "location_manager/view_deliveries";
}
$notify['receiver_id'] = $task->created_by;
$notify['message'] = sprintf($this->lang->line('task_status_change'), get_user_fullname(),detect_status_change($this->input->post("status")),'delivery',$by_whom);
if (!is_admin()) {
$this->add_notifications($notify,'1');
}else{
$this->add_notifications($notify);
}
if ($task->task_type == "designer") {
$this->add_notifications($notify,'4');
}else{
$this->add_notifications($notify,'5');
}
}
}
<file_sep>/application/controllers/Location_manager.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Location_manager extends GH_Controller {
private $data;
public $table = "locations";
public function __construct() {
parent::__construct();
$this->data['menu_class'] = "manager_menu";
$this->data['title'] = "Location Manager";
$this->data['sidebar_file'] = "location_manager/manager_sidebar";
}
function _remap($method,$param){
if (method_exists($this,$method)) {
if (!empty($param)) {
$this->$method($param[0]);
}else{
$this->$method();
}
} else {
$this->index($method);
}
}
public function index($status = 0)
{
$task_type = isset($_GET['type']) ? $_GET['type'] : '';
$this->data['type'] = $task_type;
$this->data['start_date'] = "";
$this->data['end_date'] = "";
$start_date = "";
$end_date = "";
if ($this->input->get("date_range") != "") {
$date = $this->input->get("date_range");
$data = explode("-", $date);
$start_date = date("Y-m-d", strtotime($data[0]));
$end_date = date("Y-m-d", strtotime($data[1]));
$this->data['start_date'] = date("m/d/Y", strtotime($start_date));
$this->data['end_date'] = date("m/d/Y", strtotime($end_date));
}
$where_in = array();
$join['advertisements a'] = "a.advert_id=t.advert_id";
$join['locations l'] = "a.location_id=l.location_id";
$where['t.status'] = $status;
$where['a.status'] = 1;
$user_role = get_user_role();
if ($user_role == 3) {
$where['a.created_by'] = get_user_id();
}
if ($task_type != '') {
$where['t.task_type'] = $task_type;
}else{
$where_in['t.task_type'] = array('add_advert','remove_advert');
}
if ($start_date != '' & $end_date != "") {
$where['date(t.date) >='] = $start_date;
$where['date(t.date) <='] = $end_date;
}
$this->data['tasks'] = $this->crud_model->get_data('tasks t',$where,'',$join,'','','',$where_in);
$this->data['status'] = $status;
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('location_manager/manager');
$this->load->view('common/footer');
}
public function tasks_assigned($task_id){
$where['t.task_id'] = $task_id;
$join['advertisements a'] = "a.advert_id=t.advert_id";
$join['locations l'] = "a.location_id=l.location_id";
$this->data['task'] = $this->crud_model->get_data('tasks t',$where,true,$join,'','*,t.status as task_status');
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('location_manager/tasks_assigned');
$this->load->view('common/footer');
}
public function deliver_task($task_id){
$form_data = $this->input->post();
if (!empty($form_data)) {
if ($_FILES['proof_file']['error'] == 4)
{
$this->form_validation->set_rules('proof_file', '*File', 'required', array(
'required' => '%s Missing'
));
$result = $this->form_validation->run();
}else{
$result = true;
}
if ($result) {
$proof_file = $this->crud_model->upload_file($_FILES['proof_file'],'proof_file',PROOF_UPLOAD_PATH);
if ($proof_file) {
$where['task_id'] = $task_id;
$update_data['delivery_file'] = $proof_file;
$proof = $this->crud_model->update_data("tasks",$where,$update_data);
$join['advertisements a'] = "a.advert_id=t.advert_id";
$join['users u'] = "u.user_id=a.created_by";
$user = $this->crud_model->get_data("tasks t",array("t.task_id"=>$task_id),true,$join,'','u.user_id');
$notify['receiver_id'] = $user->user_id;
$notify['message'] = sprintf($this->lang->line('task_delivered'), get_user_fullname());
$notify['link'] = "location_manager/view_deliveries";
$this->add_notifications($notify);
$this->add_notifications($notify,'1');
}
if ($proof) {
$this->session->set_flashdata("success_msg","Task Delivered");
}else{
$this->session->set_flashdata("error_msg","Task Not Delivered");
}
redirect($_SERVER['HTTP_REFERER']);
}
}
$this->data['task_id'] = $task_id;
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('location_manager/deliver_task');
$this->load->view('common/footer');
}
public function view_deliveries(){
$join['advertisements a'] = "a.advert_id=t.advert_id";
$join['locations l'] = "a.location_id=l.location_id";
$where_in['t.task_type'] = array('add_advert','remove_advert');
$where['t.delivery_file !='] = "";
$user_role = get_user_role();
if ($user_role == 3) {
$where['a.created_by'] = get_user_id();
}
$this->data['proofs'] = $this->crud_model->get_data("tasks t",$where,'',$join,'','*,t.status as task_status','',$where_in);
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('location_manager/view_deliveries');
$this->load->view('common/footer');
}
}<file_sep>/application/language/english/main_lang.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$lang['new_location_added'] = "%s added new location";
$lang['new_advert_added'] = "%s added new advertisement";
$lang['new_task_added_manager'] = "New task created for location manager";
$lang['new_task_added_designer'] = "New task created for designer";
$lang['comment_added_task'] = "%s added comment on a task";
$lang['task_delivered'] = "%s has delivered the task";
$lang['new_marketing_member'] = "%s added new marketing memeber";
$lang['new_resource'] = "A new resource has been added";
$lang['new_package'] = "Package has been added";
$lang['status_change'] = "%1s has %2s the %3s";
$lang['task_status_change'] = "%1s has %2s the %3s by %4s";
<file_sep>/application/views/location_manager/manager.php
<!-- END PAGE SIDEBAR -->
<div class="page-content-col">
<!-- BEGIN PAGE BASE CONTENT -->
<div class="col-sm-12 filterbox">
<div class="filterdiv">
<form action="">
<div class="col-sm-12 col-xs-12 ">
<div class="col-sm-10">
<div class="form-group ">
<label class="col-sm-1 col-xs-1 control-label">Filter:</label>
<div class="col-sm-11 col-xs-11">
<div class="col-md-6 ">
<input type="text" placeholder="Select Date" class="form-control dateRangePicker" name="date_range" value="">
</div>
<div class="col-md-6 ">
<select class="form-control" name="type">
<option value="">Select Type</option>
<option <?php
if ($type == 'add_advert') {
echo 'selected';
}
?>
value="add_advert">Add Advertisement</option>
<option
<?php
if ($type == 'remove_advert') {
echo 'selected';
}
?>
value="remove_advert">Remove Advertisement</option>
</select>
</div>
</div>
</div>
</div>
<div class="col-sm-2 col-xs-2">
<div class="form-group">
<input class="btn btn-danger" value="Filter Advertisements" type="submit">
<!-- <a href="javascript:void(0)" class="cleanSearchFilter">Clean the filter</a>-->
</div>
</div>
</div>
</form>
</div>
</div>
<table class="table table-bordered table-stripped datatable">
<thead>
<tr>
<th>Sr.</th>
<th>Location Name</th>
<th>Location Number</th>
<th>Advertise Number</th>
<th>Type</th>
<th>Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$i = 1;
foreach ($tasks as $key => $value) {
echo "<tr>
<td>".$i."</td>
<td>".$value->location_name."</td>
<td>".$value->location_number."</td>
<td>".$value->advert_number."</td>";
if ($value->task_type == "add_advert") {
$type = "Add Advertisement";
}elseif ($value->task_type == "remove_advert") {
$type = "Remove Advertisement";
}
echo "<td>".$type."</td><td>".$value->date."</td>";
echo "<td> <a class='btn btn-primary round-btn' href='".base_url()."location_manager/tasks_assigned/".$value->task_id."'>View Details</a>";
if ($status == 0) {
echo " <a href='".base_url()."location_manager/deliver_task/".$value->task_id."' class='btn btn-success round-btn'>Deliver</a>";
}
echo "</td></tr>";
$i++;
}
?>
</tbody>
</table>
<!-- END PAGE BASE CONTENT -->
</div>
<script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />
<script type="text/javascript">
$(document).ready(function(){
//$('.MonthPicker').MonthPicker({ MinMonth: 1,Button: false });
$('.dateRangePicker').daterangepicker({
"autoApply": true,
"autoUpdateInput": false,
// "startDate": "03/26/2019",
// "endDate": "04/01/2019",
"opens": "center"
})
$('.dateRangePicker').on('apply.daterangepicker', function(ev, picker) {
$(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY'));
});
<?php
if ($start_date!="" && $end_date!="") {
?>
$('.dateRangePicker').data('daterangepicker').setStartDate('<?=$start_date?>');
$('.dateRangePicker').data('daterangepicker').setEndDate('<?=$end_date?>');
$('.dateRangePicker').val('<?=$start_date?>' + ' - ' + '<?=$end_date?>');
<?php
}
?>
});
</script><file_sep>/application/controllers/Users.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Users extends GH_Controller {
public $data = array();
public $table = "users";
public function __construct() {
parent::__construct();
$this->data['menu_class'] = "admin_menu";
$this->data['title'] = "Admin";
$this->data['sidebar_file'] = "admin/admin_sidebar";
}
function _remap($method,$param){
if (method_exists($this,$method)) {
if (!empty($param)) {
$this->$method($param[0]);
}else{
$this->$method();
}
} else {
$this->index($method);
}
}
public function index($status = "")
{
$where = array();
if ($status != "") {
$where['status'] = $status;
}
$result = $this->crud_model->get_data('users',$where);
$this->data['users'] = $result;
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('admin/view_users');
$this->load->view('common/footer');
}
public function manage_user(){
$email_validation = 'required|valid_email';
if(!empty($_POST) && $_POST['user_id'] == ""){
$email_validation .= "|is_unique[users.email]";
}
$this->form_validation->set_rules('email', '*Email', $email_validation, array(
'required' => '%s Missing',
'is_unique' => '%s already Registered'
));
$this->form_validation->set_rules('password', '*Password', 'required|min_length[6]|max_length[12]|alpha_numeric', array(
'required' => '%s Missing',
'min_length' => '%s must be at least 6 characters',
'max_length' => '%s must be at most 12 characters',
'alpha_numeric' => '%s must be Alpha Numeric'
));
$this->form_validation->set_rules('re_password', '*Re-type Password', 'required|matches[password]', array(
'required' => '%s Missing',
'matches' => 'Password does not match'
));
$result = $this->form_validation->run();
if ($result) {
$form_data = $_POST;
$profile_image = $this->crud_model->upload_file($_FILES['profile_image'],'profile_image',PROFILE_IMAGE_UPLOAD_PATH);
if ($profile_image) {
$form_data['profile_image'] = $profile_image;
}elseif ($form_data['old_profile_image'] != "") {
$form_data['profile_image'] = $form_data['old_profile_image'];
}
unset($form_data['old_profile_image']);
unset($form_data['re_password']);
$edit = false;
if ($form_data['user_id'] != "") {
$edit = true;
$qb = true;
if ($form_data['user_role'] == 2) {
$qb_update = $this->quick_books->update_vendor($form_data);
if ($qb_update['error'] == true) {
$qb = false;
}
}elseif ($form_data['user_role'] == 6) {
$qb_update = $this->quick_books->update_customer($form_data);
if ($qb_update['error'] == true) {
$qb = false;
}
}elseif ($form_data['user_role'] != 1) {
$qb_update = $this->quick_books->update_employee($form_data);
if ($qb_update['error'] == true) {
$qb = false;
}
}
if ($qb) {
$where['user_id'] = $form_data['user_id'];
unset($form_data['user_id']);
$user_id = $this->crud_model->update_data($this->table,$where,$form_data);
}else{
$user_id = false;
$msg = $qb_update['msg'];
}
}else{
$qb = true;
if ($form_data['user_role'] == 2) {
$qb_add = $this->quick_books->add_vendor($form_data);
if ($qb_add['error'] == false) {
$form_data['user_qb_id'] = $qb_add['msg'];
}else{
$qb = false;
}
} elseif ($form_data['user_role'] == 6) {
$qb_add = $this->quick_books->add_customer($form_data);
if ($qb_add['error'] == false) {
$form_data['user_qb_id'] = $qb_add['msg'];
}else{
$qb = false;
}
}elseif ($form_data['user_role'] != 1) {
$qb_add = $this->quick_books->add_employee($form_data);
if ($qb_add['error'] == false) {
$form_data['user_qb_id'] = $qb_add['msg'];
}else{
$qb = false;
}
}
if ($qb) {
unset($form_data['user_id']);
$form_data['created_by'] = get_user_id();
$user_id = $this->crud_model->add_data($this->table,$form_data);
if ($user_id) {
$this->load->library("PhpMailerLib");
$mail = $this->phpmailerlib->welcome_email($form_data);
if (!$mail) {
$msg = $mail->ErrorInfo;
}
}
}else{
$user_id = false;
$msg = $qb_add['msg'];
}
}
if ($user_id) {
if (isset($edit)) {
if (!isset($msg)) {
$msg = "User Updated successfully";
}
}else{
if (!isset($msg)) {
$msg = "User created successfully";
}
}
$this->session->set_flashdata("success_msg",$msg);
redirect(base_url()."users/");
}else{
if (isset($edit)) {
if (!isset($msg)) {
$msg = "User Not Updated";
}
}else{
if (!isset($msg)) {
$msg = "User Not created";
}
}
$this->session->set_flashdata("error_msg",$msg);
redirect($_SERVER['HTTP_REFERER']);
}
}else{
$this->manage_user_view();
}
}
public function manage_user_view($id = "")
{
if ($id != "") {
$where['user_id'] = $id;
$this->data['user'] = $this->crud_model->get_data($this->table,$where,true);
}
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('admin/manage_user',$this->data);
$this->load->view('common/footer');
}
public function delete_user($id){
$where['user_id'] = $id;
$user = $this->crud_model->get_data($this->table,$where,true,'','','user_qb_id,user_role');
$qb = true;
if ($user->user_role == 2) {
$qb_inactive_user = $this->quick_books->inactive_vendor($user->user_qb_id);
if ($qb_inactive_user['error'] == true) {
$qb = false;
}
}elseif ($user->user_role != 1) {
$qb_inactive_user = $this->quick_books->inactive_employee($user->user_qb_id);
if ($qb_inactive_user['error'] == true) {
$qb = false;
}
}
if ($qb) {
$result = $this->crud_model->delete_data($this->table,$where);
}else{
$this->session->set_flashdata("error_msg",$qb_inactive_user['msg']);
}
redirect($_SERVER['HTTP_REFERER']);
}
}
<file_sep>/application/views/resource_center/resource_center_sidebar.php
<li class="">
<a href="<?=base_url()?>resource_center/1">
Location Contracts
</a>
</li>
<li>
<a href="<?=base_url()?>resource_center/2">
Advertisers Contracts
</a>
</li>
<li>
<a href="<?=base_url()?>resource_center/3">
Marketing / Promo
</a>
</li>
<li>
<a href="<?=base_url()?>resource_center/4">
Location Criteria
</a>
</li>
<li>
<a href="<?=base_url()?>resource_center/5">
Advertising Tips
</a>
</li><file_sep>/application/controllers/Payouts.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Payouts extends GH_Controller {
private $data;
public function __construct() {
parent::__construct();
$this->data['menu_class'] = "payouts_menu";
$this->data['title'] = "Payouts";
$this->data['sidebar_file'] = "payouts/payouts_sidebar";
}
public function index()
{
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('payouts/payouts');
$this->load->view('common/footer');
}
public function view_royalties(){
$user_role = get_user_role();
$this->data['user_role'] = $user_role;
if ($user_role == 1) {
$where_in['user_role'] = array("1","2","3");
$this->data['users'] = $this->crud_model->get_data("users",'','','','','','',$where_in);
$user_id = isset($_POST['user']) ? $_POST['user'] : '';
$this->data['user_id'] = $user_id;
}else{
$user_id = get_user_id();
}
if (isset($user_id)) {
$member_role = get_user_role($user_id);
$this->data['member_role'] = $member_role;
if ($member_role == 2) {
$where['l.location_owner'] = $user_id;
}elseif ($member_role == 1 || $member_role == 3) {
$where['l.created_by'] = $user_id;
}
$join['packages p'] = "ad.package_id=p.package_id";
$join['locations l'] = "ad.location_id=l.location_id";
$locations = $this->crud_model->get_data("advertisements ad",array(),'',$join,array(),'ad.*,l.*,p.*,ad.status as advert_status');
$net_royalty = 0;
$total_paid = 0;
$remaining = 0;
foreach ($locations as $key => $value) {
$total_cost = 0;
if ($value->advertisment_type == 1) {
$total_cost = $value->total_cost;
}elseif ($value->advertisment_type == 2 && $value->advert_status == 2) {
$total_cost = get_advert_payments($value->advert_id);
}
if ($member_role == 2) {
$value->user_royalty = ($total_cost*$value->owner_royalty)/100;
if ($value->owner_royalty_status == 0) {
$remaining += $value->user_royalty;
}elseif ($value->owner_royalty_status == 1) {
$total_paid += $value->user_royalty;
}
}elseif ($member_role == 1 || $member_role == 3) {
$value->user_royalty = ($total_cost*$value->advert_royalty)/100;
if ($value->advert_royalty_status == 0) {
$remaining += $value->user_royalty;
}elseif ($value->advert_royalty_status == 1) {
$total_paid += $value->user_royalty;
}
}
$net_royalty += $value->user_royalty;
}
$this->data['locations'] = $locations;
$this->data['net_royalty'] = round($net_royalty,2);
$this->data['remaining'] = round($remaining,2);
$this->data['total_paid'] =round($total_paid,2);
}
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('payouts/view_royalties',$this->data);
$this->load->view('common/footer');
}
public function view_commissions(){
$user_role = get_user_role();
$this->data['user_role'] = $user_role;
if ($user_role == 1) {
$where_in['user_role'] = array("1","2","3");
$this->data['users'] = $this->crud_model->get_data("users",'','','','','','',$where_in);
$user_id = isset($_POST['user']) ? $_POST['user'] : '';
$this->data['user_id'] = $user_id;
}else{
$user_id = get_user_id();
}
if (isset($user_id)) {
$member_role = get_user_role($user_id);
$where['ad.created_by'] = $user_id;
$join['packages p'] = "ad.package_id=p.package_id";
$join['locations l'] = "ad.location_id=l.location_id";
$advert = $this->crud_model->get_data("advertisements ad",$where,'',$join);
$net_commission = 0;
$total_paid = 0;
$remaining = 0;
foreach ($advert as $key => $value) {
// $start_month = DateTime::createFromFormat("m/Y", $value->start_date);
// $start_timestamp = $start_month->getTimestamp();
// $start_date = date('Y-m-01', $start_timestamp);
// $end_month = DateTime::createFromFormat("m/Y", $value->end_date);
// $end_timestamp = $end_month->modify('+1 month')->getTimestamp();
// $end_date = date('Y-m-01', $end_timestamp);
// $qty = (int)abs((strtotime($start_date) - strtotime($end_date))/(60*60*24*30));
//$cost = $value->total_cost*$qty;
$cost = 0;
if ($value->advertisment_type == 1) {
$cost = $value->total_cost;
}elseif ($value->advertisment_type == 2 && $value->advert_status == 2) {
$cost = get_advert_payments($value->advert_id);
}
$user_commission = get_user_commission($user_id);
$value->user_commission = ($cost*$user_commission)/100;
$net_commission += $value->user_commission;
if ($value->commission_status == 0) {
$remaining += $value->user_commission;
}elseif ($value->commission_status == 1) {
$total_paid += $value->user_commission;
}
}
$this->data['advert'] = $advert;
$this->data['net_commission'] = $net_commission;
$this->data['remaining'] = $remaining;
$this->data['total_paid'] = $total_paid;
}
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('payouts/view_commissions',$this->data);
$this->load->view('common/footer');
}
public function commission_status($advert_id,$status){
$where['advert_id'] = $advert_id;
$data['commission_status'] = $status;
$res = $this->crud_model->update_data('advertisements',$where,$data);
if ($res) {
$this->session->set_flashdata('success_msg','Commission status updated');
}else{
$this->session->set_flashdata('error_msg','Error! Commission status not updated');
}
redirect($_SERVER['HTTP_REFERER']);
}
public function royalty_status($location_id,$where_status,$status){
$where['location_id'] = $location_id;
$data[$where_status] = $status;
$res = $this->crud_model->update_data('locations',$where,$data);
if ($res) {
$this->session->set_flashdata('success_msg','Royalty status updated');
}else{
$this->session->set_flashdata('error_msg','Error! Royalty status not updated');
}
redirect($_SERVER['HTTP_REFERER']);
}
public function bank_details(){
}
}
<file_sep>/application/controllers/Quickbooks.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//require("quickbooks/auth2/OAuth_2/Client.php");
class Quickbooks extends GH_Controller {
public $data = array();
public function __construct() {
parent::__construct();
$this->data['menu_class'] = "admin_menu";
$this->data['title'] = "Admin";
$this->data['sidebar_file'] = "admin/admin_sidebar";
}
public function index()
{
$from = $this->input->post();
if (!empty($from)) {
$this->settings_model->set_value('qb_client_id',$from['qb_client_id']);
$this->settings_model->set_value('qb_client_secret',$from['qb_client_secret']);
}
$this->data['redirect_uri'] = $this->config->item('qb_oauth_redirect_uri');
$this->data['qb_client_secret'] = $this->settings_model->get_value("qb_client_secret");
$this->data['qb_client_id'] = $this->settings_model->get_value("qb_client_id");
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('admin/quickbooks_connect');
$this->load->view('common/footer');
}
public function save_token(){
$client_id = $this->settings_model->get_value('qb_client_id');
$client_secret = $this->settings_model->get_value('qb_client_secret');
$authorizationRequestUrl = $this->config->item('qb_authorizationRequestUrl');
$scope = $this->config->item('qb_oauth_scope');
$redirect_uri = $this->config->item('qb_oauth_redirect_uri');
$tokenEndPointUrl = $this->config->item('qb_tokenEndPointUrl');
$grant_type= 'authorization_code';
$response_type = 'code';
$state = 'RandomState';
$certFilePath = '';
$client = new Client($client_id, $client_secret, $certFilePath);
if (!isset($_GET["code"]))
{
$authUrl = $client->getAuthorizationURL($authorizationRequestUrl, $scope, $redirect_uri, $response_type, $state);
header("Location: ".$authUrl);
exit();
}else
{
$code = $_GET["code"];
$responseState = $_GET['state'];
if(strcmp($state, $responseState) != 0){
throw new Exception("The state is not correct from Intuit Server. Consider your app is hacked.");
}
$result = $client->getAccessToken($tokenEndPointUrl, $code, $redirect_uri, $grant_type);
$this->settings_model->set_value('qb_access_token',$result['access_token']);
$this->settings_model->set_value('qb_refresh_token',$result['refresh_token']);
$this->settings_model->set_value('qb_realmId',$_GET['realmId']);
$this->session->set_flashdata('success_msg',"Quickbooks Connected Successfully");
echo '<script type="text/javascript">
window.opener.location.href = window.opener.location.href;
window.close();
</script>';
}
}
}<file_sep>/application/views/advertisers/advertisers_sidebar.php
<?php
if (has_permission("advertiser_sidebar")) {
?>
<li class="">
<a href="#">
My Advertiser
</a>
</li>
<li>
<a href="<?php echo base_url() ?>advertisers/manage_advertisers">
Add New Advertiser
</a>
</li>
<li>
<a href="<?php echo base_url() ?>advertisers/view_advertisers">
All Advertisers
</a>
</li>
<?php
}
?>
<li>
<a href="<?php echo base_url() ?>advertisers/view_advertisements">
View Advertisements
</a>
</li>
<file_sep>/application/views/location/view_locations.php
<div class="page-content-col">
<div class="row">
<?php
if ($this->session->flashdata("success_msg") != "") {
?>
<div class="alert alert-success">
<?php echo $this->session->flashdata("success_msg"); ?>
</div>
<?php
}
?>
</div>
<table class="table table-bordered table-stripped" id="locations_records">
<thead>
<tr>
<th>Sr.</th>
<th>Location Name</th>
<th>Location Number</th>
<th>Owner Royalty (%)</th>
<th>Advertiser Royalty (%)</th>
<th>Location Owner</th>
<th>Added By</th>
<th>Status</th>
<?php
if ($user_role == 1) {
?>
<th width="120px">Action</th>
<?php
}
?>
</tr>
</thead>
<tbody>
<?php
$i = 1;
foreach ($locations as $key => $value) {
echo "<tr>
<td>".$i."</td>
<td>".$value->location_name."</td>
<td>".$value->location_number."</td>
<td>".$value->owner_royalty."</td>
<td>".$value->advert_royalty."</td>
<td>".$value->owner_name."</td>
<td>".$value->satff_name."</td>";
if ($user_role == 1) {
echo "<td> <input type='checkbox' ". ($value->location_status == 1 ? 'checked' : '') ." data-record_id='{$value->location_id}' data-table='locations' data-where='location_id' class='make-switch change_record_status' data-on-text='Active' data-off-text='Deactive'> </td>";
}else{
echo "<td>".get_status($value->location_status)."</td>";
}
if ($user_role == 1) {
echo "<td> <a class='btn btn-primary round-btn' href='".base_url()."locations/manage_location_view/".$value->location_id."'>Edit</a> <a href='".base_url()."locations/delete_location/".$value->location_id."' class='btn btn-danger round-btn delete-btn'>Delete</a></td>
</tr>";
}
$i++;
}
?>
</tbody>
</table>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#locations_records").DataTable({
"pageLength": 100
});
});
</script>
<file_sep>/application/controllers/analytics/Videos.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//memory_limit 8G
//max_input_vars 100000
//max_execution_time 8000
//post_max_size 8G
class Videos extends GH_Controller {
public $data = array();
public function __construct() {
parent::__construct();
$this->load->model("video_model");
$this->load->model("kairos_model");
}
function _remap($method,$param){
if (method_exists($this,$method)) {
if (!empty($param)) {
if(!isset($param[1])){
$this->$method($param[0]);
}else{
$this->$method($param[0],$param[1]);
}
}else{
$this->$method();
}
} else {
$this->index($method);
}
}
public function recordAnalytics($analyticsid,$videoID){
$this->kairos_model->analyticsApi($analyticsid,$videoID);
redirect($_SERVER['HTTP_REFERER']);
}
public function startAnalysis(){
$video = $_FILES["video"]["tmp_name"];
$galleryID = $this->video_model->makeFrames($video);
//$galleryID = generateGalleryID();
if ($galleryID) {
$videoID = $this->video_model->insertGalleryID($galleryID,$this->input->post("locationID"));
$this->kairos_model->startAnalysis($galleryID,$video,$videoID);
}
}
public function index($locationID)
{
if (isset($_POST['submit'])) {
$this->startAnalysis();
redirect($_SERVER['HTTP_REFERER']);
}
$this->data['videos'] = $this->crud_model->get_data_new(array('table'=>"videos",'where'=>array("locationID"=>$locationID)));
$this->data['locationID'] = $locationID;
$this->load->view('analytics/includes/header');
$this->load->view('analytics/includes/navbar');
$this->load->view('analytics/video/upload_video',$this->data);
$this->load->view('analytics/includes/footer');
}
public function deleteVideo($galleryID,$videoID){
$res = $this->kairos_model->deleteGallery($galleryID);
$this->video_model->deleteVideoData($videoID);
deleteDir("./frames/".$galleryID);
redirect($_SERVER['HTTP_REFERER']);
}
public function change_emotions(){
$filter = $this->input->post("filter");
$analytics_param = array();
if ($this->input->post("daterange") != "") {
$date = $this->input->post("daterange");
$data = explode("/", $date);
$start_date = $data[0];
$end_date = $data[1];
$analytics_param = array("start_date"=> $start_date , "end_date"=> $end_date);
}
$emotions = $this->video_model->get_analytics($analytics_param,$filter);
echo json_encode($emotions);
}
}
<file_sep>/application/views/advertisers/manage_advertisement.php
<!-- END PAGE SIDEBAR -->
<div class="page-content-col">
<div class="row">
<?php
if ($this->session->flashdata("error_msg") != "") {
?>
<div class="alert alert-danger">
<?php echo $this->session->flashdata("error_msg"); ?>
</div>
<?php
}
?>
<?php //echo validation_errors(); ?>
</div>
<!-- BEGIN PAGE BASE CONTENT -->
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-blue-hoki bold uppercase">Manage Advertisment</span>
</div>
<div class="tools">
<a href="" class="collapse" data-original-title="" title=""> </a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="" method="post" enctype="multipart/form-data" class="horizontal-form">
<div class="form-body">
<h3 class="form-section">Advertiser Info</h3>
<div class="row">
<div class="col-md-6">
<?php $advertiser_type = set_value('advertiser_type');
$advertiser_type_error = form_error('advertiser_type');
$advertisment_type = set_value('advertisment_type');
?>
<div class="form-group <?php echo ($advertiser_type_error != '') ? 'has-error' : '' ?> ">
<label class="control-label">Advertiser Type
</label>
<select id="advertiser_type" name="advertiser_type" class="form-control" onchange="advertiser_company_type()">
<option value="" <?php echo ($advertiser_type == '') ? 'selected' : '' ?> >Select Advertiser Type
</option>
<option value="1" <?php echo ($advertiser_type == 1) ? 'selected' : '' ?> >Select Existing Advertiser
</option>
<option value="2" <?php echo ($advertiser_type == 2) ? 'selected' : '' ?> >Add New Advertiser
</option>
</select>
<span class="help-block"> <?php echo $advertiser_type_error; ?> </span>
</div>
</div>
<div class="col-md-6 advertiser_div" style="display: none;">
<?php $advertiser_id = set_value('advertiser_id');
$advertiser_id_error = form_error('advertiser_id');
?>
<div class="form-group <?php echo ($advertiser_id_error != '') ? 'has-error' : '' ?> ">
<label class="control-label">Select Advertiser
</label>
<select name="advertiser_id" class="form-control advertiser_id">
<option value="" <?php echo ($advertiser_id == '') ? 'selected' : '' ?> >Select Advertiser
</option>
<?php
foreach ($advertisers as $key => $value) {
echo "<option ".($advertiser_id == $value->user_id ? 'selected' : '')." value='".$value->user_id."' >".$value->first_name." ".$value->last_name."</option>";
}
?>
</select>
<span class="help-block"> <?php echo $advertiser_id_error; ?> </span>
</div>
</div>
</div>
<div class="user_info" style="display: none;">
<div class="row">
<div class="col-md-6">
<?php
$company_name_error = form_error('advert[company_name]');
?>
<div class="form-group <?php echo ($company_name_error != '') ? 'has-error' : '' ?>">
<label class="control-label">Company Name</label>
<input type="text" id="" class="form-control company_name" name="advert[company_name]" placeholder="Enter Company Name" value="<?php echo (set_value('advert[company_name]')); ?>">
<span class="help-block"> <?php echo $company_name_error; ?> </span>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<?php
$website_error = form_error('advert[website]');
?>
<div class="form-group <?php echo ($website_error != '') ? 'has-error' : '' ?>">
<label class="control-label">Website</label>
<input type="text" id="" class="form-control website" placeholder="Enter Website" name="advert[website]" value="<?php echo (set_value('advert[website]')); ?>">
<span class="help-block"> <?php echo $website_error; ?> </span>
</div>
</div>
<!--/span-->
</div>
<div class="row">
<div class="col-md-6">
<?php
$first_name_error = form_error('advert[first_name]');
?>
<div class="form-group <?php echo ($first_name_error != '') ? 'has-error' : '' ?>">
<label class="control-label">First Name
</label>
<input id="firstName" class="form-control first_name" name="advert[first_name]" placeholder="Enter First Name" value="<?php echo (set_value('advert[first_name]')); ?>" type="text">
<span class="help-block"> <?php echo $first_name_error; ?> </span>
</div>
</div>
<div class="col-md-6">
<?php
$last_name_error = form_error('advert[last_name]');
?>
<div class="form-group <?php echo ($last_name_error != '') ? 'has-error' : '' ?>">
<label class="control-label">Last Name
</label>
<input id="lastName" class="form-control last_name" placeholder="Enter Last Name" name="advert[last_name]" value="<?php echo (set_value('advert[last_name]')); ?>" type="text">
<span class="help-block"> <?php echo $last_name_error; ?> </span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<?php
$email_error = form_error('advert[email]');
?>
<div class="form-group <?php echo ($email_error != '') ? 'has-error' : '' ?>">
<label class="control-label">Email
</label>
<input id="email_input" name="advert[email]" class="form-control email" value="<?php echo (set_value('advert[email]')); ?>" type="email">
<span class="help-block"> <?php echo $email_error; ?> </span>
</div>
</div>
<div class="col-md-6">
<?php
$password_error = form_error('advert[password]');
?>
<div class="form-group <?php echo ($password_error != '') ? 'has-error' : '' ?>">
<label class="control-label">Password
</label>
<input name="advert[password]" class="form-control password" value="<?php echo (set_value('advert[password]')); ?>" type="password">
<span class="help-block"> <?php echo $email_error; ?> </span>
</div>
</div>
<div class="col-md-6">
<?php
$phone_error = form_error('advert[phone_number]');
?>
<div class="form-group <?php echo ($phone_error != '') ? 'has-error' : '' ?>">
<label for="exampleInputFile1">Phone Number</label>
<input type="text" name="advert[phone_number]" class="form-control phone_number" value="<?php echo (set_value('advert[phone_number]')); ?>">
<span class="help-block"> <?php echo $phone_error; ?> </span>
</div>
</div>
</div>
<input type="hidden" name="advert[user_role]" value="6">
</div>
<h3 class="form-section">Advertisment Info</h3>
<div class="row">
<div class="col-md-6 " >
<div class="form-group ">
<label class="control-label">Select Advertisment Type
</label>
<select id="advertisment_type" name="advertisment_type" class="form-control advertisment_type" onchange="advertiser_packeg_type()">
<option value="" selected>Select Advertisment Type</option>
<option value="1" >pay per performance</option>
<option value="2" >Pay as you go</option>
</select>
<span class="help-block" style="color:red;"> <?php echo form_error('advertisment_type'); ?> </span>
</div>
</div>
</div>
<div class='packeg_div' style="display:none;">
<div class="row">
<div class="col-md-6 package_div hide_selectpack" style="display:none;">
<?php
$package_id_error = form_error('package_id');
?>
<div class=" form-group <?php echo ($package_id_error != '') ? 'has-error' : '' ?>" >
<label class="control-label">Select Package
</label>
<select name="package_id" class="form-control package_id">
<option value="" >Select Package</option>
<?php
foreach ($packages as $key => $value) {
echo "<option ".($package_id == $value->package_id ? 'selected' : '')." value='".$value->package_id."' >".$value->package_name." ($".$value->total_cost.") </option>";
}
?>
</select>
<span class="help-block" ><?php echo $package_id_error; ?> </span>
</div>
</div>
<div class="col-md-6">
<?php
$start_date_error = form_error('start_date');
?>
<div class="form-group <?php echo ($start_date_error != '') ? 'has-error' : '' ?>">
<label class="control-label">Start Date of Advertisment</label>
<input type="text" class="form-control start_date MonthPicker" name="start_date" value="<?php echo (set_value('start_date')); ?>">
<span class="help-block"><?php echo $start_date_error; ?> </span>
</div>
</div>
<div class="col-md-6 hide_enddate" style="display:none;">
<?php
$end_date_error = form_error('end_date');
?>
<div class="form-group <?php echo ($end_date_error != '') ? 'has-error' : '' ?>">
<label class="control-label">End Date of Advertisment</label>
<input type="text" class="form-control end_date MonthPicker" name="end_date" value="<?php echo (set_value('end_date')); ?>">
<span class="help-block"><?php echo $end_date_error; ?> </span>
</div>
</div>
<!--/span-->
<!-- <div class="col-md-6">
<div class="form-group">
<label class="control-label">End Month of Advertisment</label>
<input type="text" class="form-control end_date MonthPicker" name="end_date" value="<?php echo (set_value('end_date')); ?>">
</div>
</div> -->
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Design file</label>
<select name="hologram_type" class="form-control hologram_type">
<option value="1">Upload Design From Computer</option>
<option value="2">Request Advertisement Design</option>
</select>
</div>
</div>
<div class="col-md-6 hologram_file_div">
<div class="form-group">
<label class="control-label">Upload Advertisement Design</label>
<input id="hologram_file" type="file" name="hologram_file">
</div>
</div>
<!--/span-->
</div>
<div class="row hologram_description_div" style="display: none;">
<div class="col-md-12">
<div class="form-group">
<label for="exampleInputFile1">Design Description</label>
<textarea rows="5" name="hologram_description" class="form-control hologram_description"></textarea>
</div>
</div>
</div>
</div>
<div class='card_div' style="display:none;">
<h3 class="form-section">Card Info</h3>
<div class="row">
<div class="col-md-6">
<?php
$name_error = form_error('card[name]');
?>
<div class="form-group <?php echo ($name_error != '') ? 'has-error' : '' ?>">
<label class="control-label">Name</label>
<input type="text" id="" class="form-control name" name="card[name]" placeholder="Card Holder Name" value="">
<span class="help-block"> <?php echo $name_error; ?> </span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Card Number</label>
<input type="text" id="" class="form-control card_number" name="card[card_number]" placeholder="#####################" value="">
<span class="help-block"> <?php echo form_error('card[card_number]'); ?> </span>
</div>
</div>
</div>
<div class="row">
<div class="col-md-2">
<div class="form-group">
<label class="control-label">Expiry month</label>
<select class="form-control card_exp_month" name="card[card_exp_month]">
<option value=''>--Select Month--</option>
<option selected value='1'>01</option>
<option value='02'>02</option>
<option value='03'>03</option>
<option value='04'>04</option>
<option value='05'>05</option>
<option value='06'>06</option>
<option value='07'>07</option>
<option value='08'>08</option>
<option value='09'>09</option>
<option value='10'>10</option>
<option value='11'>11</option>
<option value='12'>12</option>
</select>
<span class="help-block"> <?php echo form_error('card[card_exp_month]'); ?> </span>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="control-label">Expiry year</label>
<select class="form-control card_exp_year" name="card[card_exp_year]">
<?php
for ($i=date('Y');$i<=2035;$i++){
echo "<option value=".$i.">".$i."</option>n";
}
?>
</select>
<span class="help-block"> <?php echo form_error('card[card_exp_year]'); ?> </span>
</div>
</div>
<div class="col-md-2">
<div class="form-group">
<label class="control-label">CVV</label>
<input type="text" name="card[card_cvv]" class=" form-control card_cvv" value=""/>
<span class="help-block"> <?php echo form_error('card[card_cvv]'); ?> </span>
</div>
</div>
</div>
</div>
</div>
<div class="form-actions right">
<input type="hidden" class="hologram_file" name="old_hologram_file">
<input type="hidden" class="advert_id" name="advert_id">
<input type="hidden" class="card_id" name="card_id">
<input type="hidden" name="location_id" value="<?=$location_id?>">
<button type="submit" class="btn blue">
<i class="fa fa-check"></i> Save</button>
</div>
</form>
<!-- END FORM-->
</div>
</div>
<!-- END PAGE BASE CONTENT -->
</div>
<?php
if ($advertiser_type != "") {
?>
<script type="text/javascript">
advertiser_company_type();
</script>
<?php
}
if ($advertisment_type != "") {
?>
<script type="text/javascript">
$(".advertisment_type").val("<?=$advertisment_type?>");
advertiser_packeg_type();
</script>
<?php
}
if (isset($advert) && !empty($advert)) {
?>
<script type="text/javascript">
$(document).ready(function(){
$("#advertiser_type").val("1");
advertiser_company_type();
<?php
foreach ($advert as $key => $value) {
?>
var key = "<?php echo $key ?>";
$("."+key+"").val("<?php echo $value ?>");
<?php
}
?>
$(".hologram_type").change();
advertiser_packeg_type();
});
</script>
<?php
}
?>
<script type="text/javascript">
$(document).ready(function(){
$('.MonthPicker').datepicker({ minDate : 0});
});
</script><file_sep>/application/models/Quick_books.php
<?php
require_once(APPPATH.'third_party/quickbooks/auth2/OAuth_2/Client.php');
require_once(APPPATH.'third_party/quickbooks/vendor/autoload.php');
use QuickBooksOnline\API\DataService\DataService;
use QuickBooksOnline\API\Core\Http\Serialization\XmlObjectSerializer;
use QuickBooksOnline\API\Facades\Customer;
use QuickBooksOnline\API\Facades\Invoice;
use QuickBooksOnline\API\Facades\Item;
use QuickBooksOnline\API\Facades\Vendor;
use QuickBooksOnline\API\Facades\Employee;
class Quick_books extends Settings_model{
private $dataService;
private $qb_client_id;
private $qb_client_secret;
private $qb_access_token;
private $qb_refresh_token;
private $qb_realmId;
public function __construct() {
parent::__construct();
$this->qb_client_id = $this->get_value('qb_client_id');
$this->qb_client_secret = $this->get_value('qb_client_secret');
$this->qb_refresh_token = $this->get_value('qb_refresh_token');
$this->qb_realmId = $this->get_value('qb_realmId');
}
public function add_customer($data){
$this->refresh_token();
$theResourceObj = Customer::create([
"BillAddr" => [
"Line1" => $data['street'],
"City" => $data['city'],
"Country" => $data['country'],
"PostalCode" => $data['post_code']
],
"GivenName" => $data['first_name'],
"FamilyName" => $data['last_name'],
"DisplayName" => $data['first_name'].' '.$data['last_name'],
"CompanyName" => $data['company_name'],
"PrimaryPhone" => [
"FreeFormNumber" => $data['phone_number']
],
"PrimaryEmailAddr" => [
"Address" => $data['email']
],
"WebAddr" => [
"URI" => $data['website']
]
]);
$resultingObj = $this->dataService->Add($theResourceObj);
$error = $this->dataService->getLastError();
$response = array();
if ($error) {
$response['error'] = true;
$response['msg'] = "The Response message is: " . $error->getResponseBody();
}
else {
$response['error'] = false;
$response['msg'] = $resultingObj->Id;
}
return $response;
}
public function update_customer($data){
$this->refresh_token();
$customer = $this->dataService->FindbyId('customer', $data['user_qb_id']);
$theResourceObj = Customer::update($customer , [
"BillAddr" => [
"Line1" => $data['street'],
"City" => $data['city'],
"Country" => $data['country'],
"PostalCode" => $data['post_code']
],
"GivenName" => $data['first_name'],
"FamilyName" => $data['last_name'],
"DisplayName" => $data['first_name'].' '.$data['last_name'],
"PrimaryPhone" => [
"FreeFormNumber" => $data['phone_number']
],
"PrimaryEmailAddr" => [
"Address" => $data['email']
]
]);
$resultingObj = $this->dataService->Update($theResourceObj);
$error = $this->dataService->getLastError();
$response = array();
if ($error) {
$response['error'] = true;
$response['msg'] = "The Response message is: " . $error->getResponseBody();
}
else {
$response['error'] = false;
$response['msg'] = $resultingObj->Id;
}
return $response;
}
public function inactive_customer($id){
$this->refresh_token();
$customer = $this->dataService->FindbyId('customer', $id);
$theResourceObj = Customer::update($customer , [
"Active" => false
]);
$resultingObj = $this->dataService->Update($theResourceObj);
$error = $this->dataService->getLastError();
$response = array();
if ($error) {
$response['error'] = true;
$response['msg'] = "The Response message is: " . $error->getResponseBody();
}
else {
$response['error'] = false;
$response['msg'] = $resultingObj->Id;
}
return $response;
}
public function add_vendor($data){
$this->refresh_token();
$BillAddr = array();
if (!isset($data['street'])) {
$data['street'] = "";
$data['city'] = "";
$data['post_code'] = "";
}
$theResourceObj = Vendor::create([
"BillAddr" => [
"Line1" => $data['street'],
"City" => $data['city'],
"PostalCode" => $data['post_code']
],
"GivenName" => $data['first_name'],
"FamilyName" => $data['last_name'],
"DisplayName" => $data['first_name'].' '.$data['last_name'],
"PrimaryPhone" => [
"FreeFormNumber" => $data['phone_number']
],
"PrimaryEmailAddr" => [
"Address" => $data['email']
]
]);
$resultingObj = $this->dataService->Add($theResourceObj);
$error = $this->dataService->getLastError();
$response = array();
if ($error) {
$response['error'] = true;
$response['msg'] = "The Response message is: " . $error->getResponseBody();
}
else {
$response['error'] = false;
$response['msg'] = $resultingObj->Id;
}
return $response;
}
public function update_vendor($data){
$this->refresh_token();
$vendor = $this->dataService->FindbyId('vendor', $data['user_qb_id']);
$theResourceObj = Vendor::update($vendor , [
"BillAddr" => [
"Line1" => $data['street'],
"City" => $data['city'],
"PostalCode" => $data['post_code']
],
"GivenName" => $data['first_name'],
"FamilyName" => $data['last_name'],
"DisplayName" => $data['first_name'].' '.$data['last_name'],
"PrimaryPhone" => [
"FreeFormNumber" => $data['phone_number']
],
"PrimaryEmailAddr" => [
"Address" => $data['email']
]
]);
$resultingObj = $this->dataService->Update($theResourceObj);
$error = $this->dataService->getLastError();
$response = array();
if ($error) {
$response['error'] = true;
$response['msg'] = "The Response message is: " . $error->getResponseBody();
}
else {
$response['error'] = false;
$response['msg'] = $resultingObj->Id;
}
return $response;
}
public function inactive_vendor($id){
$this->refresh_token();
$vendor = $this->dataService->FindbyId('vendor', $id);
$theResourceObj = Vendor::update($vendor , [
"Active" => false
]);
$resultingObj = $this->dataService->Update($theResourceObj);
$error = $this->dataService->getLastError();
$response = array();
if ($error) {
$response['error'] = true;
$response['msg'] = "The Response message is: " . $error->getResponseBody();
}
else {
$response['error'] = false;
$response['msg'] = $resultingObj->Id;
}
return $response;
}
public function add_item($data){
$this->refresh_token();
$theResourceObj = Item::create([
"Name" => $data['package_name'],
"UnitPrice" => $data['total_cost'],
"IncomeAccountRef" => [
"value" => "79",
"name" => "Sales of Product Income"
],
"ExpenseAccountRef" => [
"value" => "80",
"name" => "Cost of Goods Sold"
],
"Type" => "Service",
"QtyOnHand" => 1,
]);
$resultingObj = $this->dataService->Add($theResourceObj);
$error = $this->dataService->getLastError();
$response = array();
if ($error) {
$response['error'] = true;
$response['msg'] = "The Response message is: " . $error->getResponseBody();
}
else {
$response['error'] = false;
$response['msg'] = $resultingObj->Id;
}
return $response;
}
public function update_item($data){
$this->refresh_token();
$item = $this->dataService->FindbyId('item', $data['item_qb_id']);
$theResourceObj = Item::update($item , [
"Name" => $data['package_name'],
"UnitPrice" => $data['total_cost'],
"IncomeAccountRef" => [
"value" => "79",
"name" => "Sales of Product Income"
],
"ExpenseAccountRef" => [
"value" => "80",
"name" => "Cost of Goods Sold"
],
"Type" => "Service",
"QtyOnHand" => 1,
]);
$resultingObj = $this->dataService->Update($theResourceObj);
$error = $this->dataService->getLastError();
$response = array();
if ($error) {
$response['error'] = true;
$response['msg'] = "The Response message is: " . $error->getResponseBody();
}
else {
$response['error'] = false;
$response['msg'] = $resultingObj->Id;
}
return $response;
}
public function inactive_item($id){
$this->refresh_token();
$item = $this->dataService->FindbyId('item', $id);
$theResourceObj = Item::update($item , [
"Active" => false
]);
$resultingObj = $this->dataService->Update($theResourceObj);
$error = $this->dataService->getLastError();
$response = array();
if ($error) {
$response['error'] = true;
$response['msg'] = "The Response message is: " . $error->getResponseBody();
}
else {
$response['error'] = false;
$response['msg'] = $resultingObj->Id;
}
return $response;
}
public function add_employee($data){
$this->refresh_token();
$theResourceObj = Employee::create([
"PrimaryAddr" => [
"Line1" => $data['street'],
"City" => $data['city'],
"PostalCode" => $data['post_code']
],
"GivenName" => $data['first_name'],
"FamilyName" => $data['last_name'],
"DisplayName" => $data['first_name'].' '.$data['last_name'],
"PrimaryPhone" => [
"FreeFormNumber" => $data['phone_number']
],
"PrimaryEmailAddr" => [
"Address" => $data['email']
]
]);
$resultingObj = $this->dataService->Add($theResourceObj);
$error = $this->dataService->getLastError();
$response = array();
if ($error) {
$response['error'] = true;
$response['msg'] = "The Response message is: " . $error->getResponseBody();
}
else {
$response['error'] = false;
$response['msg'] = $resultingObj->Id;
}
return $response;
}
public function update_employee($data){
$this->refresh_token();
$employee = $this->dataService->FindbyId('employee', $data['user_qb_id']);
$theResourceObj = Employee::update($employee , [
"PrimaryAddr" => [
"Line1" => $data['street'],
"City" => $data['city'],
"PostalCode" => $data['post_code']
],
"GivenName" => $data['first_name'],
"FamilyName" => $data['last_name'],
"DisplayName" => $data['first_name'].' '.$data['last_name'],
"PrimaryPhone" => [
"FreeFormNumber" => $data['phone_number']
],
"PrimaryEmailAddr" => [
"Address" => $data['email']
]
]);
$resultingObj = $this->dataService->Update($theResourceObj);
$error = $this->dataService->getLastError();
$response = array();
if ($error) {
$response['error'] = true;
$response['msg'] = "The Response message is: " . $error->getResponseBody();
}
else {
$response['error'] = false;
$response['msg'] = $resultingObj->Id;
}
return $response;
}
public function inactive_employee($id){
$this->refresh_token();
$employee = $this->dataService->FindbyId('employee', $id);
$theResourceObj = Employee::update($employee , [
"Active" => false
]);
$resultingObj = $this->dataService->Update($theResourceObj);
$error = $this->dataService->getLastError();
$response = array();
if ($error) {
$response['error'] = true;
$response['msg'] = "The Response message is: " . $error->getResponseBody();
}
else {
$response['error'] = false;
$response['msg'] = $resultingObj->Id;
}
return $response;
}
public function create_invoice($data){
$this->refresh_token();
$theResourceObj = Invoice::create([
"Line" => [
[
"Amount" => $data['total_amount'],
"DetailType" => "SalesItemLineDetail",
"SalesItemLineDetail" => [
"ItemRef" => [
"value" => $data['location_qb_id'],
],
"UnitPrice" => $data['monthly_cost'],
"Qty" => $data['qty'],
]
]
],
"CustomerRef"=> [
"value"=> $data['advertiser_qb_id']
],
"EmailStatus" => "EmailSent",
"PrintStatus" => "NeedToPrint",
"BillEmail" => [
"Address" => $data['advertiser_email']
],
]);
$resultingObj = $this->dataService->Add($theResourceObj);
$error = $this->dataService->getLastError();
$response = array();
if ($error) {
$response['error'] = true;
$response['msg'] = "The Response message is: " . $error->getResponseBody();
}
else {
$response['error'] = false;
$response['msg'] = $resultingObj->Id;
}
return $response;
}
public function delete_invoice($id){
$this->refresh_token();
$invoice = $this->dataService->FindbyId('invoice', $id);
$resultingObj = $this->dataService->Delete($invoice);
$error = $this->dataService->getLastError();
$response = array();
if ($error) {
$response['error'] = true;
$response['msg'] = "The Response message is: " . $error->getResponseBody();
}
else {
$response['error'] = false;
$response['msg'] = $resultingObj->Id;
}
return $response;
}
public function refresh_token(){
$tokenEndPointUrl = $this->config->item('qb_tokenEndPointUrl');
$grant_type= 'refresh_token';
$certFilePath = APPPATH.'third_party/quickbooks/auth2/OAuth_2/Certificate/cacert.pem';
$client = new Client($this->qb_client_id, $this->qb_client_secret, $certFilePath);
$result = $client->refreshAccessToken($tokenEndPointUrl, $grant_type, $this->qb_refresh_token);
$this->set_value('qb_access_token',$result['access_token']);
$this->set_value('qb_refresh_token',$result['refresh_token']);
$this->qb_access_token = $result['access_token'];
$this->qb_refresh_token = $result['refresh_token'];
$this->dataService = DataService::Configure(array(
'auth_mode' => 'oauth2',
'ClientID' => $this->qb_client_id,
'ClientSecret' => $this->qb_client_secret,
'accessTokenKey' =>$this->qb_access_token,
'refreshTokenKey' => $this->qb_refresh_token,
'QBORealmID' => $this->qb_realmId,
'baseUrl' => "Development"
//'baseUrl' => "Production"
));
}
public function payment($card_id,$price){
$this->refresh_token();
$queryUrl = "https://sandbox.api.intuit.com/quickbooks/v4/payments/charges";
$data = array('currency'=>"USD","amount"=>$price);
$data['context'] = array("mobile"=>"false","isEcommerce"=>"false");
$card = $this->get_data('card_info',array("card_id"=>$card_id),true);
//$data['card'] = array("name"=>$card->name,"number"=>$card->number,"expMonth"=>$card->card_exp_month,"expYear"=>$card->card_exp_year,"cvc"=>$card->card_cvv,"address"=>array("postalCode"=>$card->post_code, "country"=> $card->country,"region"=> $card->region, "streetAddress"=> $card->street,"city"=> $card->city));
$data['card'] = array("name"=>$card->name,"number"=>$card->card_number,"expMonth"=>$card->card_exp_month,"expYear"=>$card->card_exp_year,"cvc"=>$card->card_cvv);
$data = json_encode($data);
$request = curl_init($queryUrl);
// set curl options
curl_setopt($request, CURLOPT_POST, true);
curl_setopt($request, CURLOPT_POSTFIELDS, $data);
curl_setopt($request, CURLOPT_HTTPHEADER, array(
"Content-type: application/json",
'accept: application/json',
'authorization: Bearer '.$this->qb_access_token,
'request-id: '. rand()
)
);
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($request);
$res = json_decode( $response);
return $res;
}
}<file_sep>/application/controllers/Advertisers.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Advertisers extends GH_Controller {
private $data;
private $table = "advertisements";
public function __construct() {
parent::__construct();
$this->data['menu_class'] = "advertisers_menu";
$this->data['title'] = "Advertisers";
$this->data['sidebar_file'] = "advertisers/advertisers_sidebar";
$this->load->model('Quick_books');
}
public function index()
{
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('advertisers/advertisers');
$this->load->view('common/footer');
}
public function manage_advertisement($location_id,$advert_id = "")
{
$form_data = $this->input->post();
if (!empty($form_data)) {
$user_role = get_user_role();
extract($form_data);
$this->form_validation->set_rules('advertiser_type', '*Advertiser Type', 'required', array(
'required' => '%s Missing'
));
if ($advertiser_type == 1) {
$this->form_validation->set_rules('advertiser_id', '*Advertiser', 'required', array(
'required' => '%s Missing'
));
}else if ($advertiser_type == 2) {
$this->form_validation->set_rules('advert[company_name]', '*Company Name', 'required', array(
'required' => '%s Missing'
));
$this->form_validation->set_rules('advert[first_name]', '*First Name', 'required', array(
'required' => '%s Missing'
));
$this->form_validation->set_rules('advert[last_name]', '*Last Name', 'required', array(
'required' => '%s Missing'
));
$this->form_validation->set_rules('advert[email]', '*Email', 'required|valid_email', array(
'required' => '%s Missing'
));
$this->form_validation->set_rules('advert[phone_number]', '*Phone Number', 'required', array(
'required' => '%s Missing'
));
}
$this->form_validation->set_rules('advertisment_type', '*Advertisment Type', 'required', array(
'required' => '%s Missing'
));
/////////////////////////
// $this->form_validation->set_rules('packeg_type', '*Advertisment Type', 'required', array(
// 'required' => '%s Missing'
// ));
if($form_data['advertisment_type'] == 1){
$this->form_validation->set_rules('start_date', '*Start date', 'required', array(
'required' => '%s Missing'
));
$this->form_validation->set_rules('package_id', '*Package', 'required', array(
'required' => '%s Missing'
));
}else if($form_data['advertisment_type'] == 2){
$this->form_validation->set_rules('start_date', '*Start date', 'required', array(
'required' => '%s Missing'
));
$this->form_validation->set_rules('end_date', '*End date', 'required', array(
'required' => '%s Missing'
));
$this->form_validation->set_rules('card[name]', '*Name', 'required', array(
'required' => '%s Missing'
));
$this->form_validation->set_rules('card[card_number]', '*Card Number', 'required', array(
'required' => '%s Missing'
));
$this->form_validation->set_rules('card[card_exp_month]', '*Expiry month', 'required', array(
'required' => '%s Missing'
));
$this->form_validation->set_rules('card[card_exp_year]', '*Expiry year', 'required', array(
'required' => '%s Missing'
));
$this->form_validation->set_rules('card[card_cvv]', '*CVV', 'required', array(
'required' => '%s Missing'
));
}
$result = $this->form_validation->run();
// if($form_data['packeg_type'] == 2){
// /////////////// Card info store /////////////
// $quicbookres = $this->Quick_books->card_request_api($form_data);
// if($quicbookres){
// $form_data1['name'] = $form_data['name'];
// $form_data1['card_number'] = $form_data['card_number'];
// $form_data1['cvc'] = $form_data['card_cvv'];
// $form_data1['expMonth'] = $form_data['card_exp_month'];
// $form_data1['expYear'] = $form_data['card_exp_year'];
// $form_data1['region'] = $form_data['region'];
// $form_data1['postalCode'] = $form_data['postal_code'];
// $form_data1['country'] = $form_data['country'];
// $form_data1['streetAddress'] = $form_data['street'];
// $form_data1['city'] = $form_data['city'];
// $form_data1['user_id'] = get_user_id();
// $where['user_id'] = get_user_id();
// $result = $this->crud_model->update_card_info($where['user_id'],$form_data1);
// if($result){
// $this->session->set_flashdata("error_msg","Card information store successfully");
// }
// //die;
// }else{
// $this->session->set_flashdata("error_msg","Quickbook not successfully Update");
// }
// //////////////////////////////////////////
// }
if ($result) {
$qb_customer = true;
if ($advertiser_type == 2) {
$form_data['advert']['street'] = "";
$form_data['advert']['city'] = "";
$form_data['advert']['country'] = "";
$form_data['advert']['post_code'] = "";
$qb_add_customer = $this->quick_books->add_customer($form_data['advert']);
if ($qb_add_customer['error'] == false) {
$form_data['advert']['user_qb_id'] = $qb_add_customer['msg'];
$form_data['advert']['created_by'] = get_user_id();
$form_data['advertiser_id'] = $this->crud_model->add_data("users",$form_data['advert']);
$form_data['card']['user_id'] = $form_data['advertiser_id'];
}else{
$qb_customer = false;
}
}
if ($qb_customer) {
$form_data['card']['user_id'] = $form_data['advertiser_id'];
$hologram_file = $this->crud_model->upload_file($_FILES['hologram_file'],'hologram_file',HOLOGRAM_FILE_UPLOAD_PATH);
if ($hologram_file) {
$form_data['hologram_file'] = $hologram_file;
}elseif ($form_data['old_hologram_file'] != "") {
$form_data['hologram_file'] = $form_data['old_hologram_file'];
}
unset($form_data['old_hologram_file']);
unset($form_data['advert']);
unset($form_data['advertiser_type']);
$edit = false;
$form_data['hologram_description'] = trim($form_data['hologram_description']);
if ($advert_id != "") {
$edit = true;
$where_card['card_id'] = $form_data['card_id'];
$card = $this->crud_model->update_data("card_info",$where_card,$form_data['card']);
$where['advert_id'] = $form_data['advert_id'];
unset($form_data['advert_id']);
unset($form_data['card']);
$advert = $this->crud_model->update_data($this->table,$where,$form_data);
}else{
$form_data['card_id'] = $this->crud_model->add_data("card_info",$form_data['card']);
unset($form_data['card']);
$advertiser = $this->crud_model->get_data('users',array("user_id"=>$form_data['advertiser_id']),true);
// $start_month = DateTime::createFromFormat("m/Y", $form_data['start_date']);
// $start_timestamp = $start_month->getTimestamp();
// $start_date = date('Y-m-01', $start_timestamp);
// $end_month = DateTime::createFromFormat("m/Y", $form_data['end_date']);
// $end_timestamp = $end_month->modify('+1 month')->getTimestamp();
// $end_date = date('Y-m-01', $end_timestamp);
if ($advertisment_type == 1) {
$package = $this->crud_model->get_data('packages',array("package_id"=>$form_data['package_id']),true);
$quick_books_data['qty'] = (int)abs((strtotime($start_date) - strtotime($end_date))/(60*60*24*30));
$quick_books_data['total_amount'] = $quick_books_data['qty'] * $package->total_cost;
$quick_books_data['qty'] = 1;
$quick_books_data['total_amount'] = $package->total_cost;
$quick_books_data['monthly_cost'] = $package->total_cost;
$quick_books_data['location_qb_id'] = $package->item_qb_id;
$quick_books_data['advertiser_qb_id'] = $advertiser->user_qb_id;
$quick_books_data['advertiser_email'] = $advertiser->email;
$qb_add = $this->quick_books->create_invoice($quick_books_data);
}else{
$qb_add['error'] = false;
$qb_add['msg'] = "";
}
// echo "<pre>";
// print_r($qb_add);
// echo "</pre>"; die;
if ($qb_add['error'] == false) {
$form_data['advert_qb_id'] = $qb_add['msg'];
$form_data['advert_number'] = ADVERT_NUMBER_PREFIX.mt_rand(100000, 999999);
$form_data['created_by'] = get_user_id();
if ($user_role == 1) {
$form_data['status'] = 1;
}
$advert = $this->crud_model->add_data($this->table,$form_data);
//$notify['receiver_id'] = $location->location_owner;
$notify['message'] = sprintf($this->lang->line('new_advert_added'), get_user_fullname());
$notify['link'] = "advertisers/view_advertisements";
//$this->add_notifications($notify);
$this->add_notifications($notify,'1');
$task['advert_id'] = $advert;
$task['task_type'] = "add_advert";
//$task['date'] = date('Y-01-m', $start_timestamp);
$start_date= date_create($form_data['start_date']);
$task['date'] = date_format($start_date,"Y-m-d");
$task1 = $this->crud_model->add_data('tasks',$task);
if ($task1) {
$notify['message'] = $this->lang->line('new_task_added_manager');
$notify['link'] = "location_manager";
$this->add_notifications($notify,'5');
$this->add_notifications($notify,'1');
}
if($form_data['advertisment_type'] == 2){
$task['task_type'] = "remove_advert";
$end_date=date_create($form_data['end_date']);
$task['date'] = date_format($end_date,"Y-m-d");
$task2 = $this->crud_model->add_data('tasks',$task);
if ($task2) {
$notify['message'] = $this->lang->line('new_task_added_manager');
$notify['link'] = "location_manager";
$this->add_notifications($notify,'5');
$this->add_notifications($notify,'1');
}
}
if ($form_data['hologram_type'] == 2) {
$task['task_type'] = "designer";
//$task['date'] = date('Y-01-m', $start_timestamp);
$start_date=date_create($form_data['start_date']);
$task['date'] = date_format($start_date,"Y-m-d");
$task3 = $this->crud_model->add_data('tasks',$task);
if ($task3) {
$notify['message'] = $this->lang->line('new_task_added_designer');
$notify['link'] = "designer";
$this->add_notifications($notify,'4');
$this->add_notifications($notify,'1');
}
}
}else{
$advert = false;
$msg = $qb_add['msg'];
}
}
}else{
$advert = false;
$msg = $qb_add_customer['msg'];
}
if ($advert) {
if (isset($edit)) {
$this->session->set_flashdata("success_msg","Advertisement Updated successfully");
}else{
$this->session->set_flashdata("success_msg","Advertisement created successfully");
}
redirect(base_url()."advertisers/view_advertisements");
}else{
if (isset($edit)) {
if (!isset($msg)) {
$msg = "Advertisement Not updated";
}
}else{
if (!isset($msg)) {
$msg = "Advertisement Not created";
}
$this->session->set_flashdata("error_msg",$msg);
}
$msg = $qb_add['msg'];
$this->session->set_flashdata("error_msg",$msg);
//redirect($_SERVER['HTTP_REFERER']);
}
}
}
$this->data['location_id'] = $location_id;
if ($advert_id != "") {
$where['advert_id'] = $advert_id;
$join['card_info'] = 'card_info.card_id=advertisements.card_id';
$this->data['advert'] = $this->crud_model->get_data($this->table,$where,true,$join);
}
$this->data['advertisers'] = $this->crud_model->get_data('users',array("user_role"=>6));
$this->data['packages'] = $this->crud_model->get_data('packages');
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('advertisers/manage_advertisement',$this->data);
$this->load->view('common/footer');
}
public function view_advertisements()
{
$join['locations l'] = "ad.location_id=l.location_id";
$join['users u'] = "u.user_id=ad.advertiser_id";
$where = array();
$user_role = get_user_role();
$this->data['user_role'] = $user_role;
if ($user_role != 1) {
if ($user_role == 3) {
$where['ad.created_by'] = get_user_id();
}elseif ($user_role == 2) {
$where['l.location_owner'] = get_user_id();
}elseif ($user_role == 6) {
$where['ad.advertiser_id'] = get_user_id();
}
}
$this->data['adverts'] = $this->crud_model->get_data("advertisements ad",$where,'',$join,'','*,ad.status as advert_status');
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('advertisers/view_advertisements');
$this->load->view('common/footer');
}
public function advertisement_info($location_id,$advert_id)
{
$join['locations l'] = "ad.location_id=l.location_id";
$join['users u'] = "u.user_id=ad.advertiser_id";
$join['packages p'] = "p.package_id=ad.package_id";
$where = array();
$user_role = get_user_role();
$this->data['user_role'] = $user_role;
$where['advert_id'] = $advert_id;
$where['l.location_id'] = $location_id;
if ($user_role != 1) {
if ($user_role == 3) {
$where['ad.created_by'] = get_user_id();
}elseif ($user_role == 2) {
$where['l.location_owner'] = get_user_id();
}
}
$this->data['locations'] = $this->crud_model->get_data("advertisements ad",$where,true,$join,'','*,ad.status as advert_status');
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('advertisers/view_advertisements_info',$this->data);
$this->load->view('common/footer');
}
public function delete_advertisement($id){
$where['advert_id'] = $id;
$advert = $this->crud_model->get_data($this->table,$where,true,'','','advert_qb_id');
if ($advert->advertisment_type == 1) {
$qb_delete_invoice = $this->quick_books->delete_invoice($advert->advert_qb_id);
}else{
$qb_delete_invoice['error'] = false;
}
if ($qb_delete_invoice['error'] == false) {
$result = $this->crud_model->delete_data($this->table,$where);
}else{
$this->session->set_flashdata("error_msg",$qb_delete_invoice['msg']);
}
redirect($_SERVER['HTTP_REFERER']);
}
public function manage_advertisers($user_id = ""){
$form_data = $this->input->post();
if (!empty($form_data)) {
$user_role = get_user_role();
$edit = false;
if ($user_id != "") {
$edit = true;
$qb_update_customer = $this->quick_books->update_customer($form_data);
if ($qb_update_customer['error'] == false) {
$where['user_id'] = $form_data['user_id'];
unset($form_data['user_id']);
$advert = $this->crud_model->update_data('users',$where,$form_data);
}else{
$advert = false;
$msg = $qb_update_customer['msg'];
}
}else{
$qb_add_customer = $this->quick_books->add_customer($form_data);
if ($qb_add_customer['error'] == false) {
$form_data['created_by'] = get_user_id();
$form_data['user_qb_id'] = $qb_add_customer['msg'];
if ($user_role == 1) {
$form_data['status'] = 1;
}
$advert = $this->crud_model->add_data('users',$form_data);
}else{
$advert = false;
$msg = $qb_add_customer['msg'];
}
}
if ($advert) {
if (isset($edit)) {
if (!isset($msg)) {
$msg = "Advertiser Updated successfully";
}
}else{
if (!isset($msg)) {
$msg = "Advertiser created successfully";
}
}
$this->session->set_flashdata("success_msg",$msg);
redirect(base_url()."advertisers/view_advertisers");
}else{
if (isset($edit)) {
if (!isset($msg)) {
$msg = "Advertiser Not Updated";
}
}else{
if (!isset($msg)) {
$msg = "Advertiser Not created";
}
}
$this->session->set_flashdata("error_msg",$msg);
redirect($_SERVER['HTTP_REFERER']);
}
}
if ($user_id != "") {
$where['user_id'] = $user_id;
$this->data['user'] = $this->crud_model->get_data('users',$where,true);
}
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('advertisers/manage_advertisers');
$this->load->view('common/footer');
}
public function view_advertisers()
{
$where = array();
$user_role = get_user_role();
$this->data['user_role'] = $user_role;
if ($user_role != 1) {
$where['created_by'] = get_user_id();
}
$where['user_role'] = 6;
$this->data['advertisers'] = $this->crud_model->get_data("users",$where);
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('advertisers/view_advertisers');
$this->load->view('common/footer');
}
public function delete_advertiser($id){
$where['user_id'] = $id;
$advertiser = $this->crud_model->get_data("users",$where,true,'','','user_qb_id');
$qb_inactive_customer = $this->quick_books->inactive_customer($advertiser->user_qb_id);
if ($qb_inactive_customer['error'] == false) {
$result = $this->crud_model->delete_data('users',$where);
}else{
$this->session->set_flashdata("error_msg",$qb_inactive_customer['msg']);
}
redirect($_SERVER['HTTP_REFERER']);
}
public function advertisementReport($advert_id){
$this->load->model("video_model");
$advert_videos = $this->crud_model->get_data("advert_video_relation",array('advert_id'=>$advert_id),'','','','video_id');
$video_ids = array();
foreach ($advert_videos as $key => $value) {
$video_ids[] = $value->video_id;
}
$analytics_param = array('video_ids'=>$video_ids);
$data['analytics'] = $this->video_model->get_analytics($analytics_param);
$join['locations'] = "locations.location_id=advertisements.location_id";
$data['analytics']['add'] = $this->crud_model->get_data("advertisements",array('advert_id'=>$advert_id),true,$join);
$this->load->library('Dom_pdf');
$this->load->view('analytics/report',$data);
$html = $this->output->get_output();
$this->dompdf->loadHtml($html);
// (Optional) Setup the paper size and orientation
$this->dompdf->setPaper('A4', 'portrait');
$this->dompdf->set_option('enable_html5_parser', TRUE);
$this->dompdf->set_option('isPhpEnabled', true);
$this->dompdf->set_option('defaultFont', 'Montserrat');
// Render the HTML as PDF
$this->dompdf->render();
$this->dompdf->stream($data['analytics']['add']->advert_number.".pdf", array("Attachment" => 1));
//exit(0);
}
}
<file_sep>/application/views/analytics/video/upload_video.php
<div class="col-md-9 col-lg-10 col-xl-10 col-sm-12 col-xs-12 pr30 pl30sm ">
<div class="content-body">
<!-- Hospital Info cards -->
<!-- plr0 -->
<div class="row mr0">
<div class="col-md-12 col-lg-2 col-xl-2 col-sm-12 col-xs-12" id="hider">
<!-- <img src="images/Calender Icon.png">
<button class="btn-outline-secondary round btn-custom-hvr"><i class="fas fa-caret-left" ></i> HIDE</button> -->
</div>
<div class="add-col12 col-md-12 col-sm-12 col-xs-12 ">
<div class="card border_video">
<div class="card-header">
<h2>Upload New Media</h2>
</div>
<div class="card-body">
<!-- <form action="#" id="video_upload" method="post" enctype="multipart/form-data">
-->
<form method="post" enctype="multipart/form-data">
<div class="row text-center">
<div class="col-12">
<input type="file" name="video">
</div>
</div>
<div class="row text-right">
<div class="col-12">
<input type="submit" name="submit" class="btn btn-info" value="Submit" name="">
<input type="hidden" name="locationID" value="<?=$locationID?>">
</div>
</div>
</form>
</div>
</div>
<?php
if ($this->session->flashdata("msg") != "") {
?>
<div class="alert alert-info" role="alert">
<?=$this->session->flashdata("msg")?>
</div>
<?php
}
?>
<?php
if ($this->session->flashdata("error_msg") != "") {
?>
<div class="alert alert-danger" role="alert">
<?php echo $this->session->flashdata("error_msg");
?>
</div>
<?php
}
?>
<div class="card col-12">
<div class="table-responsive">
<table id="example" class="table table-striped table-bordered">
<tr>
<thead>
<th>Sr.#</th>
<th>Video Id</th>
<th>Collection Id</th>
<th>Action</th>
</thead>
</tr>
<tbody>
<?php
$i = 1;
foreach ($videos as $key => $value) {
?>
<tr>
<td><?=$i?></td>
<td><?=$value->videoID?></td>
<td><?=$value->galleryID?></td>
<td><a href="<?=base_url()?>analytics/videos/deleteVideo/<?=$value->galleryID?>/<?=$value->videoID?>" title="Delete Video" onclick="return confirm('Are you sure you wanted to delete this video?')"><i class="far fa-trash-alt"></i></a>
<?php
if ($value->emotionStatus != "Completed") {
?>
<a href="<?=base_url()?>analytics/videos/recordAnalytics/<?=$value->emotionID?>/<?=$value->videoID?>" title="Record Analytics"><i class="fas fa-eye"></i></a>
<?php
}
?>
</td>
</tr>
<?php
$i++;
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
//$('#example').DataTable();
$("#video_upload").submit(function(e){
e.preventDefault();
$(".loading").show();
setTimeout(function(){
$(".loading").find("span").html("Analyzing");
}, 10000);
$(".main_div").css("opacity","0.7");
$.ajax({
type:'post',
url:"<?=base_url()?>Videos/startAnalysis",
data:new FormData(this),
dataType:'json',
contentType: false,
cache: false,
processData:false,
success:function(res)
{
},
complete: function(){
$(".loading").find("span").html("Complete");
setTimeout(function(){
window.location.reload();
}, 1000);
},
});
return false;
})
} );
</script>
<file_sep>/application/views/payouts/payouts_sidebar.php
<li class="">
<a href="<?php echo base_url()?>payouts/bank_details"">
Bank Details
</a>
</li>
<li>
<a href="<?php echo base_url()?>payouts/view_commissions">
Commisions
</a>
</li>
<li>
<a href="<?php echo base_url()?>payouts/view_royalties">
Royalties
</a>
</li>
<file_sep>/application/views/resource_center/resource_center.php
<!-- END PAGE SIDEBAR -->
<div class="page-content-col">
<!-- BEGIN PAGE BASE CONTENT -->
<div class="col-md-12">
<div class="portlet box green">
<div class="portlet-title">
<div class="caption">
Resouce Center </div>
<div class="tools">
<a href="javascript:;" class="collapse" data-original-title="" title=""> </a>
</div>
</div>
<div class="portlet-body">
<div class="panel-group accordion" id="accordion1">
<?php
foreach ($resources as $key => $value) {
?>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a class="accordion-toggle collapsed" data-toggle="collapse" data-parent="#accordion1" href="#collapse_<?=$value->resource_id?>" aria-expanded="false"> <?=$value->title?> </a>
</h4>
</div>
<div id="collapse_<?=$value->resource_id?>" class="panel-collapse collapse" aria-expanded="false" style="height: 0px;">
<div class="panel-body">
<div class="row">
<div class="col-md-12">
<b>Resource Type:</b> <?=get_resouce_type($value->resource_type)?>
</div>
</div>
<br>
<div class="row">
<div class="col-md-12">
<?=$value->description?>
</div>
</div>
<div class="text-right">
<a class="btn btn-primary" href="<?=base_url().RESOURCE_CENTER_UPLOAD_PATH.$value->resource_file?>" download="">Download File</a>
</div>
</div>
</div>
</div>
<?php
}
?>
</div>
</div>
</div>
</div>
<!-- END PAGE BASE CONTENT -->
</div>
<file_sep>/application/views/analytics/dashboard/index.php
<style type="text/css">
.daterange{
text-align: center;
}
</style>
<div class=" col-md-9 col-lg-10 col-xl-10 col-sm-12 col-xs-12 pr30 pl30sm ">
<?php
include 'first_div.php';
include 'second_div.php';
include 'third_div.php';
include 'fourth_div.php';
?>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('input[name="dates"]').daterangepicker({
"autoApply": true,
// "startDate": "03/26/2019",
// "endDate": "04/01/2019",
"opens": "center"
}, function(start, end, label) {
window.location.href = "<?=base_url()?>/analytics/dashboard/<?=$locationID?>?daterange="+start.format('YYYY-MM-DD')+'/'+ end.format('YYYY-MM-DD');
});
$('input[name="dates"]').val('Date Filter');
<?php
if (isset($start_date) && isset($end_date)) {
?>
$('input[name="dates"]').data('daterangepicker').setStartDate('<?=$start_date?>');
$('input[name="dates"]').data('daterangepicker').setEndDate('<?=$end_date?>');
<?php
}
?>
$(".change_emotions").click(function(){
var filter = $(this).data("filter");
$(".emotion_filter").html(filter);
$.ajax({
url: "<?=base_url("videos/change_emotions")?>",
data:{
filter: filter,
daterange: "<?php echo $this->input->get('daterange') ?>"
},
type: "POST",
datatype: "json",
success:function(res){
res = JSON.parse(res);
if (filter == "Percentage") {
$(".happy_text").html(res.happy_cent+"%");
$(".normal_text").html(res.normal_cent+"%");
$(".sad_text").html(res.sad_cent+"%");
$(".male_text").html(res.male_cent+"%")
$(".female_text").html(res.female_cent+"%")
trs = '';
$.each(res.age_group,function(k,v){
if (v != 0) {
trs += `
<tr>
<td>`+k+`</td>
<td>`+(v/res.total_visitors*100)+`%</td>
</tr>
`;
}
})
$(".age_groups").html(trs);
}else{
$(".happy_text").html(res.happy_cent);
$(".normal_text").html(res.normal_cent);
$(".sad_text").html(res.sad_cent);
$(".male_text").html(res.male_cent)
$(".female_text").html(res.female_cent)
trs = '';
$.each(res.age_group,function(k,v){
if (v != 0) {
trs += `
<tr>
<td>`+k+`</td>
<td>`+v+`</td>
</tr>
`;
}
})
$(".age_groups").html(trs);
}
}
})
return false;
});
})
</script>
<file_sep>/application/views/payouts/view_commissions.php
<!-- END PAGE SIDEBAR -->
<div class="page-content-col">
<!-- BEGIN PAGE BASE CONTENT -->
<div class="row">
<?php
if ($this->session->flashdata("error_msg") != "") {
?>
<div class="alert alert-danger">
<?php echo $this->session->flashdata("error_msg"); ?>
</div>
<?php
}else if ($this->session->flashdata("success_msg") != ""){
?>
<div class="alert alert-success">
<?php echo $this->session->flashdata("success_msg"); ?>
</div>
<?php } ?>
</div>
<?php if ($user_role == 1) { ?>
<div class="col-sm-12 filterbox">
<div class="filterdiv">
<form action="" method="post">
<div class="col-sm-12 col-xs-12 ">
<div class="col-sm-10">
<div class="form-group ">
<label class="col-sm-1 col-xs-1 control-label">Filter:</label>
<div class="col-sm-11 col-xs-11">
<div class="col-md-6 ">
<select class="form-control" name="user">
<option value="">Select User</option>
<?php
foreach ($users as $key => $value) {
echo '<option '.($user_id == $value->user_id ? "selected":"").' value="'.$value->user_id.'">'.$value->first_name.' '.$value->last_name.'</option>';
}
?>
</select>
</div>
</div>
</div>
</div>
<div class="col-sm-2 col-xs-2">
<div class="form-group">
<input class="btn btn-danger" value="Filter User" type="submit">
<!-- <a href="javascript:void(0)" class="cleanSearchFilter">Clean the filter</a>-->
</div>
</div>
</div>
</form>
</div>
</div>
<?php }
if (!empty($advert)) {
?>
<div class="row">
<div class="col-md-12">
<div class="db-stats-standard cf js-db-stats ">
<span><small>Net Commission</small>$<?=$net_commission?></span>
<span><small>Total Paid</small>$<?=$total_paid?></span>
<span><small>Remaining</small>$<?=$remaining?></span>
</div>
</div>
</div>
<?php } ?>
<table class="table table-bordered table-stripped datatable">
<thead>
<tr>
<th>Sr.</th>
<th>Location Name</th>
<th>Location Number</th>
<th>Advertise Number</th>
<th>Commission</th>
<?php
if ($user_role == 1) {
echo "<th>Action</th>";
}
?>
</tr>
</thead>
<tbody>
<?php
if (!empty($advert)) {
$i = 1;
foreach ($advert as $key => $value) {
echo "<tr>
<td>".$i."</td>
<td>".$value->location_name."</td>
<td>".$value->location_number."</td>
<td>".$value->advert_number."</td>
<td>".$value->user_commission."</td>";
if ($user_role == 1) {
if ($value->commission_status == 0) {
echo "<td> <a href='".base_url()."payouts/commission_status/".$value->advert_id."/1' class='btn btn-success' >Mark as Paid</a> </td>";
}else{
echo "<td> <a href='".base_url()."payouts/commission_status/".$value->advert_id."/0' class='btn btn-danger' >Mark as Unpaid</a> </td>";
}
}
echo "</tr>";
$i++;
}
}
?>
</tbody>
</table>
<!-- END PAGE BASE CONTENT -->
</div><file_sep>/application/controllers/Resource_center.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Resource_center extends GH_Controller {
public $data = array();
public $table = 'resource_center';
public function __construct() {
parent::__construct();
$this->data['menu_class'] = "resource_menu";
$this->data['title'] = "Resource Center";
$this->data['sidebar_file'] = "resource_center/resource_center_sidebar";
}
function _remap($method,$param){
if (method_exists($this,$method)) {
if (!empty($param)) {
$this->$method($param[0]);
}else{
$this->$method();
}
} else {
$this->index($method);
}
}
public function index($type = "")
{
$where = array();
if ($type != "") {
$where['resource_type'] = $type;
}
$this->data['resources'] = $this->crud_model->get_data($this->table,$where);
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('resource_center/resource_center',$this->data);
$this->load->view('common/footer');
}
}
<file_sep>/application/views/analytics/dashboard/first_div.php
<div class="row">
<div class="col-xl-2 col-lg-6 col-md-6 col-sm-12">
<div class="card pull-up">
<div class="card-content">
<div class="">
<div class="">
<div class="row mlr0">
<div class="col-12 bgd-blue border_radius">
<p class="text-white font12 margin0 center_img ptb20"><?=$location->location_name?> </p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-2 col-lg-6 col-md-6 col-sm-12">
<div class="card pull-up">
<div class="card-content">
<div class="">
<div class="">
<div class="row mlr0">
<div class="col-12 bgd-blue border_radius">
<p class="text-white margin0 font12 center_img ptb20">Compare Location</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-2 col-lg-6 col-md-6 col-sm-12 border_radius ">
<div class=" pull-up">
<div class="card-content">
<div class="">
<div class="">
<div class="row mlr0">
<div class="col-12">
<div class="row text-right ">
<button type="button" id="rangecalendar" class="font12md btn btn-block border498bbe font20 p-1 pmd text498bbe bg-white" data-toggle="dropdown" aria-haspopup="true"><input type="text" name="dates" class="border0 font11 daterange font10dynamic"></button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-6 col-sm-12 mt2sm">
<div class="card pull-up">
<div class="card-content">
<div class="row mlr0">
<div class="col-4 center_img">
<div class="">
<img src="<?php echo base_url() ?>frontend/images/users.png" width="50px" class="img_res" height="50px">
</div>
</div>
<div class="col-8 bgd-blue border_radius_r">
<div class="row text-right ">
<span class="lg_nmbr"><?=$analytics['total_visitors']?> </span>
<p class="text-white font12md margin0 center_img ">TOTAL VISITORS</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-lg-6 col-md-6 col-sm-12">
<div class="card pull-up">
<div class="card-content">
<div class="">
<div class="">
<div class="row mlr0">
<div class="col-4 center_img">
<div class="">
<img src="<?php echo base_url() ?>frontend/images/time.png" class="img_res" width="50px" height="50px">
</div>
</div>
<div class="col-8 bgd-blue border_radius_r">
<div class="row text-right ">
<span class="lg_nmbr pr0a"><?=$analytics['avg_age']?> </span>
<p class="text-white margin0 font12md center_img">AVG. AGE</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div><file_sep>/application/models/Location_model.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Location_model extends Crud_model{
public function __construct() {
parent::__construct();
}
public function get_location_marker($where = ""){
$query = "SELECT *,location_lat as lat,location_lng as lng FROM locations ";
if ($where != "") {
$query .= "WHERE ".$where;
}
$res = $this->db->query($query)->result();
return $res;
}
}
<file_sep>/application/views/payouts/view_royalties.php
<!-- END PAGE SIDEBAR -->
<div class="page-content-col">
<!-- BEGIN PAGE BASE CONTENT -->
<div class="row">
<?php
if ($this->session->flashdata("error_msg") != "") {
?>
<div class="alert alert-danger">
<?php echo $this->session->flashdata("error_msg"); ?>
</div>
<?php
}else if ($this->session->flashdata("success_msg") != ""){
?>
<div class="alert alert-success">
<?php echo $this->session->flashdata("success_msg"); ?>
</div>
<?php } ?>
</div>
<?php if ($user_role == 1) { ?>
<div class="col-sm-12 filterbox">
<div class="filterdiv">
<form action="" method="post">
<div class="col-sm-12 col-xs-12 ">
<div class="col-sm-10">
<div class="form-group ">
<label class="col-sm-1 col-xs-1 control-label">Filter:</label>
<div class="col-sm-11 col-xs-11">
<div class="col-md-6 ">
<select class="form-control" name="user">
<option value="">Select User</option>
<?php
foreach ($users as $key => $value) {
echo '<option '.($user_id == $value->user_id ? "selected":"").' value="'.$value->user_id.'">'.$value->first_name.' '.$value->last_name.'</option>';
}
?>
</select>
</div>
</div>
</div>
</div>
<div class="col-sm-2 col-xs-2">
<div class="form-group">
<input class="btn btn-danger" value="Filter User" type="submit">
<!-- <a href="javascript:void(0)" class="cleanSearchFilter">Clean the filter</a>-->
</div>
</div>
</div>
</form>
</div>
</div>
<?php }
if (!empty($locations)) {
?>
<div class="row">
<div class="col-md-12">
<div class="db-stats-standard cf js-db-stats ">
<span><small>Net Royalty</small>$<?=$net_royalty?></span>
<span><small>Total Paid</small>$<?=$total_paid?></span>
<span><small>Remaining</small>$<?=$remaining?></span>
</div>
</div>
</div>
<?php } ?>
<table class="table table-bordered table-stripped datatable">
<thead>
<tr>
<th>Sr.</th>
<th>Location Name</th>
<th>Location Number</th>
<th>Royalty</th>
<?php
if ($user_role == 1) {
echo "<th>Action</th>";
}
?>
</tr>
</thead>
<tbody>
<?php
if (isset($locations)) {
$i = 1;
foreach ($locations as $key => $value) {
echo "<tr>
<td>".$i."</td>
<td>".$value->location_name."</td>
<td>".$value->location_number."</td>
<td>".$value->user_royalty."</td>";
if ($user_role == 1) {
if ($member_role == 2) {
if ($value->owner_royalty_status == 0) {
echo "<td> <a href='".base_url()."payouts/royalty_status/".$value->location_id."/owner_royalty_status/1' class='btn btn-success' >Mark as Paid</a> </td>";
}else{
echo "<td> <a href='".base_url()."payouts/royalty_status/".$value->location_id."/owner_royalty_status/0' class='btn btn-danger' >Mark as Unpaid</a> </td>";
}
}elseif ($member_role == 1 || $member_role == 3) {
if ($value->advert_royalty_status == 0) {
echo "<td> <a href='".base_url()."payouts/royalty_status/".$value->location_id."/advert_royalty_status/1' class='btn btn-success' >Mark as Paid</a> </td>";
}else{
echo "<td> <a href='".base_url()."payouts/royalty_status/".$value->location_id."/advert_royalty_status/0' class='btn btn-danger' >Mark as Unpaid</a> </td>";
}
}
}
echo "</tr>";
$i++;
}
}
?>
</tbody>
</table>
<!-- END PAGE BASE CONTENT -->
</div><file_sep>/application/controllers/Contact.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Contact extends CI_Controller {
public $data = array();
public $table = "locations";
public function __construct() {
parent::__construct();
$this->load->model("location_model");
$this->load->helper("custom");
}
public function index($value='')
{
$locations = $this->crud_model->get_data($this->table);
$filters = array();
foreach ($locations as $key => $value) {
$demographic = explode(',', $value->main_demographic);
foreach ($demographic as $k => $v) {
$filters[] = trim($v);
}
$filters[] = trim($value->industry);
}
$filters = array_unique($filters);
$this->data['filters'] = array_filter($filters, function($value) { return $value !== ''; });
$this->load->view('contact_us/contact_us',$this->data);
}
public function send_mail()
{
$form_data = $this->input->post();
$this->load->library("PhpMailerLib");
$mail = $this->phpmailerlib->contact_us_mail($form_data);
if (!$mail) {
$msg = $mail->ErrorInfo;
$this->session->set_flashdata('error',$msg);
redirect(base_url("contact"));
}
else
{
$msg = " We Will Update You Shortly";
$this->session->set_flashdata('success',$msg);
redirect(base_url("contact"));
}
}
public function get_location_marker(){
$where = "";
$where_query = true;
$or_where = false;
$where .= 'location_type = 1';
$filters = $this->input->post('filter');
if ($filters != "") {
if ($where_query) {
$where .= " AND (";
}
foreach ($filters as $key => $value) {
if ($or_where) {
$where .= " OR ";
}
$where .= " industry like '%".$value."%'";
$where .= " OR main_demographic like '%".$value."%'";
$or_where = true;
}
if ($where_query) {
$where .= ")";
}
}
$locations = $this->location_model->get_location_marker($where);
$res = array();
foreach ($locations as $key => $value) {
$arr['lat'] = (float) $value->lat;
$arr['lng'] = (float) $value->lng;
$locations[$key]->lat_lng = $arr;
$locations[$key]->infowindow_content = $this->load->view("location/infowindow_content",$value,true);
}
echo json_encode($locations);
exit();
}
public function form_load()
{
$id = $_POST['id'];
$where['location_id'] = $id;
$data['location'] = $this->location_model->get_data("locations",$where,true);
$this->load->view('contact_us/model.php',$data);
}
}
<file_sep>/application/views/common/header.php
<!DOCTYPE html>
<!--[if IE 8]>
<html lang="en" class="ie8 no-js">
<![endif]-->
<!--[if IE 9]>
<html lang="en" class="ie9 no-js">
<![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
<meta charset="utf-8" />
<title>GOHOLO | <?php echo $title; ?></title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1" name="viewport" />
<meta content="" name="description" />
<meta content="" name="author" />
<!-- BEGIN LAYOUT FIRST STYLES -->
<link href="//fonts.googleapis.com/css?family=Oswald:400,300,700" rel="stylesheet" type="text/css" />
<!-- END LAYOUT FIRST STYLES -->
<!-- BEGIN GLOBAL MANDATORY STYLES -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css" />
<link href="<?php echo base_url(); ?>assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<link href="<?php echo base_url(); ?>assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css" />
<link href="<?php echo base_url(); ?>assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="<?php echo base_url(); ?>assets/global/plugins/bootstrap-switch/css/bootstrap-switch.min.css" rel="stylesheet" type="text/css" />
<!-- END GLOBAL MANDATORY STYLES -->
<!-- BEGIN THEME GLOBAL STYLES -->
<link href="<?php echo base_url(); ?>assets/global/css/components.min.css" rel="stylesheet" id="style_components" type="text/css" />
<link href="<?php echo base_url(); ?>assets/global/css/plugins.min.css" rel="stylesheet" type="text/css" />
<!-- END THEME GLOBAL STYLES -->
<!-- BEGIN THEME LAYOUT STYLES -->
<link href="<?php echo base_url(); ?>assets/layouts/layout5/css/layout.css" rel="stylesheet" type="text/css" />
<link href="<?php echo base_url(); ?>assets/layouts/layout5/css/custom.css" rel="stylesheet" type="text/css" />
<!-- END THEME LAYOUT STYLES -->
<link href="<?php echo base_url(); ?>assets/global/plugins/datatables/datatables.min.css" rel="stylesheet" type="text/css" />
<link href="<?php echo base_url(); ?>assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.css" rel="stylesheet" type="text/css" />
<link href="<?php echo base_url(); ?>assets/global/plugins/bootstrap-switch/css/bootstrap-switch.min.css" rel="stylesheet" type="text/css" />
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<link href="<?php echo base_url(); ?>assets/css/MonthPicker.min.css" rel="stylesheet" type="text/css" />
<link href="<?php echo base_url(); ?>assets/global/plugins/select2/css/select2.min.css" rel="stylesheet" type="text/css" />
<link href="<?php echo base_url(); ?>assets/global/plugins/select2/css/select2-bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="<?php echo base_url(); ?>assets/pages/css/contact.min.css" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" href="favicon.ico" />
<script src="<?php echo base_url(); ?>assets/global/plugins/jquery.min.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/global/plugins/js.cookie.min.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script>
<!-- END CORE PLUGINS -->
<!-- BEGIN THEME GLOBAL SCRIPTS -->
<script src="<?php echo base_url(); ?>assets/global/scripts/app.min.js" type="text/javascript"></script>
<!-- END THEME GLOBAL SCRIPTS -->
<!-- BEGIN THEME LAYOUT SCRIPTS -->
<script src="<?php echo base_url(); ?>assets/layouts/layout5/scripts/layout.min.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/layouts/global/scripts/quick-sidebar.min.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/global/scripts/datatable.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/global/plugins/datatables/datatables.min.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/pages/scripts/components-bootstrap-switch.min.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/global/plugins/bootbox/bootbox.min.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/pages/scripts/ui-bootbox.min.js" type="text/javascript"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=
<KEY>&libraries=places&callback=initialize" async defer></script>
<script src="<?php echo base_url(); ?>assets/layouts/layout5/scripts/custom.js" type="text/javascript"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<script src="https://cdn.rawgit.com/digitalBush/jquery.maskedinput/1.4.1/dist/jquery.maskedinput.min.js"></script>
<script src="<?php echo base_url(); ?>assets/js/MonthPicker.min.js"></script>
<script src="<?php echo base_url(); ?>assets/global/plugins/select2/js/select2.full.min.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/pages/scripts/components-select2.min.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/html5lightbox/html5lightbox.js"></script>
<script type="text/javascript">
let base_url = "<?php echo base_url() ?>";
const LOCATION_IMAGE_UPLOAD_PATH = "<?php echo LOCATION_IMAGE_UPLOAD_PATH ?>";
$(document).ready(function(){
let page_menu = $(".<?php echo $menu_class ?>");
page_menu.addClass("active open selected");
})
</script>
</head>
<!-- END HEAD -->
<body class="page-header-fixed page-sidebar-closed-hide-logo">
<!-- BEGIN CONTAINER -->
<!-- BEGIN HEADER -->
<header class="page-header">
<nav class="navbar mega-menu" role="navigation">
<div class="container-fluid">
<div class="clearfix navbar-fixed-top">
<!-- Brand and toggle get grouped for better mobile display -->
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar-responsive-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="toggle-icon">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</span>
</button>
<!-- End Toggle Button -->
<!-- BEGIN LOGO -->
<a id="index" class="page-logo" href="index.html">
<img src="<?php echo base_url(); ?>assets/layouts/layout5/img/logo.png" alt="Logo"> </a>
<!-- END LOGO -->
<!-- BEGIN SEARCH -->
<!-- END SEARCH -->
<!-- BEGIN TOPBAR ACTIONS -->
<ul class="nav navbar-nav" id="navbar-responsive-collapse">
<?php
if (has_permission("locations")) {
?>
<li class="dropdown dropdown-fw dropdown-fw-disabled location_menu ">
<a href="<?php echo base_url()."locations"; ?>" class="">
Locations
</a>
</li>
<?php
}
if (has_permission("advertisers")) {
if (get_user_role() == 6) {
$action = "advertisers/view_advertisements";
}else{
$action = "advertisers/view_advertisers";
}
?>
<li class="dropdown dropdown-fw dropdown-fw-disabled advertisers_menu ">
<a href="<?php echo base_url().$action; ?>" class="">
Advertisers </a>
</li>
<?php
}
if (has_permission("recriutment")) {
?>
<li class="dropdown dropdown-fw dropdown-fw-disabled recruitments_menu ">
<a href="<?php echo base_url()."recruitments"; ?>" class="">
Recriutment </a>
</li>
<?php
}
if (has_permission("location_manager")) {
?>
<li class="dropdown dropdown-fw dropdown-fw-disabled manager_menu ">
<a href="<?php echo base_url()."location_manager"; ?>" class="">
Location Manager </a>
</li>
<?php
}
if (has_permission("designer")) {
?>
<li class="dropdown dropdown-fw dropdown-fw-disabled designer_menu ">
<a href="<?php echo base_url()."designer"; ?>" class="">
Designer </a>
</li>
<?php
}
if (has_permission("payouts")) {
?>
<li class="dropdown dropdown-fw dropdown-fw-disabled payouts_menu ">
<a href="<?php echo base_url()."payouts/view_commissions"; ?>" class="">
Payouts </a>
</li>
<?php
}
if (has_permission("resource_center")) {
?>
<li class="dropdown dropdown-fw dropdown-fw-disabled resource_menu">
<a href="<?php echo base_url()."resource_center"; ?>" class="">
Resource Center </a>
</li>
<?php
}
if (has_permission("admin")) {
?>
<li class="dropdown dropdown-fw dropdown-fw-disabled admin_menu">
<a href="<?php echo base_url()."users"; ?>" class="">
Admin </a>
</li>
<?php
}
?>
</ul>
<!-- END TOPBAR ACTIONS -->
<?php
if (get_user_role() != 6) {
$notify = $this->crud_model->get_data("notifications",array("receiver_id"=>get_user_id(),'read'=>0));
$count = count($notify);
?>
<div class="btn-group-notification btn-group" id="header_notification_bar">
<button type="button" class="btn btn-sm md-skip dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true" aria-expanded="false">
<i class="icon-bell"></i>
<span class="badge"><?=$count?></span>
</button>
<ul class="dropdown-menu-v2">
<li class="external">
<h3>
<span class="bold"><?=$count?> pending</span> notifications</h3>
</li>
<li>
<div class="slimScrollDiv" style="position: relative; width: auto; height: 250px;"><ul class="dropdown-menu-list scroller" style="height: 250px; padding: 0px;width: auto;" data-handle-color="#637283" data-initialized="1">
<?php
$order_by = "notify_id DESC";
$notify = $this->crud_model->get_data("notifications",array("receiver_id"=>get_user_id()),'','','','','','',$order_by);
foreach ($notify as $key => $value) {
?>
<li class="<?php echo ($value->read == 0 ? 'bg-gray' : '' ) ?>">
<a href="javascript:;">
<span class="details">
<span class="label label-sm label-icon label-success md-skip">
</span> <a href="<?=base_url().$value->link?>?notify_id=<?=$value->notify_id?>&read=<?=$value->read?>"><?=$value->message?></a> </span>
</a>
</li>
<?php
}
?>
</ul><div class="slimScrollBar" style="background: rgb(99, 114, 131); width: 7px; position: absolute; top: 0px; opacity: 0.4; display: block; border-radius: 7px; z-index: 99; right: 1px;"></div><div class="slimScrollRail" style="width: 7px; height: 100%; position: absolute; top: 0px; display: none; border-radius: 7px; background: rgb(234, 234, 234); opacity: 0.2; z-index: 90; right: 1px;"></div></div>
</li>
</ul>
</div>
<?php
}else{
?>
<span style="float: right;padding: 10px;font-size: 18px; color: white"> <b>Total Impressions:</b> <?php echo getImpressionForAdvertisor(); ?> </span>
<?php
}
?>
</div>
<!-- BEGIN HEADER MENU -->
</div>
</nav>
</header>
<!-- END HEADER -->
<div class="">
<file_sep>/application/helpers/custom_helper.php
<?php
function get_role_byid($id)
{
switch ($id) {
case '1':
return "Super Admin";
break;
case '2':
return "Location Owner";
break;
case '3':
return "Marketing Team";
break;
case '4':
return "Designer";
break;
case '5':
return "Location Manager";
break;
case '6':
return "Advertisor";
break;
default:
return "";
break;
}
}
function get_user_fullname(){
$ci = &get_instance();
$user=$ci->session->userdata("user_session");
return $user->first_name." ". $user->last_name;
}
function get_user_id(){
$ci = &get_instance();
$user=$ci->session->userdata("user_session");
return $user->user_id;
}
function get_user_role($user_id = ""){
$ci = &get_instance();
if ($user_id == "") {
$user = $ci->session->userdata("user_session");
}else{
$user = $ci->crud_model->get_data("users",array("user_id"=>$user_id),true);
}
return $user->user_role;
}
function get_user_commission($user_id = ""){
$ci = &get_instance();
if ($user_id == "") {
$user_id = get_user_id();
}
$user = $ci->crud_model->get_data("users",array("user_id"=>$user_id),true);
return $user->user_commission;
}
function is_admin($user_id = ""){
$ci = &get_instance();
if ($user_id == "") {
$user = $ci->session->userdata("user_session");
}else{
$user = $ci->crud_model->get_data("users",array("user_id"=>$user_id),true);
}
if ($user->user_role == 1) {
return true;
}
return false;
}
function has_permission($permission, $roleid = ""){
$ci = &get_instance();
$roleid = ($roleid == '' ? get_user_role() : $roleid);
if ($roleid == 1) {
return true;
}
$join['permissions p'] = "p.permissionid=r.permissionid";
$where['r.roleid'] = $roleid;
$where['p.shortname'] = $permission;
$permet = $ci->crud_model->get_data("rolepermissions r",$where,true,$join,'','permission');
if ($permet->permission == 1) {
return true;
}
return false;
}
function get_resouce_type($type){
if ($type == 1) {
$resource_type = "Location Contract";
}else if ($type == 2) {
$resource_type = "Advertisers Contract";
}else if ($type == 3){
$resource_type = "Marketing/Promo";
}else if ($type == 4){
$resource_type = "Location Criteria";
}else if ($type == 5){
$resource_type = "Advertising Tips";
}
return $resource_type;
}
function get_status($status){
if ($status == 1) {
return "Active";
}else{
return "Dective";
}
}
function detect_status_change($status){
if ($status == 1) {
return "approved";
}else{
return "disapproved";
}
}
if (!function_exists('modal_anchor')) {
function modal_anchor($url, $title = '', $attributes = '') {
$attributes["data-act"] = "ajax-modal";
if (get_array_value($attributes, "data-modal-title")) {
$attributes["data-title"] = get_array_value($attributes, "data-modal-title");
} else {
$attributes["data-title"] = get_array_value($attributes, "title");
}
$attributes["data-action-url"] = $url;
return js_anchor($title, $attributes);
}
}
function generateGalleryID()
{
$v1=rand(1111,9999);
$v2=rand(1111,9999);
$v3=$v1.$v2;
$v3=md5($v3);
return $v3;
}
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
function deleteDir($dirPath) {
if (! is_dir($dirPath)) {
throw new InvalidArgumentException("$dirPath must be a directory");
}
if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
$dirPath .= '/';
}
$files = glob($dirPath . '*', GLOB_MARK);
foreach ($files as $file) {
if (is_dir($file)) {
deleteDir($file);
} else {
unlink($file);
}
}
rmdir($dirPath);
}
function getImpressionForAdvertisor(){
$ci = &get_instance();
$userid = get_user_id();
$impressions = 0;
$advertisements = $ci->crud_model->get_data('advertisements',array("advertiser_id"=>$userid));
foreach ($advertisements as $key => $value) {
$impressions += $value->impressions;
}
return $impressions;
}
function getBase64Image($url){
$path = base_url().'/assets/'.$url;
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
return $base64;
}
function get_advert_payments($advert_id){
$ci = &get_instance();
$payments = $ci->crud_model->get_data('payments',array("advert_id"=>$advert_id),true,array(),array(),'sum(amount) as total_payment');
return $payments->total_payment;
}<file_sep>/application/views/admin/admin_sidebar.php
<li class="">
<a href="<?php echo base_url() ?>users">
View Users
</a>
</li>
<li>
<a href="<?php echo base_url() ?>users/manage_user_view">
Add User
</a>
</li>
<li>
<a href="<?php echo base_url() ?>users/0">
Unapproved Users
</a>
</li>
<li>
<a href="<?php echo base_url() ?>admin/unapproved_locations">
Unapproved Locations
</a>
</li>
<li>
<a href="<?php echo base_url() ?>admin/view_resource_center">
Manage Resource Center
</a>
</li>
<li>
<a href="<?php echo base_url() ?>admin/view_packages">
Manage Packages
</a>
</li>
<li>
<a href="<?php echo base_url() ?>quickbooks/index">
QuickBooks
</a>
</li>
<li>
<a href="<?php echo base_url() ?>cron_job">
Cron Job
</a>
</li>
<file_sep>/application/views/advertisers/view_advertisers.php
<div class="page-content-col">
<div class="row">
<?php
if ($this->session->flashdata("success_msg") != "") {
?>
<div class="alert alert-success">
<?php echo $this->session->flashdata("success_msg"); ?>
</div>
<?php
}
?>
</div>
<table class="table table-bordered table-stripped datatable">
<thead>
<tr>
<th>Sr.</th>
<th>Advertiser's Name</th>
<th>Advertiser's Email</th>
<th>Advertiser's Phone</th>
<th>Status</th>
<?php
if ($user_role == 1) {
?>
<th width="120px">Action</th>
<?php
}
?>
</tr>
</thead>
<tbody>
<?php
$i = 1;
foreach ($advertisers as $key => $value) {
echo "<tr>
<td>".$i."</td>
<td>".$value->first_name.' '.$value->last_name."</td>
<td>".$value->email."</td>
<td>".$value->phone_number."</td>";
if ($user_role == 1) {
echo "<td> <input type='checkbox' ". ($value->status != 0 ? 'checked' : '') ." data-record_id='{$value->user_id}' data-table='users' data-where='user_id' class='make-switch change_record_status' data-on-text='Active' data-off-text='Deactive'> </td>";
}else{
echo "<td>".get_status($value->status)."</td>";
}
if ($user_role == 1) {
echo "<td> <a class='btn btn-primary round-btn' href='".base_url()."advertisers/manage_advertisers/".$value->user_id."'>Edit</a> <a href='".base_url()."advertisers/delete_advertiser/".$value->user_id."' class='btn btn-danger round-btn delete-btn'>Delete</a></td>
</tr>";
}
$i++;
}
?>
</tbody>
</table>
</div>
<file_sep>/application/controllers/Locations.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Locations extends GH_Controller {
private $data;
public $table = "locations";
public function __construct() {
parent::__construct();
$user_role = get_user_role();
if ($user_role == 4) {
$redirect_url = base_url()."designer";
redirect($redirect_url);
}elseif ($user_role == 5) {
$redirect_url = base_url()."location_manager";
redirect($redirect_url);
}
$this->load->model("location_model");
$this->load->dbforge();
$this->data['menu_class'] = "location_menu";
$this->data['title'] = "Locations";
$this->data['sidebar_file'] = "location/location_sidebar";
}
public function index()
{
$locations = $this->crud_model->get_data($this->table);
$filters = array();
foreach ($locations as $key => $value) {
$demographic = explode(',', $value->main_demographic);
foreach ($demographic as $k => $v) {
$filters[] = trim($v);
}
$filters[] = trim($value->industry);
}
$filters = array_unique($filters);
$this->data['filters'] = array_filter($filters, function($value) { return $value !== ''; });
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('location/location');
$this->load->view('common/footer');
}
public function manage_location_view($id = ""){
$form_data = $this->input->post();
if (!empty($form_data)) {
$user_role = get_user_role();
extract($form_data);
$this->form_validation->set_rules('location_address', '*Location Address', 'required', array(
'required' => '%s Missing'
));
// $this->form_validation->set_rules('owner_type', '*Owner Type', 'required', array(
// 'required' => '%s Missing'
// ));
// if ($owner_type == 1) {
// $this->form_validation->set_rules('location_owner', '*Location Owner', 'required', array(
// 'required' => '%s Missing'
// ));
// }elseif ($owner_type == 2) {
// $this->form_validation->set_rules('user[first_name]', '*First Name', 'required', array(
// 'required' => '%s Missing'
// ));
// $this->form_validation->set_rules('user[last_name]', '*Last Name', 'required', array(
// 'required' => '%s Missing'
// ));
// $this->form_validation->set_rules('user[email]', '*Email', 'required|valid_email|is_unique[users.email]', array(
// 'required' => '%s Missing',
// 'is_unique' => '%s already Registered'
// ));
// $this->form_validation->set_rules('user[password]', '*Password', 'required|min_length[6]|max_length[12]|alpha_numeric', array(
// 'required' => '%s Missing',
// 'min_length' => '%s must be at least 6 characters',
// 'max_length' => '%s must be at most 12 characters',
// 'alpha_numeric' => '%s must be Alpha Numeric'
// ));
// $this->form_validation->set_rules('user[re_password]', '*Re-type Password', 'required|matches[user[password]]', array(
// 'required' => '%s Missing',
// 'matches' => 'Password does not match'
// ));
// }
$result = $this->form_validation->run();
if ($result) {
$qb_vendor = true;
if ($owner_type == 2) {
$qb_add_vendor = $this->quick_books->add_vendor($form_data['user']);
if ($qb_add_vendor['error'] == false) {
$form_data['user']['user_qb_id'] = $qb_add_vendor['msg'];
unset($form_data['user']['re_password']);
$form_data['user']['user_role'] = 2;
if ($user_role != 1) {
$form_data['user']['status'] = 0;
}
$form_data['user']['created_by'] = get_user_id();
$form_data['location_owner'] = $this->crud_model->add_data("users",$form_data['user']);
// if ($form_data['location_owner']) {
// $this->load->library("PhpMailerLib");
// $mail = $this->phpmailerlib->welcome_email($form_data['user']);
// if (!$mail['res']) {
// $msg = $mail['data']->ErrorInfo;
// }
// }
}else{
$qb_vendor = false;
}
}
if ($qb_vendor) {
$location_image = $this->crud_model->upload_file($_FILES['location_image'],'location_image',LOCATION_IMAGE_UPLOAD_PATH);
if ($location_image) {
$form_data['location_image'] = $location_image;
}elseif ($form_data['old_location_image'] != "") {
$form_data['location_image'] = $form_data['old_location_image'];
}
$location_video = $this->crud_model->upload_file($_FILES['location_video'],'location_video',LOCATION_VIDEO_UPLOAD_PATH);
if ($location_video) {
$form_data['location_video'] = $location_video;
}elseif ($form_data['old_location_video'] != "") {
$form_data['location_video'] = $form_data['old_location_video'];
}
unset($form_data['old_location_image']);
unset($form_data['old_location_video']);
unset($form_data['user']);
unset($form_data['owner_type']);
$form_data['location_description'] = $this->db->escape_str($form_data['location_description']);
$form_data['other_notes'] = $this->db->escape_str($form_data['other_notes']);
$edit = false;
if ($location_id != "") {
$edit = true;
//$qb_update_item = $this->quick_books->update_item($form_data);
//if ($qb_update_item['error'] == false) {
$where['location_id'] = $form_data['location_id'];
unset($form_data['location_id']);
$location = $this->crud_model->update_data($this->table,$where,$form_data);
// }else{
// $location = false;
// $msg = $qb_update_item['msg'];
// }
}else{
// $qb_add_item = $this->quick_books->add_item($form_data);
// if ($qb_add_item['error'] == false) {
// $form_data['location_qb_id'] = $qb_add_item['msg'];
$form_data['created_by'] = get_user_id();
$form_data['location_number'] = LOCATION_NUMBER_PREFIX.mt_rand(100000, 999999);
if ($user_role == 1) {
$form_data['status'] = 1;
}
$loc_number = $form_data['location_number'];
if(!empty($loc_number)){
$fields = array(
'ip' => array(
'type' => 'VARCHAR',
'constraint' => '150'
),
'mac' => array(
'type' => 'VARCHAR',
'constraint' => '150'
),
'devicename' => array(
'type' => 'VARCHAR',
'constraint' => '150'
),
'times' => array(
'type' => 'INT',
'constraint' => 11,
),
'check_status' => array(
'type' =>'BOOLEAN',
'default' => '0',
),
'created' => array(
'type' =>'TIMESTAMP',
),
);
//$this->dbforge->add_key('impression_id', TRUE);
$this->dbforge->add_field($fields);
$this->dbforge->create_table($loc_number, TRUE);
}
$location = $this->crud_model->add_data("locations",$form_data);
$notify['receiver_id'] = $form_data['location_owner'];
$notify['message'] = sprintf($this->lang->line('new_location_added'), get_user_fullname());
$notify['link'] = "locations/view_locations";
$this->add_notifications($notify);
if ($user_role != 1) {
$notify['link'] = "admin/unapproved_locations";
}
$this->add_notifications($notify,'1');
// }else{
// $location = false;
// $msg = $qb_add_item['msg'];
// }
}
}else{
$location = false;
$msg = $qb_add_vendor['msg'];
}
if ($location) {
if (isset($edit)) {
if (!isset($msg)) {
$msg = "Location Updated successfully";
}
}else{
if (!isset($msg)) {
$msg = "Location created successfully";
}
}
$this->session->set_flashdata("success_msg",$msg);
redirect(base_url()."locations/view_locations");
}else{
if (isset($edit)) {
if (!isset($msg)) {
$msg = "Location Not Updated";
}
}else{
if (!isset($msg)) {
$msg = "Location Not created";
}
}
$this->session->set_flashdata("error_msg",$msg);
redirect($_SERVER['HTTP_REFERER']);
}
}
}
$this->data['owners'] = $this->crud_model->get_data("users",array("user_role"=>2));
if ($id != "") {
$where['l.location_id'] = $id;
$this->data['location'] = $this->crud_model->get_data('locations l',$where,true);
}
$where_in['user_role'] = array(1,2,3);
$this->data['users'] = $this->crud_model->get_data("users",'','','','','','',$where_in);
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('location/manage_location');
$this->load->view('common/footer');
}
public function view_locations(){
$join['users ou'] = "ou.user_id=l.location_owner";
$join['users su'] = "su.user_id=l.created_by";
$where = array();
$user_role = get_user_role();
$this->data['user_role'] = $user_role;
$this->data['locations'] = $this->crud_model->get_data("locations l",$where,'',$join,'','*,l.status as location_status,CONCAT(ou.first_name, " " ,ou.last_name) AS owner_name,CONCAT(su.first_name, " " ,su.last_name) AS satff_name,l.created_by as created_by');
if ($user_role != 1) {
foreach ($this->data['locations'] as $key => $value) {
if ($user_role == 3) {
if ($value->created_by != get_user_id() && $value->location_type == 0) {
unset($this->data['locations'][$key]);
}
}elseif ($user_role == 2) {
if ($value->location_owner != get_user_id() && $value->location_type == 0) {
unset($this->data['locations'][$key]);
}
}
}
}
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('location/view_locations',$this->data);
$this->load->view('common/footer');
}
public function delete_location($id){
$where['location_id'] = $id;
// $location = $this->crud_model->get_data($this->table,$where,true,'','','location_qb_id');
// $qb_inactive_location = $this->quick_books->inactive_item($location->location_qb_id);
// if ($qb_inactive_location['error'] == false) {
$result = $this->crud_model->delete_data($this->table,$where);
// }else{
// $this->session->set_flashdata("error_msg",$qb_inactive_location['msg']);
// }
redirect($_SERVER['HTTP_REFERER']);
}
public function get_location_marker(){
$user_role = get_user_role();
$where = "";
$where_query = false;
$or_where = false;
$location_id = $this->input->post('location_id');
if ($location_id != "") {
$where .= 'location_id = '.$location_id;
$where_query = true;
}
$filters = $this->input->post('filter');
if ($filters != "") {
if ($where_query) {
$where .= " AND (";
}
foreach ($filters as $key => $value) {
if ($or_where) {
$where .= " OR ";
}
$where .= " industry like '%".$value."%'";
$where .= " OR main_demographic like '%".$value."%'";
$or_where = true;
}
if ($where_query) {
$where .= ")";
}
}
$locations = $this->location_model->get_location_marker($where);
if ($user_role != 1) {
foreach ($locations as $key => $value) {
if ($user_role == 3) {
if ($value->created_by != get_user_id() && $value->location_type == 0) {
unset($locations[$key]);
}
}elseif ($user_role == 2) {
if ($value->location_owner != get_user_id() && $value->location_type == 0) {
unset($locations[$key]);
}
}
}
}
$res = array();
foreach ($locations as $key => $value) {
$arr['lat'] = (float) $value->lat;
$arr['lng'] = (float) $value->lng;
$locations[$key]->lat_lng = $arr;
$value->user_role = $user_role;
$locations[$key]->infowindow_content = $this->load->view("location/infowindow_content",$value,true);
}
// echo "<pre>";
// print_r($locations);
// exit();
echo json_encode($locations);
exit();
}
}
<file_sep>/application/views/location_manager/manager_sidebar.php
<li class="">
<a href="<?php echo base_url()?>location_manager">
Tasks Assigned
</a>
</li>
<li>
<a href="<?php echo base_url()?>location_manager/1">
Tasks Completed
</a>
</li>
<li>
<a href="<?php echo base_url()?>location_manager/view_deliveries">
Deliveries
</a>
</li>
<file_sep>/db/goholo.sql
-- phpMyAdmin SQL Dump
-- version 4.8.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Nov 13, 2018 at 06:05 PM
-- Server version: 10.1.34-MariaDB
-- PHP Version: 7.2.8
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `goholo`
--
-- --------------------------------------------------------
--
-- Table structure for table `advertisements`
--
CREATE TABLE `advertisements` (
`advert_id` int(11) NOT NULL,
`advert_qb_id` int(11) NOT NULL,
`advertiser_id` int(11) NOT NULL,
`advert_number` varchar(50) NOT NULL,
`start_date` varchar(20) NOT NULL,
`end_date` varchar(20) NOT NULL,
`hologram_type` int(11) NOT NULL,
`hologram_description` longtext NOT NULL,
`hologram_file` longtext NOT NULL,
`location_id` int(11) NOT NULL,
`commission_status` tinyint(1) NOT NULL DEFAULT '0',
`status` int(11) NOT NULL DEFAULT '0',
`created_by` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `advertisements`
--
INSERT INTO `advertisements` (`advert_id`, `advert_qb_id`, `advertiser_id`, `advert_number`, `start_date`, `end_date`, `hologram_type`, `hologram_description`, `hologram_file`, `location_id`, `commission_status`, `status`, `created_by`, `created_at`) VALUES
(15, 155, 7, 'AD999735', '11/2018', '11/2018', 1, '', '1690722895aveune_nightclub.jpg', 38, 0, 1, 40, '2018-10-31 20:06:35'),
(17, 158, 7, 'AD199584', '12/2018', '12/2018', 1, '', '222016334WWW.YIFY-TORRENTS.COM.jpg', 38, 0, 1, 8, '2018-10-31 22:07:19'),
(18, 159, 7, 'AD777782', '11/2018', '11/2018', 2, '3d animation on my logo ', '1281418911GOHOLOBLUEGLOWWHITEBG.png', 38, 0, 1, 40, '2018-11-01 05:02:11'),
(19, 160, 7, 'AD802803', '12/2018', '12/2018', 2, 'test haider', '223893921WWW.YIFY-TORRENTS.COM.jpg', 40, 0, 1, 8, '2018-11-01 13:28:44'),
(20, 161, 7, 'AD758312', '12/2018', '12/2018', 2, 'QA testing. ', '2591435691531149398695_CV_2017-converted.pdf', 39, 0, 1, 43, '2018-11-01 13:47:04'),
(21, 162, 7, 'AD131602', '12/2018', '12/2018', 1, '', '864170662shefield-sons-tobacconists-storefront-1.jpg', 43, 0, 1, 40, '2018-11-02 00:58:34');
-- --------------------------------------------------------
--
-- Table structure for table `advertisers`
--
CREATE TABLE `advertisers` (
`advertiser_id` int(11) NOT NULL,
`advertiser_qb_id` int(11) NOT NULL,
`advertiser_first_name` varchar(50) NOT NULL,
`advertiser_last_name` varchar(50) NOT NULL,
`advertiser_company_name` varchar(100) NOT NULL,
`advertiser_website` varchar(100) NOT NULL,
`advertiser_email` varchar(50) NOT NULL,
`advertiser_phone_number` varchar(20) NOT NULL,
`advertiser_street` longtext NOT NULL,
`advertiser_city` varchar(20) NOT NULL,
`advertiser_country` varchar(20) NOT NULL,
`advertiser_post_code` varchar(20) NOT NULL,
`status` tinyint(1) NOT NULL,
`created_by` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `advertisers`
--
INSERT INTO `advertisers` (`advertiser_id`, `advertiser_qb_id`, `advertiser_first_name`, `advertiser_last_name`, `advertiser_company_name`, `advertiser_website`, `advertiser_email`, `advertiser_phone_number`, `advertiser_street`, `advertiser_city`, `advertiser_country`, `advertiser_post_code`, `status`, `created_by`) VALUES
(7, 96, 'Jamal', 'Alfarela', 'Gadget Cloud', '', '<EMAIL>', '7809772322', '', '', '', '', 0, 40);
-- --------------------------------------------------------
--
-- Table structure for table `locations`
--
CREATE TABLE `locations` (
`location_id` int(11) NOT NULL,
`location_qb_id` int(11) NOT NULL,
`location_number` varchar(50) NOT NULL,
`location_name` varchar(50) NOT NULL,
`displays` varchar(50) NOT NULL,
`monthly_views` varchar(100) NOT NULL,
`monthly_cost` varchar(50) NOT NULL,
`owner_royalty` int(11) NOT NULL,
`advert_royalty` int(11) NOT NULL,
`advert_royalty_status` tinyint(1) NOT NULL DEFAULT '0',
`owner_royalty_status` tinyint(1) NOT NULL DEFAULT '0',
`main_demographic` varchar(255) NOT NULL,
`industry` varchar(50) NOT NULL,
`age_group` varchar(50) NOT NULL,
`location_description` longtext NOT NULL,
`other_notes` longtext NOT NULL,
`location_image` longtext NOT NULL,
`location_video` longtext NOT NULL,
`location_address` longtext NOT NULL,
`location_street` varchar(255) NOT NULL,
`location_city` varchar(50) NOT NULL,
`location_state` varchar(50) NOT NULL,
`location_post_code` varchar(50) NOT NULL,
`location_country` varchar(50) NOT NULL,
`location_lat` varchar(50) NOT NULL,
`location_lng` varchar(50) NOT NULL,
`location_owner` int(11) NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '0',
`created_by` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `locations`
--
INSERT INTO `locations` (`location_id`, `location_qb_id`, `location_number`, `location_name`, `displays`, `monthly_views`, `monthly_cost`, `owner_royalty`, `advert_royalty`, `advert_royalty_status`, `owner_royalty_status`, `main_demographic`, `industry`, `age_group`, `location_description`, `other_notes`, `location_image`, `location_video`, `location_address`, `location_street`, `location_city`, `location_state`, `location_post_code`, `location_country`, `location_lat`, `location_lng`, `location_owner`, `status`, `created_by`, `created_at`) VALUES
(38, 33, 'LOC288305', 'Avenue Nightclub ', '1', '4000 ', '200', 0, 0, 0, 0, 'Nightlife ', 'Nightlife / club ', '21+', 'Beverages / Liquor\\r\\nConsumer\\r\\ntest\\r\\nxyz', '', '922296741aveune_nightclub.jpg', '', '10888 Jasper Ave, Edmonton, AB T5K 0K9, Canada', '10888,Jasper Avenue', 'Edmonton', 'AB', 'T5K 0K9', 'Canada', '53.5412927', '-113.50810580000001', 0, 1, 40, '2018-10-31 20:03:23'),
(39, 34, 'LOC750895', 'Care It Urban Deli Crestwood ', '1', '4000 ', '200', 10, 0, 0, 0, 'Health conscious, Active people who tend to live a well balanced lifestyle ', 'Food ', '21+', 'Beverages \\r\\nLocal Events \\r\\nTaxi / MADD ads \\r\\nSports\\r\\nConsumer Goods \\r\\nRestaurants \\r\\n', 'Owner is open to any ads ', '', '681134175Care_it_Urban_Deli_CRESTWOOD.MP4', '9672 142 St NW, Edmonton, AB, Canada', '9672,142 Street Northwest', 'Edmonton', 'AB', 'T5N 4B2', 'Canada', '53.5344023', '-113.56665229999999', 0, 1, 40, '2018-11-01 04:56:50'),
(40, 35, 'LOC538217', 'Care It Urban Deli Downtown ', '1', '4000 ', '200', 10, 0, 0, 0, 'Corporate, Office workers, Collage Students, Health conscious people ', 'Food ', '21+', 'Beverages \\r\\nLocal Events \\r\\nTaxi / MADD ads \\r\\nSports\\r\\nConsumer Goods \\r\\nRestaurants \\r\\n', 'Owner is open to any type of ads ', '', '1169548166Care_it_Urban_Deli_DOWNTOWN.MP4', '10226 104 Street Northwest, Edmonton, AB, Canada', '10226,104 Street Northwest', 'Edmonton', 'AB', 'T5J 1B8', 'Canada', '53.5436629', '-113.49951620000002', 0, 1, 40, '2018-11-01 04:59:19'),
(42, 38, 'LOC874773', 'Shefield Express', '1', '200,000+', '950', 10, 0, 0, 0, '', '', '', '- Consumer Goods / Beverages\\r\\n- Kingsway Mall Advertising \\r\\n- Lottery \\r\\n', 'Some ads are restricted here, Please send request before getting payment to insure your ad can be displayed ', '459415305shefield-sons-tobacconists-storefront-1.jpg', '', 'Hudson\'s Bay Kingsway Mall, 109 Street, Edmonton, Alberta T5G 3A6, Canada', '109 Street Northwest', 'Edmonton', 'AB', 'T5G 3A6', 'Canada', '53.5606736', '-113.50490450000001', 0, 1, 40, '2018-11-02 00:52:37'),
(43, 39, 'LOC669791', 'Liquor House', '1', '3000 - 5000', '200', 10, 0, 0, 0, '', 'Beverages / Liquor', '18+', 'Beverages / Liquor \\r\\nTaxi / MADD ads \\r\\nRealtor / real estate \\r\\nEvents / Clubs \\r\\nRestaurants \\r\\n', '', '', '', '16510 59A ST, Edmonton, AB T5Y 3S9', '16510 59A ST, Edmonton', 'Edmonton', 'AB', 'T5Y 3S9', 'Canada', '53.6282928', '-113.34445490000002', 0, 1, 40, '2018-11-02 00:55:29'),
(44, 40, 'LOC112600', 'Seorak Restaurant ', '1', '750,000 +', '950', 10, 0, 0, 0, '', 'Food / Beverage', '', 'Beverages / liquor \\r\\nYoung Adults \\r\\nNightlife / Taxi / MADD ads \\r\\nLocal Events \\r\\nSports \\r\\n', 'The ad spot is on whyte ave which makes it a very busy area thats great for advertising events and parties ', '540609668rs=w_538,h_269,cg_true.jpeg', '', '10828 82 Ave NW, Edmonton, AB T6E 2B3, Canada', '10828,82 Avenue Northwest', 'Edmonton', 'AB', 'T6E 2B3', 'Canada', '53.5183542', '-113.51061820000001', 0, 1, 40, '2018-11-02 01:01:35'),
(45, 41, 'LOC573100', 'Liquor House (West)', '1', '3000 - 5000', '150', 10, 0, 0, 0, '', 'Beverages / Liquor', '', 'Beverages / liquor \\r\\nLocal Events \\r\\nTaxi / MADD ads \\r\\n', 'Owner is open to any ad', '', '', '15255 111 Ave NW, Edmonton, AB, Canada', '15255,111 Avenue Northwest', 'Edmonton', 'AB', 'T5M 2R1', 'Canada', '53.558521', '-113.58389', 0, 1, 40, '2018-11-02 01:04:38'),
(46, 42, 'LOC559949', 'Liquor Merchants ', '1', '3000 - 5000', '150', 10, 0, 0, 0, '', 'Beverages / Liquor', '18+', 'Beverages / liquor \\r\\nLocal Events \\r\\nTaxi / MADD ads \\r\\n', 'Owner is open to any ad ', '', '', '13132 82 Street Northwest, Edmonton, AB, Canada', '13132,82 Street Northwest', 'Edmonton', 'AB', 'T5E 2T5', 'Canada', '53.5917817', '-113.46790470000002', 0, 1, 40, '2018-11-02 01:10:17'),
(47, 43, 'LOC131926', 'Liquor Store', '1', '3000 - 5000', '150', 10, 0, 0, 0, '', '', '', 'Beverages / liquor \\r\\nLocal Events \\r\\nTaxi / MADD ads \\r\\n', 'Owner is open to any ad', '', '', '12965 97 Street Northwest, Edmonton, AB, Canada', '12965,97 Street Northwest', 'Edmonton', 'AB', 'T5E 4C4', 'Canada', '53.5894418', '-113.49137189999999', 0, 1, 40, '2018-11-02 01:11:25'),
(48, 44, 'LOC582500', '66 Bar & Grill ', '1', '8000', '395', 10, 0, 0, 0, '', 'Beverages / Food', '', 'Beverages / Liquor \\r\\nMall Ads \\r\\nLocal Events \\r\\nTaxi / MADD ads \\r\\nSports\\r\\nLondonderry Mall Ads ', 'Owner is open to any ad ', '1278491238file-10.jpeg', '10234975313DEFD7FE-4228-4ADC-B9BA-A316C240AFBC-1_(1).MP4', 'Londonderry Mall, Londonderry Square NW, Edmonton, AB, Canada', '1,Londonderry Square Northwest', 'Edmonton', 'AB', 'T5C 3C8', 'Canada', '53.6023306', '-113.44569639999997', 0, 1, 40, '2018-11-02 01:21:57'),
(49, 45, 'LOC983746', 'Poxys Convenience Store ', '1', '4000 ', '249', 10, -16, 0, 0, '', 'Convenience Store ', '', 'Beverages \\r\\nLocal Events \\r\\nTaxi / MADD ads \\r\\nSports\\r\\nConsumer Goods \\r\\nRestaurants\\r\\n', 'Owner is open to any ad ', '', '', '13204 82 St NW, Edmonton, AB T5E 2T7, Canada', '13204,82 Street Northwest', 'Edmonton', 'AB', 'T5E 2T7', 'Canada', '53.5926029', '-113.46779300000003', 0, 1, 40, '2018-11-02 01:26:25'),
(50, 46, 'LOC589423', '<NAME> ', '1', '2000 - 3000', '150', 10, 0, 0, 0, '', 'Cannabis ', '', 'Beverages \\r\\nLocal Events \\r\\nTaxi / MADD ads \\r\\nCannabis Ads \\r\\nConsumer Goods \\r\\nRestaurants \\r\\n', 'Owner is open to any ad', '', '', '13104 82 Street Northwest, Edmonton, AB, Canada', '13104,82 Street Northwest', 'Edmonton', 'AB', 'T5E 2T5', 'Canada', '53.59132049999999', '-113.46764710000002', 0, 1, 40, '2018-11-02 01:29:27'),
(51, 47, 'LOC872445', 'Soup & Sandwich Co ', '1', '4000 ', '200', 10, 0, 0, 0, 'Health conscious, Active people who tend to live a well balanced lifestyle ', 'Food ', '', 'Beverages \\r\\nLocal Events \\r\\nTaxi / MADD ads \\r\\nCannabis Ads \\r\\nConsumer Goo\\r\\n', 'Owner is open to any ad ', '435838977download.jpeg', '', '2833 Broadmoor Blvd, Sherwood Park, AB T8H 2H2, Canada', '2833,Broadmoor Boulevard', 'Sherwood Park', 'AB', 'T8H 2M8', 'Canada', '53.5639992', '-113.3190176', 0, 1, 40, '2018-11-02 01:32:02'),
(52, 48, 'LOC757729', 'Orbits Convenience Store', '1', '100,000 + ', '395', 10, 0, 0, 0, 'LRT Users ', 'Public Transit ', '', 'Owner is open to any ad ', 'Anyone coming in and out of the Edmonton Central LRT Station will see an ad displayed here ', '959545702ls_(1).jpg', '', '10020 Jasper Ave, Edmonton, AB T5J 1R2, Canada', '10020,Jasper Avenue', 'Edmonton', 'AB', 'T5J 1R2', 'Canada', '53.5413959', '-113.49153530000001', 0, 1, 40, '2018-11-02 01:40:04');
-- --------------------------------------------------------
--
-- Table structure for table `notifications`
--
CREATE TABLE `notifications` (
`notify_id` int(11) NOT NULL,
`receiver_id` int(11) NOT NULL,
`message` longtext NOT NULL,
`link` varchar(100) NOT NULL,
`read` tinyint(1) NOT NULL DEFAULT '0',
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `notifications`
--
INSERT INTO `notifications` (`notify_id`, `receiver_id`, `message`, `link`, `read`, `created`) VALUES
(143, 35, 'test test added new location', 'locations/view_locations', 0, '2018-10-30 16:48:27'),
(144, 8, 'test test added new location', 'locations/view_locations', 0, '2018-10-30 16:48:27'),
(145, 36, 'test test added new location', 'locations/view_locations', 0, '2018-10-30 16:54:47'),
(146, 8, 'test test added new location', 'locations/view_locations', 0, '2018-10-30 16:54:47'),
(147, 37, 'test test added new location', 'locations/view_locations', 0, '2018-10-30 16:59:27'),
(148, 8, 'test test added new location', 'locations/view_locations', 0, '2018-10-30 16:59:28'),
(149, 39, 'test test added new location', 'locations/view_locations', 0, '2018-10-30 17:35:41'),
(150, 8, 'test test added new location', 'locations/view_locations', 0, '2018-10-30 17:35:41'),
(151, 39, 'test test added new location', 'locations/view_locations', 0, '2018-10-30 18:56:30'),
(152, 8, 'test test added new location', 'locations/view_locations', 0, '2018-10-30 18:56:30'),
(153, 41, 'test test added new location', 'locations/view_locations', 0, '2018-10-31 13:37:04'),
(154, 8, 'test test added new location', 'locations/view_locations', 0, '2018-10-31 13:37:04'),
(155, 40, 'test test added new location', 'locations/view_locations', 0, '2018-10-31 13:37:04'),
(156, 8, '<NAME> added new location', 'locations/view_locations', 0, '2018-10-31 20:03:23'),
(157, 40, '<NAME> added new location', 'locations/view_locations', 0, '2018-10-31 20:03:23'),
(158, 0, '<NAME> added new advertisement', 'advertisers/view_advertisements', 0, '2018-10-31 20:06:35'),
(159, 8, '<NAME> added new advertisement', 'advertisers/view_advertisements', 0, '2018-10-31 20:06:35'),
(160, 40, '<NAME> added new advertisement', 'advertisers/view_advertisements', 0, '2018-10-31 20:06:35'),
(161, 8, 'New task created for location manager', 'location_manager', 0, '2018-10-31 20:06:35'),
(162, 40, 'New task created for location manager', 'location_manager', 0, '2018-10-31 20:06:35'),
(163, 8, 'New task created for location manager', 'location_manager', 0, '2018-10-31 20:06:35'),
(164, 40, 'New task created for location manager', 'location_manager', 0, '2018-10-31 20:06:35'),
(165, 0, 'test test added new advertisement', 'advertisers/view_advertisements', 0, '2018-10-31 20:08:57'),
(166, 8, 'test test added new advertisement', 'advertisers/view_advertisements', 0, '2018-10-31 20:08:57'),
(167, 40, 'test test added new advertisement', 'advertisers/view_advertisements', 0, '2018-10-31 20:08:57'),
(168, 8, 'New task created for location manager', 'location_manager', 0, '2018-10-31 20:08:57'),
(169, 40, 'New task created for location manager', 'location_manager', 0, '2018-10-31 20:08:57'),
(170, 8, 'New task created for location manager', 'location_manager', 0, '2018-10-31 20:08:57'),
(171, 40, 'New task created for location manager', 'location_manager', 0, '2018-10-31 20:08:57'),
(172, 8, 'test test added new advertisement', 'advertisers/view_advertisements', 0, '2018-10-31 22:07:19'),
(173, 40, 'test test added new advertisement', 'advertisers/view_advertisements', 0, '2018-10-31 22:07:19'),
(174, 8, 'New task created for location manager', 'location_manager', 0, '2018-10-31 22:07:19'),
(175, 40, 'New task created for location manager', 'location_manager', 0, '2018-10-31 22:07:19'),
(176, 8, 'New task created for location manager', 'location_manager', 0, '2018-10-31 22:07:19'),
(177, 40, 'New task created for location manager', 'location_manager', 0, '2018-10-31 22:07:19'),
(178, 8, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-01 04:56:50'),
(179, 40, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-01 04:56:50'),
(180, 8, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-01 04:59:19'),
(181, 40, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-01 04:59:19'),
(182, 8, '<NAME> added new advertisement', 'advertisers/view_advertisements', 0, '2018-11-01 05:02:11'),
(183, 40, '<NAME> added new advertisement', 'advertisers/view_advertisements', 0, '2018-11-01 05:02:11'),
(184, 8, 'New task created for location manager', 'location_manager', 0, '2018-11-01 05:02:11'),
(185, 40, 'New task created for location manager', 'location_manager', 0, '2018-11-01 05:02:11'),
(186, 8, 'New task created for location manager', 'location_manager', 0, '2018-11-01 05:02:11'),
(187, 40, 'New task created for location manager', 'location_manager', 0, '2018-11-01 05:02:11'),
(188, 8, 'New task created for designer', 'designer', 0, '2018-11-01 05:02:11'),
(189, 40, 'New task created for designer', 'designer', 0, '2018-11-01 05:02:11'),
(190, 8, '<NAME> added comment on a task', 'designer/tasks_assigned/34', 0, '2018-11-01 05:02:57'),
(191, 40, '<NAME> added comment on a task', 'designer/tasks_assigned/34', 0, '2018-11-01 05:02:57'),
(192, 8, 'test test added new advertisement', 'advertisers/view_advertisements', 0, '2018-11-01 13:28:44'),
(193, 40, 'test test added new advertisement', 'advertisers/view_advertisements', 0, '2018-11-01 13:28:44'),
(194, 8, 'New task created for location manager', 'location_manager', 0, '2018-11-01 13:28:44'),
(195, 40, 'New task created for location manager', 'location_manager', 0, '2018-11-01 13:28:44'),
(196, 8, 'New task created for location manager', 'location_manager', 0, '2018-11-01 13:28:44'),
(197, 40, 'New task created for location manager', 'location_manager', 0, '2018-11-01 13:28:44'),
(198, 8, 'New task created for designer', 'designer', 0, '2018-11-01 13:28:44'),
(199, 40, 'New task created for designer', 'designer', 0, '2018-11-01 13:28:44'),
(200, 8, 'Designer test7 added comment on a task', 'designer/tasks_assigned/37', 0, '2018-11-01 13:41:50'),
(201, 40, 'Designer test7 added comment on a task', 'designer/tasks_assigned/37', 0, '2018-11-01 13:41:50'),
(202, 42, 'test test added comment on a task', 'designer/tasks_assigned/37', 0, '2018-11-01 13:42:12'),
(203, 8, 'test test added comment on a task', 'designer/tasks_assigned/37', 0, '2018-11-01 13:42:12'),
(204, 40, 'test test added comment on a task', 'designer/tasks_assigned/37', 0, '2018-11-01 13:42:12'),
(205, 8, 'Marketing test7 added new advertisement', 'advertisers/view_advertisements', 0, '2018-11-01 13:47:04'),
(206, 40, 'Marketing test7 added new advertisement', 'advertisers/view_advertisements', 0, '2018-11-01 13:47:04'),
(207, 8, 'New task created for location manager', 'location_manager', 0, '2018-11-01 13:47:04'),
(208, 40, 'New task created for location manager', 'location_manager', 0, '2018-11-01 13:47:04'),
(209, 8, 'New task created for location manager', 'location_manager', 0, '2018-11-01 13:47:04'),
(210, 40, 'New task created for location manager', 'location_manager', 0, '2018-11-01 13:47:04'),
(211, 42, 'New task created for designer', 'designer', 0, '2018-11-01 13:47:04'),
(212, 8, 'New task created for designer', 'designer', 0, '2018-11-01 13:47:04'),
(213, 40, 'New task created for designer', 'designer', 0, '2018-11-01 13:47:04'),
(214, 0, 'test test has approved the advertisement', 'advertisers/view_advertisements', 0, '2018-11-01 13:47:24'),
(215, 43, 'test test has approved the advertisement', 'advertisers/view_advertisements', 0, '2018-11-01 13:47:24'),
(216, 8, 'test test has approved the advertisement', 'advertisers/view_advertisements', 0, '2018-11-01 13:47:24'),
(217, 40, 'test test has approved the advertisement', 'advertisers/view_advertisements', 0, '2018-11-01 13:47:24'),
(218, 42, 'Marketing test7 added comment on a task', 'designer/tasks_assigned/40', 0, '2018-11-01 13:47:50'),
(219, 8, 'Marketing test7 added comment on a task', 'designer/tasks_assigned/40', 0, '2018-11-01 13:47:50'),
(220, 40, 'Marketing test7 added comment on a task', 'designer/tasks_assigned/40', 0, '2018-11-01 13:47:50'),
(221, 42, 'test test added comment on a task', 'designer/tasks_assigned/40', 0, '2018-11-01 13:48:05'),
(222, 8, 'test test added comment on a task', 'designer/tasks_assigned/40', 0, '2018-11-01 13:48:05'),
(223, 40, 'test test added comment on a task', 'designer/tasks_assigned/40', 0, '2018-11-01 13:48:05'),
(224, 43, 'Designer test7 added comment on a task', 'designer/tasks_assigned/40', 0, '2018-11-01 13:48:44'),
(225, 8, 'Designer test7 added comment on a task', 'designer/tasks_assigned/40', 0, '2018-11-01 13:48:44'),
(226, 40, 'Designer test7 added comment on a task', 'designer/tasks_assigned/40', 0, '2018-11-01 13:48:44'),
(227, 8, 'test test added new location', 'locations/view_locations', 0, '2018-11-02 00:39:04'),
(228, 40, 'test test added new location', 'locations/view_locations', 0, '2018-11-02 00:39:04'),
(229, 8, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 00:52:37'),
(230, 40, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 00:52:37'),
(231, 8, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 00:55:29'),
(232, 40, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 00:55:29'),
(233, 8, '<NAME> added new advertisement', 'advertisers/view_advertisements', 0, '2018-11-02 00:58:34'),
(234, 40, '<NAME> added new advertisement', 'advertisers/view_advertisements', 0, '2018-11-02 00:58:34'),
(235, 8, 'New task created for location manager', 'location_manager', 0, '2018-11-02 00:58:34'),
(236, 40, 'New task created for location manager', 'location_manager', 0, '2018-11-02 00:58:34'),
(237, 8, 'New task created for location manager', 'location_manager', 0, '2018-11-02 00:58:34'),
(238, 40, 'New task created for location manager', 'location_manager', 0, '2018-11-02 00:58:34'),
(239, 8, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 01:01:35'),
(240, 40, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 01:01:35'),
(241, 8, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 01:04:38'),
(242, 40, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 01:04:38'),
(243, 8, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 01:10:17'),
(244, 40, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 01:10:17'),
(245, 8, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 01:11:25'),
(246, 40, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 01:11:25'),
(247, 8, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 01:21:58'),
(248, 40, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 01:21:58'),
(249, 8, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 01:26:25'),
(250, 40, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 01:26:25'),
(251, 8, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 01:29:27'),
(252, 40, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 01:29:27'),
(253, 8, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 01:32:02'),
(254, 40, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 01:32:02'),
(255, 8, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 01:40:04'),
(256, 40, '<NAME> added new location', 'locations/view_locations', 0, '2018-11-02 01:40:04');
-- --------------------------------------------------------
--
-- Table structure for table `permissions`
--
CREATE TABLE `permissions` (
`permissionid` int(11) NOT NULL,
`name` varchar(50) NOT NULL,
`shortname` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `permissions`
--
INSERT INTO `permissions` (`permissionid`, `name`, `shortname`) VALUES
(1, 'Locations', 'locations'),
(2, 'Advertisers', 'advertisers'),
(3, 'Location Manager', 'location_manager'),
(4, 'Designer', 'designer'),
(5, 'Payouts', 'payouts'),
(6, 'Resource Center', 'resource_center'),
(7, 'Admin', 'admin'),
(8, 'Recriutment', 'recriutment'),
(9, 'Add Location', 'add_location');
-- --------------------------------------------------------
--
-- Table structure for table `proofs`
--
CREATE TABLE `proofs` (
`proof_id` int(11) NOT NULL,
`advert_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`proof_file` longtext NOT NULL,
`proof_type` varchar(20) NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '0',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `proofs`
--
INSERT INTO `proofs` (`proof_id`, `advert_id`, `user_id`, `proof_file`, `proof_type`, `status`, `created_at`) VALUES
(21, 9, 8, '391223364SIMPLE_FARES_APP_FLOW_.pdf', 'designer', 1, '2018-08-28 08:43:02');
-- --------------------------------------------------------
--
-- Table structure for table `resource_center`
--
CREATE TABLE `resource_center` (
`resource_id` int(11) NOT NULL,
`title` varchar(50) NOT NULL,
`resource_type` int(11) NOT NULL DEFAULT '3',
`description` longtext NOT NULL,
`resource_file` longtext NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `resource_center`
--
INSERT INTO `resource_center` (`resource_id`, `title`, `resource_type`, `description`, `resource_file`) VALUES
(6, 'Location Criteria ', 4, 'Please download PDF file to see all Criteria the location needs to match with in order to be added to The GoHOLO ads Network ', '752278402Location_Criteria_for_G0HOLO_ads_(2).pdf'),
(7, 'Proposal / Location Contract to add new Ad Locatio', 1, 'Please download PDF file and get Location owner to fill out below details and send the filled out form to <EMAIL>. The third page is used to upload location details to Website and make the location officially part of the GOHOLO ADS NETWORK ', '1282710255GOHOLO_ads_Proposal_(11).pdf'),
(8, 'Hologram Specs ', 3, '', '1575145097GoHOLO_specs.pdf');
-- --------------------------------------------------------
--
-- Table structure for table `rolepermissions`
--
CREATE TABLE `rolepermissions` (
`rolepermissionid` int(11) NOT NULL,
`permissionid` int(11) NOT NULL,
`roleid` int(11) NOT NULL,
`permission` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `rolepermissions`
--
INSERT INTO `rolepermissions` (`rolepermissionid`, `permissionid`, `roleid`, `permission`) VALUES
(1, 1, 3, 1),
(2, 2, 3, 1),
(3, 3, 3, 1),
(4, 4, 3, 1),
(5, 5, 3, 1),
(6, 6, 3, 1),
(7, 7, 3, 0),
(8, 8, 3, 1),
(9, 1, 2, 1),
(10, 2, 2, 1),
(11, 3, 2, 0),
(12, 4, 2, 0),
(13, 5, 2, 1),
(14, 6, 2, 1),
(15, 7, 2, 0),
(16, 8, 2, 0),
(17, 9, 2, 0),
(18, 9, 3, 1),
(19, 1, 4, 0),
(20, 2, 4, 0),
(21, 3, 4, 0),
(22, 4, 4, 1),
(23, 5, 4, 0),
(24, 6, 4, 1),
(25, 7, 4, 0),
(26, 8, 4, 0),
(27, 9, 4, 0),
(28, 1, 5, 0),
(29, 2, 5, 0),
(30, 3, 5, 1),
(31, 4, 5, 0),
(32, 5, 5, 0),
(33, 6, 5, 1),
(34, 7, 5, 0),
(35, 8, 5, 0),
(36, 9, 5, 0);
-- --------------------------------------------------------
--
-- Table structure for table `settings`
--
CREATE TABLE `settings` (
`setting_id` int(11) NOT NULL,
`setting_key` longtext NOT NULL,
`setting_value` longtext NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `settings`
--
INSERT INTO `settings` (`setting_id`, `setting_key`, `setting_value`) VALUES
(1, 'qb_client_id', 'Q0PGBYwNj2MazWdKIo5gc4XelXDV6HI3LOmRJ8<KEY>'),
(2, 'qb_client_secret', '<KEY>'),
(3, 'qb_access_token', '<KEY>'),
(4, 'qb_refresh_token', '<KEY>'),
(5, 'qb_realmId', '123146090862619');
-- --------------------------------------------------------
--
-- Table structure for table `tasks`
--
CREATE TABLE `tasks` (
`task_id` int(11) NOT NULL,
`advert_id` int(11) NOT NULL,
`task_type` varchar(20) NOT NULL,
`date` date NOT NULL,
`delivery_file` varchar(100) NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `tasks`
--
INSERT INTO `tasks` (`task_id`, `advert_id`, `task_type`, `date`, `delivery_file`, `status`) VALUES
(26, 15, 'add_advert', '2018-01-12', '', 0),
(27, 15, 'remove_advert', '2019-01-01', '', 0),
(28, 16, 'add_advert', '2018-01-12', '', 0),
(29, 16, 'remove_advert', '2019-01-01', '', 0),
(30, 17, 'add_advert', '2018-01-12', '', 0),
(31, 17, 'remove_advert', '2019-01-01', '', 0),
(32, 18, 'add_advert', '2018-01-11', '', 0),
(33, 18, 'remove_advert', '2018-01-12', '', 0),
(34, 18, 'designer', '2018-01-11', '', 0),
(35, 19, 'add_advert', '2018-01-12', '', 0),
(36, 19, 'remove_advert', '2019-01-01', '', 0),
(37, 19, 'designer', '2018-01-12', '', 0),
(38, 20, 'add_advert', '2018-01-12', '', 0),
(39, 20, 'remove_advert', '2019-01-01', '', 0),
(40, 20, 'designer', '2018-01-12', '', 0),
(41, 21, 'add_advert', '2018-01-12', '', 0),
(42, 21, 'remove_advert', '2019-01-01', '', 0);
-- --------------------------------------------------------
--
-- Table structure for table `task_comments`
--
CREATE TABLE `task_comments` (
`comment_id` int(11) NOT NULL,
`task_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`comment` longtext NOT NULL,
`comment_file` longtext NOT NULL,
`task_created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `task_comments`
--
INSERT INTO `task_comments` (`comment_id`, `task_id`, `user_id`, `comment`, `comment_file`, `task_created`) VALUES
(12, 34, 40, 'test this is a test ', '1526588726GOHOLOBLUEGLOWBLACK.png', '2018-11-01 05:02:57'),
(13, 37, 42, 'designer', '', '2018-11-01 13:41:50'),
(14, 37, 8, 'admin', '', '2018-11-01 13:42:12'),
(15, 40, 43, 'Testing QA 1', '', '2018-11-01 13:47:50'),
(16, 40, 8, 'testing qa2', '', '2018-11-01 13:48:05'),
(17, 40, 42, 'testing qa3', '', '2018-11-01 13:48:44');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`user_id` int(11) NOT NULL,
`user_qb_id` int(11) NOT NULL,
`first_name` varchar(30) NOT NULL,
`last_name` varchar(30) NOT NULL,
`email` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`gender` tinyint(1) NOT NULL,
`date_of_birth` date NOT NULL,
`user_role` int(11) NOT NULL,
`paypal_id` varchar(50) NOT NULL,
`phone_number` varchar(50) NOT NULL,
`profile_image` longtext NOT NULL,
`user_commission` int(11) NOT NULL,
`transit_number` int(11) NOT NULL,
`institution_number` int(11) NOT NULL,
`account_number` int(11) NOT NULL,
`street` varchar(255) NOT NULL,
`city` varchar(50) NOT NULL,
`state` varchar(50) NOT NULL,
`post_code` varchar(10) NOT NULL,
`status` tinyint(1) NOT NULL DEFAULT '1',
`created_by` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`user_id`, `user_qb_id`, `first_name`, `last_name`, `email`, `password`, `gender`, `date_of_birth`, `user_role`, `paypal_id`, `phone_number`, `profile_image`, `user_commission`, `transit_number`, `institution_number`, `account_number`, `street`, `city`, `state`, `post_code`, `status`, `created_by`, `created_at`) VALUES
(8, 0, 'test', 'test', '<EMAIL>', 'admin123', 1, '2016-05-01', 1, '<EMAIL>', '', '119394679518342456_1401500969873052_5560180181826082461_n.jpg', 0, 0, 0, 0, 'jh', 'g', 'jgjh', 'jh', 1, 0, '2018-08-02 21:17:43'),
(40, 0, 'Jamal', 'Alfarela', '<EMAIL>', 'Jamal123', 1, '1993-12-24', 1, '', '7809772322', '', 30, 0, 0, 0, '8532 Jasper ave ', 'Edmonton', 'AB', 't5h 3s4', 1, 8, '2018-10-30 20:53:51'),
(41, 93, 'New', 'Owner7', '<EMAIL>', 'owner123', 1, '0000-00-00', 2, '', '', '', 0, 0, 0, 0, '', '', '', '', 1, 8, '2018-10-31 13:37:01'),
(42, 98, 'Designer', 'test7', '<EMAIL>', 'designer123', 1, '0000-00-00', 4, '', '', '', 15, 0, 0, 0, '', '', '', '', 1, 8, '2018-11-01 13:40:44'),
(43, 99, 'Marketing', 'test7', '<EMAIL>', 'market123', 1, '0000-00-00', 3, '', '', '', 15, 0, 0, 0, '', '', '', '', 1, 8, '2018-11-01 13:43:48');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `advertisements`
--
ALTER TABLE `advertisements`
ADD PRIMARY KEY (`advert_id`);
--
-- Indexes for table `advertisers`
--
ALTER TABLE `advertisers`
ADD PRIMARY KEY (`advertiser_id`);
--
-- Indexes for table `locations`
--
ALTER TABLE `locations`
ADD PRIMARY KEY (`location_id`),
ADD UNIQUE KEY `location_number` (`location_number`);
--
-- Indexes for table `notifications`
--
ALTER TABLE `notifications`
ADD PRIMARY KEY (`notify_id`);
--
-- Indexes for table `permissions`
--
ALTER TABLE `permissions`
ADD PRIMARY KEY (`permissionid`);
--
-- Indexes for table `proofs`
--
ALTER TABLE `proofs`
ADD PRIMARY KEY (`proof_id`);
--
-- Indexes for table `resource_center`
--
ALTER TABLE `resource_center`
ADD PRIMARY KEY (`resource_id`);
--
-- Indexes for table `rolepermissions`
--
ALTER TABLE `rolepermissions`
ADD PRIMARY KEY (`rolepermissionid`);
--
-- Indexes for table `settings`
--
ALTER TABLE `settings`
ADD PRIMARY KEY (`setting_id`);
--
-- Indexes for table `tasks`
--
ALTER TABLE `tasks`
ADD PRIMARY KEY (`task_id`);
--
-- Indexes for table `task_comments`
--
ALTER TABLE `task_comments`
ADD PRIMARY KEY (`comment_id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`user_id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `advertisements`
--
ALTER TABLE `advertisements`
MODIFY `advert_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;
--
-- AUTO_INCREMENT for table `advertisers`
--
ALTER TABLE `advertisers`
MODIFY `advertiser_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT for table `locations`
--
ALTER TABLE `locations`
MODIFY `location_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=53;
--
-- AUTO_INCREMENT for table `notifications`
--
ALTER TABLE `notifications`
MODIFY `notify_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=257;
--
-- AUTO_INCREMENT for table `permissions`
--
ALTER TABLE `permissions`
MODIFY `permissionid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
--
-- AUTO_INCREMENT for table `proofs`
--
ALTER TABLE `proofs`
MODIFY `proof_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;
--
-- AUTO_INCREMENT for table `resource_center`
--
ALTER TABLE `resource_center`
MODIFY `resource_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT for table `rolepermissions`
--
ALTER TABLE `rolepermissions`
MODIFY `rolepermissionid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=37;
--
-- AUTO_INCREMENT for table `settings`
--
ALTER TABLE `settings`
MODIFY `setting_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6;
--
-- AUTO_INCREMENT for table `tasks`
--
ALTER TABLE `tasks`
MODIFY `task_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=43;
--
-- AUTO_INCREMENT for table `task_comments`
--
ALTER TABLE `task_comments`
MODIFY `comment_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=44;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/application/controllers/Admin.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Admin extends GH_Controller {
public $data = array();
public function __construct() {
parent::__construct();
$this->data['menu_class'] = "admin_menu";
$this->data['title'] = "Admin";
$this->data['sidebar_file'] = "admin/admin_sidebar";
}
public function index()
{
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('admin/admin');
$this->load->view('common/footer');
}
public function manage_resource_center($id = ""){
$form_data = $this->input->post();
if (!empty($form_data)) {
$resource_file = $this->crud_model->upload_file($_FILES['resource_file'],'resource_file',RESOURCE_CENTER_UPLOAD_PATH);
if ($resource_file) {
$form_data['resource_file'] = $resource_file;
}elseif ($form_data['old_resource_file'] != "") {
$form_data['resource_file']= $form_data['old_resource_file'];
}
unset($form_data['old_resource_file']);
$edit = false;
if ($form_data['resource_id'] != "") {
$edit = true;
$where['resource_id'] = $form_data['resource_id'];
unset($form_data['resource_id']);
$resource_id = $this->crud_model->update_data('resource_center',$where,$form_data);
}else{
unset($form_data['resource_id']);
$resource_id = $this->crud_model->add_data('resource_center',$form_data);
$notify['message'] = $this->lang->line('new_resource');
$notify['link'] = "admin/view_resource_center";
$this->add_notifications($notify,array("2","3","4","5"));
}
if ($resource_id) {
if (isset($edit)) {
$this->session->set_flashdata("success_msg","Resource Updated successfully");
}else{
$this->session->set_flashdata("success_msg","Resource created successfully");
}
redirect(base_url()."admin/view_resource_center");
}else{
if (isset($edit)) {
$this->session->set_flashdata("error_msg","Resource Not Updated");
}else{
$this->session->set_flashdata("error_msg","Resource Not created");
}
redirect($_SERVER['HTTP_REFERER']);
}
}
if ($id != "") {
$where['resource_id'] = $id;
$this->data['resource'] = $this->crud_model->get_data('resource_center',$where,true);
}
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('resource_center/manage_resource_center');
$this->load->view('common/footer');
}
public function view_resource_center(){
$this->data['resources'] = $this->crud_model->get_data('resource_center');
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('resource_center/admin_resource_center',$this->data);
$this->load->view('common/footer');
}
public function delete_resource($id){
$where['resource_id'] = $id;
$result = $this->crud_model->delete_data('resource_center',$where);
if ($result) {
redirect($_SERVER['HTTP_REFERER']);
}
}
public function delete_package($id){
$where['package_id'] = $id;
$package = $this->crud_model->get_data("packages",$where,true,'','','item_qb_id');
$qb_inactive_package = $this->quick_books->inactive_item($package->item_qb_id);
if ($qb_inactive_package['error'] == false) {
$result = $this->crud_model->delete_data("packages",$where);
}else{
$this->session->set_flashdata("error_msg",$qb_inactive_package['msg']);
}
if ($result) {
redirect($_SERVER['HTTP_REFERER']);
}
}
public function manage_packages($id = ""){
$form_data = $this->input->post();
if (!empty($form_data)) {
$edit = false;
$form_data['total_cost'] = ($form_data['total_impressions']*$form_data['cost_per_impression'])+$form_data['hologram_price'];
if ($form_data['package_id'] != "") {
$edit = true;
$qb_update_item = $this->quick_books->update_item($form_data);
if ($qb_update_item['error'] == false) {
$where['package_id'] = $form_data['package_id'];
unset($form_data['package_id']);
$package_id = $this->crud_model->update_data('packages',$where,$form_data);
}else{
$package_id = false;
$msg = $qb_update_item['msg'];
}
}else{
$qb_add_item = $this->quick_books->add_item($form_data);
if ($qb_add_item['error'] == false) {
$form_data['item_qb_id'] = $qb_add_item['msg'];
unset($form_data['package_id']);
$package_id = $this->crud_model->add_data('packages',$form_data);
}else{
$package_id = false;
$msg = $qb_add_item['msg'];
}
//$notify['message'] = $this->lang->line('new_package');
//$notify['link'] = "admin/view_resource_center";
//$this->add_notifications($notify,array("2","3","4","5"));
}
if ($package_id) {
if (isset($edit)) {
$this->session->set_flashdata("success_msg","Package Updated successfully");
}else{
$this->session->set_flashdata("success_msg","Package created successfully");
}
redirect(base_url()."admin/view_packages");
}else{
if (isset($edit)) {
if (!isset($msg)) {
$msg = "Package Not Updated";
}
}else{
if (!isset($msg)) {
$msg = "Package Not created";
}
}
$this->session->set_flashdata("error_msg",$msg);
redirect($_SERVER['HTTP_REFERER']);
}
}
if ($id != "") {
$where['package_id'] = $id;
$this->data['package'] = $this->crud_model->get_data('packages',$where,true);
}
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('packages/manage_packages');
$this->load->view('common/footer');
}
public function view_packages(){
$this->data['packages'] = $this->crud_model->get_data('packages');
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('packages/view_packages',$this->data);
$this->load->view('common/footer');
}
public function change_record_status(){
$where[$this->input->post("where")] = $this->input->post("record_id");
$update_data['status'] = $this->input->post("status");
$res = $this->crud_model->update_data($this->input->post("table"),$where,$update_data);
$this->notify_status();
if ($res) {
$response['success'] = true;
}else{
$response['error'] = true;
}
echo json_encode($response);
}
public function unapproved_locations(){
$join['users ou'] = "ou.user_id=l.location_owner";
$join['users su'] = "su.user_id=l.created_by";
$where = array();
$user_role = get_user_role();
$this->data['user_role'] = $user_role;
if ($user_role != 1) {
if ($user_role == 3) {
$where['l.created_by'] = get_user_id();
}elseif ($user_role == 2) {
$where['l.location_owner'] = get_user_id();
}
}
$where['l.status'] = 0;
$this->data['locations'] = $this->crud_model->get_data("locations l",$where,'',$join,'','*,l.status as location_status,CONCAT(ou.first_name, " " ,ou.last_name) AS owner_name,CONCAT(su.first_name, " " ,su.last_name) AS satff_name');
$this->load->view('common/header',$this->data);
$this->load->view('common/sidebar',$this->data);
$this->load->view('location/view_locations',$this->data);
$this->load->view('common/footer');
}
}
<file_sep>/application/views/advertisers/view_advertisements_info.php
<div class="page-content-col">
<?php
$date = $locations->created_at;
$format = date_create($date);
$formatted_date = date_format($format,"Y-m-d");
?>
<div class="portlet box blue">
<div class="portlet-title">
<div class="caption">
locations Details </div>
<div class="tools">
<a href="javascript:;" class="collapse" data-original-title="" title=""> </a>
</div>
<span style="float: right;padding: 10px;font-size: 18px;"> <b>Total Impressions:</b> <?=$locations->impressions?> </span>
</div>
<div class="portlet-body form">
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Location Name:</b>
<div class="col-md-8">
<p> <?=$locations->location_name?> </p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Location Number:</b>
<div class="col-md-8">
<p> <?=$locations->location_number?> </p>
</div>
</div>
</div>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<div class="col-md-6">
<div class="form-group">
<b class=" col-md-4">Advertise Number:</b>
<div class="col-md-8">
<p > <?=$locations->advert_number?> </p>
</div>
</div>
</div>
<?php
if ($locations->hologram_type == 2) {
$locations->hologram_file = "";
$delivery = $this->crud_model->get_data('tasks',array("advert_id"=>$locations->advert_id,'task_type'=>'designer','status'=>1),true);
if (!empty($delivery)) {
$locations->hologram_file = $delivery->delivery_file;
}
}
?>
<?php
if (!empty($locations->hologram_file)) {
?>
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Hologram File:</b>
<div class="col-md-8">
<p> <?php
if ($locations->hologram_file != "") {
?>
<a href="<?php echo base_url().HOLOGRAM_FILE_UPLOAD_PATH.$locations->hologram_file ?>" download> Download File</a>
<?php
}else{
echo "Waiting for the designs from the designer";
}
?> </p>
</div>
</div>
</div>
<?php
}
?>
<!--/span-->
</div>
<!--/row-->
<div class="row">
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Delivery Date:</b>
<div class="col-md-8">
<p> <?=$formatted_date?> </p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Delivery Type:</b>
<div class="col-md-8">
<p>Design Hologram</p>
</div>
</div>
</div>
</div>
<div class="row">
<?php
if ($locations->advertisment_type == 1) {
?>
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Advertisment Type:</b>
<div class="col-md-8">
<p>Package Based</p>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Total Views:</b>
<div class="col-md-8">
<p> <?=$locations->total_impressions?> </p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Views Remaining:</b>
<div class="col-md-8">
<p> <?=$locations->total_impressions-$locations->impressions?></p>
</div>
</div>
</div>
<?php
}elseif ($locations->advertisment_type == 2) {
?>
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Advertisment Type:</b>
<div class="col-md-8">
<p>Pay As You Go</p>
</div>
</div>
</div>
<?php
}
?>
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Current Views:</b>
<div class="col-md-8">
<p> <?=$locations->impressions?></p>
</div>
</div>
</div>
</div>
<hr>
<?php
if (!empty($delivery_file)) {
?>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Delivery File:</b>
<div class="col-md-8">
<p> <a href="<?php echo base_url().PROOF_UPLOAD_PATH.$delivery_file->proof_file ?>" download> Download File</a> </p>
</div>
</div>
</div>
</div>
<?php
}
?>
<?php
if (!empty($locations->delivery_file)) {
?>
<div class="row">
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Delivery File:</b>
<div class="col-md-8">
<p> <a href="<?php echo base_url().PROOF_UPLOAD_PATH.$locations->delivery_file ?>" download> Download File</a> </p>
</div>
</div>
</div>
<!--/span-->
</div>
<?php
}
?>
<?php
if (!empty($locations->hologram_description)) {
?>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<b class="col-md-3">Hologram Description:</b>
<div class="col-md-12">
<p> <?=$locations->hologram_description?> </p>
</div>
</div>
</div>
</div>
<?php
}
?>
<h3 class="form-section">Address</h3>
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<b class="col-md-2">Address:</b>
<div class="col-md-10">
<p> <?=$locations->location_address?> </p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">City:</b>
<div class="col-md-8">
<p class=""> <?=$locations->location_city?> </p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">State:</b>
<div class="col-md-8">
<p class=""> <?=$locations->location_state?> </p>
</div>
</div>
</div>
<!--/span-->
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Post Code:</b>
<div class="col-md-8">
<p class=""> <?=$locations->location_post_code?> </p>
</div>
</div>
</div>
<!--/span-->
<div class="col-md-6">
<div class="form-group">
<b class="col-md-4">Country:</b>
<div class="col-md-8">
<p class=""> <?=$locations->location_country?> </p>
</div>
</div>
</div>
<!--/span-->
</div>
</div>
<div class="col-md-12">
<input type="hidden" class="lat" value="<?php echo $locations->location_lat?>">
<input type="hidden" class="lng" value="<?php echo $locations->location_lng?>">
<input type="hidden" class="cost" value="<?php echo $locations->total_cost?>">
<input type="hidden" class="location_id" value="<?php echo $locations->location_id?>">
<div id="location_map" style="height: 400px"></div>
</div>
</div>
</div>
</div>
</div>
</div><file_sep>/application/controllers/analytics/Dashboard.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//memory_limit 8G
//max_input_vars 100000
//max_execution_time 8000
//post_max_size 8G
class Dashboard extends GH_Controller {
public $data = array();
public function __construct() {
parent::__construct();
$this->load->model("video_model");
}
function _remap($method,$param){
if (method_exists($this,$method)) {
if (!empty($param)) {
$this->$method($param[0]);
}else{
$this->$method();
}
} else {
$this->index($method);
}
}
public function index($locationID)
{
$analytics_param = array('locationID'=>$locationID);
if ($this->input->get("daterange") != "") {
$date = $this->input->get("daterange");
$data = explode("/", $date);
$start_date = $data[0];
$end_date = $data[1];
$this->data['start_date'] = date("m/d/Y", strtotime($start_date));
$this->data['end_date'] = date("m/d/Y", strtotime($end_date));
$analytics_param = array("start_date"=> $start_date , "end_date"=> $end_date);
}
$location = $this->video_model->get_data_new(array('table' => 'locations' , 'where'=> array("location_id"=>$locationID), 'single_row'=>true ));
$this->data['location'] = $location;
$this->data['locationID'] = $locationID;
$this->data['analytics'] = $this->video_model->get_analytics($analytics_param);
$this->load->view('analytics/includes/header');
$this->load->view('analytics/includes/navbar');
$this->load->view('analytics/dashboard/index',$this->data);
$this->load->view('analytics/includes/footer');
}
}
<file_sep>/application/views/packages/manage_packages.php
<!-- END PAGE SIDEBAR -->
<div class="page-content-col">
<?php
if (isset($package) && !empty($package)) {
?>
<script type="text/javascript">
$(document).ready(function(){
<?php
foreach ($package as $key => $value) {
?>
var key = "<?php echo $key ?>";
$("."+key+"").val("<?php echo $value ?>");
<?php
}
?>
});
</script>
<?php
}
?>
<div class="row">
<?php
if ($this->session->flashdata("error_msg") != "") {
?>
<div class="alert alert-danger">
<?php echo $this->session->flashdata("error_msg"); ?>
</div>
<?php
}
?>
</div>
<!-- BEGIN PAGE BASE CONTENT -->
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption">
<span class="caption-subject font-blue-hoki bold uppercase">Add Package</span>
</div>
<div class="tools">
<a href="" class="collapse" data-original-title="" title=""> </a>
</div>
</div>
<div class="portlet-body form">
<!-- BEGIN FORM-->
<form action="<?php echo base_url() ?>admin/manage_packages" method="post" enctype="multipart/form-data" class="horizontal-form">
<div class="form-body">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Package Name</label>
<input type="text" class="form-control package_name" name="package_name">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Total Impressions</label>
<input type="text" class="form-control total_impressions" name="total_impressions">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Cost / Impression</label>
<input type="text" class="form-control cost_per_impression" name="cost_per_impression">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Hologram Price</label>
<input type="text" class="form-control hologram_price" name="hologram_price">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Total Cost</label>
<input type="text" class="form-control total_cost" name="total_cost" readonly="">
</div>
</div>
</div>
</div>
<div class="form-actions right">
<input type="hidden" name="package_id" class="package_id">
<input type="hidden" name="item_qb_id" class="item_qb_id">
<button type="submit" class="btn blue">
<i class="fa fa-check"></i> Save</button>
</div>
</form>
<!-- END FORM-->
</div>
</div>
<!-- END PAGE BASE CONTENT -->
</div>
<file_sep>/application/views/common/sidebar.php
<div class="page-content">
<!-- BEGIN BREADCRUMBS -->
<div class="">
<!-- Sidebar Toggle Button -->
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".page-sidebar">
<span class="sr-only">Toggle navigation</span>
<span class="toggle-icon">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</span>
</button>
<!-- Sidebar Toggle Button -->
</div>
<!-- END BREADCRUMBS -->
<!-- BEGIN SIDEBAR CONTENT LAYOUT -->
<div class="page-content-container">
<div class="page-content-row">
<!-- BEGIN PAGE SIDEBAR -->
<div class="page-sidebar">
<nav class="navbar" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<!-- Collect the nav links, forms, and other content for toggling -->
<ul class="nav navbar-nav margin-bottom-35">
<li class="nav-item start li-setting">
<div class="row">
<div class="col-md-12 col-xs-12">
<div class="col-md-6 col-xs-6 mt-20">
<?php
$user=$this->session->userdata("user_session");
if ($user->profile_image != "") {
$img_src = base_url().PROFILE_IMAGE_UPLOAD_PATH.$user->profile_image;
}else{
$img_src = base_url()."assets/layouts/layout4/img/avatar.png";
}
?>
<img style="width: 55px; height: 70px;" class="img-circle" src="<?=$img_src?>" alt="">
</div>
<div class="col-md-6 col-xs-6 mt-20" style=" color: white; ">
<div class="row" style="margin-top: 18px;margin-bottom: 10px;">
<?php
echo get_user_fullname();
?>
</div>
<div class="row">
<small><a href="<?php echo base_url() ?>logout">Logout</a></small>
</div>
</div>
</div>
</div>
</li>
<li class="li-setting">
<form class="search" action="extra_search.html" method="GET">
<input type="name" class="form-control mt-20 mb-20" name="query" placeholder="Search...">
<a href="javascript:;" class="btn submit md-skip search-icon">
<i class="fa fa-search"></i>
</a>
</form>
</li>
<?php $this->load->view($sidebar_file); ?>
</ul>
</nav>
</div> | aac081490dad94f21d91db90cde7dec4b18bf0a7 | [
"SQL",
"PHP"
] | 78 | PHP | hdr105/goholo | efc675fa27b783a24303b562d71dbf9ecbc71bcd | 112f942230343c90b6a832537541b3dbf8961d42 |
refs/heads/master | <file_sep>package com.joenck.votemanager.exceptions;
public class NoDataFoundException extends RuntimeException {
public NoDataFoundException(Long id, String className) {
super(String.format("Nenhum dado encontrado com id %d para %s",id,className));
}
}
<file_sep>package com.joenck.votemanager.exceptions;
public class InvalidZoneIdException extends RuntimeException {
public InvalidZoneIdException(String fusoHorario) {
super(String.format("Fuso horário %s ainda não é suportado, somente America/Sao_Paulo",fusoHorario));
}
}
<file_sep>package com.joenck.votemanager.votos;
import com.joenck.votemanager.exceptions.ClosedVoteException;
import com.joenck.votemanager.exceptions.DuplicateVoteException;
import com.joenck.votemanager.pautas.Pauta;
import com.joenck.votemanager.pautas.PautaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class VotoService {
@Autowired
VotoRepository votoRepository;
@Autowired
PautaService pautaService;
public Voto registrarVoto(Long pautaId, String cpf, String decisao) {
if(pautaService.votacaoAberta(pautaId)) {
Pauta pauta = pautaService.getById(pautaId);
if(!votoRepository.existsByCpfAndPauta(cpf,pauta)){
Voto voto = new Voto(pauta, cpf, Voto.Decisao.get(decisao));
return votoRepository.save(voto);
} else {
throw new DuplicateVoteException(cpf,pauta.getId());
}
} else {
throw new ClosedVoteException(pautaId);
}
}
public Map<String, Long> contagemVotos(Long pautaId) {
Map<String, Long> resultado = votoRepository.findAllByPauta(pautaService.getById(pautaId))
.stream()
.map(Voto::getDecisao)
.collect(Collectors.groupingBy(Voto.Decisao::name,Collectors.counting()));
return resultado;
}
}
<file_sep>package com.joenck.votemanager.votos;
import com.joenck.votemanager.exceptions.InvalidCpfException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import lombok.extern.log4j.Log4j2;
import java.util.Map;
@Log4j2
@CrossOrigin
@RestController
@RequestMapping("/api/1")
public class VotoController {
@Autowired
VotoService votoService;
@PostMapping("/pautas/{id}/votos")
public Voto registrarVoto(@PathVariable("id") Long id, @RequestBody Map<String,String> body) {
ResponseEntity<String> response = new RestTemplate().getForEntity(String.format("https://user-info.herokuapp.com/users/%s",body.get("cpf")), String.class);
if(response.getBody().contains("UNABLE_TO_VOTE")) {
throw new InvalidCpfException(body.get("cpf"));
}
return votoService.registrarVoto(id, body.get("cpf"), body.get("decisao"));
}
@GetMapping("/pautas/{id}/votos")
public Map<String,Long> contagemVotos(@PathVariable("id") Long id) {
return votoService.contagemVotos(id);
}
}
<file_sep># Documentação API
## Pautas endpoints
Request
|Método|URL |
|:-----|:---------------------|
|POST |api/1/pautas |
Parâmetros
|Tipo |Param |Valor |
|:-----|:---------|:-----|
|BODY |descricao |string|
Response
|Status|Response |
|:-----|:------------------------------------------------------------------------------|
|200 |Exemplo:<br> `{"id":9887,"descricao":"teste performance","limiteVotacao":null}`|
|400 |`{"status": 400,"messagem": "Descrição não pode ser nula"}`|
|400 |`{"status": 400,"messagem": "Descrição não pode ser vazia"}`|
|400 |`{"status": 400,"messagem": "Descrição não pode ultrapassar de 255 caracteres"}`|
|400 |`{"status": 400,"messagem": "Formato de parametros não reconhecido"}`|
Request
|Método|URL |
|:-----|:---------------------|
|PUT |api/1/pautas/<pauta_id> |
Parâmetros
|Tipo |Param |Valor |
|:-----|:---------|:-----|
|BODY |limiteVotacao |date |
|URL_PARAM |pauta_id |number|
**limiteVotacao**<br>
formato: "yyyy-MM-dd HH:mm:ss VV" sendo VV o fuso horário<br>
somente o fuso "America/Sao_Paulo" é válido no momento
Response
|Status|Response |
|:-----|:------------------------------------------------------------------------------|
|200 |Exemplo:<br> `{"id":9887,"descricao":"teste performance","limiteVotacao":"2019-08-16T23:34:54.481-03:00"}`|
|400 |`{"status": 400,"messagem": "Formato de data inválido. Padrão esperado: yyyy-MM-dd HH:mm:ss VV no fuso horário de America/Sao_Paulo"}`|
|400 |`{"status": 400,"messagem": "Fuso horário America/Anchorag ainda não é suportado, somente America/Sao_Paulo"}`|
|400 |`{"status": 400,"messagem": "Pauta 10034 já tem uma data limite para votação"}`|
|400 |`{"status": 400,"messagem": "Formato de parametros não reconhecido"}`|
|404 |`{"status": 404,"messagem": "Nenhum dado achado com id 1 para Pauta"}`|
## Votos endpoints
Request
|Método|URL |
|:-----|:----------------------------|
|POST |api/1/pautas/<pauta_id>/votos|
Parâmetros
|Tipo |Param |Valor |
|:----------|:---------|:-----|
|BODY |decisao |string|
|BODY |cpf |string|
|URL_PARAM |pauta_id |string|
Response
|Status|Response |
|:-----|:------------------------------------------------------------------------------|
|200 |Exemplo:<br> `{"id":9887,"descricao":"teste performance","limiteVotacao":null}`|
|400 |`{"status": 400,"messagem": "Votação para pauta 1 não está aberta/disponível"}`|
|400 |`{"status": 400,"messagem": "Já existe um voto do cpf 12345678 para pauta 1"}`|
|400 |`{"status": 400,"messagem": "Decisão inválida. Escolha entre Sim e Não"}`|
|400 |`{"status": 400,"messagem": "Associado 12345678 não está apto para votar"}`|
|400 |`{"status": 400,"messagem": "Formato de parametros não reconhecido"}`|
|404 |`{"status": 404,"messagem": "Associado não existe"}`|
|404 |`{"status": 404,"messagem": "Nenhum dado achado com id 1 para Pauta"}`|
Request
|Método|URL |
|:-----|:---------------------|
|GET |api/1/pautas/<pauta_id>/votos|
Response
|Status|Response |
|:-----|:------------------------------------------------------------------------------|
|200 |Exemplo:<br> `{"SIM":2,"NÃO":"3"}`|
|404 |`{"status": 404,"messagem": "Nenhum dado achado com id 1 para Pauta"}`|
## Considerações
### Tarefa Bônus 3
Utilizei JMeter para rodar 100000 pedidos, infelizmente devido ao volume o computador não suportou o teste por muito tempo e forcei o encerramento,
segue resultados
|# Samples|Avg|Min |Max |Std. Dev.|Error %|
|:-----|:---------|:-----|:-----|:---------|:-----|
|15479|4899|2|21482|7661.38|0.10%|
### Tarefa Bônus 4
Prefiro usar o formato de versionamento "api/versão" na própria URL, este formato providência uma maneira
fácil de manter a documentação organizada por versões, flexível para alterar o backend e o usuário final consegue visualizar
versão de rapidamente.
### Configuração
usei o arquivo application.properties para manter as credencias para o banco de dados. No momento elas estão em branco e devem
ser adicionadas para a aplicação funcionar
### Logs
Usei Spring AOP para automaticamente adicionar um log no começo de métodos nos controllers e services e um log
com o resultado dos métodos de services. Escolhi usar esse módulo para reduzir a redundância de código
### Exceções
Pela mesma razão que nos logs usei a anotação @ControlleAdvice para tratar de erros de maneira centralizada e evitar
redundância de código
<file_sep>package com.joenck.votemanager.votos;
import com.joenck.votemanager.pautas.Pauta;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface VotoRepository extends JpaRepository<Voto,Long> {
List<Voto> findAllByPauta(Pauta pauta);
boolean existsByCpfAndPauta(String cpf, Pauta pauta);
}
<file_sep>package com.joenck.votemanager.pautas;
import com.joenck.votemanager.exceptions.NoDataFoundException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.junit4.SpringRunner;
import javax.validation.ConstraintViolationException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.util.List;
@RunWith(SpringRunner.class)
@DataJpaTest
public class PautaRepositoryTest {
@Autowired
private TestEntityManager entityManager;
@Autowired
private PautaRepository pautaRepository;
@Before
public void setUp(){
Pauta pautaValida = new Pauta("Votação teste 1");
Pauta pautaValida2 = new Pauta("Votação teste 2");
entityManager.persist(pautaValida);
entityManager.persist(pautaValida2);
}
@Test
public void quandoFindById_entaoRetornePauta() {
Pauta pauta = pautaRepository.findById(1L).orElseThrow(() -> new NoDataFoundException(1L,Pauta.class.getSimpleName()));
System.out.println(pauta.toString());
assertThat(pauta.getDescricao()).isEqualTo("Votação teste 1");
}
@Test
public void quandoFindAll_entaoRetorneListaPautas() {
List<Pauta> pautas = pautaRepository.findAll();
assertThat(pautas).hasSize(2);
}
@Test
public void quandoFindByIdInexistente_entaoRetorneNoDataFoundExceptionException() {
Long id = 999L;
String className = Pauta.class.getSimpleName();
assertThatExceptionOfType(NoDataFoundException.class).isThrownBy(() -> {
Pauta pauta = pautaRepository.findById(999L).orElseThrow(() -> new NoDataFoundException(id,className));
}).withMessageContaining(String.format("Nenhum dado encontrado com id %d para %s",id,className));
}
@Test
public void quandoInserirDescricaoLonga_entaoRetorneConstraintViolationException() {
assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> {
Pauta pautaInvalida = new Pauta("DescricaoExtremamenteLongaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
entityManager.persist(pautaInvalida);
entityManager.flush();
}).withMessageContaining("'size must be between 0 and 255'");
}
@Test
public void quandoInserirDescricaoNula_entaoRetorneConstraintViolationException() {
assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> {
Pauta pautaInvalida = new Pauta(null);
entityManager.persist(pautaInvalida);
entityManager.flush();
}).withMessageContaining("'must not be null'");
}
}
<file_sep>package com.joenck.votemanager.exceptions;
public class ClosedVoteException extends RuntimeException {
public ClosedVoteException(Long id) {
super(String.format("Votação para pauta %d não está aberta/disponível",id));
}
}
<file_sep>package com.joenck.votemanager.exceptions;
public class InvalidCpfException extends RuntimeException {
public InvalidCpfException(String cpf) {
super(String.format("Associado %s não está apto para votar",cpf));
}
}
| fffbdbb936925f9009d4182532e2c56292ac9655 | [
"Markdown",
"Java"
] | 9 | Java | RicardJoenck/votemanager | 6600ddceeb18e775f02af3e64fe48c37bbdbf806 | a56da933990730872f06263f24259a5fc1843067 |
refs/heads/main | <file_sep>#include<iostream>
#define _WIN32_WINNT 0x0500
#include<windows.h>
#include <ctime>
using namespace std;
int runTime=500;
void set() {
HWND hWnd = GetConsoleWindow(); //获得cmd窗口句柄
RECT rc;
GetWindowRect(hWnd, &rc); //获得cmd窗口对应矩形
//改变cmd窗口风格
SetWindowLongPtr(hWnd,
GWL_STYLE, GetWindowLong(hWnd, GWL_STYLE) & ~WS_THICKFRAME & ~WS_MAXIMIZEBOX & ~WS_MINIMIZEBOX);
//因为风格涉及到边框改变,必须调用SetWindowPos,否则无效果
SetWindowPos(hWnd,
HWND_TOPMOST,
150,
150,
rc.right - rc.left, rc.bottom - rc.top,
SWP_NOMOVE | SWP_NOSIZE);
}
int main() {
HWND hWnd = GetConsoleWindow();
system("mode con cols=19 lines=2");
system("title Clockly");
system("color 0f");
set();
int cd=200;
int nowsecond=0;
while(1) {
time_t tt = time(0);
char tmp[64];
strftime(tmp,sizeof(tmp),"%Y/%m/%d ",localtime(&tt));
cd--;
int nowtime=time(0);
int seconds=nowtime;
int minutes=seconds/60;
int hours=minutes/60;
int days=hours/24;
int months=days/30;
int year=1970+days/365;
int second=seconds-minutes*60;
int minute=minutes-hours*60;
int hour=hours-days*24+8;
int month=(months-days/365*12)/2;
int day=days-months*30-12;
if(runTime==500) {
while(year<1970) {
int q=MessageBox(hWnd,"Your computer time is incorrect. Continue?","Cot Clockly",MB_ABORTRETRYIGNORE);
if(q==3) {
return 0;
} else if(q==4) {
continue;
} else if(q==5) {
runTime--;
break;
}
}
}
if(year<1970) runTime--;
if(nowsecond!=time(0)) {
system("cls");
cout<<" Computer Time"<<endl;
cout<<tmp;
if(hour<10) {
cout<<"0"<<hour<<":";
} else {
cout<<hour<<":";
}
if(minute<10) {
cout<<"0"<<minute<<":";
} else {
cout<<minute<<":";
}
if(second<10) {
cout<<"0"<<second;
} else {
cout<<second;
}
nowsecond=time(0);
}
if(runTime<10) {
system("cls");
cout<<" ???????? Time"<<endl<<"????/??/??/ ??:??:??";
MessageBox(hWnd,"Unknown error!","Cot Clockly",MB_ICONERROR);
return 0;
}
system("title Clockly");
Sleep(20);
}
return 0;
}
<file_sep># Cot Clockly
A simple clock on windows, which floats on the foreground. Written by C++.
## Intro
Cot Clockly is a clock running on your windows system. It is light, fast and simple. It will automatically floats in the front of your tasks.
## Developing Requiments
I'm sorry. I mean Dev-cpp. | 38feabf74f062cab01115730cd49b1ea75a4fe5d | [
"Markdown",
"C++"
] | 2 | C++ | zjx2007/CLY_Cot-Clockly | 659d1dacbc87d3b27330989b5c3c60704261164c | 5328338e91288bbdeaffee473391577d94110642 |
refs/heads/master | <repo_name>Nadiavelly/-<file_sep>/дзООП.py
class Student:
students_list = []
def __init__(self, name, surname, gender):
self.name = name
self.surname = surname
self.gender = gender
self.finished_courses = []
self.courses_in_progress = []
self.grades = {}
def add_courses(self, course_name):
self.finished_courses.append(course_name)
def rate_l(self, lecturer, course, grade):
if isinstance(lecturer, Lecturer) and course in lecturer.courses_attached and course in self.courses_in_progress:
lecturer.grades += [grade]
else:
return 'Ошибка'
def aver(self):
n = 0
sum = 0
for course, grades in self.grades.items():
for gr in grades:
n +=1
sum += gr
if n != 0:
return (sum / n)
else:
print('Студент не получил еще ни одной оценки')
return 0
def __str__(self):
return 'Имя: ' + self.name + '\n' + 'Фамилия: ' + self.surname + '\n' + 'Средняя оценка за домашние задания: ' + str(
self.aver()) + '\n' + 'Курсы в процессе изучения: ' + ', '.join(self.courses_in_progress) + '\n' + 'Завершенные курсы: ' + ', '.join(self.finished_courses)
def __lt__(self, other):
if not isinstance(other, Student):
print('Not a student')
return self.aver() < other.aver()
def aver_course(self, students_list, course):
sum = 0
n = 0
for student in students_list:
for courses, grades in student.grades.items():
if courses == course:
for grade in student.grades[course]:
sum += grade
n += 1
if n != 0:
return (sum / n)
else:
print('Никто не получал оценки по этому курсу')
class Mentor:
def __init__(self, name, surname):
self.name = name
self.surname = surname
self.courses_attached = []
class Lecturer(Mentor):
lecturers_list = []
def __init__(self, name, surname):
super().__init__(name, surname)
self.grades = []
def aver(self):
sum = 0
n =0
for grade in self.grades:
sum += grade
n += 1
if n != 0:
return (sum / n)
else:
print('Никто не оценил этого лектора')
return 0
def __str__(self):
return 'Имя: ' + self.name + '\n' + 'Фамилия: ' + self.surname + '\n' + 'Средняя оценка за лекции: ' + str(self.aver())
def __lt__(self, other):
if not isinstance(other, Lecturer):
print('Not a lecturer')
return self.aver() < other.aver()
def aver_lecture(self, lecturers_list, course):
sum = 0
n = 0
for lecturer in lecturers_list:
if course in lecturer.courses_attached:
sum += lecturer.aver()
n += 1
if n != 0:
return (sum / n)
else:
print('Никто не оценил этот курс')
class Reviewer(Mentor):
def __init__(self, name, surname):
super().__init__(name, surname)
def rate_hw(self, student, course, grade):
if isinstance(student, Student) and course in self.courses_attached and course in student.courses_in_progress:
if course in student.grades:
student.grades[course] += [grade]
else:
student.grades[course] = [grade]
else:
return 'Ошибка'
def __str__(self):
return 'Имя: ' + self.name + '\n' + 'Фамилия: ' + self.surname
best_student = Student('Ruoy', 'Eman', 'your_gender')
best_student.students_list += [best_student]
best_student.courses_in_progress += ['Python']
best_student.courses_in_progress += ['Git']
best_student.finished_courses += ['Введение в программирование']
best_student_2 = Student('Nick', 'Evan', 'your_gender')
best_student_2.students_list += [best_student_2]
best_student_2.courses_in_progress += ['Python']
best_student_2.courses_in_progress += ['Git']
best_student_2.finished_courses += ['Введение в программирование']
cool_reviewer = Reviewer('Ed', 'Bud')
cool_reviewer.courses_attached += ['Python']
cool_reviewer_2 = Reviewer('Anna', 'Bale')
cool_reviewer_2.courses_attached += ['Git']
cool_lecturer = Lecturer('James', 'Croll')
cool_lecturer.lecturers_list += [cool_lecturer]
cool_lecturer.courses_attached += ['Python']
cool_lecturer_2 = Lecturer('John', 'Don')
cool_lecturer_2.lecturers_list += [cool_lecturer_2]
cool_lecturer_2.courses_attached += ['Git']
best_student.rate_l(cool_lecturer, 'Python', 10)
best_student.rate_l(cool_lecturer, 'Python',7)
best_student.rate_l(cool_lecturer, 'Python', 10)
best_student_2.rate_l(cool_lecturer_2, 'Git', 10)
best_student_2.rate_l(cool_lecturer_2, 'Git',8)
best_student_2.rate_l(cool_lecturer_2, 'Git', 10)
cool_reviewer.rate_hw(best_student, 'Python', 10)
cool_reviewer.rate_hw(best_student, 'Python', 9)
cool_reviewer.rate_hw(best_student, 'Python', 7)
cool_reviewer.rate_hw(best_student_2, 'Python', 10)
cool_reviewer.rate_hw(best_student_2, 'Python', 9)
cool_reviewer_2.rate_hw(best_student_2, 'Git', 9)
cool_reviewer_2.rate_hw(best_student_2, 'Git', 9)
print(cool_reviewer)
print(cool_lecturer)
print(best_student)
print(cool_lecturer_2)
print(best_student_2)
print(best_student < best_student_2)
print(cool_lecturer < cool_lecturer_2)
print(cool_lecturer.aver_lecture(cool_lecturer.lecturers_list, 'Python'))
print(cool_lecturer.aver_lecture(cool_lecturer.lecturers_list, 'Git'))
print(best_student.aver_course(best_student.students_list, 'Python'))
print(best_student.aver_course(best_student.students_list, 'Git'))
| a978281a320f5cd4d7b8ed84884fce6a3125b892 | [
"Python"
] | 1 | Python | Nadiavelly/- | 05d09da2d88b7ea0bef16ca75cb14730bd4fd01d | 0c2d32e0a192781a96addf5e82da434f039a8a01 |
refs/heads/master | <file_sep># Basic computation in R
2+3
6/3
(3*8)/(2*3)
log(12)
sqrt(121)
# -------------------------------------
# Variable assigment
a <- 10
b <- 20
c <- a + b
c -> y
(y) + (a * b) -> m
# -------------------------------------
# Basic data type
rm(list = ls()) # clear object
name <- 'lap;oy' # character
who <- paste(name, 'v.') # string concat
price <- 1500 # numberic
x <-1; y <-2; z <-3
# c() = combind function
v <-c(x,y,z) # double vector
bar <- 6:11 # integer vector
e <- exp(1) # create double from function
# -------------------------------------
rm(list = ls()) # clear object
# Aritmetic operators
v <- c(1,2,3)
t <- c(2,2,1)
a <- v + t # adding two vectors
s <- v - t # substracts vector
m <- v * t # multiply
d <- v / t # divide
r <- v %% t # remainder
e <- v ^ t # exponent
# Relation operators
g <- v > t # is greater?
b <- v < t # is less?
b <- v == t # is equal?
f <- v != t # is NOT equla?
# -------------------------------------
# Array
rm(list = ls()) # clear object
# 2 dimensions array
a <- array(c(1,2,3,4,5,6,7,8,9,10,11,12), dim=c(3,4))
b <- a[1,3] # get row 1 column 3 value to b
a[1,3] <- 123 # write to array element
# -------------------------------------
# Matrix
rm(list = ls()) # clear object
# create vector with 12 values
v <- c(1,2,3,4,5,6,7,8,9,10,11,12)
# create matrix from vector
m <- matrix(data = v, nrow = 3, ncol= 4)
a <- m[1,3] # access a vector
m[1,3] <- 1234 # chave vector value
# -------------------------------------
# List
rm(list = ls()) # clear object
# a list containing a number and string
e <- list(thing='hat', size=8.25)
print(e)
a1 <- e$thing # access using key
a2 <- e[[1]] # access using index
b1 <- e$size # access using key
b2 <- e[[2]] # access using index
# list can contain other list
g <- list(name='loy', age=25, e)
print(g)
# -------------------------------------
# Data frame
rm(list = ls()) # clear object
# create namne vector variable
name <- c('Loy', 'Jim', 'Bo', 'Alice', 'Tan')
# create age vector variable
age <- c(19,17,22,12,24)
# create gender vector variable
gender <- c('M', 'M', 'F', 'F', 'M')
# create data frame from vector
student <- data.frame(name, age,gender)
student$gender == 'F' # look for female student
student$age > 20 # look for student older than 20
# -------------------------------------
# If statement
rm(list = ls()) # clear object
x <- 1
if(x == 1){
print('same')
} else if(x > 1){
print('bigger')
} else {
print('smaller')
}
# ifelse function
a = c(5,7,2,9)
ifelse(a %% 2 == 0, 'even', 'odd')
# -------------------------------------
# For loop
rm(list = ls()) # clear object
x <- c(2,5,3,9.8,11,6)
# iterate through elements
for(v in x) {
print(v)
}
# count even element
count <- 0
for(val in x){
if(val %% 2 == 0)
count = count + 1
}
# -------------------------------------
# While
i <- 1
while (i < 6) {
print(i)
i = i+1
}
# -------------------------------------
# Plotting
# line chart
# Define the cars vector with 5 values
cars <- c(1, 3, 6, 4, 9)
# Graph the cars vector with all defaults
plot(cars)
# Define the cars vector with 5 values
cars <- c(1, 3, 6, 4, 9)
# Graph cars using blue points overlayed by a line
plot(cars, type="o", col="blue")
# Create a title with a red, bold/italic font
title(main="Autos", col.main="red", font.main=4)
# Define 2 vectors
cars <- c(1, 3, 6, 4, 9)
trucks <- c(2, 5, 4, 5, 12)
# Graph cars using a y axis that ranges from 0 to 12
plot(cars, type="o", col="blue", ylim=c(0,12))
# Graph trucks with red dashed line and square points
lines(trucks, type="o", pch=22, lty=2, col="red")
# Create a title with a red, bold/italic font
# Read values from tab-delimited autos.dat
autos_data <- read.table("C:/R/autos.dat", header=T, sep="\t")
# Graph autos with adjacent bars using rainbow colors
barplot(as.matrix(autos_data), main="Autos", ylab= "Total",
beside=TRUE, col=rainbow(5))
# Place the legend at the top-left corner with no frame
# using rainbow colors
legend("topleft", c("Mon","Tue","Wed","Thu","Fri"), cex=0.6,
bty="n", fill=rainbow(5));
# Define cars vector with 5 values
cars <- c(1, 3, 6, 4, 9)
# Create a pie chart for cars
pie(cars)
# Define cars vector with 5 values
cars <- c(1, 3, 6, 4, 9)
# Create a pie chart with defined heading and
# custom colors and labels
pie(cars, main="Cars", col=rainbow(length(cars)),
labels=c("Mon","Tue","Wed","Thu","Fri"))
<file_sep># Azure Machine Leanring course
Repository for Student of Microsoft Azure Machine Learning Course www.laploy.com
<br><br>
Handout text source<br>
https://notebooks.azure.com/laploy/libraries/loyml<br>
<br><br>
Azure Machine Learning course files<br>
https://github.com/laploy/ML<br>
<br><br>
Note Share (Source code and dataset)<br>
https://gist.github.com/laploy<br>
<br><br>
Titanic winapp<br>
https://github.com/laploy/ML-CS-Titanic-Winapp<br>
<br><br>
ML Python feature engineering soure code<br>
https://github.com/laploy/ML-Python-feature<br>
<br><br>
ML R feature engineering soure code<br>
https://github.com/laploy/ML-R-Feature<br>
<br><br>
Azure Machine Learning Batch Execution Example with Titanic Data set.<br>
https://github.com/laploy/ML-CS-BES<br>
<br><br>
Loy's Cortana Intelligence gallery<br>
https://gallery.cortanaintelligence.com/browse?s=laploy<br>
| 3c69d56a05e37bdaacb3a3b717c9a67785e27f77 | [
"Markdown",
"R"
] | 2 | R | josephyaman/ML | b826f9167695cd030484d0405811729367960302 | 710ba5191a696db74b6e56f7acdee97c2319fa1c |
refs/heads/main | <repo_name>ethilesen/CE-S3videostreamer<file_sep>/app.py
from flask import Flask, render_template, url_for, request, redirect
import json,boto3,botocore,os
##
app = Flask(__name__)
try:
with open('config.json', 'r') as f:
config = json.loads(f.read().strip())
endpoint = config['endpoint']
accessKey = config['accessKey']
secretAccessKey = config['secretAccessKey']
bucketName = config['bucketName']
region = config['region']
presignedURLExpiration = config['presignedURLExpiration']
except:
print('Did not find any config.json')
finally:
print('- running with variables')
endpoint = os.getenv('endpoint',"")
accessKey = os.getenv('accessKey',"")
secretAccessKey = os.getenv('secretAccessKey',"")
bucketName = os.getenv('bucketName',"")
region = os.getenv('region',"")
presignedURLExpiration = os.getenv('presignedURLExpiration',"")
def s3ClientCall():
try:
s3 = boto3.client('s3',
aws_access_key_id = accessKey,
aws_secret_access_key = secretAccessKey,
endpoint_url = endpoint,
region_name = region
)
return(s3)
except ValueError as e:
return(str(e))
@app.route('/', methods=['POST', 'GET'])
def index():
clientCall = s3ClientCall()
try:
bucketObjects = clientCall.list_objects(
Bucket = bucketName,
Delimiter = '/',
)
'''print()
print("[#] All directories/objects in main dir: ")
print(bucketObjects)
print()'''
objects = []
dirs = []
if 'ResponseMetadata' in bucketObjects and bucketObjects['ResponseMetadata']['HTTPStatusCode'] == 200:
if "Contents" in bucketObjects:
for files in bucketObjects['Contents']:
bucketKeys = files['Key']
#print(bucketKeys)
objects.append(bucketKeys)
if "CommonPrefixes" in bucketObjects:
for directories in bucketObjects['CommonPrefixes']:
bucketDirs = directories['Prefix']
#print(bucketDirs)
dirs.append(bucketDirs)
else:
print("[!] There was some issue fetching the contents of the bucket")
print(request.method, request)
# return bucketKeys, bucketDirs
return render_template('index.html', files=objects, directories=dirs)
except botocore.exceptions.ParamValidationError as e:
return render_template('error.html', exception=e)
except botocore.exceptions.ClientError as e:
return render_template('error.html', exception=e)
except AttributeError:
return render_template('error.html', exception=clientCall)
@app.route('/list', methods=['GET'])
def list():
clientCall = s3ClientCall()
directory = request.args.get('directory')
bucketObjects = clientCall.list_objects(
Bucket = bucketName,
Delimiter = '/',
Prefix = directory,
)
objects = []
dirs = []
if 'ResponseMetadata' in bucketObjects and bucketObjects['ResponseMetadata']['HTTPStatusCode'] == 200:
if "Contents" in bucketObjects:
for files in bucketObjects['Contents']:
bucketKeys = files['Key']
print(bucketKeys)
objects.append(bucketKeys)
if "CommonPrefixes" in bucketObjects:
for directories in bucketObjects['CommonPrefixes']:
bucketDirs = directories['Prefix']
print(bucketDirs)
dirs.append(bucketDirs)
else:
print("[!] There was some issue fetching the contents of the bucket")
print(request.method, request)
# return bucketKeys, bucketDirs
return render_template('index.html', files=objects, directories=dirs)
@app.route('/play', methods=['GET'])
def play():
clientCall = s3ClientCall()
objectName = request.args.get('name')
#print(objectName, type(objectName))
#clientCall = boto3.client('s3', config=Config(signature_version='s3v4'))
presignedURL = clientCall.generate_presigned_url('get_object',
Params = {
'Bucket': bucketName,
'Key': objectName
},
ExpiresIn = presignedURLExpiration
)
'''print()
print(f"[#] Presigned URL: {presignedURL}")
print()'''
return render_template('play.html', videoURL=presignedURL, objectName=objectName)
if __name__ == '__main__':
app.run(debug = True)
<file_sep>/README.md
Test S3 video streamer to run on IBM Code Engine
| c6523e36473f9067e048404388963e1a08e5b617 | [
"Markdown",
"Python"
] | 2 | Python | ethilesen/CE-S3videostreamer | c21cfa2fdb89ba622036e930f89919857a34fdda | 179c7112979a609138c9d02444e0311b0cf802b5 |
refs/heads/master | <file_sep>import React from 'react';
export default class PeopleList extends React.Component {
render() {
const { people } = this.props;
return(
<div className="row">
<table className="table table-bordered table striped">
<tbody>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
<th>Delete</th>
</tr>
{people.map((p, idx) =>
<tr key={idx}>
<td>{p.firstName}</td>
<td>{p.lastName}</td>
<td>{p.age}</td>
<td><button onClick={() => { this.props.delete(idx) }}
className="btn btn-danger">Delete Person</button></td>
</tr>
)}
</tbody>
</table>
</div>
)
}
}<file_sep>import React from 'react';
export default class PersonSubmitter extends React.Component {
render() {
return (
<div className="row">
<div className="col-md-4">
<input value={this.props.firstName}
type="text" className="form-control"
placeholder="Enter First Name"
onChange={this.props.firstNameChange}/>
<input value={this.props.lastName}
type="text" className="form-control"
placeholder="Enter Last Name"
onChange={this.props.lastNameChange}/>
<input value={this.props.age}
type="text" className="form-control"
placeholder="Enter Age"
onChange={this.props.ageChange}/>
</div>
<div className="col-md-4">
<button onClick={this.props.submitPerson}
className="btn btn-primary">Add Person</button>
<button onClick={this.props.clear}
className="btn btn-warning">Clear Textboxes</button>
<button onClick={this.props.submitClear}
className="btn btn-danger">Clear Table</button>
</div>
</div>
)
}
} | 9e2f88c12a33558dd901132e45db2ee546118fb7 | [
"JavaScript"
] | 2 | JavaScript | ChanieT/PeopleTableReact | 0765716f5085ced75671855fc6ca9cb8a622c73a | 860b78dca5403b28f9880ce3ee8340c33742a915 |
refs/heads/master | <repo_name>Tomomi1411/furima-29668<file_sep>/spec/models/user_spec.rb
require 'rails_helper'
RSpec.describe User, type: :model do
describe '#create' do
before do
@user = FactoryBot.build(:user)
end
it "nameとemail、passwordとpassword_confirmationが存在すれば登録できること" do
expect(@user).to be_valid
end
it "nameが空では登録できないこと" do
@user.name = nil
@user.valid?
expect(@user.errors.full_messages).to include("Name can't be blank")
end
it "emailが空では登録できないこと" do
@user.email = nil
@user.valid?
expect(@user.errors.full_messages).to include("Email can't be blank")
end
it"emailには@が含まれないと登録できないこと" do
@user.email = "aaaaaaaa"
@user.valid?
expect(@user.errors.full_messages).to include("Email is invalid")
end
it "passwordが空では登録できないこと" do
@user.password = nil
@user.valid?
expect(@user.errors.full_messages).to include("Password can't be blank")
end
it "passwordが存在してもpassword_confirmationが空では登録できないこと" do
@user.password_confirmation = ""
@user.valid?
expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password")
end
it "passwordが5文字以下であれば登録できない" do
@user.password = "<PASSWORD>"
@user.password_confirmation = "<PASSWORD>"
@user.valid?
expect(@user.errors.full_messages).to include("Password is too short (minimum is 6 characters)")
end
it "重複したemailが存在する場合登録できないこと" do
@user.save
another_user = FactoryBot.build(:user, email: @user.email)
another_user.valid?
expect(another_user.errors.full_messages).to include("Email has already been taken")
end
it "surnameが必須であること" do
@user.surname = ""
@user.valid?
expect(@user.errors.full_messages).to include("Surname can't be blank")
end
it "nameが全角であること" do
@user.name = "aaa"
@user.valid?
expect(@user.errors.full_messages).to include("Name is invalid. Input full-width characters.")
end
it "surnameが全角であること" do
@user.surname = "aaa"
@user.valid?
expect(@user.errors.full_messages).to include("Surname is invalid. Input full-width characters.")
end
it "name_kanaが必須であること" do
@user.name_kana = ""
@user.valid?
expect(@user.errors.full_messages).to include("Name kana can't be blank")
end
it "surname_kanaが必須であること" do
@user.surname_kana = ""
@user.valid?
expect(@user.errors.full_messages).to include("Surname kana can't be blank")
end
it "name_kanaが全角であること" do
@user.name_kana = "あああ"
@user.valid?
expect(@user.errors.full_messages).to include("Name kana is invalid. Input full-width katakana characters.")
end
it "surname_kanaが全角であること" do
@user.surname_kana = "あああ"
@user.valid?
expect(@user.errors.full_messages).to include("Surname kana is invalid. Input full-width katakana characters.")
end
it "birthが必須であること" do
@user.birth = ""
@user.valid?
expect(@user.errors.full_messages).to include("Birth can't be blank")
end
end
end
<file_sep>/spec/factories/orders_addresses.rb
FactoryBot.define do
factory :order_address do
postal_code {'557-0025'}
prefecture_id {40}
municipality {"浪速区"}
address {"青山1-1-1"}
building_name {"柳ビル"}
phone_number {'09050684705'}
token {"<KEY>"}
association :user
association :item
end
end
<file_sep>/spec/factories/items.rb
FactoryBot.define do
factory :item do
name {"名前"}
explanation {"商品説明"}
condition_id {5}
day_id {2}
price {1000000}
pay_id {2}
area_id {40}
category_id {2}
association :user
end
end<file_sep>/app/models/user.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
has_many :items
has_many :orders
REGIX = /\A[a-z0-9]+\z/i
NAMEREGIX = /\A[ぁ-んァ-ン一-龥]/
KANAREGIX = /\A[ァ-ヶーR-]+\z/
with_options presence: true do
validates :nickname, format: { with: REGIX, message: "is invalid. Input half-width characters."}
validates :password, format: { with: REGIX, message: "is invalid. Input half-width characters."}
validates :password_confirmation, format: { with: REGIX, message: "is invalid. Input half-width characters."}
validates :name, format: { with: NAMEREGIX, message: "is invalid. Input full-width characters."}
validates :surname, format: { with: NAMEREGIX, message: "is invalid. Input full-width characters."}
validates :name_kana, format: { with: KANAREGIX, message: "is invalid. Input full-width katakana characters."}
validates :surname_kana, format: { with: KANAREGIX, message: "is invalid. Input full-width katakana characters."}
validates :birth
end
end
<file_sep>/spec/models/item_spec.rb
require 'rails_helper'
RSpec.describe Item, type: :model do
before do
@item = FactoryBot.build(:item)
end
describe "出品商品情報の登録" do
it "すべての情報が正しいフォーマットで入力されていれば登録できる" do
expect(@item).to be_valid
end
it "nameが空では登録できないこと" do
@item.name = ''
@item.valid?
expect(@item.errors.full_messages).to include("Name can't be blank")
end
it "explanationが空では登録できないこと" do
@item.explanation = ''
@item.valid?
expect(@item.errors.full_messages).to include("Explanation can't be blank")
end
it"category_idが空では登録できないこと" do
@item.category_id = ''
@item.valid?
expect(@item.errors.full_messages).to include("Category is not a number")
end
it"category_idは1では登録できないこと" do
@item.category_id = '1'
@item.valid?
expect(@item.errors.full_messages).to include("Category must be other than 1")
end
it "condition_idが空では登録できないこと" do
@item.name = ''
@item.valid?
expect(@item.errors.full_messages).to include("Name can't be blank")
end
it"condition_idは1では登録できないこと" do
@item.condition_id = '1'
@item.valid?
expect(@item.errors.full_messages).to include("Condition must be other than 1")
end
it "pay_idが空では登録できないこと" do
@item.name = ''
@item.valid?
expect(@item.errors.full_messages).to include("Name can't be blank")
end
it"pay_idは1では登録できないこと" do
@item.pay_id = '1'
@item.valid?
expect(@item.errors.full_messages).to include("Pay must be other than 1")
end
it "area_idが空では登録できないこと" do
@item.area_id = ''
@item.valid?
expect(@item.errors.full_messages).to include("Area is not a number")
end
it"area_idは1では登録できないこと" do
@item.area_id = '1'
@item.valid?
expect(@item.errors.full_messages).to include("Area must be other than 1")
end
it "day_idが空では登録できないこと" do
@item.day_id = ''
@item.valid?
expect(@item.errors.full_messages).to include("Day is not a number")
end
it "day_idは1では登録できないこと" do
@item.day_id = '1'
@item.valid?
expect(@item.errors.full_messages).to include("Day must be other than 1")
end
it "priceが300円未満だと登録できないこと" do
@item.price = "299"
@item.valid?
expect(@item.errors.full_messages).to include("Price must be greater than or equal to 300")
end
it "priceが9,999,999円を超えると登録できないこと" do
@item.price = "10000000"
@item.valid?
expect(@item.errors.full_messages).to include("Price must be less than or equal to 9999999")
end
it "priceが半角数字であること" do
@item.price = "あああ"
@item.valid?
expect(@item.errors.full_messages).to include("Price is not a number")
end
end
end
<file_sep>/spec/factories/users.rb
FactoryBot.define do
factory :user do
nickname {"Tomomi"}
email {Faker::Internet.free_email}
password {F<PASSWORD>(min_length: 8)}
password_confirmation {<PASSWORD>}
surname {"眞邊"}
name {"智己"}
surname_kana{"マナベ"}
name_kana{"トモミ"}
birth{'1994-05-31'}
end
end<file_sep>/spec/models/order_address_spec.rb
require 'rails_helper'
RSpec.describe OrderAddress, type: :model do
before do
@user1 = FactoryBot.create(:user)
@user2 = FactoryBot.create(:user)
@item = FactoryBot.create(:item, user_id: @user1.id)
@orderaddress = FactoryBot.build(:order_address, user_id: @user2.id, item_id: @item.id)
end
describe "購入内容の確認" do
context "登録できるケース" do
it "すべての情報が正しいフォーマットで入力されていれば登録できる" do
expect(@orderaddress).to be_valid
end
it"building_nameが空でも登録できること" do
@orderaddress.building_name = ''
expect(@orderaddress).to be_valid
end
end
context "登録ができないケース" do
it "postal_codeが空では登録できないこと" do
@orderaddress.postal_code = ''
@orderaddress.valid?
expect(@orderaddress.errors.full_messages).to include("Postal code can't be blank")
end
it "postal_codeにはハイフンが必要であること" do
@orderaddress.postal_code = ''
@orderaddress.valid?
expect(@orderaddress.errors.full_messages).to include("Postal code can't be blank")
end
it "prefecture_idは1では登録できないこと" do
@orderaddress.prefecture_id = '1'
@orderaddress.valid?
expect(@orderaddress.errors.full_messages).to include("Prefecture must be other than 1")
end
it "prefecture_idが空では登録できないこと" do
@orderaddress.prefecture_id = ''
@orderaddress.valid?
expect(@orderaddress.errors.full_messages).to include("Prefecture can't be blank")
end
it"municipalityが空では登録できないこと" do
@orderaddress.municipality = ''
@orderaddress.valid?
expect(@orderaddress.errors.full_messages).to include("Municipality can't be blank")
end
it"addressが空では登録できないこと" do
@orderaddress.address = ''
@orderaddress.valid?
expect(@orderaddress.errors.full_messages).to include("Address can't be blank")
end
it"phone_numberが空では登録できないこと" do
@orderaddress.phone_number = ''
@orderaddress.valid?
expect(@orderaddress.errors.full_messages).to include("Phone number can't be blank")
end
it"phone_numberは11桁以内でないと登録できないこと" do
@orderaddress.phone_number = '000000000000'
@orderaddress.valid?
expect(@orderaddress.errors.full_messages).to include("Phone number is invalid")
end
end
end
end
| 503a93879e8afaaaaa49c304d901ceab3da2cd52 | [
"Ruby"
] | 7 | Ruby | Tomomi1411/furima-29668 | 17b6ad6260739bd36693ace25ab5fc2f3fb039df | 9bf01a59fa8aa9518c82d93b958f0b06e3078efa |
refs/heads/master | <repo_name>jizongFox/MCD_DA<file_sep>/MCD_DA/classification/datasets/svhn.py
from scipy.io import loadmat
import numpy as np
from ..utils.utils import dense_to_one_hot
import sys
sys.path.insert(0, 'MCD_DA/classification/data')
def load_svhn():
svhn_train = loadmat('MCD_DA/classification/data/train_32x32.mat')
svhn_test = loadmat('MCD_DA/classification/data/test_32x32.mat')
svhn_train_im = svhn_train['X']
svhn_train_im = svhn_train_im.transpose(3, 2, 0, 1).astype(np.float32)
svhn_label = dense_to_one_hot(svhn_train['y'])
svhn_test_im = svhn_test['X']
svhn_test_im = svhn_test_im.transpose(3, 2, 0, 1).astype(np.float32)
svhn_label_test = dense_to_one_hot(svhn_test['y'])
return svhn_train_im, svhn_label, svhn_test_im, svhn_label_test
<file_sep>/MCD_DA/classification/datasets/base_data_loader.py
class BaseDataLoader():
def __init__(self):
pass
def initialize(self, batch_size):
self.batch_size = batch_size
self.serial_batches = 0
self.nThreads = 2
self.max_dataset_size = float("inf")
pass
def load_data(self):
return None
<file_sep>/MCD_DA/classification/datasets/__init__.py
from .svhn import load_svhn<file_sep>/MCD_DA/visda_classification/basenet.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
# from resnet200 import Res200
# from resnext import ResNeXt
from torch.autograd import Function
from torch.autograd import Variable
from torchvision import models
class GradReverse(Function):
def __init__(self, lambd):
self.lambd = lambd
def forward(self, x):
return x.view_as(x)
def backward(self, grad_output):
return (grad_output * -self.lambd)
def grad_reverse(x, lambd=1.0):
return GradReverse(lambd)(x)
def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=False)
class ResnetBlock(nn.Module):
def __init__(self, dim, padding_type, norm_layer, use_dropout):
super(ResnetBlock, self).__init__()
self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout)
def build_conv_block(self, dim, padding_type, norm_layer, use_dropout):
conv_block = []
p = 0
# TODO: support padding types
assert (padding_type == 'zero')
p = 1
# TODO: InstanceNorm
conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p),
norm_layer(dim, affine=True),
nn.ReLU(True)]
if use_dropout:
conv_block += [nn.Dropout(0.5)]
conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p),
norm_layer(dim, affine=True)]
return nn.Sequential(*conv_block)
def forward(self, x):
out = x + self.conv_block(x)
return out
class L2Norm(nn.Module):
def __init__(self, n_channels, scale):
super(L2Norm, self).__init__()
self.n_channels = n_channels
self.gamma = scale or None
self.eps = 1e-10
self.weight = nn.Parameter(torch.Tensor(self.n_channels))
self.reset_parameters()
def reset_parameters(self):
init.constant(self.weight, self.gamma)
def forward(self, x):
norm = x.pow(2).sum(1).sqrt() + self.eps
x /= norm.expand_as(x)
out = self.weight.unsqueeze(0).expand_as(x) * x
return out
class BaseNet(nn.Module):
# Model VGG
def __init__(self):
super(BaseNet, self).__init__()
model_ft = models.vgg16(pretrained=True)
mod = list(model_ft.features.children())
self.features = nn.Sequential(*mod)
mod = list(model_ft.classifier.children())
mod.pop()
self.classifier = nn.Sequential(*mod)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), 512 * 7 * 7)
return x
class AlexNet(nn.Module):
def __init__(self):
super(AlexNet, self).__init__()
model_ft = models.alexnet(pretrained=True)
mod = list(model_ft.features.children())
self.features = model_ft.features # nn.Sequential(*mod)
print(self.features[0])
# mod = list(model_ft.classifier.children())
# mod.pop()
# self.classifier = nn.Sequential(*mod)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), 9216)
# x = self.classifier(x)
return x
class AlexNet_office(nn.Module):
def __init__(self):
super(AlexNet_office, self).__init__()
model_ft = models.alexnet(pretrained=True)
mod = list(model_ft.features.children())
self.features = model_ft.features # nn.Sequential(*mod)
mod = list(model_ft.classifier.children())
mod.pop()
print(mod)
self.classifier = nn.Sequential(*mod)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), 9216)
x = self.classifier(x)
# x = F.dropout(F.relu(self.top(x)),training=self.training)
return x
class AlexMiddle_office(nn.Module):
def __init__(self):
super(AlexMiddle_office, self).__init__()
self.top = nn.Linear(4096, 256)
def forward(self, x):
x = F.dropout(F.relu(self.top(x)), training=self.training)
return x
class AlexClassifier(nn.Module):
# Classifier for VGG
def __init__(self, num_classes=12):
super(AlexClassifier, self).__init__()
mod = []
mod.append(nn.Dropout())
mod.append(nn.Linear(4096, 256))
# mod.append(nn.BatchNorm1d(256,affine=True))
mod.append(nn.ReLU())
# mod.append(nn.Linear(256,256))
mod.append(nn.Dropout())
# mod.append(nn.ReLU())
mod.append(nn.Dropout())
# self.top = nn.Linear(256,256)
mod.append(nn.Linear(256, 31))
self.classifier = nn.Sequential(*mod)
def set_lambda(self, lambd):
self.lambd = lambd
def forward(self, x, reverse=False):
if reverse:
x = grad_reverse(x, self.lambd)
x = self.classifier(x)
return x
class Classifier(nn.Module):
# Classifier for VGG
def __init__(self, num_classes=12):
super(Classifier, self).__init__()
model_ft = models.alexnet(pretrained=False)
mod = list(model_ft.classifier.children())
mod.pop()
mod.append(nn.Linear(4096, num_classes))
self.classifier = nn.Sequential(*mod)
def forward(self, x):
x = self.classifier(x)
return x
class ClassifierMMD(nn.Module):
def __init__(self, num_classes=12):
super(ClassifierMMD, self).__init__()
model_ft = models.vgg16(pretrained=True)
mod = list(model_ft.classifier.children())
mod.pop()
self.classifier1 = nn.Sequential(*mod)
self.classifier2 = nn.Sequential(
nn.Dropout(),
nn.Linear(4096, 1000),
nn.ReLU(inplace=True),
)
self.classifier3 = nn.Sequential(
nn.BatchNorm1d(1000, affine=True),
nn.Dropout(),
nn.ReLU(inplace=True),
)
self.last = nn.Linear(1000, num_classes)
def forward(self, x):
x = self.classifier1(x)
x1 = self.classifier2(x)
x2 = self.classifier3(x1)
x3 = self.last(x2)
return x3, x2, x1
class ResBase(nn.Module):
def __init__(self, option='resnet18', pret=True):
super(ResBase, self).__init__()
self.dim = 2048
if option == 'resnet18':
model_ft = models.resnet18(pretrained=pret)
self.dim = 512
if option == 'resnet50':
model_ft = models.resnet50(pretrained=pret)
if option == 'resnet101':
model_ft = models.resnet101(pretrained=pret)
if option == 'resnet152':
model_ft = models.resnet152(pretrained=pret)
if option == 'resnet200':
model_ft = Res200()
if option == 'resnetnext':
model_ft = ResNeXt(layer_num=101)
mod = list(model_ft.children())
mod.pop()
# self.model_ft =model_ft
self.features = nn.Sequential(*mod)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), self.dim)
return x
class ResBasePlus(nn.Module):
def __init__(self, option='resnet18', pret=True):
super(ResBasePlus, self).__init__()
self.dim = 2048
if option == 'resnet18':
model_ft = models.resnet18(pretrained=pret)
self.dim = 512
if option == 'resnet50':
model_ft = models.resnet50(pretrained=pret)
if option == 'resnet101':
model_ft = models.resnet101(pretrained=pret)
if option == 'resnet152':
model_ft = models.resnet152(pretrained=pret)
if option == 'resnet200':
model_ft = Res200()
if option == 'resnetnext':
model_ft = ResNeXt(layer_num=101)
mod = list(model_ft.children())
mod.pop()
# self.model_ft =model_ft
self.layer = nn.Sequential(
nn.Dropout(),
nn.Linear(2048, 1000),
nn.ReLU(inplace=True),
nn.BatchNorm1d(1000, affine=True),
nn.Dropout(),
nn.ReLU(inplace=True),
)
self.features = nn.Sequential(*mod)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), self.dim)
x = self.layer(x)
return x
class ResNet_all(nn.Module):
def __init__(self, option='resnet18', pret=True):
super(ResNet_all, self).__init__()
self.dim = 2048
if option == 'resnet18':
model_ft = models.resnet18(pretrained=pret)
self.dim = 512
if option == 'resnet50':
model_ft = models.resnet50(pretrained=pret)
if option == 'resnet101':
model_ft = models.resnet101(pretrained=pret)
if option == 'resnet152':
model_ft = models.resnet152(pretrained=pret)
if option == 'resnet200':
model_ft = Res200()
if option == 'resnetnext':
model_ft = ResNeXt(layer_num=101)
# mod = list(model_ft.children())
# mod.pop()
# self.model_ft =model_ft
self.conv1 = model_ft.conv1
self.bn0 = model_ft.bn1
self.relu = model_ft.relu
self.maxpool = model_ft.maxpool
self.layer1 = model_ft.layer1
self.layer2 = model_ft.layer2
self.layer3 = model_ft.layer3
self.layer4 = model_ft.layer4
self.pool = model_ft.avgpool
self.fc = nn.Linear(2048, 12)
def forward(self, x, layer_return=False, input_mask=False, mask=None, mask2=None):
if input_mask:
x = self.conv1(x)
x = self.bn0(x)
x = self.relu(x)
conv_x = x
x = self.maxpool(x)
fm1 = mask * self.layer1(x)
fm2 = mask2 * self.layer2(fm1)
fm3 = self.layer3(fm2)
fm4 = self.pool(self.layer4(fm3))
x = fm4.view(fm4.size(0), self.dim)
x = self.fc(x)
return x # ,fm1
else:
x = self.conv1(x)
x = self.bn0(x)
x = self.relu(x)
conv_x = x
x = self.maxpool(x)
fm1 = self.layer1(x)
fm2 = self.layer2(fm1)
fm3 = self.layer3(fm2)
fm4 = self.pool(self.layer4(fm3))
x = fm4.view(fm4.size(0), self.dim)
x = self.fc(x)
if layer_return:
return x, fm1, fm2
else:
return x
class Mask_Generator(nn.Module):
def __init__(self):
super(Mask_Generator, self).__init__()
self.conv1 = nn.Conv2d(256, 256, kernel_size=1, stride=1, padding=0)
self.bn1 = nn.BatchNorm2d(256)
self.conv2 = nn.Conv2d(256, 256, kernel_size=1, stride=1, padding=0)
self.conv1_2 = nn.Conv2d(512, 256, kernel_size=1, stride=1, padding=0)
self.bn1_2 = nn.BatchNorm2d(256)
self.conv2_2 = nn.Conv2d(256, 512, kernel_size=1, stride=1, padding=0)
def forward(self, x, x2):
x = F.relu(self.bn1(self.conv1(x)))
x = F.sigmoid(self.conv2(x))
x2 = F.relu(self.bn1_2(self.conv1_2(x2)))
x2 = F.sigmoid(self.conv2_2(x2))
return x, x2
class ResMiddle_office(nn.Module):
def __init__(self, option='resnet18', pret=True):
super(ResMiddle_office, self).__init__()
self.dim = 2048
layers = []
layers.append(nn.Linear(self.dim, 256))
layers.append(nn.ReLU(inplace=True))
layers.append(nn.Dropout())
self.bottleneck = nn.Sequential(*layers)
# self.features = nn.Sequential(*mod)
def forward(self, x):
x = self.bottleneck(x)
return x
class ResBase_office(nn.Module):
def __init__(self, option='resnet18', pret=True):
super(ResBase_office, self).__init__()
self.dim = 2048
if option == 'resnet18':
model_ft = models.resnet18(pretrained=pret)
self.dim = 512
if option == 'resnet50':
model_ft = models.resnet50(pretrained=pret)
if option == 'resnet101':
model_ft = models.resnet101(pretrained=pret)
if option == 'resnet152':
model_ft = models.resnet152(pretrained=pret)
if option == 'resnet200':
model_ft = Res200()
if option == 'resnetnext':
model_ft = ResNeXt(layer_num=101)
# mod = list(model_ft.children())
# mod.pop()
# self.model_ft =model_ft
self.conv1 = model_ft.conv1
self.bn0 = model_ft.bn1
self.relu = model_ft.relu
self.maxpool = model_ft.maxpool
self.layer1 = model_ft.layer1
self.layer2 = model_ft.layer2
self.layer3 = model_ft.layer3
self.layer4 = model_ft.layer4
self.pool = model_ft.avgpool
# self.bottleneck = nn.Sequential(*layers)
# self.features = nn.Sequential(*mod)
def forward(self, x):
x = self.conv1(x)
x = self.bn0(x)
x = self.relu(x)
conv_x = x
x = self.maxpool(x)
fm1 = self.layer1(x)
fm2 = self.layer2(fm1)
fm3 = self.layer3(fm2)
fm4 = self.pool(self.layer4(fm3))
x = fm4.view(fm4.size(0), self.dim)
# x = self.bottleneck(x)
return x
class ResBase_D(nn.Module):
def __init__(self, option='resnet18', pret=True):
super(ResBase_D, self).__init__()
self.dim = 2048
if option == 'resnet18':
model_ft = models.resnet18(pretrained=pret)
self.dim = 512
if option == 'resnet50':
model_ft = models.resnet50(pretrained=pret)
if option == 'resnet101':
model_ft = models.resnet101(pretrained=pret)
if option == 'resnet152':
model_ft = models.resnet152(pretrained=pret)
if option == 'resnet200':
model_ft = Res200()
if option == 'resnetnext':
model_ft = ResNeXt(layer_num=101)
# mod = list(model_ft.children())
# mod.pop()
# self.model_ft =model_ft
self.conv1 = model_ft.conv1
self.bn0 = model_ft.bn1
self.relu = model_ft.relu
self.maxpool = model_ft.maxpool
self.drop0 = nn.Dropout2d()
self.layer1 = model_ft.layer1
self.drop1 = nn.Dropout2d()
self.layer2 = model_ft.layer2
self.drop2 = nn.Dropout2d()
self.layer3 = model_ft.layer3
self.drop3 = nn.Dropout2d()
self.layer4 = model_ft.layer4
self.drop4 = nn.Dropout2d()
self.pool = model_ft.avgpool
# self.features = nn.Sequential(*mod)
def forward(self, x):
x = self.conv1(x)
x = self.bn0(x)
x = self.relu(x)
x = self.drop0(x)
conv_x = x
x = self.maxpool(x)
fm1 = self.layer1(x)
x = self.drop1(x)
fm2 = self.layer2(fm1)
x = self.drop2(x)
fm3 = self.layer3(fm2)
x = self.drop3(x)
fm4 = self.pool(self.drop4(self.layer4(fm3)))
x = fm4.view(fm4.size(0), self.dim)
return x
class ResBasePararrel(nn.Module):
def __init__(self, option='resnet18', pret=True, gpu_ids=[]):
super(ResBasePararrel, self).__init__()
self.dim = 2048
if option == 'resnet18':
model_ft = models.resnet18(pretrained=pret)
self.dim = 512
if option == 'resnet50':
model_ft = models.resnet50(pretrained=pret)
if option == 'resnet101':
model_ft = models.resnet101(pretrained=pret)
if option == 'resnet152':
model_ft = models.resnet152(pretrained=pret)
if option == 'resnet200':
model_ft = Res200()
if option == 'resnetnext':
model_ft = ResNeXt(layer_num=101)
mod = list(model_ft.children())
mod.pop()
# self.model_ft =model_ft
self.gpu_ids = [0, 1]
self.features = nn.Sequential(*mod)
def forward(self, x):
x = x + Variable(torch.randn(x.size()).cuda()) * 0.05
x = nn.parallel.data_parallel(self.features, x, self.gpu_ids)
# x = self.features(x)
x = x.view(x.size(0), self.dim)
return x
class ResFreeze(nn.Module):
def __init__(self, option='resnet18', pret=True):
super(ResFreeze, self).__init__()
self.dim = 2048 * 2 * 2
if option == 'resnet18':
model_ft = models.resnet18(pretrained=pret)
self.dim = 512
if option == 'resnet50':
model_ft = models.resnet50(pretrained=pret)
if option == 'resnet101':
model_ft = models.resnet101(pretrained=pret)
if option == 'resnet152':
model_ft = models.resnet152(pretrained=pret)
if option == 'resnet200':
model_ft = Res200()
self.conv1 = model_ft.conv1
self.bn0 = model_ft.bn1
self.relu = model_ft.relu
self.maxpool = model_ft.maxpool
self.layer1 = model_ft.layer1
self.layer2 = model_ft.layer2
self.layer3 = model_ft.layer3
self.layer4 = model_ft.layer4
self.avgpool = model_ft.avgpool
def forward(self, x):
x = self.conv1(x)
x = self.bn0(x)
x = self.relu(x)
conv_x = x
x = self.maxpool(x)
pool_x = x
fm1 = self.layer1(x)
fm2 = self.layer2(fm1)
fm3 = self.layer3(fm2)
fm4 = F.max_pool2d(self.layer4(fm3), kernel_size=3)
# print(fm1)
# print(fm2)
# print(fm3)
# print(fm4)
# x = self.avgpool(fm4)
x = fm4.view(fm4.size(0), self.dim)
return x
class DenseBase(nn.Module):
def __init__(self, option='densenet201', pret=True):
super(DenseBase, self).__init__()
self.dim = 2048
if option == 'densenet201':
model_ft = models.densenet201(pretrained=pret)
self.dim = 1920
if option == 'densenet161':
model_ft = models.densenet161(pretrained=pret)
self.dim = 2208
mod = list(model_ft.children())
# mod.pop()
self.features = nn.Sequential(*mod)
def forward(self, x):
x = self.features(x)
# print x
# x = F.avg_pool2d(x,(7,7))
# x = x.view(x.size(0), self.dim)
return x
class ResClassifier(nn.Module):
def __init__(self, num_classes=13, num_layer=2, num_unit=2048, prob=0.5, middle=1000):
super(ResClassifier, self).__init__()
layers = []
# currently 10000 units
layers.append(nn.Dropout(p=prob))
layers.append(nn.Linear(num_unit, middle))
layers.append(nn.BatchNorm1d(middle, affine=True))
layers.append(nn.ReLU(inplace=True))
for i in range(num_layer - 1):
layers.append(nn.Dropout(p=prob))
layers.append(nn.Linear(middle, middle))
layers.append(nn.BatchNorm1d(middle, affine=True))
layers.append(nn.ReLU(inplace=True))
layers.append(nn.Linear(middle, num_classes))
self.classifier = nn.Sequential(*layers)
# self.classifier = nn.Sequential(
# nn.Dropout(),
# nn.Linear(2048, 1000),
# nn.BatchNorm1d(1000,affine=True),
# nn.ReLU(inplace=True),
# nn.Dropout(),
# nn.Linear(1000, 1000),
# nn.BatchNorm1d(1000,affine=True),
# nn.ReLU(inplace=True),
# nn.Linear(1000, num_classes),
def set_lambda(self, lambd):
self.lambd = lambd
def forward(self, x, reverse=False):
if reverse:
x = grad_reverse(x, self.lambd)
x = self.classifier(x)
return x
class ResClassifier_office(nn.Module):
def __init__(self, num_classes=12, num_layer=2, num_unit=2048, prob=0.5, middle=256):
super(ResClassifier_office, self).__init__()
layers = []
# currently 10000 units
layers.append(nn.Dropout(p=prob))
layers.append(nn.Linear(num_unit, middle))
layers.append(nn.BatchNorm1d(middle, affine=True))
layers.append(nn.ReLU(inplace=True))
layers.append(nn.Dropout(p=prob))
layers.append(nn.Linear(middle, num_classes))
self.classifier = nn.Sequential(*layers)
def set_lambda(self, lambd):
self.lambd = lambd
def forward(self, x, reverse=False):
if reverse:
x = grad_reverse(x, self.lambd)
x = self.classifier(x)
return x
class DenseClassifier(nn.Module):
def __init__(self, num_classes=12, num_layer=2):
super(DenseClassifier, self).__init__()
layers = []
# currently 1000 units
layers.append(nn.Dropout())
layers.append(nn.Linear(1000, 500))
layers.append(nn.BatchNorm1d(500, affine=True))
layers.append(nn.ReLU(inplace=True))
for i in range(num_layer - 1):
layers.append(nn.Dropout())
layers.append(nn.Linear(500, 500))
layers.append(nn.BatchNorm1d(500, affine=True))
layers.append(nn.ReLU(inplace=True))
layers.append(nn.Linear(500, num_classes))
# layers.append(nn.BatchNorm1d(num_classes,affine=True,momentum=0.95))
self.classifier = nn.Sequential(*layers)
# self.classifier = nn.Sequential(
# nn.Dropout(),
# nn.Linear(2048, 1000),
# nn.BatchNorm1d(1000,affine=True),
# nn.ReLU(inplace=True),
# nn.Dropout(),
# nn.Linear(1000, 1000),
# nn.BatchNorm1d(1000,affine=True),
# nn.ReLU(inplace=True),
# nn.Linear(1000, num_classes),
# )
def forward(self, x):
x = self.classifier(x)
# x = self.classifier(x)
return x
class AE(nn.Module):
def __init__(self, num_classes=12, num_layer=2, ngf=32, norm_layer=nn.BatchNorm2d):
super(AE, self).__init__()
layers = []
layers.append(nn.Dropout())
layers.append(nn.Linear(512, 32 * 8 * 8))
# layers.append(nn.BatchNorm1d(64*8*8,affine=True))
layers.append(nn.ReLU(inplace=True))
self.classifier = nn.Sequential(*layers)
n_downsampling = 5
mult = 2 ** n_downsampling
n_blocks = 3
model2 = [nn.Conv2d(32, ngf * mult, kernel_size=5,
stride=4, padding=1),
norm_layer(ngf * mult, affine=True),
nn.ReLU()]
# model2 = [nn.ConvTranspose2d(64, ngf * mult,
# kernel_size=3, stride=2,
# padding=1, output_padding=1),
# norm_layer(ngf * mult, affine=True),
# nn.ReLU()]
for i in range(n_blocks):
model2 += [ResnetBlock(ngf * mult, 'zero', norm_layer=norm_layer, use_dropout=True)]
# print ngf*mult
for i in range(n_downsampling):
mult = 2 ** (n_downsampling - i)
model2 += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2),
kernel_size=3, stride=2,
padding=1, output_padding=1),
norm_layer(int(ngf * mult / 2), affine=True),
nn.ReLU()]
# model2 += [nn.Conv2d(ngf*mult/2, ngf,
# kernel_size=1, padding=1),
# norm_layer(int(ngf), affine=True),
# nn.ReLU()]
# model2 += [nn.Conv2d(int(ngf * mult / 2), 3, kernel_size=, padding=3)]
model2 += [nn.Conv2d(ngf, 3, kernel_size=11, padding=1)]
model2 += [nn.Tanh()]
self.classifier2 = nn.Sequential(*model2)
def forward(self, x):
x = self.classifier(x)
x = x.view(x.size(0), 32, 8, 8)
x = self.classifier2(x)
return x
class InceptionBase(nn.Module):
def __init__(self):
super(InceptionBase, self).__init__()
model_ft = models.inception_v3(pretrained=True)
# mod = list(model_ft.children())
# mod.pop()
self.features = model_ft # nn.Sequential(*mod)
def forward(self, x):
x = self.features(x)
# x = x.view(x.size(0), 2048)
return x
class InceptionClassifier(nn.Module):
def __init__(self, num_classes=12, num_layer=2):
super(InceptionClassifier, self).__init__()
layers = []
layers.append(nn.Dropout())
layers.append(nn.Linear(1000, 1000))
layers.append(nn.BatchNorm1d(1000, affine=True))
layers.append(nn.ReLU(inplace=True))
for i in range(num_layer - 1):
layers.append(nn.Dropout())
layers.append(nn.Linear(1000, 1000))
layers.append(nn.BatchNorm1d(1000, affine=True))
layers.append(nn.ReLU(inplace=True))
layers.append(nn.Linear(1000, num_classes))
self.classifier = nn.Sequential(*layers)
def forward(self, x):
x = self.classifier(x)
# x = self.classifier(x)
return x
class ResClassifierMMD(nn.Module):
def __init__(self, num_classes=12):
super(ResClassifierMMD, self).__init__()
self.classifier = nn.Sequential(
nn.Linear(512, 1000),
nn.BatchNorm1d(1000, affine=True),
# nn.Dropout(),
nn.ReLU(inplace=True),
)
self.classifier2 = nn.Sequential(
nn.Linear(1000, 256),
nn.BatchNorm1d(256, affine=True),
# nn.Dropout(),
nn.ReLU(inplace=True),
)
self.last = nn.Linear(256, num_classes)
def forward(self, x):
x1 = self.classifier(x)
x2 = self.classifier2(x1)
x3 = self.last(x2)
return x3, x2, x1
class BaseShallow(nn.Module):
def __init__(self, num_classes=12):
super(BaseShallow, self).__init__()
layers = []
nc = 3
ndf = 64
self.features = nn.Sequential(
# input is (nc) x 64 x 64
nn.Conv2d(nc, ndf, 7, 2, 1, bias=False),
nn.ReLU(inplace=True),
# state size. (ndf) x 32 x 32
nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False),
# nn.BatchNorm2d(ndf * 2),
nn.ReLU(inplace=True),
# state size. (ndf*2) x 16 x 16
nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False),
# nn.BatchNorm2d(ndf * 4),
nn.ReLU(inplace=True),
# state size. (ndf*4) x 8 x 8
nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False),
# nn.BatchNorm2d(ndf * 8),
nn.ReLU(inplace=True),
# state size. (ndf*8) x 4 x 4
nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False),
)
self.last = nn.Sequential(
nn.Linear(256, num_classes),
)
def forward(self, x):
x1 = self.features(x)
x1 = x1.view(-1, 100)
# x2 = self.last(x1)
# x3 = self.last(x2)
return x1
class ClassifierShallow(nn.Module):
def __init__(self, num_classes=12):
super(ClassifierShallow, self).__init__()
self.classifier2 = nn.Sequential(
nn.Dropout(),
nn.Linear(100, 1000),
nn.ReLU(inplace=True),
nn.BatchNorm1d(1000, affine=True),
nn.Dropout(),
nn.ReLU(inplace=True),
nn.Linear(1000, num_classes),
)
def forward(self, x):
# x = self.classifier1(x)
x = self.classifier2(x)
return x
class Discriminator(nn.Module):
def __init__(self, num_classes=12):
super(Discriminator, self).__init__()
self.classifier = nn.Sequential(
nn.Dropout(),
nn.Linear(2048, 100),
nn.ReLU(inplace=True),
nn.BatchNorm1d(100, affine=True),
nn.Dropout(),
nn.ReLU(inplace=True),
nn.Linear(100, 2),
)
def forward(self, x):
# x = self.classifier1(x)
# print x
x = self.classifier(x)
return x
class EClassifier(nn.Module):
def __init__(self, num_classes=12):
super(EClassifier, self).__init__()
self.classifier = nn.Sequential(
nn.Dropout(),
nn.Linear(9216 + 12, 1000),
nn.ReLU(inplace=True),
nn.BatchNorm1d(1000, affine=True),
nn.Dropout(),
nn.ReLU(inplace=True),
nn.Linear(1000, num_classes),
)
self.classifier2 = nn.Sequential(
nn.Linear(num_classes, 12),
)
def forward(self, x1, x2):
x = torch.cat([x1, x2], 1)
x = self.classifier(x)
x_source = self.classifier2(x)
return x, x_source
class Resbridge(nn.Module):
def __init__(self, num_classes=12, num_layer=2, num_unit=2048, prob=0.5):
super(Resbridge, self).__init__()
layers = []
# currently 1000 units
layers.append(nn.Dropout(p=prob))
layers.append(nn.Linear(num_unit, 500))
layers.append(nn.BatchNorm1d(500, affine=True))
layers.append(nn.ReLU(inplace=True))
self.classifier1 = nn.Sequential(*layers)
layers2 = []
layers2.append(nn.Dropout(p=prob))
layers2.append(nn.Linear(1000, 500))
layers2.append(nn.BatchNorm1d(500, affine=True))
layers2.append(nn.ReLU(inplace=True))
for i in range(num_layer - 1):
layers2.append(nn.Dropout(p=prob))
layers2.append(nn.Linear(500, 500))
layers2.append(nn.BatchNorm1d(500, affine=True))
layers2.append(nn.ReLU(inplace=True))
layers2.append(nn.Linear(500, num_classes))
self.classifier2 = nn.Sequential(*layers2)
layers3 = []
# currently 1000 units
layers3.append(nn.Dropout(p=prob))
layers3.append(nn.Linear(num_unit, 500))
layers3.append(nn.BatchNorm1d(500, affine=True))
layers3.append(nn.ReLU(inplace=True))
self.classifier3 = nn.Sequential(*layers3)
layers4 = []
layers4.append(nn.Dropout(p=prob))
layers4.append(nn.Linear(1000, 500))
layers4.append(nn.BatchNorm1d(500, affine=True))
layers4.append(nn.ReLU(inplace=True))
for i in range(num_layer - 1):
layers4.append(nn.Dropout(p=prob))
layers4.append(nn.Linear(500, 500))
layers4.append(nn.BatchNorm1d(500, affine=True))
layers4.append(nn.ReLU(inplace=True))
layers4.append(nn.Linear(500, num_classes))
self.classifier4 = nn.Sequential(*layers4)
def forward(self, x):
x1 = self.classifier1(x)
x3 = self.classifier3(x)
x2 = torch.cat((x1, x3), 1)
x2 = self.classifier2(x2)
x4 = torch.cat((x3, x1), 1)
x4 = self.classifier4(x4)
return x2, x4
<file_sep>/setup.py
import setuptools
setuptools.setup(name='MCD_DA',
version='1.0',
description='Python Distribution Utilities',
author='<NAME>',
author_email='<EMAIL>',
url='https://www.python.org/sigs/distutils-sig/',
packages=setuptools.find_packages()
)
<file_sep>/MCD_DA/classification/model/build_gen.py
from MCD_DA.classification.model import svhn2mnist
from MCD_DA.classification.model import usps
from MCD_DA.classification.model import syn2gtrsb
# from MCD_DA.classification.model import syndig2svhn
def Generator(source, target, pixelda=False):
if source == 'usps' or target == 'usps':
return usps.Feature()
elif source == 'svhn':
return svhn2mnist.Feature()
# return svhn2mnist_Feature()
elif source == 'synth':
return syn2gtrsb.Feature()
def Classifier(source, target):
if source == 'usps' or target == 'usps':
return usps.Predictor()
if source == 'svhn':
return svhn2mnist.Predictor()
if source == 'synth':
return syn2gtrsb.Predictor()
<file_sep>/test.py
from MCD_DA.classification.datasets.base_data_loader import BaseDataLoader
from MCD_DA.classification.datasets.svhn import load_svhn
b = BaseDataLoader()
svhn = load_svhn() | 4346a2ffac3b1cb1c1238808f9a584b1eab80bac | [
"Python"
] | 7 | Python | jizongFox/MCD_DA | 5dd34a0afbcd987dcdd7cb05ec3d2543c984a748 | 08041721f33bc8944c402671d821af3199eb420a |
refs/heads/master | <file_sep>require "omniauth-ufc/version"
require "omniauth/strategies/ufc"
<file_sep>require "spec_helper"
describe OmniAuth::Strategies::Ufc do
let(:access_token) { stub('AccessToken', options: {}) }
let(:parsed_response) { stub('ParsedResponse') }
let(:response) { stub('Response', parsed: parsed_response) }
let(:enterprise_site) { 'https://some.other.site.com/api/v3' }
let(:enterprise_authorize_url) { 'https://some.other.site.com/login/oauth/authorize' }
let(:enterprise_token_url) { 'https://some.other.site.com/login/oauth/access_token' }
let(:enterprise_token_header) { 'header' }
let(:enterprise_token_param_name) { 'enterprise_token' }
let(:enterprise) do
OmniAuth::Strategies::Ufc.new('UFC_KEY', 'UFC_SECRET',
{
client_options: {
site: enterprise_site,
authorize_url: enterprise_authorize_url,
token_url: enterprise_token_url
},
access_token_options: {
header_format: enterprise_token_header,
param_name: enterprise_token_param_name
}
}
)
end
subject do
OmniAuth::Strategies::Ufc.new({})
end
before(:each) do
subject.stub!(:access_token).and_return(access_token)
end
context "client options" do
it 'should have correct site' do
subject.options.client_options.site.should eq("https://launchpad.ufcfit.com")
end
it 'should have correct authorize url' do
subject.options.client_options.authorize_url.should eq('/oauth/auth')
end
it 'should have correct token url' do
subject.options.client_options.token_url.should eq('/oauth/token')
end
describe "should be overrideable" do
it "for site" do
enterprise.options.client_options.site.should eq(enterprise_site)
end
it "for authorize url" do
enterprise.options.client_options.authorize_url.should eq(enterprise_authorize_url)
end
it "for token url" do
enterprise.options.client_options.token_url.should eq(enterprise_token_url)
end
end
end
context "access token options" do
it { expect(subject.options.access_token_options.header_format).to eq('OAuth %s') }
it { expect(subject.options.access_token_options.param_name).to eq('access_token') }
describe "should be overrideable" do
it { expect(enterprise.options.access_token_options.header_format).to eq(enterprise_token_header) }
it { expect(enterprise.options.access_token_options.param_name).to eq(enterprise_token_param_name) }
end
end
context "#raw_info" do
it "should use relative paths" do
access_token.should_receive(:get).with('/oauth/user').and_return(response)
subject.raw_info.should eq(parsed_response)
end
end
context "#info" do
context "when attributes is available" do
before do
subject.stub!(:raw_info).and_return({
'email' => '<EMAIL>',
'first_name' => 'John',
'last_name' => 'Doe',
'country' => {'alpha3' => 'USA'}
})
end
it { expect(subject.info[:email]).to eq('<EMAIL>') }
it { expect(subject.info[:first_name]).to eq('John') }
it { expect(subject.info[:last_name]).to eq('Doe') }
it { expect(subject.info[:country]).to eq({'alpha3' => 'USA'}) }
end
context "when attributes is not allowed" do
before do
subject.stub!(:raw_info).and_return({})
end
it { expect(subject.info[:email]).to be_nil }
it { expect(subject.info[:first_name]).to be_nil }
it { expect(subject.info[:first_name]).to be_nil }
it { expect(subject.info[:country]).to be_nil }
end
end
end
<file_sep>require 'omniauth-oauth2'
module OmniAuth
module Strategies
class Ufc < OmniAuth::Strategies::OAuth2
option :name, "ufc"
option :client_options, {
site: 'https://launchpad.ufcfit.com',
authorize_url: '/oauth/auth',
token_url: '/oauth/token'
}
option :access_token_options, {
header_format: 'OAuth %s',
param_name: 'access_token'
}
uid { raw_info['uid'].to_s }
info do
{
email: raw_info['email'],
first_name: raw_info['first_name'],
last_name: raw_info['last_name'],
country: raw_info['country']
}
end
extra do
{ raw_info: raw_info }
end
def raw_info
access_token.options[:mode] = :query
@raw_info ||= access_token.get('/oauth/user').parsed
end
protected
def build_access_token
super.tap do |token|
token.options.merge!(access_token_options)
end
end
def access_token_options
options.access_token_options.inject({}) { |h,(k,v)| h[k.to_sym] = v; h }
end
end
end
end
OmniAuth.config.add_camelization 'ufc', 'Ufc'
<file_sep>source 'https://rubygems.org'
gem 'rack'
gem 'sinatra'
gem 'multi_json'
gem 'omniauth-ufc', path: '../'
<file_sep># Omniauth::Ufc
This is the OmniAuth strategy for authentificating to UFCFit.
## Installation
Add this line to your application's Gemfile:
gem 'omniauth-ufc'
And then execute:
$ bundle
Or install it yourself as:
$ gem install omniauth-ufc
## Usage
Each OmniAuth strategy is a Rack Middleware. That means that you can use
it the same way that you use any other Rack middleware.
As far as OmniAuth is built for *multi-provider* authentication, it has
a room to run multiple strategies. For this, the built-in `OmniAuth::Builder`
class gives an easy way to specify multiple strategies.
```ruby
use OmniAuth::Builder do
provider :ufc, ENV['CLIENT_ID'], ENV['CLIENT_SECRET']
end
```
The following example you might put into a Rails initializer at `config/initializers/omniauth.rb`:
```ruby
Rails.application.config.middleware.use OmniAuth::Builder do
provider :developer if Rails.env.development?
provider :ufc, ENV['UFC_CLIENT_ID'], ENV['UFC_CLIENT_SECRET']
end
```
To override default options, you can pass it along with `OmniAuth::Builder`.
It can be helpful for different App environments, like development or staging:
```ruby
Rails.application.config.middleware.use OmniAuth::Builder do
provider :ufc, ENV['UFC_CLIENT_ID'], ENV['UFC_CLIENT_SECRET'],
{
client_options: {
site: "http://localhost:3001",
authorize_url: '/oauth/auth',
token_url: '/oauth/token'
}
}
end
```
<file_sep>require 'bundler/setup'
require 'sinatra/base'
require 'omniauth-ufc'
class App < Sinatra::Base
get '/' do
redirect '/auth/ufc'
end
get '/auth/:provider/callback' do
content_type 'application/json'
MultiJson.encode(request.env['omniauth.auth']) rescue "No Data"
end
get '/auth/failure' do
content_type 'text/html'
MultiJson.encode(request.env['omniauth.auth']) rescue "No Data"
end
end
use Rack::Session::Cookie, secret: ENV['RACK_COOKIE_SECRET']
use OmniAuth::Builder do
provider :ufc, ENV['CLIENT_ID'], ENV['CLIENT_SECRET'],
{ client_options: {
site: "http://localhost:3001",
authorize_url: '/oauth/auth',
token_url: '/oauth/token' }
}
end
run App.new
<file_sep>source 'https://rubygems.org'
# Specify your gem's dependencies in omniauth-ufc.gemspec
gemspec
group :development, :test do
gem "rspec"
end
| 11cb6e1ade2a16965d9d644b6ec1420e55223b30 | [
"Markdown",
"Ruby"
] | 7 | Ruby | RoR-ecommerce/omniauth | 31b726e6b340e66f3b0317db4c9863cf1ff90d26 | 914f4d3b1b6b0bff05891c6ee4f93302e45cd181 |
refs/heads/master | <repo_name>AlexHurtado23/ProgrammingTwo<file_sep>/First_plot_Python.py
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 15 19:40:34 2020
@author: <NAME>
"""
'''Make a program that prints a main plot with 3 functions.
And then one subplot for each fuction.'''
# <NAME> Data 2A
# Importing numpay and change its indicator to np
import numpy as np
# Importing matplotlib.pyplot and change its indicator to plt
import matplotlib.pyplot as plt
x = np.arange(0,11) # Defining the domain showed in the plot and subplots
y1 = np.cos(x)-1 # Initializing fuction 1
y2 = 2*np.sin(x/3.) # Initializing fuction 2
y3 = (x**2)/20.-2 # Initializing fuction 3
plt.plot(x, y1) # Adding function 1 to plot
plt.plot(x, y2) # Adding function 2 to plot
plt.plot(x, y3) # Adding function 3 to plot
plt.xlabel("X axis") # Defaining the name of x axis
plt.ylabel("Y axis") # Defaining the name of y axis
plt.title("Original Graph") # Defaining the title of the plot
plt.legend(["cos(x-1)", "2sin(x/3)", "(x^2)/20-2"]) # Defining legends
plt.show() # Showing plot on screen
plt.subplot(3,1,1) # Creting subplot
plt.plot(x,y1) # Adding function 1 to subplot
plt.xlabel("X axis") # Defaining the name of x axis
plt.ylabel("Y axis") # Defaining the name of y axis
plt.title("Function 1") # Defaining the title of the subplot
plt.legend(["cos(x-1)"]) # Defining legends
plt.show() # Showing subplot on screen
plt.subplot(3,1,2) # Creting subplot
plt.plot(x,y2) # Adding function 2 to subplot
plt.xlabel("X axis") # Defaining the name of x axis
plt.ylabel("Y axis") # Defaining the name of y axis
plt.title("Function 2") # Defaining the title of the subplot
plt.legend(["2sin(x/3)"]) # Defining legends
plt.show() # Showing subplot on screen
plt.subplot(3,1,3) # Creting subplot
plt.plot(x,y3) # Adding function 3 to subplot
plt.xlabel("X axis") # Defaining the name of x axis
plt.ylabel("Y axis") # Defaining the name of y axis
plt.title("Function 3") # Defaining the title of the subplot
plt.legend(["(x^2)/20-2"]) # Defining legends
plt.show() # Showing subplot on screen
'''
References:
https://cs231n.github.io/python-numpy-tutorial/
https://www.machinelearningplus.com/python/101-numpy-exercises-python/
'''<file_sep>/Array_Operations.py
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 15 20:17:35 2020
@author: <NAME>
"""
'''Make a program that preforms all the posible array operations
with 2 given vectors by the user'''
# <NAME> Data 2A
import numpy as np # Importing numpay and change its indicator to np
import sys # Importing system library
size_x = int(input("Length of array x: ")) # Aksing for the length of array x
size_y = int(input("Lenght of array y: ")) # Aksing for the length of array y
print("\n")
x = np.zeros((1,size_x)) # Creating array x filling it with zeros
y = np.zeros((1,size_y)) # Creating array y filling it with zeros
if (size_x != size_y): # Condition to acomplish to preform operations
print("Sorry we cannot preform the operations. Watch your sizes!")
sys.exit()
else:
# Asking for the value of each element of array x
print("Give values for array x: ")
for i in range(0,size_x):
x[0,i]= input("Element [0,"+str(i+1)+"]: ")
print("\n")
# Asking for the value of each element of array y
print("Give values for array y: ")
for i in range(0,size_y):
y[0,i]= input("Element [0,"+str(i+1)+"]: ")
print("\n")
# Showing the given arrays
print("Given arrays")
print("array x: ",x)
print("array y: ",y)
print("\n")
# Making addition of both arrays
print("Addition of the given arrays is: ",np.add(x,y))
# Making substraction of both arrays
print("Subtraction of the given arrays is: ",np.subtract(x,y))
# Making multiplication of both arrays
print("Multiplication of the given arrays is: ",np.multiply(x,y))
# Making division of both arrays
print("Division of the given arrays is: ",np.divide(x,y))
# Making the square root of array x
print("Square root of the given array x is: ",np.sqrt(x))
# Making the square root of array y
print("Square root of the given array y is:",np.sqrt(y))
'''
References:
https://cs231n.github.io/python-numpy-tutorial/
https://www.machinelearningplus.com/python/101-numpy-exercises-python/
'''<file_sep>/Pong Game.py
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 23 09:29:06 2020
@author: <NAME> Data 2A
"""
'''Pong Game'''
'''This game is only for 2 Human Players'''
'''Importing turtle Module'''
import turtle
window = turtle.Screen() # Turtle window
window.title("Pong Game") # Title of the window
window.bgcolor("black") # Color of the window
window.setup(width=800, height=600) # Size of the window
window.tracer(0) # Stops the window from updating
'''Scores'''
score_a = 0 # Score counter of Player A
score_b = 0 # Score counter of Player B
'''Paddle A'''
paddle_a = turtle.Turtle() # Paddle A is a turtle object
paddle_a.speed(0) # Speed of animation to maximum
paddle_a.shape("square") # Shape of the object
paddle_a.color("white") # Color of the object
paddle_a.shapesize(stretch_wid=5, stretch_len=1) # Size of the object
paddle_a.penup() # Don't draw any trayectory lines
paddle_a.goto(-350, 0) # Located in (-350,0)
'''Paddle B'''
paddle_b = turtle.Turtle() # Paddle B is a turtle object
paddle_b.speed(0) # Speed of animation to maximum
paddle_b.shape("square") # Shape of the object
paddle_b.color("white") # Color of the object
paddle_b.shapesize(stretch_wid=5, stretch_len=1) # Size of the object
paddle_b.penup() # Don't draw any trayectory lines
paddle_b.goto(350, 0) # Located in (350,0)
'''Ball'''
ball = turtle.Turtle() # Ball is a turtle object
ball.speed(0) # Speed of Animation to maximum
ball.shape("square") # Shape of the object
ball.color("white") # Color of the object
ball.penup() # Don't draw any trayectory lines
ball.goto(0, 0) # Located in (0,0)
ball.dx = 0.15 # Ball's X inicial speed
ball.dy = 0.15 # Ball's Y inicial speed
'''Pen'''
pen = turtle.Turtle() # Ball is a turtle object
pen.speed(0) # Speed of Animation to maximum
pen.color("white") # Color of the object
pen.penup() # Don't draw any trayectory lines
pen.hideturtle() # Make the turtle invisible
pen.goto(0,260) # Located in (0,260)
pen.write("Player A: {} Player B: {}".format(score_a, score_b), align="center", font=("Arial", 24, "normal"))
# Content of the Pen showed on screen
'''Methods'''
# Paddle A up movement
def paddle_a_up():
y = paddle_a.ycor()
y += 30
paddle_a.sety(y)
if(paddle_a.ycor()>250): # If structure avoid that the Paddle left the screen
paddle_a.sety(250)
# Paddle A down movement
def paddle_a_down():
y = paddle_a.ycor()
y -= 30
paddle_a.sety(y)
if(paddle_a.ycor()<-250): # If structure avoid that the Paddle left the screen
paddle_a.sety(-250)
# Paddle B up movement
def paddle_b_up():
y = paddle_b.ycor()
y += 30
paddle_b.sety(y)
if(paddle_b.ycor()>250): # If structure avoid that the Paddle left the screen
paddle_b.sety(250)
# Paddle B down movement
def paddle_b_down():
y = paddle_b.ycor()
y -= 30
paddle_b.sety(y)
if(paddle_b.ycor()<-250): # If structure avoid that the Paddle left the screen
paddle_b.sety(-250)
'''Keyboard blinding'''
window.listen() # Pay attention
window.onkeypress(paddle_a_up, "w") # Activete method paddle_a_up when press w
window.onkeypress(paddle_a_down, "s") # Activete method paddle_a_down when press s
window.onkeypress(paddle_b_up, "Up") # Activete method paddle_b_up when press Up
window.onkeypress(paddle_b_down, "Down") # Activete method paddle_b_down when press Down
'''Main game loop'''
while True:
window.update() # Every time the main loop runs, it updates the screen
'''Bal's movement'''
ball.setx(ball.xcor() + ball.dx) # Movement on X axis
ball.sety(ball.ycor() + ball.dy) # Movement on Y axis
'''Borders delimitation'''
# Border checking axis Y
if ball.ycor() > 290: # if the ball hits the top of the window, then it bounces down
ball.sety(290)
ball.dy *= -1
if ball.ycor() < -290: # if the ball hits the end of the window, then it bounces up
ball.sety(-290)
ball.dy *= -1
# Border checking axis X
if ball.xcor() > 390: # If the ball crosses player B's goal, return it to the center and +1 point to Player A
ball.goto(0,0)
ball.dx *= -1
score_a += 1
pen.clear()
pen.write("Player A: {} Player B: {}".format(score_a, score_b), align="center", font=("Arial", 24, "normal"))
if ball.xcor() < -390: # If the ball crosses player A's goal, return it to the center and +1 point to Player B
ball.goto(0,0)
ball.dx *= -1
score_b += 1
pen.clear()
pen.write("Player A: {} Player B: {}".format(score_a, score_b), align="center", font=("Arial", 24, "normal"))
'''Paddles Collisions'''
# Paddle B and ball collisions
# If the ball hits the Paddle B, the ball bounce back
if(ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < paddle_b.ycor() + 40 and ball.ycor() > paddle_b.ycor() -40):
ball.setx(340)
ball.dx *= -1
# Paddle A and ball collisions
# If the ball hits the Paddle A, the ball bounce back
if(ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < paddle_a.ycor() + 40 and ball.ycor() > paddle_a.ycor() -40):
ball.setx(-340)
ball.dx *= -1
'''
References:
freeCodeCamp.org(2018) Python Pong Game: https://www.youtube.com/watch?v=C6jJg9Zan7w
Python 3.3.7 Documentations: https://docs.python.org/3.3/library/turtle.html?highlight=turtle
'''<file_sep>/Tic-Tac-Toe.py
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 16 08:33:52 2020
@author: <NAME> 2A
"""
'''TIC-TAC-TOE'''
'''This game is only for 2 Human Players'''
'''Importing tkinter Module'''
from tkinter import *
from tkinter import messagebox
from tkinter import simpledialog
'''Method that blocks the buttons'''
def block():
for i in range(0,9):
button_list[i].config(state="disable") # Disables every button
''' Method that starts the game by cliking the "Start Game" button '''
def start():
for i in range(0,9):
button_list[i].config(state="normal") # Ables every button
button_list[i].config(bg="lightgray") # Change its colors
button_list[i].config(text="") # Pirnt nothing on they
t[i] = "N" # Asing N value to Check Table
'''Method that change the turn and prints on the buttons the correspondent symbol'''
def change(num): # Recibes num
global turno, P1, P2 # Using global variables to can work
if (t[num]=="N" and turno==0): # If in Check Table posicion[num] is free and is turn of Player X
button_list[num].config(text="X") # In button_list posicion[num] print "X"
button_list[num].config(bg="white") # Change its color to white
t[num] = "X" # Put in Check Table in posicion [num] an "X"
turno = 1 # Change turn
turnoPlayer.set("Turn: " + P2) # Change turn to Player X
elif (t[num]=="N" and turno==1): # If in Check Table posicion[num] is free and is turn of Player Y
button_list[num].config(text="O") # In button_list posicion[num] print "O"
button_list[num].config(bg="lightblue") # Change its color to lightblue
t[num] = "O" # Put in Check Table in posicion [num] an "O"
turno = 0 # Change turn
turnoPlayer.set("Turn: " + P1) # Change turn to Player O
button_list[num].config(state="disable") # Disable the button
verify() # Verify if someone won
'''Method that verifies when a Player wins the game'''
def verify():
global turno, P1, P2 # Using global variables to can work
# Player 1 Wins when:
if (t[0]=="X" and t[1]=="X" and t[2]=="X") or (t[3]=="X" and t[4]=="X" and t[5]=="X") or (t[6]=="X" and t[7]=="X" and t[8]=="X"):
block()
messagebox.showinfo("Winner!", "You won Player X!") # Won by Horizontal
turno = 0 # In the new game starts Player X
turnoPlayer.set("Turn: " + P1) # Change turn to Player X
elif (t[0]=="X" and t[3]=="X" and t[6]=="X") or (t[1]=="X" and t[4]=="X" and t[7]=="X") or (t[2]=="X" and t[5]=="X" and t[8]=="X"):
block()
messagebox.showinfo("Winner!", "You won Player X!") # Won by Vertical
turno = 0 # In the new game starts Player X
turnoPlayer.set("Turn: " + P1) # Change turn to Player X
elif (t[0]=="X" and t[4]=="X" and t[8]=="X") or (t[2]=="X" and t[4]=="X" and t[6]=="X"):
block()
messagebox.showinfo("Winner!", "You won Player X!") # Won by Middle Cross
turno = 0 # In the new game starts Player X
turnoPlayer.set("Turn: " + P1) # Change turn to Player X
# Player 2 Wins when:
elif (t[0]=="O" and t[1]=="O" and t[2]=="O") or (t[3]=="O" and t[4]=="O" and t[5]=="O") or (t[6]=="O" and t[7]=="O" and t[8]=="O"):
block()
messagebox.showinfo("Winner!", "You won Player O!") # Won by Horizontal
turno = 1 # In the new game starts Player O
turnoPlayer.set("Turn: " + P2) # Change turn to Player O
elif (t[0]=="O" and t[3]=="O" and t[6]=="O") or (t[1]=="O" and t[4]=="O" and t[7]=="O") or (t[2]=="O" and t[5]=="O" and t[8]=="O"):
block()
messagebox.showinfo("Winner!", "You won Player O!") # Won by Vertical
turno = 1 # In the new game starts Player O
turnoPlayer.set("Turn: " + P2) # Change turn to Player O
elif (t[0]=="O" and t[4]=="O" and t[8]=="O") or (t[2]=="O" and t[4]=="O" and t[6]=="O"):
block()
messagebox.showinfo("Winner!", "You won Player O!") # Won by Middle Cross
turno = 1 # In the new game starts Player O
turnoPlayer.set("Turn: " + P2) # Change turn to Player O
window = Tk() # Creating window
window.geometry("400x500") # Defining dimensions of window
window.title("Tic-Tac-Toe") # Defining title of window
button_list = [] # Creating a list of buttons
t = [] # X O N # Creating Check Table
P1 = "Player X" # Player X string
P2 = "Player O" # Player O string
turnoPlayer = StringVar() # Turn Player string
# Asking to users which one is going to start the game (Player X or Player O)
chose = simpledialog.askstring("Chose Order", "Press X to start as Player X or Press O to start as Player O ")
if(chose=="X" or chose=="x"):
turno = 0 # Defining first turn for Player X
turnoPlayer.set("Turn: " + P1) # Turn to Player X
elif(chose=="O" or chose=="o"):
turno = 1 # Defining first turn for Player O
turnoPlayer.set("Turn: " + P2) # Turn to Player O
# Filling Check Table with "N"s
for i in range(0,9):
t.append("N")
# Creating button0
boton0 = Button(window,width=9,height=3,command=lambda: change(0))
button_list.append(boton0) # Adding buton0 to button_list
boton0.place(x=50, y=130) # Placing button0 on window
# Creating button1
boton1 = Button(window,width=9,height=3,command=lambda: change(1))
button_list.append(boton1) # Adding buton1 to button_list
boton1.place(x=150, y=130) # Placing button1 on window
# Creating button2
boton2 = Button(window,width=9,height=3,command=lambda: change(2))
button_list.append(boton2) # Adding buton2 to button_list
boton2.place(x=250, y=130) # Placing button2 on window
# Creating button3
boton3 = Button(window,width=9,height=3,command=lambda: change(3))
button_list.append(boton3) # Adding buton3 to button_list
boton3.place(x=50, y=230) # Placing button3 on window
# Creating button4
boton4 = Button(window,width=9,height=3,command=lambda: change(4))
button_list.append(boton4) # Adding buton4 to button_list
boton4.place(x=150, y=230) # Placing button4 on window
# Creating button5
boton5 = Button(window,width=9,height=3,command=lambda: change(5))
button_list.append(boton5) # Adding buton5 to button_list
boton5.place(x=250, y=230) # Placing button5 on window
# Creating button6
boton6 = Button(window,width=9,height=3,command=lambda: change(6))
button_list.append(boton6) # Adding buton6 to button_list
boton6.place(x=50, y=330) # Placing button6 on window
# Creating button7
boton7 = Button(window,width=9,height=3,command=lambda: change(7))
button_list.append(boton7) # Adding buton7 to button_list
boton7.place(x=150, y=330) # Placing button7 on window
# Creating button8
boton8 = Button(window,width=9,height=3,command=lambda: change(8))
button_list.append(boton8) # Adding buton8 to button_list
boton8.place(x=250, y=330) # Placing button8 on window
# Note: Lambda in this case allows calling Method "change" only if the button is pressed
# Showing Title of the game
titleE = Label(window,text="Tic-Tac-Toe", font=("Arial Bold",30)).place(x=80, y= 30)
# Showing Players Turns
turnE = Label(window,textvariable=turnoPlayer).place(x=150, y =85)
# Creating start button
start_boton = Button(window,bg='#006',fg='white',text='Start Game',width=15,height=3, command= start).place(x=130,y=425)
block() # Blocks the buttton Until the Start Game will be pressed
window.mainloop() # Loop that allows the window work
'''
References:
<NAME>: https://likegeeks.com/es/ejemplos-de-la-gui-de-python/
SProgramacion: https://www.youtube.com/watch?v=ZvbB2k398kw
''' | 656b4c6898c5003d66be26300031aa1efd1b7009 | [
"Python"
] | 4 | Python | AlexHurtado23/ProgrammingTwo | 73523fc95b675bd574cdbc2c7f2822df06f47429 | d89d119513b422052650d5f6fd1dfb0195176b11 |
refs/heads/master | <repo_name>rayrinaldy/hegarsumberkreasi<file_sep>/app/models/db_connection_reference.js
var mongoose = require('mongoose'),
mongo = mongoose.connection,
dbURI = 'mongodb://localhost:27017/rayresto';
// Create the database connection
mongoose.connect(dbURI);
// CONNECTION EVENTS
// When successfully connected
mongo.on('connected', function() {
console.log('Mongoose default connection open to ' + dbURI);
});
// If the connection throws an error
mongo.on('error', function(err) {
console.log('Mongoose default connection error: ' + err);
});
// When the connection is disconnected
mongo.on('disconnected', function() {
console.log('Mongoose default connection disconnected');
});
// If the Node process ends, close the Mongoose connection
process.on('SIGINT', function() {
mongo.close(function() {
console.log('Mongoose default connection disconnected through app termination');
process.exit(0);
});
});
//SCHEMAS & MODELS
require('./../model/schema'); <file_sep>/app/models/user.js
var mongoose = require('mongoose');
module.exports = mongoose.model('User',{
username: {
type: String,
unique : true,
require : true
},
password: <PASSWORD>,
email: String,
firstName: String,
lastName: String
});
// bcrypt = require('bcrypt-nodejs'),
// Schema = mongoose.Schema;
// var userSchema = new Schema({
// local : {
// username : {
// type : String,
// unique : true,
// require : true
// },
// password : String,
// },
// facebook : {
// id : String,
// token : String,
// email : String,
// name : String
// },
// twitter : {
// id : String,
// token : String,
// displayName : String,
// username : String
// },
// google : {
// id : String,
// token : String,
// email : String,
// name : String
// }
// });
// // generating a hash
// userSchema.methods.generateHash = function(password) {
// return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
// };
// // checking if password is valid
// userSchema.methods.validPassword = function(password) {
// return bcrypt.compareSync(password, this.local.password);
// };
// var User = mongoose.model('User', userSchema);
// module.exports = User;
| b92454ee8f02140ba5ea553189e939338e583a8e | [
"JavaScript"
] | 2 | JavaScript | rayrinaldy/hegarsumberkreasi | 4b1ec40645f14cf75a24f4b6958ced704354e5e0 | c17164188ae3267d78cb24ec4964341e32267eee |
refs/heads/master | <repo_name>Kumsuraj/MoblieAutomationsuraj<file_sep>/src/test/java/com/cyient/nativeappp/InstallApp2.java
package com.cyient.nativeappp;
public class InstallApp2 {
public static void main(String[] args) {
}
}
| 68470fec24b1c67f0cc4ac22f67caf50d4c5a6ec | [
"Java"
] | 1 | Java | Kumsuraj/MoblieAutomationsuraj | 0c8fc9bfb972b1b43dbe437dc2d127ac0a794cda | 7b8c7828ccfe2665127e8fa6328f61e370e543f1 |
refs/heads/master | <file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from models import *
# Register your models here.
class TxnAdmin(admin.ModelAdmin):
pass
admin.site.register(Txn, TxnAdmin)<file_sep>Django==1.11.10
djangorestframework==3.7.7
pymongo==3.6.0
pytz==2017.3
six==1.11.0
<file_sep># -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import date
from django.db import models
class Txn(models.Model):
BatchID = models.CharField(max_length=60)
RowNumInFile = models.IntegerField()
TxnID = models.CharField(max_length=100)
AccountID = models.CharField(max_length=50)
TxnTypeCode = models.CharField(max_length=50)
PaymentType = models.CharField(max_length=50,default=None)
Channel = models.CharField(max_length=50,default=None)
IsForeignTxn = models.CharField(max_length=1)
IsCashTxn = models.CharField(max_length=1)
CashInAmount = models.DecimalField(max_digits=19, decimal_places=2)
CashOutAmount = models.DecimalField(max_digits=19, decimal_places=2,default=None)
TransferInAmount = models.DecimalField(max_digits=19, decimal_places=2,default=None)
TransferOutAmount = models.DecimalField(max_digits=19, decimal_places=2,default=None)
Amount = models.DecimalField(max_digits=19, decimal_places=2,default=None)
BaseCurrency = models.CharField(max_length=10,default=None)
CheckNumber = models.CharField(max_length=150,default=None)
EnteredDate = models.DateField(default=None)
EffectiveDate = models.DateField(default=date.today)
ReversalDate = models.DateField(default=None)
OrginalITxnCode = models.CharField(max_length=50,default=None)
ApplicationID = models.CharField(max_length=20,default=None)
SourceSystem = models.CharField(max_length=20)
UserDefined1 = models.CharField(max_length=255,default=None)
UserDefined2 = models.CharField(max_length=255,default=None)
UserDefined3 = models.CharField(max_length=255,default=None)
UserDefined4 = models.CharField(max_length=255,default=None)
UserDefined5 = models.CharField(max_length=255,default=None)
def __unicode__(self):
return self.TxnID<file_sep># -*- coding: utf-8 -*-
import json
from django.shortcuts import render
from rest_framework.views import APIView
from django.shortcuts import HttpResponse
from django.forms.models import model_to_dict
from models import Txn
# Create your views here.
from datetime import datetime
from datetime import date
from decimal import Decimal
class DatetimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime):
return obj.strftime('%Y-%m-%dT%H:%M:%SZ')
elif isinstance(obj, date):
return obj.strftime('%Y-%m-%d')
# Let the base class default method raise the TypeError
return json.JSONEncoder.default(self, obj)
class GetTxnID(APIView):
def get(self, request,format=None):
txn_id = request.GET.get('id', '')
txn_object = Txn.objects.get(TxnID=txn_id)
txn_data = model_to_dict(txn_object)
txn_data_ = dict((k,str(v)) if isinstance(v,Decimal) else (k,v) for k,v in txn_data.items())
data = {'status':200,'data':txn_data_}
return HttpResponse(json.dumps(data,cls=DatetimeEncoder),content_type="application/json")<file_sep># -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-02-01 19:06
from __future__ import unicode_literals
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Txn',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('BatchID', models.CharField(max_length=60)),
('RowNumInFile', models.IntegerField()),
('TxnID', models.CharField(max_length=100)),
('AccountID', models.CharField(max_length=50)),
('TxnTypeCode', models.CharField(max_length=50)),
('PaymentType', models.CharField(default=None, max_length=50)),
('Channel', models.CharField(default=None, max_length=50)),
('IsForeignTxn', models.CharField(max_length=1)),
('IsCashTxn', models.CharField(max_length=1)),
('CashInAmount', models.DecimalField(decimal_places=2, max_digits=19)),
('CashOutAmount', models.DecimalField(decimal_places=2, default=None, max_digits=19)),
('TransferInAmount', models.DecimalField(decimal_places=2, default=None, max_digits=19)),
('TransferOutAmount', models.DecimalField(decimal_places=2, default=None, max_digits=19)),
('Amount', models.DecimalField(decimal_places=2, default=None, max_digits=19)),
('BaseCurrency', models.CharField(default=None, max_length=10)),
('CheckNumber', models.CharField(default=None, max_length=150)),
('EnteredDate', models.DateField(default=None)),
('EffectiveDate', models.DateField(default=datetime.date.today)),
('ReversalDate', models.DateField(default=None)),
('OrginalITxnCode', models.CharField(default=None, max_length=50)),
('ApplicationID', models.CharField(default=None, max_length=20)),
('SourceSystem', models.CharField(max_length=20)),
('UserDefined1', models.CharField(default=None, max_length=255)),
('UserDefined2', models.CharField(default=None, max_length=255)),
('UserDefined3', models.CharField(default=None, max_length=255)),
('UserDefined4', models.CharField(default=None, max_length=255)),
('UserDefined5', models.CharField(default=None, max_length=255)),
],
),
]
| dd645d348628d811318bb60b587d7525eb5e3c0e | [
"Python",
"Text"
] | 5 | Python | 36rahu/oasisTxn | 5e79215e567a6ee8584db63c1574951652d89655 | 4ea324a0763b581bec8bea40d3c07d2c956d6912 |
refs/heads/master | <repo_name>jpush/jpush-flutter-plugin<file_sep>/android/src/main/java/com/jiguang/jpush/JPushEventReceiver.java
package com.jiguang.jpush;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.JPushMessage;
import cn.jpush.android.service.JPushMessageReceiver;
import io.flutter.plugin.common.MethodChannel.Result;
public class JPushEventReceiver extends JPushMessageReceiver {
@Override
public void onTagOperatorResult(Context context, final JPushMessage jPushMessage) {
super.onTagOperatorResult(context, jPushMessage);
final JSONObject resultJson = new JSONObject();
final int sequence = jPushMessage.getSequence();
try {
resultJson.put("sequence", sequence);
} catch (JSONException e) {
e.printStackTrace();
}
final Result callback = JPushPlugin.instance.callbackMap.get(sequence);//instance.eventCallbackMap.get(sequence);
if (callback == null) {
Log.i("JPushPlugin", "Unexpected error, callback is null!");
return;
}
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (jPushMessage.getErrorCode() == 0) { // success
Set<String> tags = jPushMessage.getTags();
List<String> tagList = new ArrayList<>(tags);
Map<String, Object> res = new HashMap<>();
res.put("tags", tagList);
callback.success(res);
} else {
try {
resultJson.put("code", jPushMessage.getErrorCode());
} catch (JSONException e) {
e.printStackTrace();
}
callback.error(Integer.toString(jPushMessage.getErrorCode()), "", "");
}
JPushPlugin.instance.callbackMap.remove(sequence);
}
});
}
@Override
public void onCheckTagOperatorResult(Context context, final JPushMessage jPushMessage) {
super.onCheckTagOperatorResult(context, jPushMessage);
final int sequence = jPushMessage.getSequence();
final Result callback = JPushPlugin.instance.callbackMap.get(sequence);
if (callback == null) {
Log.i("JPushPlugin", "Unexpected error, callback is null!");
return;
}
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (jPushMessage.getErrorCode() == 0) {
Set<String> tags = jPushMessage.getTags();
List<String> tagList = new ArrayList<>(tags);
Map<String, Object> res = new HashMap<>();
res.put("tags", tagList);
callback.success(res);
} else {
callback.error(Integer.toString(jPushMessage.getErrorCode()), "", "");
}
JPushPlugin.instance.callbackMap.remove(sequence);
}
});
}
@Override
public void onAliasOperatorResult(Context context, final JPushMessage jPushMessage) {
super.onAliasOperatorResult(context, jPushMessage);
final int sequence = jPushMessage.getSequence();
final Result callback = JPushPlugin.instance.callbackMap.get(sequence);
if (callback == null) {
Log.i("JPushPlugin", "Unexpected error, callback is null!");
return;
}
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
if (jPushMessage.getErrorCode() == 0) { // success
Map<String, Object> res = new HashMap<>();
res.put("alias", (jPushMessage.getAlias() == null)? "" : jPushMessage.getAlias());
callback.success(res);
} else {
callback.error(Integer.toString(jPushMessage.getErrorCode()), "", "");
}
JPushPlugin.instance.callbackMap.remove(sequence);
}
});
}
@Override
public void onNotificationSettingsCheck(Context context, boolean isOn, int source) {
super.onNotificationSettingsCheck(context, isOn, source);
HashMap<String, Object> map = new HashMap();
map.put("isEnabled",isOn);
JPushPlugin.instance.runMainThread(map,null,"onReceiveNotificationAuthorization");
}
}
<file_sep>/documents/APIs.md
[Common API](#common-api)
- [addEventHandler](#addeventhandler)
- [setup](#setup)
- [getRegistrationID](#getregistrationid)
- [stopPush](#stoppush)
- [resumePush](#resumepush)
- [setAlias](#setalias)
- [deleteAlias](#deletealias)
- [addTags](#addtags)
- [deleteTags](#deletetags)
- [setTags](#settags)
- [cleanTags](#cleantags)
- [getAllTags](getalltags)
- [sendLocalNotification](#sendlocalnotification)
- [clearAllNotifications](#clearallnotifications)
[iOS Only]()
- [applyPushAuthority](#applypushauthority)
- [setBadge](#setbadge)
- [getLaunchAppNotification](#getlaunchappnotification)
**注意:addEventHandler 方法建议放到 setup 之前,其他方法需要在 setup 方法之后调用,**
#### addEventHandler
添加事件监听方法。
```dart
JPush jpush = new JPush();
jpush.addEventHandler(
// 接收通知回调方法。
onReceiveNotification: (Map<String, dynamic> message) async {
print("flutter onReceiveNotification: $message");
},
// 点击通知回调方法。
onOpenNotification: (Map<String, dynamic> message) async {
print("flutter onOpenNotification: $message");
},
// 接收自定义消息回调方法。
onReceiveMessage: (Map<String, dynamic> message) async {
print("flutter onReceiveMessage: $message");
},
);
```
#### setup
添加初始化方法,调用 setup 方法会执行两个操作:
- 初始化 JPush SDK
- 将缓存的事件下发到 dart 环境中。
**注意:** 插件版本 >= 0.0.8 android 端支持在 setup 方法中动态设置 channel,动态设置的 channel 优先级比 manifestPlaceholders 中的 JPUSH_CHANNEL 优先级要高。
```dart
JPush jpush = new JPush();
jpush.setup(
appKey: "替换成你自己的 appKey",
channel: "theChannel",
production: false,
debug: false, // 设置是否打印 debug 日志
);
```
#### getRegistrationID
获取 registrationId,这个 JPush 运行通过 registrationId 来进行推送.
```dart
JPush jpush = new JPush();
jpush.getRegistrationID().then((rid) { });
```
#### stopPush
停止推送功能,调用该方法将不会接收到通知。
```dart
JPush jpush = new JPush();
jpush.stopPush();
```
#### resumePush
调用 stopPush 后,可以通过 resumePush 方法恢复推送。
```dart
JPush jpush = new JPush();
jpush.resumePush();
```
#### setAlias
设置别名,极光后台可以通过别名来推送,一个 App 应用只有一个别名,一般用来存储用户 id。
```
JPush jpush = new JPush();
jpush.setAlias("your alias").then((map) { });
```
#### deleteAlias
可以通过 deleteAlias 方法来删除已经设置的 alias。
```dart
JPush jpush = new JPush();
jpush.deleteAlias().then((map) {})
```
#### addTags
在原来的 Tags 列表上添加指定 tags。
```
JPush jpush = new JPush();
jpush.addTags(["tag1","tag2"]).then((map) {});
```
#### deleteTags
在原来的 Tags 列表上删除指定 tags。
```
JPush jpush = new JPush();
jpush.deleteTags(["tag1","tag2"]).then((map) {});
```
#### setTags
重置 tags。
```dart
JPush jpush = new JPush();
jpush.setTags(["tag1","tag2"]).then((map) {});
```
#### cleanTags
清空所有 tags
```dart
jpush.setTags().then((map) {});
```
#### getAllTags
获取当前 tags 列表。
```dart
JPush jpush = new JPush();
jpush.getAllTags().then((map) {});
```
#### sendLocalNotification
指定触发时间,添加本地推送通知。
```dart
// 延时 3 秒后触发本地通知。
JPush jpush = new JPush();
var fireDate = DateTime.fromMillisecondsSinceEpoch(DateTime.now().millisecondsSinceEpoch + 3000);
var localNotification = LocalNotification(
id: 234,
title: 'notification title',
buildId: 1,
content: 'notification content',
fireTime: fireDate,
subtitle: 'notification subtitle', // 该参数只有在 iOS 有效
badge: 5, // 该参数只有在 iOS 有效
extras: {"fa": "0"} // 设置 extras ,extras 需要是 Map<String, String>
);
jpush.sendLocalNotification(localNotification).then((res) {});
```
#### clearAllNotifications
清楚通知栏上所有通知。
```dart
JPush jpush = new JPush();
jpush.clearAllNotifications();
```
**iOS Only**
#### applyPushAuthority
申请推送权限,注意这个方法只会向用户弹出一次推送权限请求(如果用户不同意,之后只能用户到设置页面里面勾选相应权限),需要开发者选择合适的时机调用。
**注意: iOS10+ 可以通过该方法来设置推送是否前台展示,是否触发声音,是否设置应用角标 badge**
```dart
JPush jpush = new JPush();
jpush.applyPushAuthority(new NotificationSettingsIOS(
sound: true,
alert: true,
badge: true));
```
#### setBadge
设置应用 badge 值,该方法还会同步 JPush 服务器的的 badge 值,JPush 服务器的 badge 值用于推送 badge 自动 +1 时会用到。
```dart
JPush jpush = new JPush();
jpush.setBadge(66).then((map) {});
```
### getLaunchAppNotification
获取 iOS 点击推送启动应用的那条通知。
```dart
JPush jpush = new JPush();
jpush.getLaunchAppNotification().then((map) {});
```
<file_sep>/README.md
[]()
# JPush Flutter Plugin
> flutter 2.0 请切换至 dev-2.x 分支。
### 安装
在工程 pubspec.yaml 中加入 dependencies
```
//github 集成
dependencies:
jpush_flutter:
git:
url: git://github.com/jpush/jpush-flutter-plugin.git
ref: master
// pub 集成
dependencies:
jpush_flutter: 2.1.4
```
### 配置
##### Android:
在 `/android/app/build.gradle` 中添加下列代码:
```groovy
android: {
....
defaultConfig {
applicationId "替换成自己应用 ID"
...
ndk {
//选择要添加的对应 cpu 类型的 .so 库。
abiFilters 'armeabi', 'armeabi-v7a', 'x86', 'x86_64', 'mips', 'mips64', 'arm64-v8a',
}
manifestPlaceholders = [
JPUSH_PKGNAME : applicationId,
JPUSH_APPKEY : "appkey", // NOTE: JPush 上注册的包名对应的 Appkey.
JPUSH_CHANNEL : "developer-default", //暂时填写默认值即可.
]
}
}
```
##### iOS:
- 在 xcode8 之后需要点开推送选项: TARGETS -> Capabilities -> Push Notification 设为 on 状态
### 使用
```dart
import 'package:jpush_flutter/jpush_flutter.dart';
```
### APIs
**注意** : 需要先调用 JPush.setup 来初始化插件,才能保证其他功能正常工作。
[参考](./documents/APIs.md)
<file_sep>/android/settings.gradle
rootProject.name = 'jpush'
<file_sep>/android/src/main/java/com/jiguang/jpush/JPushPlugin.java
package com.jiguang.jpush;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import cn.jiguang.api.JCoreInterface;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.data.JPushLocalNotification;
import io.flutter.embedding.engine.plugins.FlutterPlugin;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
/**
* JPushPlugin
*/
public class JPushPlugin implements FlutterPlugin, MethodCallHandler {
private static String TAG = "| JPUSH | Flutter | Android | ";
public static JPushPlugin instance;
static List<Map<String, Object>> openNotificationCache = new ArrayList<>();
private boolean dartIsReady = false;
private boolean jpushDidinit = false;
private List<Result> getRidCache;
private Context context;
private MethodChannel channel;
public Map<Integer, Result> callbackMap;
private int sequence;
public JPushPlugin() {
this.callbackMap = new HashMap<>();
this.sequence = 0;
this.getRidCache = new ArrayList<>();
instance = this;
}
@Override
public void onAttachedToEngine(FlutterPluginBinding flutterPluginBinding) {
channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "jpush");
channel.setMethodCallHandler(this);
context = flutterPluginBinding.getApplicationContext();
}
@Override
public void onDetachedFromEngine(FlutterPluginBinding binding) {
channel.setMethodCallHandler(null);
instance.dartIsReady = false;
}
@Override
public void onMethodCall(MethodCall call, Result result) {
Log.i(TAG, call.method);
if (call.method.equals("getPlatformVersion")) {
result.success("Android " + android.os.Build.VERSION.RELEASE);
} else if (call.method.equals("setup")) {
setup(call, result);
} else if (call.method.equals("setTags")) {
setTags(call, result);
} else if (call.method.equals("cleanTags")) {
cleanTags(call, result);
} else if (call.method.equals("addTags")) {
addTags(call, result);
} else if (call.method.equals("deleteTags")) {
deleteTags(call, result);
} else if (call.method.equals("getAllTags")) {
getAllTags(call, result);
} else if (call.method.equals("setAlias")) {
setAlias(call, result);
} else if (call.method.equals("deleteAlias")) {
deleteAlias(call, result);
;
} else if (call.method.equals("stopPush")) {
stopPush(call, result);
} else if (call.method.equals("resumePush")) {
resumePush(call, result);
} else if (call.method.equals("clearAllNotifications")) {
clearAllNotifications(call, result);
} else if (call.method.equals("clearNotification")) {
clearNotification(call, result);
} else if (call.method.equals("getLaunchAppNotification")) {
getLaunchAppNotification(call, result);
} else if (call.method.equals("getRegistrationID")) {
getRegistrationID(call, result);
} else if (call.method.equals("sendLocalNotification")) {
sendLocalNotification(call, result);
} else if (call.method.equals("setBadge")) {
setBadge(call, result);
} else if (call.method.equals("isNotificationEnabled")) {
isNotificationEnabled(call, result);
} else if (call.method.equals("openSettingsForNotification")) {
openSettingsForNotification(call, result);
} else if (call.method.equals("setWakeEnable")) {
setWakeEnable(call, result);
} else {
result.notImplemented();
}
}
private void setWakeEnable(MethodCall call, Result result) {
HashMap<String, Object> map = call.arguments();
if (map == null) {
return;
}
Boolean enable = (Boolean) map.get("enable");
if (enable == null) {
enable = false;
}
JCoreInterface.setWakeEnable(context,enable);
}
// 主线程再返回数据
public void runMainThread(final Map<String, Object> map, final Result result, final String method) {
Log.d(TAG, "runMainThread:" + "map = " + map + ",method =" + method);
android.os.Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
if (result == null && method != null) {
channel.invokeMethod(method, map);
} else {
result.success(map);
}
}
});
}
public void setup(MethodCall call, Result result) {
Log.d(TAG, "setup :" + call.arguments);
HashMap<String, Object> map = call.arguments();
boolean debug = (boolean) map.get("debug");
JPushInterface.setDebugMode(debug);
JPushInterface.init(context); // 初始化 JPush
String channel = (String) map.get("channel");
JPushInterface.setChannel(context, channel);
JPushPlugin.instance.dartIsReady = true;
// try to clean getRid cache
scheduleCache();
}
public void scheduleCache() {
Log.d(TAG, "scheduleCache:");
List<Object> tempList = new ArrayList<Object>();
if (dartIsReady) {
// try to shedule notifcation cache
List<Map<String, Object>> openNotificationCacheList = JPushPlugin.openNotificationCache;
for (Map<String, Object> notification : openNotificationCacheList) {
JPushPlugin.instance.channel.invokeMethod("onOpenNotification", notification);
tempList.add(notification);
}
openNotificationCacheList.removeAll(tempList);
}
if (context == null) {
Log.d(TAG, "scheduleCache,register context is nil.");
return;
}
String rid = JPushInterface.getRegistrationID(context);
boolean ridAvailable = rid != null && !rid.isEmpty();
if (ridAvailable && dartIsReady) {
// try to schedule get rid cache
tempList.clear();
List<Result> resultList = JPushPlugin.instance.getRidCache;
for (Result res : resultList) {
Log.d(TAG, "scheduleCache rid = " + rid);
res.success(rid);
tempList.add(res);
}
resultList.removeAll(tempList);
}
}
public void setTags(MethodCall call, Result result) {
Log.d(TAG, "setTags:");
List<String> tagList = call.arguments();
Set<String> tags = new HashSet<>(tagList);
sequence += 1;
callbackMap.put(sequence, result);
JPushInterface.setTags(context, sequence, tags);
}
public void cleanTags(MethodCall call, Result result) {
Log.d(TAG, "cleanTags:");
sequence += 1;
callbackMap.put(sequence, result);
JPushInterface.cleanTags(context, sequence);
}
public void addTags(MethodCall call, Result result) {
Log.d(TAG, "addTags: " + call.arguments);
List<String> tagList = call.arguments();
Set<String> tags = new HashSet<>(tagList);
sequence += 1;
callbackMap.put(sequence, result);
JPushInterface.addTags(context, sequence, tags);
}
public void deleteTags(MethodCall call, Result result) {
Log.d(TAG, "deleteTags: " + call.arguments);
List<String> tagList = call.arguments();
Set<String> tags = new HashSet<>(tagList);
sequence += 1;
callbackMap.put(sequence, result);
JPushInterface.deleteTags(context, sequence, tags);
}
public void getAllTags(MethodCall call, Result result) {
Log.d(TAG, "getAllTags: ");
sequence += 1;
callbackMap.put(sequence, result);
JPushInterface.getAllTags(context, sequence);
}
public void setAlias(MethodCall call, Result result) {
Log.d(TAG, "setAlias: " + call.arguments);
String alias = call.arguments();
sequence += 1;
callbackMap.put(sequence, result);
JPushInterface.setAlias(context, sequence, alias);
}
public void deleteAlias(MethodCall call, Result result) {
Log.d(TAG, "deleteAlias:");
String alias = call.arguments();
sequence += 1;
callbackMap.put(sequence, result);
JPushInterface.deleteAlias(context, sequence);
}
public void stopPush(MethodCall call, Result result) {
Log.d(TAG, "stopPush:");
JPushInterface.stopPush(context);
}
public void resumePush(MethodCall call, Result result) {
Log.d(TAG, "resumePush:");
JPushInterface.resumePush(context);
}
public void clearAllNotifications(MethodCall call, Result result) {
Log.d(TAG, "clearAllNotifications: ");
JPushInterface.clearAllNotifications(context);
}
public void clearNotification(MethodCall call, Result result) {
Log.d(TAG, "clearNotification: ");
Object id = call.arguments;
if (id != null) {
JPushInterface.clearNotificationById(context, (int) id);
}
}
public void getLaunchAppNotification(MethodCall call, Result result) {
Log.d(TAG, "");
}
public void getRegistrationID(MethodCall call, Result result) {
Log.d(TAG, "getRegistrationID: ");
if (context == null) {
Log.d(TAG, "register context is nil.");
return;
}
String rid = JPushInterface.getRegistrationID(context);
if (rid == null || rid.isEmpty()) {
getRidCache.add(result);
} else {
result.success(rid);
}
}
public void sendLocalNotification(MethodCall call, Result result) {
Log.d(TAG, "sendLocalNotification: " + call.arguments);
try {
HashMap<String, Object> map = call.arguments();
JPushLocalNotification ln = new JPushLocalNotification();
ln.setBuilderId((Integer) map.get("buildId"));
ln.setNotificationId((Integer) map.get("id"));
ln.setTitle((String) map.get("title"));
ln.setContent((String) map.get("content"));
HashMap<String, Object> extra = (HashMap<String, Object>) map.get("extra");
if (extra != null) {
JSONObject json = new JSONObject(extra);
ln.setExtras(json.toString());
}
long date = (long) map.get("fireTime");
ln.setBroadcastTime(date);
JPushInterface.addLocalNotification(context, ln);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setBadge(MethodCall call, Result result) {
Log.d(TAG, "setBadge: " + call.arguments);
HashMap<String, Object> map = call.arguments();
Object numObject = map.get("badge");
if (numObject != null) {
int num = (int) numObject;
JPushInterface.setBadgeNumber(context, num);
result.success(true);
}
}
/// 检查当前应用的通知开关是否开启
private void isNotificationEnabled(MethodCall call, Result result) {
Log.d(TAG, "isNotificationEnabled: ");
int isEnabled = JPushInterface.isNotificationEnabled(context);
//1表示开启,0表示关闭,-1表示检测失败
HashMap<String, Object> map = new HashMap();
map.put("isEnabled", isEnabled == 1 ? true : false);
runMainThread(map, result, null);
}
private void openSettingsForNotification(MethodCall call, Result result) {
Log.d(TAG, "openSettingsForNotification: ");
JPushInterface.goToAppNotificationSettings(context);
}
/**
* 接收自定义消息,通知,通知点击事件等事件的广播
* 文档链接:http://docs.jiguang.cn/client/android_api/
*/
public static class JPushReceiver extends BroadcastReceiver {
private static final List<String> IGNORED_EXTRAS_KEYS = Arrays.asList("cn.jpush.android.TITLE",
"cn.jpush.android.MESSAGE", "cn.jpush.android.APPKEY", "cn.jpush.android.NOTIFICATION_CONTENT_TITLE", "key_show_entity", "platform");
public JPushReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(JPushInterface.ACTION_REGISTRATION_ID)) {
String rId = intent.getStringExtra(JPushInterface.EXTRA_REGISTRATION_ID);
Log.d("JPushPlugin", "on get registration");
JPushPlugin.transmitReceiveRegistrationId(rId);
} else if (action.equals(JPushInterface.ACTION_MESSAGE_RECEIVED)) {
handlingMessageReceive(intent);
} else if (action.equals(JPushInterface.ACTION_NOTIFICATION_RECEIVED)) {
handlingNotificationReceive(context, intent);
} else if (action.equals(JPushInterface.ACTION_NOTIFICATION_OPENED)) {
handlingNotificationOpen(context, intent);
}
}
private void handlingMessageReceive(Intent intent) {
Log.d(TAG, "handlingMessageReceive " + intent.getAction());
String msg = intent.getStringExtra(JPushInterface.EXTRA_MESSAGE);
Map<String, Object> extras = getNotificationExtras(intent);
JPushPlugin.transmitMessageReceive(msg, extras);
}
private void handlingNotificationOpen(Context context, Intent intent) {
Log.d(TAG, "handlingNotificationOpen " + intent.getAction());
String title = intent.getStringExtra(JPushInterface.EXTRA_NOTIFICATION_TITLE);
String alert = intent.getStringExtra(JPushInterface.EXTRA_ALERT);
Map<String, Object> extras = getNotificationExtras(intent);
JPushPlugin.transmitNotificationOpen(title, alert, extras);
Intent launch = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
if (launch != null) {
launch.addCategory(Intent.CATEGORY_LAUNCHER);
launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
context.startActivity(launch);
}
}
private void handlingNotificationReceive(Context context, Intent intent) {
Log.d(TAG, "handlingNotificationReceive " + intent.getAction());
String title = intent.getStringExtra(JPushInterface.EXTRA_NOTIFICATION_TITLE);
String alert = intent.getStringExtra(JPushInterface.EXTRA_ALERT);
Map<String, Object> extras = getNotificationExtras(intent);
JPushPlugin.transmitNotificationReceive(title, alert, extras);
}
private Map<String, Object> getNotificationExtras(Intent intent) {
Log.d(TAG, "");
Map<String, Object> extrasMap = new HashMap<String, Object>();
for (String key : intent.getExtras().keySet()) {
if (!IGNORED_EXTRAS_KEYS.contains(key)) {
if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
extrasMap.put(key, intent.getIntExtra(key, 0));
} else {
extrasMap.put(key, intent.getStringExtra(key));
}
}
}
return extrasMap;
}
}
static void transmitMessageReceive(String message, Map<String, Object> extras) {
Log.d(TAG, "transmitMessageReceive " + "message=" + message + "extras=" + extras);
if (instance == null) {
return;
}
Map<String, Object> msg = new HashMap<>();
msg.put("message", message);
msg.put("extras", extras);
JPushPlugin.instance.channel.invokeMethod("onReceiveMessage", msg);
}
static void transmitNotificationOpen(String title, String alert, Map<String, Object> extras) {
Log.d(TAG, "transmitNotificationOpen " + "title=" + title + "alert=" + alert + "extras=" + extras);
Map<String, Object> notification = new HashMap<>();
notification.put("title", title);
notification.put("alert", alert);
notification.put("extras", extras);
JPushPlugin.openNotificationCache.add(notification);
if (instance == null) {
Log.d("JPushPlugin", "the instance is null");
return;
}
if (instance.dartIsReady) {
Log.d("JPushPlugin", "instance.dartIsReady is true");
JPushPlugin.instance.channel.invokeMethod("onOpenNotification", notification);
JPushPlugin.openNotificationCache.remove(notification);
}
}
static void transmitNotificationReceive(String title, String alert, Map<String, Object> extras) {
Log.d(TAG, "transmitNotificationReceive " + "title=" + title + "alert=" + alert + "extras=" + extras);
if (instance == null) {
return;
}
Map<String, Object> notification = new HashMap<>();
notification.put("title", title);
notification.put("alert", alert);
notification.put("extras", extras);
JPushPlugin.instance.channel.invokeMethod("onReceiveNotification", notification);
}
static void transmitReceiveRegistrationId(String rId) {
Log.d(TAG, "transmitReceiveRegistrationId: " + rId);
if (instance == null) {
return;
}
JPushPlugin.instance.jpushDidinit = true;
// try to clean getRid cache
JPushPlugin.instance.scheduleCache();
}
}
<file_sep>/CHANGELOG.md
## 2.1.4
+ 新增:Android push 新增 setWakeEnable 接口
## 2.1.2
+ 升级:升级 android push 4.0.8 jcore 2.8.2,ios push 3.6.1,jcore 2.6.2。
## 2.0.9
+ 适配:处理 demo 运行时报错。
## 2.0.7
+ 适配:适配 null safety
## 2.0.5
+ 升级:android jcore 升级 2.7.8
## 2.0.3
+ 升级:android push 升级4.0.6,ios push 升级 3.5.2
## 2.0.1
+ 适配Flutter 2.0,Flutter 2.0 以下版本请使用 0.6.3版本
## 0.6.3
+ 修复:Android端获取RegistrationID偶现奔溃问题
## 0.6.2
+ 同步更最新版本SDK
## 0.6.1
+ 修复:Android 端 context为空时的crash问题
## 0.6.0
+ 修复:修复已知bug
## 0.5.9
+ 适配最新版本 JPush SDK Android 3.8.0 , IOS 3.3.6
## 0.5.6
+ 修复:iOS点击本地通知的通知栏消息缺少extras 字段
## 0.5.5
+ 适配iOS点击本地通知的通知栏消息响应事件
+ 更新最新Android SDK
## 0.5.3
+ 修复一个可能引起崩溃的日志打印代码
## 0.5.2
+ 内部安全策略优化
+ 同步 JPush SDK 版本
## 0.5.1
+ 修改 minSdkVersion 最小支持 17
## 0.5.0
+ 适配最新版本 JPush SDK
+ 适配新版 SDK 的新功能接口
## 0.3.0
+ 新增:清除通知栏单条通知方法
+ 修复:点击通知栏无法获取消息问题
+ 同步最新版 SDK
## 0.2.0
+ 适配最新版本 JPush SDK
+ Android 支持设置角标 badge
## 0.1.0
+ 修复:调用 sendLocalNotification 接口 crash 问题;
+ 修复:iOS 启动 APP 角标自动消失问题;
+ 修复执行 flutter build apk 打包错误问题;
+ 更新配置
## 0.0.13
featurn:
适配flutter 1.7.8
升级 jpush sdk 版本为3.3.4
## 0.0.12
featurn: 修改LocalNotification的属性名为"extra"
## 0.0.11
iOS: 修复 getLaunchAppNotification 返回 null 的情况。
featurn: APNS 推送字段将 extras 字段移动到 notification.extras 中和 android 保持一致。
## 0.0.9
android: 修复 JPushReceiver 类型转换的错误。
## 0.0.8
更新 setup 方法,android 端现在支持 channel 字段,用于动态设置 channel,和 iOS 保持一致。
注意通过 setup 设置 的 channel 会覆盖 manifestPlaceholders 中的 JPUSH_CHANNEL 字段。
## 0.0.7
修改 setup 方法,添加 boolean debug 参数,如果 debug 为 true 这打印日志,如果为 false 则不打印日志。
## 0.0.6
增加 swift 工程支持。
## 0.0.3
添加 localnotification api。
## 0.0.2
修复 android 类名文件名不匹配问题。
## 0.0.1
第一个版本。
| 08e8b8de55753efc66b76d60376d522dc481ffcc | [
"Markdown",
"Java",
"Gradle"
] | 6 | Java | jpush/jpush-flutter-plugin | 61f19f4695a2ced7d887d219351311848bfeae03 | 47daae3d5acb002269a720892c2a8491294a70ab |
refs/heads/master | <file_sep>set('Mississippi')<file_sep>x = open ('test.txt', 'w')
x.write('Hello World')
x.close()<file_sep># hello-world
a=10
a=a+a
type(a)
<file_sep>"Python rule{}!".format("s")<file_sep>a=10
a+a=a
type(a)<file_sep>"Hello World"[8]<file_sep>"tinker"[1:4] | 6f10ce7d3ca98091e5ba71d4826f271337dff840 | [
"Markdown",
"Python"
] | 7 | Python | treysmith170/hello-world | cfb51858e861b5a7d5656e5127a874ebfa31eacc | de14de47e5e3e68937d89078bfa2ecb6f6f2ec23 |
refs/heads/master | <file_sep>MaaSAlerts Change Log
==========
Version 1.3.2 *(2016-11-15)*
----------------------------
* Fix for PROD alerts
Version 1.3.1 *(2016-10-05)*
----------------------------
* Update Google Play Service to 9.6.1
* Updated to Core 3.0.2
Version 1.3.0 *(2016-08-01)*
----------------------------
* Build script enhancements
* Updated to Core 3.0.0
* Bug fixes in base and s3 URLs
Version 1.2.9 *(2015-09-30)*
----------------------------
* Change phunware.com endpoints to HTTPS.
* Rename the lib name from MaaSAlerts.jar to PWAlerts.jar.
Version 1.2.8 *(2015-01-26)*
----------------------------
* Change to using the GoogleCloudMessaging class instead of deprecated GCMRegistar class.
Version 1.2.6 *(2014-02-26)*
----------------------------
* Fixed builds to produce Java 6 compatible binaries using 'sourceCompatibility' and 'targetCompatibility' equal to '1.6'.
* Requires MaaSCore v1.3.5
Version 1.2.5 *(2014-01-30)*
----------------------------
* Adding support for custom locations for extra data associated with alerts.
Version 1.2.4 *(2013-11-08)*
----------------------------
* Hotfix to temporarily re-register alerts on each application launch.
Version 1.2.3 *(2013-11-08)*
----------------------------
* Updating subscriptions to use schema 1.2
Version 1.2.2 *(2013-10-23)*
----------------------------
* Updating subscriptions to use schema 1.1
Version 1.2.1
----------------------------
* Requires Core 1.3.1
* Optimizing network calls.
Version 1.2.0 *(2013-10-17)*
----------------------------
Reducing interaction between SDK and GCM when an alert is received.
* Removed `onMessageAlerts` and `onMessageAlertsError` methods.
* Callback for alerts now come through `onMessage(context, extras)`.
Version 1.1.3 *(2013-09-24)*
----------------------------
* Removed abstract method "onAlertMessageWithoutPayload" from PwAlertsIntentServices
Version 1.1.2 *(2013-09-23)*
----------------------------
* Now handles push messages without associated S3 payload.
<file_sep>package com.phunware.alerts.sample;
import java.util.ArrayList;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.phunware.alerts.PwAlertsSubscriptions;
import com.phunware.alerts.models.PwSubscription;
import com.phunware.alerts.sample.ConsoleOutput.ConsoleLogger;
import com.phunware.core.PwLog;
import com.phunware.core.exceptions.PwException;
public class SubscriptionsFragment extends ListFragment {
public final static String TAG = "SubscriptionsFragment";
private ArrayList<PwSubscription> mAllSubscriptions;
private SubscriptionAdapter mAdapter;
private View mListLayout, mProgressLayout;
private ConsoleLogger mConsole;
private static final String SP_SUBSCRIPTION_PREFIX = "!@#";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_subscriptions,
container, false);
setHasOptionsMenu(true);
mListLayout = view.findViewById(R.id.list_layout);
mProgressLayout = view.findViewById(R.id.progress_layout);
return view;
}
@Override
public void onAttach(Activity activity) {
if (!(activity instanceof ConsoleLogger))
throw new RuntimeException(
"SubscriptionsFragment's Activity must implement ConsoleLogger");
mConsole = (ConsoleLogger) activity;
super.onAttach(activity);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// check for saved list
boolean getSubscriptions = false;
if (savedInstanceState != null) {
mAllSubscriptions = savedInstanceState
.getParcelableArrayList("subs");
if (mAllSubscriptions == null) {
getSubscriptions = true;
mAllSubscriptions = new ArrayList<PwSubscription>();
} else
updateSubscriptionListState();
} else // no saved data
{
getSubscriptions = true;
mAllSubscriptions = new ArrayList<PwSubscription>();
}
// set list adapter
mAdapter = new SubscriptionAdapter();
setListAdapter(mAdapter);
// get subscriptions if they haven't been obtained already
// this is being called after the list has been initialized.
if (getSubscriptions)
fetchSubscriptions();
else {
mAdapter.notifyDataSetChanged();
hideLoading();
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putParcelableArrayList("subs", mAllSubscriptions);
super.onSaveInstanceState(outState);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main, menu);
menu.getItem(Utils.MENU_INDEX_CLEAR).setVisible(false);
menu.getItem(Utils.MENU_INDEX_EMAIL).setVisible(false);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_refresh) {
mAllSubscriptions.clear();
fetchSubscriptions();
return true;
}
else if (id == R.id.menu_update) {
saveSubscriptions();
return true;
}
return super.onOptionsItemSelected(item);
}
// ListView Adapter
private class SubscriptionAdapter extends BaseAdapter {
@Override
public int getCount() {
return mAllSubscriptions.size();
}
@Override
public PwSubscription getItem(int position) {
return mAllSubscriptions.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.subscription, parent, false);
holder = new ViewHolder();
holder.switchView = (CompoundButton) convertView
.findViewById(R.id.subscriptionSwitch);
holder.title = (TextView) convertView
.findViewById(R.id.subscriptionText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Update UI
String name = getItem(position).getName();
holder.title.setText(name);
holder.switchView
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// Update the changes made by the user to the
// subscription list.
PwLog.d("Phun_Alerts",
"OnCheckedChanged: Position=" + position
+ " isChecked=" + isChecked);
mAllSubscriptions.get(position).setIsSubscribed(isChecked);
}
});
holder.switchView.setChecked(getItem(position).isSubscribed());
return convertView;
}
private final class ViewHolder {
CompoundButton switchView;
TextView title;
}
}
/**
* Helper method to asynchronously get subscriptions
*/
private void fetchSubscriptions() {
showLoading();
new AsyncTask<Void, String, String>() {
@Override
protected String doInBackground(Void... params) {
try {
// Retrieve the subscription list.
mAllSubscriptions = new ArrayList<PwSubscription>(
PwAlertsSubscriptions
.getSubscriptionGroups(getActivity()));
} catch (PwException e) {
return "Failed! " + e.getMessage();
}
return "Success! Found subscription group.";
}
@Override
protected void onPostExecute(String result) {
PwLog.d(TAG, "Fetch subscription lists. Result is " + result);
mConsole.printToConsole("Fetch subscription lists. Result is "
+ result);
updateSubscriptionListState();
mAdapter.notifyDataSetChanged();
hideLoading();
}
}.execute();
}
/**
* Helper method to asynchronously save the subscription data
*/
private void saveSubscriptions() {
showLoading();
new AsyncTask<Void, String, String>() {
@Override
protected String doInBackground(Void... params) {
try {
// Save the subscription list. This call will tell the
// server to wipe out the subscription settings and replace
// it with the one from the client.
PwAlertsSubscriptions.saveSubscriptions(getActivity(),
mAllSubscriptions);
} catch (PwException e) {
return "Failed to update subscription list! "
+ e.getMessage();
}
return "Success! Updated subscription list.";
}
@Override
protected void onPostExecute(String result) {
PwLog.d(TAG, "Update subscription lists. Result is " + result);
mConsole.printToConsole("Update subscription lists. Result is "
+ result);
if (result.contains("Success")) {
// save settings to shared prefs
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
SharedPreferences.Editor edit = sp.edit();
for (PwSubscription s : mAllSubscriptions) {
edit.putBoolean(SP_SUBSCRIPTION_PREFIX + s.getId(),
s.isSubscribed());
Log.v(TAG,
"saving preference: "
+ SP_SUBSCRIPTION_PREFIX
+ s.getId()
+ " = "
+ sp.getBoolean(SP_SUBSCRIPTION_PREFIX
+ s.getId(), false)
+ " and should be " + s.isSubscribed());
}
edit.commit();
} else {
Toast.makeText(
getActivity(),
"Failed to update subscriptions, please try again later...",
Toast.LENGTH_SHORT).show();
}
hideLoading();
}
}.execute();
}
private void updateSubscriptionListState() {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
for (PwSubscription s : mAllSubscriptions) {
s.setIsSubscribed(sp.getBoolean(SP_SUBSCRIPTION_PREFIX + s.getId(),
false));
Log.v(TAG, "updating from preference: " + SP_SUBSCRIPTION_PREFIX
+ s.getId() + " - " + s.isSubscribed());
}
}
/**
* Hide the list, show the loading indicator
*/
public void showLoading() {
mListLayout.setVisibility(View.GONE);
mProgressLayout.setVisibility(View.VISIBLE);
}
/**
* Show the List, hide the loading indicator
*/
public void hideLoading() {
mProgressLayout.setVisibility(View.GONE);
mListLayout.setVisibility(View.VISIBLE);
}
}
<file_sep>package com.phunware.alerts.sample;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
public class Utils {
public static final int MENU_INDEX_REFRESH = 2;
public static final int MENU_INDEX_UPDATE = 3;
public static final int MENU_INDEX_CLEAR = 4;
public static final int MENU_INDEX_EMAIL = 5;
public static final String INTENT_ALERT_DATA = "com.phunware.alerts.sample.INTENT_ALERT_DATA";
public static final String INTENT_ALERT_EXTRA = "com.phunware.alerts.sample.INTENT_ALERT_EXTRA";
public static final String INTENT_ALERT_EXTRA_PID = "com.phunware.alerts.sample.PID";
public static final String BROADCAST_MESSAGE_ACTION = "com.phunware.core.BROADCAST_MESSAGE_ACTION";
public static final String BROADCAST_MESSAGE_KEY = "com.phunware.core.BROADCAST_MESSAGE_KEY";
public static final String BROADCAST_SUCCESSFUL_KEY = "com.phunware.alerts.BROADCAST_SUCCESSFUL_KEY";
public static final String ACTION_ON_REGISTERED = "com.phunware.alerts.sample.ACTION_ON_REGISTERED";
public static final String ACTION_ON_UNREGISTERED = "com.phunware.alerts.sample.ACTION_ON_UNREGISTERED";
public static void email(Context packageContext, String body) {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { "<EMAIL>", "<EMAIL>" });
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, body);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "MaaS Alerts Console "+getCurrentTimeFormatted());
packageContext.startActivity(Intent.createChooser(emailIntent, "Send email..."));
}
/**
* Given a date, convert the string into a long format.
* @param date
* @return
*/
@SuppressLint("SimpleDateFormat")
public static long convertDateToLong(String date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar uc = Calendar.getInstance(TimeZone.getDefault());
long offset = uc.get(Calendar.ZONE_OFFSET) + uc.get(Calendar.DST_OFFSET);
try {
uc.setTime(sdf.parse(date + offset));
} catch (ParseException e) {
e.printStackTrace();
}
return uc.getTimeInMillis();
}
public static String convertLongToString(long timestamp)
{
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Calendar uc = Calendar.getInstance();
uc.setTimeInMillis(timestamp);
return sdf.format(uc.getTime());
}
/**
* Convenience method to get the current time as a string formatted as
* <code>yyyy-MM-dd'T'HH:mm:ss.SSS'Z'</code>.
*
* @return The current time formatted as
* <code>yyyy-MM-dd'T'HH:mm:ss'Z'</code>; RFC3339 format
*/
public static String getCurrentTimeFormatted() {
long now = System.currentTimeMillis();
TimeZone utc = TimeZone.getTimeZone("UTC");
GregorianCalendar cal = new GregorianCalendar(utc);
cal.setTimeInMillis(now);
SimpleDateFormat formatter = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
formatter.setTimeZone(utc);
return formatter.format(cal.getTime());
}
}
<file_sep>package com.phunware.alerts.sample.db;
import android.provider.BaseColumns;
public final class Contracts {
public abstract static class AlertEntry implements BaseColumns{
public static final String TABLE_NAME = "alerts";
public static final String C_PID = "pid";
public static final String C_MESSAGE = "message";
public static final String C_TARGET_GROUP = "target_group";
public static final String C_TIMESTAMP = "timestamp";
public static final int I_ID = 0;
public static final int I_PID = 1;
public static final int I_MESSAGE = 2;
public static final int I_TARGET_GROUP = 3;
public static final int I_TIMESTAMP = 4;
public static final String[] PROJECTION = {
_ID,
C_PID,
C_MESSAGE,
C_TARGET_GROUP,
C_TIMESTAMP
};
public static final String CREATE_SQL =
"CREATE TABLE " + TABLE_NAME + " ("
+ _ID + " INTEGER PRIMARY KEY,"
+ C_PID + " INTEGER,"
+ C_MESSAGE + " TEXT, "
+ C_TARGET_GROUP + " TEXT, "
+ C_TIMESTAMP + " DATETIME"
+ ");";
/**
* Trigger SQL to set the timestamp to "now" whenever a row is inserted.
*/
public static final String TIMESTAMP_TRIGGER =
"CREATE TRIGGER updateAlertTimestampOnInsert " +
"AFTER INSERT ON "+TABLE_NAME+" FOR EACH ROW BEGIN " +
"UPDATE "+TABLE_NAME+" SET "+C_TIMESTAMP+" = datetime('now') WHERE "+
_ID+" = last_insert_rowid(); " +
"END;";
}
}
<file_sep>package com.phunware.alerts.sample.db;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class AlertsProvider {
private static final String TAG = "AlertsProvider";
/**
* The database that the provider uses as its underlying data store
*/
private static final String DATABASE_NAME = "alerts.db";
/**
* The database version
*/
private static final int DATABASE_VERSION = 1;
private DatabaseHelper mDb;
/**
* Open a new database object
*
* @param context
*/
public AlertsProvider(Context context) {
mDb = new DatabaseHelper(context);
}
/**
* Close any open database object
*/
public void close() {
mDb.close();
}
/**
* Return a cursor for all alert entries, default order by last modified descending
* @param orderBy
* @return
*/
public Cursor getAllAlerts(String orderBy)
{
SQLiteDatabase db = mDb.getReadableDatabase();
if(orderBy == null)
orderBy = Contracts.AlertEntry.C_TIMESTAMP +" DESC";
return db.query(Contracts.AlertEntry.TABLE_NAME, Contracts.AlertEntry.PROJECTION,
null, null, null, null, orderBy);
}
/**
* Insert a new Alert into the db
*
* @param values
* @return the row id or -1 if an error
*/
public long insertAlert(ContentValues values) {
SQLiteDatabase db = mDb.getWritableDatabase();
return db.insert(Contracts.AlertEntry.TABLE_NAME, null, values);
}
/**
* Delete a single alert by its id
* @param alertId
* @return the number of rows affected.
*/
public int deleteAlert(long alertId)
{
SQLiteDatabase db = mDb.getWritableDatabase();
String whereClause = Contracts.AlertEntry._ID + " LIKE ?";
String whereArgs[] = new String[]{String.valueOf(alertId)};
return db.delete(Contracts.AlertEntry.TABLE_NAME, whereClause, whereArgs);
}
static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
// calls the super constructor, requesting the default cursor
// factory.
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(Contracts.AlertEntry.CREATE_SQL);
db.execSQL(Contracts.AlertEntry.TIMESTAMP_TRIGGER);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Logs that the database is being upgraded
Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
// Kills the table and existing data
db.execSQL("DROP TABLE IF EXISTS " + Contracts.AlertEntry.TABLE_NAME);
// Recreates the database with a new version
onCreate(db);
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
}
}
<file_sep>package com.phunware.alerts.sample.db;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import com.phunware.alerts.models.PwAlertExtras;
import com.phunware.alerts.sample.Utils;
public class AlertModel implements Parcelable{
private static final String TAG = "AlertModel";
public long id;
public long pid;
public String message;
public String targetGroup;
public long timestamp;
public AlertModel()
{
id = -1;
pid = -1;
message = "";
targetGroup = "";
timestamp = -1;
}
public AlertModel(long pid, String message, String targetGroup) {
this();
this.pid = pid;
this.message = message;
this.targetGroup = targetGroup;
}
/**
* Create an object with a {@link Cursor}.
* The cursor must already be at the desired position
* @param c
*/
public AlertModel(Cursor c)
{
id = c.getLong(Contracts.AlertEntry.I_ID);
pid = c.getLong(Contracts.AlertEntry.I_PID);
message = c.getString(Contracts.AlertEntry.I_MESSAGE);
targetGroup = c.getString(Contracts.AlertEntry.I_TARGET_GROUP);
timestamp = Utils.convertDateToLong(c.getString(Contracts.AlertEntry.I_TIMESTAMP));
}
public AlertModel(PwAlertExtras extras, JSONObject data)
{
this();
Log.v(TAG, extras.toString());
this.pid = Long.parseLong(extras.getDataPID());
this.message = extras.getAlertMessage();
try {
JSONArray subs = data.getJSONArray("subscriptionGroups");
int size = subs.length();
String t = "";
for(int i=0; i<size; i++)
{
String tt = "";
if(!t.equals(""))
tt = ", ";
t += tt + subs.getJSONObject(i).getString("name");
}
this.targetGroup = t;
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
public ContentValues toContentValues(boolean includeId)
{
ContentValues values = new ContentValues();
if(includeId)
values.put(Contracts.AlertEntry._ID, id);
values.put(Contracts.AlertEntry.C_PID, pid);
values.put(Contracts.AlertEntry.C_MESSAGE, message);
values.put(Contracts.AlertEntry.C_TARGET_GROUP, targetGroup);
return values;
}
/**
* Save this alert model into the database. This does not run asynchronously and should be run as such.
* @param db Database provider
* @return id of the inserted row, or -1 if error
*/
public long save(AlertsProvider db)
{
id = db.insertAlert(toContentValues(false));
return id;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(id);
dest.writeLong(pid);
dest.writeString(message);
dest.writeString(targetGroup);
dest.writeLong(timestamp);
}
public static final Parcelable.Creator<AlertModel> CREATOR = new Parcelable.Creator<AlertModel>() {
public AlertModel createFromParcel(Parcel in) {
return new AlertModel(in);
}
public AlertModel[] newArray(int size) {
return new AlertModel[size];
}
};
private AlertModel(Parcel in) {
id = in.readLong();
pid = in.readLong();
message = in.readString();
targetGroup = in.readString();
timestamp = in.readLong();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((message == null) ? 0 : message.hashCode());
result = prime * result + (int) (pid ^ (pid >>> 32));
result = prime * result + ((targetGroup == null) ? 0 : targetGroup.hashCode());
result = prime * result + (int) (timestamp ^ (timestamp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AlertModel other = (AlertModel) obj;
if (id != other.id)
return false;
if (message == null) {
if (other.message != null)
return false;
} else if (!message.equals(other.message))
return false;
if (pid != other.pid)
return false;
if (targetGroup == null) {
if (other.targetGroup != null)
return false;
} else if (!targetGroup.equals(other.targetGroup))
return false;
if (timestamp != other.timestamp)
return false;
return true;
}
@Override
public String toString() {
return "AlertModel [id=" + id + ", pid=" + pid + ", message=" + message + ", targetGroup=" + targetGroup + ", timestamp=" + timestamp + "]";
}
}
<file_sep>MaaS Alerts SDK for Android
==================
Version 1.3.2
This is Phunware's Android SDK for the Alerts & Notifications module. Visit http://maas.phunware.com/ for more details and to sign up.
Requirements
------------
* Android SDK 4.0.3+ (API level 15) or above
Documentation
------------
Phunware Alerts documentation is included both in the Documents folder in the repository as HTML and via maven. You can also find the latest documentation here: http://phunware.github.io/maas-alerts-android-sdk/
Overview
---------
The Phunware Alerts SDK provides push notification functionality.
Once installed, the SDK will automatically attempt to register for push notifications.
If unsuccessful, the attempt is made again the next time the app starts.
Server Setup
------------
*For detailed instructions, see our [GCM setup documentation](http://phunware.github.io/maas-alerts-android-sdk/how-to/Setup%20GCM%20Project.htm).*
Log into your [Google account's API console](https://code.google.com/apis/console). (You will need an email account with Google to have access to the console.)
Select "Services" and enable "Google Cloud Messaging for Android."
Once GCM is turned on, select "API Access" from the menu and look for the "API Key" under the section "Key for Android apps." Record the API key.
Once you have the API key, you will need the sender ID.
To get the sender ID, view the Google console's address bar and copy the value of the "project" key (i.e. https://code.google.com/apis/console/X/X/#project:111111111:access).
Once you have both the API key and sender ID, log into maas.phunware.com. Select the Alerts & Notifications tab from the menu, then select configure. Select an app you've created, otherwise create one first. Once you have an app, select the desired app and enter the token, which is your API key and sender ID. Select save to finish configuring your app.
Prerequisites
-------------
The Phunware Alerts SDK automatically imports the latest `Core SDK` (3.0.0) and Google Play Services 9.4.0
To import the library, add the following to your `repositories` tag in your top level `build.gradle` file.
```XML
projects {
repositories {
...
maven {
url "https://nexus.phunware.com/content/groups/public/"
}
...
}
}
```
Import the Phunware Analytics library by adding the following to your app's `build.gradle` file:
```
compile 'com.phunware.alerts:alerts:1.3.2'
```
Be sure to install the module in the `Application` `onCreate` method before registering keys. For example:
``` Java
@Override
public void onCreate() {
super.onCreate();
/* Other code */
PwCoreSession.getInstance().installModules(PwAlertsModule.getInstance(), ...);
/* Other code */
}
```
Integration
------------
### How do I receive push notifications?
There are a few steps to follow in order to be able to receive and handle push notifications.
#### Step 1: Update Permissions
Update the `AndroidManifest.xml` to include the following permissions.
These go outside of the `application` tag:
``` XML
<uses-permission android:name="android.permission.INTERNET" />
<!-- GCM requires a Google account. -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Keeps the processor from sleeping when a message is received. -->
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!--
Creates a custom permission so only this app can receive its messages.
NOTE: The permission must be called PACKAGE.permission.C2D_MESSAGE,
where PACKAGE is the application's package name.
-->
<permission
android:name="com.phunware.alerts.sample.permission.C2D_MESSAGE"
android:protectionLevel="signature" />
<uses-permission android:name="com.phunware.alerts.sample.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive data messages. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
```
#### Step 2: Register Services
An `IntentService` runs to handle received messages.
Create a class called `GCMIntentService` that extends `PwAlertsIntentService`.
Then, register the service in the manifest.
``` Java
public class GCMIntentService extends PwAlertsIntentService {
@Override
public void onMessage(Context context, PwAlertExtras extras) {
}
@Override
public void onDelete(Context context, Intent intent) {
}
@Override
public void onError(Context context, Intent intent) {
}
}
```
The service should be registered with the correct path to the service in the manifest.
The `service` should be defined inside of the `application` tag.
If` GCMIntentService` is in the package root, follow the below example:
``` XML
<!--
Application-specific subclass of PwAlertsIntentService that will
handle received messages.
-->
<service android:name=".GCMIntentService" />
```
#### Step 3: Register Receivers
Register the GCM receiver in the manifest.
This will receive intents from GCM services, then forward them through to the `IntentService` defined above.
Be sure to replace the category tag with your own package name.
The `receiver` should be defined inside of the `application` tag.
``` XML
<!--
BroadcastReceiver will receive intents from GCM
services and handle them to the custom IntentService.
The com.google.android.c2dm.permission.SEND permission is necessary
so only GCM services can send data messages for the app.
-->
<receiver
android:name="com.phunware.alerts.GCMBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<!-- Receives the actual messages. -->
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<!-- Receives the registration ID. -->
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<!-- [Your Package Name Here] -->
<category android:name="com.your.package.name.here" />
</intent-filter>
</receiver>
```
#### Step 4: Handle Received Alerts
In the `GCMIntentService`, there is a callback to receive a message and a callback to see when an error has occurred.
`onMessage` will provide a `PwAlertsExtras` object, which holds all of the parsed information from
the alert and provides convenient GET methods for them. For example:
``` Java
public void onMessage(Context context, PwAlertExtras extras) {
String message = extras.getAlertMessage();
/*
* Here is where the alert can be handled and built into a notification (or otherwise).
*/
}
```
##### Get Extra Data
If extra data is expected in the alert, then forward the alert extras object to the method when handling the message: `getExtraData(Context, PwAlertExtras)`
```Java
@Override
public void onMessage(Context context, PwAlertExtras extras) {
// Create a bundle to pass to notification creation.
final Bundle bundle = new Bundle();
// Add ‘alertExtras’ to the bundle.
bundle.putParcelable("alertExtras", extras);
try {
// Delegate to getExtraData(context, extras).
final JSONObject data = getExtraData(context, extras);
try {
// Process key/value pairs contained in the data and add them to the bundle.
bundle.putString(Utils.INTENT_ALERT_DATA, data.toString(2));
} catch (JSONException e) {
bundle.putString(Utils.INTENT_ALERT_DATA, data.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
// Create a notification using the extra data bundle.
}
```
#### Analytic Event Trigger
When an alert reaches the device and is interacted with it is up to the responsibility of the developer to trigger a positive click. This should be called once the alert has been interacted with by a user. This increments the Alerts Opened counter.
```JAVA
// Trigger a positive click event for an alert by its PID.
PwAlertsRegister.sendPositiveClick(context, pid);
```
Verify Manifest
---------------
`PwAlertsModule` has a convenience method to check if the manifest for the Alerts SDK is set up properly.
This should only be used for development and testing, not in production.
Call the method with the line `PwAlertsModule.validateManifestAlertsSetup(context)`. The passed-in context should be the
application context. If there is an error, then an `IllegalStateException` will be thrown with an error message regarding what
couldn't be found.
Troubleshooting
---------------
### Why am I not getting alerts?
Make sure the SDK is properly configured:
1. Double-check that your manifest is correct and no errors are thrown when running `PwAlertsModule.validateManifestAlertsSetup(context)`.
2. Make sure that the `GCMIntentService` is in your root package. See [this post](http://stackoverflow.com/questions/16951216/gcmbaseintentservice-callback-only-in-root-package/16951296?noredirect=1#16951296) to see how to move the service to another location.
3. Check that your Google API keys are properly configured on the MaaS portal in the Alerts & Notifications tab.
### How do I dynamically unregister and register?
You can manually perform an unregister and register action simply by calling the static methods:
`PwAlertsRegister.unregister(Context context)` or `PwAlertsRegister.register(Context context)`
### How do I get a list of subscriptions?
To get the list of available subscriptions, call the line
`PwAlertsSubscriptions.getSubscriptionGroups(Context context)`.
This will return an `ArrayList` of `PwSubscription` objects.
Each object maintains an `id`, a `name`, an `isSubscribed` flag and an `ArrayList` of
children `PwSubscription` objects (referred to as sub-segments).
The server and the Alerts SDK maintain state for each subscription.
### How do I send an updated list of subscription preferences to the server?
Use the `saveSubscriptions()` method to save the subscription state on the server. **This method should be called asynchronously, or outside of the main UI thread.**
`PwAlertsSubscriptions.saveSubscriptions(Context context, List<PwSubscription> subscriptions)`.
This will use the `isSubscribed` flag in each of the models in the list.
**NOTE**: When the Alerts SDK is installed for the first time, or when it runs on the app’s first start,
a call is made to the backend in order to reset all the subscriptions to an unsubscribed state.**_
### How can I check whether the device is registered?
Use `PwAlertsRegister.gcmIsRegistered(Context)`. It will return true when the device is registered to GCM, false if not. Make sure the context you pass is not null, otherwise false will be returned.
### Can I retrieve the GCM device token?
Yes, you can. Use `PwAlertsRegister.deviceGCMToken(Context)`. It will return GCM device token or null if one isn't available.
-----------
Privacy
-----------
You understand and consent to Phunware’s Privacy Policy located at www.phunware.com/privacy. If your use of Phunware’s software requires a Privacy Policy of your own, you also agree to include the terms of Phunware’s Privacy Policy in your Privacy Policy to your end users.
Terms
-----------
Use of this software requires review and acceptance of our terms and conditions for developer use located at http://www.phunware.com/terms/
| 2221ecf3bff194714e8348260b0cdc5ecc038a21 | [
"Markdown",
"Java"
] | 7 | Markdown | phunware/maas-alerts-android-sdk | aed9309fbbe882835bcf39b44cef7ed2fb043693 | b601e609b3578d4cd9817d01cbb3cc3b0c12126b |
refs/heads/master | <file_sep># Evaluate the car using KNN Algorithm
<li>This project is a simple example of KNN algorithm</li>
<li>This is a beginner level ML project</li>
<li>Dataset: https://archive.ics.uci.edu/ml/machine-learning-databases/car/ </li>
<li>Runing the project:</li>
<ol>
<li>pip install -r requirements.txt</li>
<li>python main.py</li>
</ol>
<li>Output:</li>
<img src="https://github.com/rishav-karanjit/Evaluate-the-car/blob/master/Output.png"></img>
<file_sep>import numpy as np
import pandas as pd
from sklearn import neighbors, metrics
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
data = pd.read_csv('car.data')
# print(data.head())
X = data[[
'buying',
'maint',
'safety',
]].values
Y = data[['class']]
# print(X,Y)
Encode = LabelEncoder()
for i in range(len(X[0])):
X[:, i] = Encode.fit_transform(X[:, i])
# print(X)
label_mapping = {
'unacc' : 0,
'acc' : 1,
'good' : 2,
'vgood' : 3
}
Y['class'] = Y['class'].map(label_mapping)
Y = np.array(Y)
# print(Y)
knn = neighbors.KNeighborsClassifier(n_neighbors = 25, weights = "uniform")
X_train, X_test, Y_train, Y_test = train_test_split(X,Y,test_size=0.2)
knn.fit(X_train, Y_train)
prediction = knn.predict(X_test)
accuracy = metrics.accuracy_score(Y_test,prediction)
print("Prediction: ", prediction)
print("Accuracy: ", accuracy)
print("actual value:",Y[20])
print("predicted value:",knn.predict(X)[20]) | 8e627d54338527be4c194a20d2def636ef89c011 | [
"Markdown",
"Python"
] | 2 | Markdown | rishav-karanjit/Evaluate-the-car | 931d064cfeb361b55fddaa7830ec5689976acab1 | 118da0f16f6d447fcb6003a59fc4f163f1eb6391 |
refs/heads/master | <file_sep>class FixColumnName < ActiveRecord::Migration
def change
rename_column :recipes, :type, :ctype
end
end
<file_sep>class RecipesController < ApplicationController
skip_before_action :verify_authenticity_token
before_action :verify_custom_authenticity_token
def verify_custom_authenticity_token
# checks whether the request comes from a trusted source
end
def index
@recipes = Recipe.all
end
def show
@recipe = Recipe.find(params[:id])
end
def new
@recipe = Recipe.new
end
def edit
@recipe = Recipe.find(params[:id])
end
def create
@recipe = Recipe.new(recipe_params_new)
if @recipe.save
redirect_to @recipe
else
render 'new'
end
end
def update
@recipe = Recipe.find(params[:id])
if @recipe.update(recipe_params)
redirect_to @recipe
else
render 'edit'
end
end
def destroy
@recipe = Recipe.find(params[:id])
@recipe.destroy
redirect_to recipes_path
end
private
def recipe_params_new
params.require(:recipe).permit(:name, :glass, :ctype, :instructions, ingredients_attributes: [:id, :amount, :ingredient, :_destroy])
end
def recipe_params
params.require(:recipe).permit(:name, :glass, :ctype, :instructions, :recipe_reviewed, ingredients_attributes: [:id, :amount, :ingredient, :_destroy])
end
end
<file_sep>class AddReviewedToRecipe < ActiveRecord::Migration
def change
add_column :recipes, :recipe_reviewed, :boolean
end
end
<file_sep>json.name @recipe.name
json.type @recipe.ctype
json.glass @recipe.glass
json.ingredients @recipe.ingredients do |ingredient|
json.amount ingredient.amount
json.ingredient ingredient.ingredient
end
json.instructions @recipe.instructions
<file_sep>class Recipe < ActiveRecord::Base
has_many :ingredients
accepts_nested_attributes_for :ingredients, :allow_destroy => true
validates :name, presence: true, length: {minimum: 2}
validates :instructions, presence: true, length: {minimum: 2}
scope :approved, -> { where(recipe_reviewed: true) }
scope :pending, -> { where(recipe_reviewed: false) }
scope :newest, -> { order("created_at desc") }
end
<file_sep>json.array! @recipes.approved do |recipe|
json.name recipe.name
json.type recipe.ctype
json.glass recipe.glass
json.ingredients recipe.ingredients do |ingredient|
json.amount ingredient.amount
json.ingredient ingredient.ingredient
end
json.instructions recipe.instructions
json.approved recipe.recipe_reviewed
end
| e189b07204665e52a7e0473c44d1c21c77ba6329 | [
"Ruby"
] | 6 | Ruby | mrkantz/cocktails-app-api | 0649d245414ca19bfa2a022cba1c703ce42c34c5 | b6349c367cc7ade65db40fa06fd9880aa9db1a4a |
refs/heads/master | <repo_name>argeebee/mygarageapp<file_sep>/index.js
//click events
var addCar = document.getElementById("addCar");
var removeCar = document.getElementById("removeCar");
//event listeners
document.getElementById("removeCar").addEventListener("click", function(){
var plateNumber = document.getElementById("plateNumber").value;
removeCar(licenseNumber);
});
document.getElementById("addCar").addEventListener("click", function(){
var car = new cars("red", "Zyris", "#mycar", "mustang");
var car = new cars("blue", "Bob", "#hiscar", "camry");
});
// var garageStack = createStack();
// function createStack(){
// }
<file_sep>/stack.js
var carStack = [];
var tempStack = [];
function addCar(thisCar){
carStack.push(thisCar);
console.log(carStack);
}
// search to remove car based on plate number
function removeCar(plateNumber){
var poppedCar = carStack.pop();
if(plateNumber == poppedCar.plateNumber){
alert("The " + poppedCar.model + " has been returned.")
}
if(plateNumber != poppedCar.plateNumber){
alert("Car License #: " + poppedCar.plateNumber + " "
+ poppedCar.model + " was removed. Searching for your")
tempStack.push(poppedCar);
console.log(tempStack);
}
} | e0bfd3445b270a8b855256eea90c0ae267b5ba1d | [
"JavaScript"
] | 2 | JavaScript | argeebee/mygarageapp | 288fada88d72096ae670845e04252047b63648fa | f0b1aa41fbf1060d3453f32067bc2031c502651c |
refs/heads/dev | <repo_name>ethan786/hacktoberfest2021-1<file_sep>/Python/Armstrong.py
num = int(input('Enter a number: '))
num_original =num2=num
sum1 = 0
cnt=0
while(num>0):
cnt=cnt+1
num=num//10
while num2>0:
rem = num2% 10
sum1 += rem ** cnt
num2//= 10
if(num_original==sum1):
print('Armstrong!!')
else:
print('Not Armstrong!')
<file_sep>/Python/Palindrome_of_a_Number.py
num1 = int(input("Enter the number: "))
temp = num1
reverse = 0
while num1 >0:
remainder = num1 %10
reverse = (reverse*10) + remainder
num1 = num1//10
if temp == reverse:
print("The given number is a palindrome")
else:
print("The number is not a palindrome")<file_sep>/Python/Matric_Product.py
# Python3 code to demonstrate
# Matrix Product
# Using list comprehension + loop
# getting Product
def prod(val) :
res = 1
for ele in val:
res *= ele
return res
# initializing list
test_list = [[1, 4, 5], [7, 3], [4], [46, 7, 3]]
# printing original list
print("The original list : " + str(test_list))
# using list comprehension + loop
# Matrix Product
res = prod([ele for sub in test_list for ele in sub])
# print result
print("The total element product in lists is : " + str(res))
<file_sep>/C/01KnapsackDP.cpp
#include<bits/stdc++.h>
#include<cmath>
using namespace std;
int KnapsackDp(int fw, int values[], int weight[], int n)
{
int dp[n+1][fw+1];
for(int i=0; i<=n; i++)
dp[i][0] = 0;
for(int i=0; i<=fw; i++)
dp[0][i] = 0;
for(int i=1; i<=n; i++)
{
for(int j=1; j<=fw; j++)
{
if(weight[i-1] > j)
{
dp[i][j] = dp[i-1][j];
}
else{
dp[i][j] = max(values[i-1] + dp[i-1][j-weight[i-1]], dp[i-1][j]);
}
}
}
return dp[n][fw];
}
int main()
{
int n, fw;
cin>>n;
cin>>fw;
int values[n], weight[n];
for(int i=0; i<n; i++)
cin>>values[i];
for(int i=0; i<n; i++)
cin>>weight[i];
cout<<KnapsackDp(fw, values, weight, n);
return 0;
}<file_sep>/Python/digiclock.py
#''' DIGITAL CLOCK USING TKINTER'''
from tkinter import*
import time # '''USING TIME MODULE TO GET SYSTEM TIME'''
root=Tk()
root.title("DIGITAL CLOCK")
root.geometry("1350x700+0+0")
root.config(bg="#081923")
def clock():
h=str(time.strftime("%H"))
m=str(time.strftime("%M"))
s=str(time.strftime("%S"))
# print(h,m,s)
#IF THIS IS NOT USED IT WILL SHOE TIME IN 24 HR CLOCK SYSTEM
if int(h)>=12 and int(m)>0: #'''MAKING THE CHANGE IN AM TO PM ACCORDING TO TIME'''
lbl_noon.config(text="PM")
if int(h)>12:
h=str(int((int(h)-12)))
lbl_hr.config(text=h)
lbl_min.config(text=m)
lbl_sec.config(text=s)
lbl_hr.after(200,clock)
# use either lucida writing or bradley handwiting
lbl_hr=Label(root,text="12",font=("lucida calligraphy",50,"bold"),bg="#087587",fg="white")
lbl_hr.place(x=350,y=200,width=150,height=150)
lbl_hr2=Label(root,text="HOUR",font=("lucida calligraphy",20,"bold"),bg="#087587",fg="white")
lbl_hr2.place(x=350,y=360,width=150,height=50)
lbl_min=Label(root,text="12",font=("lucida calligraphy",50,"bold"),bg="#008EA4",fg="white")
lbl_min.place(x=520,y=200,width=150,height=150)
lbl_min2=Label(root,text="MINUTE",font=("lucida calligraphy",20,"bold"),bg="#008EA4",fg="white")
lbl_min2.place(x=520,y=360,width=150,height=50)
lbl_sec=Label(root,text="12",font=("lucida calligraphy",50,"bold"),bg="#DF002A",fg="white")
lbl_sec.place(x=690,y=200,width=150,height=150)
lbl_sec2=Label(root,text="SECOND",font=("lucida calligraphy",20,"bold"),bg="#DF002A",fg="white")
lbl_sec2.place(x=690,y=360,width=150,height=50)
lbl_noon=Label(root,text="AM",font=("lucida calligraphy",50,"bold"),bg="#DF002A",fg="white")
lbl_noon.place(x=860,y=200,width=150,height=150)
lbl_noon2=Label(root,text="NOON",font=("lucida calligraphy",20,"bold"),bg="#DF002A",fg="white")
lbl_noon2.place(x=860,y=360,width=150,height=50)
clock() #CALLING FUNCTION
root.mainloop()
#WORKING GOOD<file_sep>/Python/connect4.py
import numpy as np
import pygame
import sys
import math
import random
# Global Constants
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
YELLOW = (255, 255, 0)
PLAYER = 0
AI = 1
WINDOW_LENGTH = 4
EMPTY = 0
PLAYER_PIECE = 1
AI_PIECE = 2
ROW_COUNT = 6
COLUMN_COUNT = 7
SQUARESIZE = 100
RADIUS = int(SQUARESIZE/2 - 5)
width = COLUMN_COUNT * SQUARESIZE
height = (ROW_COUNT+1) * SQUARESIZE
size = (width, height)
turn = random.randint(PLAYER, AI)
class Board:
def __init__(self, rows, columns):
self.rows = rows
self.columns = columns
def create_board(self):
board = np.zeros((self.rows, self.columns))
return board
def drop_piece(self, board, row, col, piece):
board[row][col] = piece
def is_valid_location(self, board, col):
return board[ROW_COUNT-1][col] == 0
def get_next_open_row(self, board, col):
for r in range(ROW_COUNT):
if board[r][col] == 0:
return r
def print_board(self, board):
self.board = board
print(np.flip(self.board, 0))
def winning_move(self, board, piece):
# Check horizontal locations for win
for c in range(COLUMN_COUNT-3):
for r in range(ROW_COUNT):
if board[r][c] == piece and board[r][c+1] == piece and board[r][c+2] == piece and board[r][c+3] == piece:
return True
# Check vertical locations for win
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT-3):
if board[r][c] == piece and board[r+1][c] == piece and board[r+2][c] == piece and board[r+3][c] == piece:
return True
# Check positively sloped diaganols
for c in range(COLUMN_COUNT-3):
for r in range(ROW_COUNT-3):
if board[r][c] == piece and board[r+1][c+1] == piece and board[r+2][c+2] == piece and board[r+3][c+3] == piece:
return True
# Check negatively sloped diaganols
for c in range(COLUMN_COUNT-3):
for r in range(3, ROW_COUNT):
if board[r][c] == piece and board[r-1][c+1] == piece and board[r-2][c+2] == piece and board[r-3][c+3] == piece:
return True
def evaluate_win(self, window, piece):
score = 0
opp_piece = PLAYER_PIECE
if piece == PLAYER_PIECE:
opp_piece = AI_PIECE
if window.count(piece) == 4:
score += 100
elif window.count(piece) == 3 and window.count(EMPTY) == 1:
score += 5
elif window.count(piece) == 2 and window.count(EMPTY) == 2:
score += 2
if window.count(opp_piece) == 3 and window.count(EMPTY) == 1:
score -= 4
return score
def score_position(self, board, piece):
score = 0
# Center Score
center_array = [int(i) for i in list(board[:, COLUMN_COUNT//2])]
center_count = center_array.count(piece)
score += center_count * 3
## Horizontal Score
for r in range(ROW_COUNT):
row_array = [int(i) for i in list(board[r,:])]
for c in range(COLUMN_COUNT-3):
window = row_array[c:c+WINDOW_LENGTH]
score += self.evaluate_win(window, piece)
## Vertical Score
for c in range(COLUMN_COUNT):
col_array = [int(i) for i in list(board[:,c])]
for r in range(ROW_COUNT-3):
window = col_array[r:r+WINDOW_LENGTH]
score += self.evaluate_win(window, piece)
## Diagonal Score
for r in range(ROW_COUNT-3):
for c in range(COLUMN_COUNT-3):
window = [board[r+i][c+i] for i in range(WINDOW_LENGTH)]
score += self.evaluate_win(window, piece)
for r in range(ROW_COUNT-3):
for c in range(COLUMN_COUNT-3):
window = [board[r+3-i][c+i] for i in range(WINDOW_LENGTH)]
score += self.evaluate_win(window, piece)
return score
def is_terminal_node(self, board):
return self.winning_move(board, PLAYER_PIECE) or self.winning_move(board, AI_PIECE) or len(self.get_valid_locations(board)) == 0
def minimax(self, board, depth, alpha, beta, maximizingPlayer):
valid_locations = self.get_valid_locations(board)
is_terminal = self.is_terminal_node(board)
if depth ==0 or is_terminal:
if is_terminal:
if self.winning_move(board, AI_PIECE):
return (None, 1000000000000000000000)
elif self.winning_move(board, PLAYER_PIECE):
return (None, -1000000000000000000000)
else: #GAme Over
return (None, 0)
else: #Zero Depth
return (None, self.score_position(board, AI_PIECE))
if maximizingPlayer:
value = -math.inf
column = random.choice(valid_locations)
for col in valid_locations:
row = self.get_next_open_row(board, col)
b_copy = board.copy()
self.drop_piece(b_copy, row, col, AI_PIECE)
new_score = self.minimax(b_copy, depth-1, alpha, beta, False)[1]
if new_score > value:
value = new_score
column = col
alpha = max(alpha, value)
if alpha >= beta:
break
return column, value
else:
value = math.inf
column = random.choice(valid_locations)
for col in valid_locations:
row = self.get_next_open_row(board, col)
b_copy = board.copy()
self.drop_piece(b_copy, row, col, PLAYER_PIECE)
new_score = self.minimax(b_copy, depth-1, alpha, beta, True)[1]
if new_score < value:
value = new_score
column = col
beta = min(beta, value)
if alpha >= beta:
break
return column, value
def get_valid_locations(self, board):
valid_locations = []
for col in range(COLUMN_COUNT):
if self.is_valid_location(board, col):
valid_locations.append(col)
return valid_locations
def pick_best_move(self, board, piece):
valid_locations = self.get_valid_locations(board)
best_score = -10000
best_col = random.choice(valid_locations)
for col in valid_locations:
row = self.get_next_open_row(board, col)
temp_board = board.copy()
self.drop_piece(temp_board, row, col, piece)
score = self.score_position(temp_board, piece)
if score > best_score:
best_score = score
best_col = col
return best_col
def draw_board(self, board):
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT):
pygame.draw.rect(
screen, BLUE, (c*SQUARESIZE, r*SQUARESIZE + SQUARESIZE, SQUARESIZE, SQUARESIZE))
pygame.draw.circle(screen, BLACK, (int(
c*SQUARESIZE + SQUARESIZE/2), int(r*SQUARESIZE + SQUARESIZE+SQUARESIZE/2)), RADIUS)
for c in range(COLUMN_COUNT):
for r in range(ROW_COUNT):
if board[r][c] == PLAYER_PIECE:
pygame.draw.circle(screen, RED, (int(
c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS)
elif board[r][c] == AI_PIECE:
pygame.draw.circle(screen, YELLOW, (int(
c*SQUARESIZE+SQUARESIZE/2), height-int(r*SQUARESIZE+SQUARESIZE/2)), RADIUS)
pygame.display.update()
if __name__ == "__main__":
board = Board(ROW_COUNT, COLUMN_COUNT)
game_over = False
game = board.create_board()
board.print_board(game)
pygame.init()
screen = pygame.display.set_mode(size)
myFont = pygame.font.SysFont("monopsace", 75)
board.draw_board(game)
pygame.display.update()
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.MOUSEMOTION:
pygame.draw.rect(screen, BLACK, (0,0, width, SQUARESIZE))
posx = event.pos[0]
if turn == PLAYER:
pygame.draw.circle(screen, RED, (posx, int(SQUARESIZE/2)), RADIUS)
pygame.display.update()
if event.type == pygame.MOUSEBUTTONDOWN:
pygame.draw.rect(screen, BLACK, (0,0, width, SQUARESIZE))
print(event.pos)
#Ask For Player 1
if turn == PLAYER:
posx = event.pos[0]
col = int(math.floor(posx/SQUARESIZE))
if board.is_valid_location(game, col):
row = board.get_next_open_row(game, col)
board.drop_piece(game, row, col, PLAYER_PIECE)
if board.winning_move(game, PLAYER_PIECE):
label = myFont.render("Player 1 Wins !!", 1, RED)
screen.blit(label, (40,10))
game_over = True
turn += 1
turn = turn%2
board.print_board(game)
board.draw_board(game)
#Ask for Player 2
if turn == AI and not game_over:
col, minimax_score = board.minimax(game, 6, -math.inf, math.inf, True)
if board.is_valid_location(game, col):
""" pygame.time.wait(500) """
row = board.get_next_open_row(game, col)
board.drop_piece(game, row, col, AI_PIECE)
if board.winning_move(game, AI_PIECE):
label = myFont.render("Player 2 Wins !!", 1, YELLOW)
screen.blit(label, (40,10))
game_over = True
board.print_board(game)
board.draw_board(game)
turn += 1
turn = turn % 2
if game_over:
pygame.time.wait(3000)<file_sep>/Python/Clock.py
from tkinter.ttk import*
from time import strftime
from tkinter import Label, Tk
#======= Configuring window ========
window = Tk()
window.title("Digital Clock")
window.geometry("600x250")
window.configure(bg="darkred")
window.resizable(False, False)
clock_label = Label(window, bg="black", fg="white", font = ("Times", 100, 'bold'), relief='flat')
clock_label.place(x = 20, y = 20)
def update_label():
current_time = strftime('%H: %M: %S')
clock_label.configure(text = current_time)
clock_label.after(80, update_label)
update_label()
window.mainloop()
<file_sep>/Python/Python_script_sttuff_here.py
#!/bin/python3
import math
import os
import random
import re
import sys
import string
symbols_low = string.ascii_lowercase
symbols_up = string.ascii_uppercase
def caesarCipher(s, k):
res = []
for c in s:
if c.isupper():
res.append(symbols_up[(symbols_up.index(c)+k)%len(symbols_up)])
elif c.islower():
res.append(symbols_low[(symbols_low.index(c)+k)%len(symbols_low)])
else:
res.append(c)
return "".join(map(str, res))
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
s = input()
k = int(input().strip())
result = caesarCipher(s, k)
fptr.write(result + '\n')
fptr.close()
<file_sep>/JavaScript/quote-generator/script.js
const API_URL = 'https://api.quotable.io/random';
const TWEET_API_URL = 'https://twitter.com/intent/tweet';
const COLORS = [
'#F44336', '#E91E63', '#9C27B0', '#673AB7', '#3F51B5', '#2196F3',
'#03A9F4', '#00BCD4', '#009688', '#4CAF50', '#8BC34A', '#CDDC39',
'#FFC107', '#FF9800', '#FF5722', '#795548', '#9E9E9E', '#607D8B',
];
const chooseRandom = (list) => {
const index = Math.floor(Math.random() * list.length);
return list[index];
}
const buildTweetURL = ({ author, text }) =>
`${TWEET_API_URL}?hashtags=quotes&text="${text}" ${author}`;
const Button = ({ children, id, color, onClick, style, href }) => {
const customStyle = { backgroundColor: color, ...style };
return (
<a
id={id}
className="button"
onClick={onClick}
style={customStyle}
href={href /* required to pass tests */}
target="_blank"
>
{children}
</a>
);
};
const QuoteBox = ({ color, text, author, onNewQuote, onTweetQuote }) => (
<div id="quote-box" style={{ color }}>
<div id="text">
{text}
</div>
<div id="author">{author}</div>
<div id="buttons-bar">
<Button
id="tweet-quote"
onClick={onTweetQuote}
color={color}
href={buildTweetURL({ author, text })}
>
<i className="fa fa-fw fa-twitter" />
</Button>
<Button
id="new-quote"
onClick={onNewQuote}
color={color}
style={{ marginLeft: 'auto' }}
>
New quote
</Button>
</div>
</div>
);
class App extends React.Component {
state = {
bgColor: '',
quote: {
text: null,
author: null,
}
}
componentDidMount = () => {
this.fetchNewQuote();
}
fetchNewQuote = () => {
this.chooseRandomBgColor();
fetch(API_URL)
.then((response) => response.json())
.then((data) => {
const quote = {
author: data.author,
text: data.content,
};
this.setState({ quote });
});
}
chooseRandomBgColor = () => {
const bgColor = chooseRandom(COLORS);
this.setState({ bgColor });
}
tweetQuote = () => {
const { quote } = this.state;
const url = buildTweetURL(quote);
window.open(url, '_blank');
}
render() {
const bgColor = this.state.bgColor || 'black';
return (
<div
id="quote-container"
style={{ backgroundColor: bgColor }}
>
<QuoteBox
color={bgColor}
text={this.state.quote.text}
author={this.state.quote.author}
onNewQuote={this.fetchNewQuote}
onTweetQuote={this.tweetQuote}
/>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));<file_sep>/Python/morse_code.py
morse_code = {
'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.',
'G':'--.', 'H':'....', 'I':'..', 'J':'.---', 'K':'-.-', 'L':'.-..',
'M':'--', 'N':'-.', 'O':'---', 'P':'.--.', 'Q':'--.-', 'R':'.-.',
'S':'...', 'T':'-', 'U':'..-', 'V':'...-', 'W':'.--', 'X':'-..-',
'Y':'-.--', 'Z':'--..'
}
def english_to_morse():
'''
Translate a letter/word/phrase from english to the morse code equivalent. Prints a list of each
character in its morse code dot and dash form using Python.
'''
your_string = input('Enter string to translate to morse code:\n')
your_string = your_string.upper()
# creates empty list to append morse code keys to
translated_string = []
print('\ntranslating,....translating,....*bing*\n')
# loops through each character in the user string
for char in your_string:
# loops through each key in the dictionary for each character in the string
for item in morse_code:
# if the character matches the dictionary key
if item[0] == char:
# appends that value to the translated list
translated_string.append(morse_code[item])
# prints the final translation
print('Your code for each character in morse is:\n')
print(translated_string)
<file_sep>/C/procmeminfo.c
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#define BUFF_SIZE 1024
int main() {
int fd = open("/proc/meminfo", O_RDONLY);
char* buffer = (char*) malloc(BUFF_SIZE);
if (buffer == NULL) {
printf("error: malloc failed.\n");
exit(1);
}
/* we cannot determine the file size of a proc file */
int length = read(fd, buffer, BUFF_SIZE);
char* unit1 = (char*) malloc(3);
char* unit2 = (char*) malloc(3);
char* unit3 = (char*) malloc(3);
int mem_total, mem_free, cached;
sscanf(buffer, "%*s %d %s %*s %d %s %*s %*d %*s %*s %d %s",
&mem_total, unit1, &mem_free, unit2, &cached, unit3);
printf("Free Memory: %d %s\n", mem_free, unit2);
printf("Total Memory: %d %s\n", mem_total, unit1);
printf("Cached: %d %s\n", cached, unit3);
close(fd);
free(buffer);
}
<file_sep>/CPP/triplet_that_sum_to_a_given_value.cpp
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
int n,x;
cin>>n;
cin>>x;
int A[n];
for(int i=0;i<n;i++){
cin>>A[i];
}
int ans=0;
for(int i=0;i<n-2;i++){
unordered_set<int>s;
int sum=x-A[i];
for(int j=i+1;j<n;j++){
if(s.find(sum-A[i])!=s.end()){
ans=1;
break;
}
s.insert(A[j]);
}
}
cout<<ans<<endl;
}
}<file_sep>/CPP/Min_Steps_in_Infinite_Grid.cpp
#include <bits/stdc++.h>
using namespace std;
int coverPoints(vector<int> &A, vector<int> &B) {
int n=A.size();
int count=0;
for (int i = 0; i < n-1; ++i)
{
if(abs(A[i]-A[i+1])<=abs(B[i]-B[i+1])){
count+=abs(B[i]-B[i+1]);
}else{
count+=abs(A[i]-A[i+1]);
}
}
return count;
}
int main(){
vector<int> A = {0, 1, 1};
vector<int> B = {0, 1, 2};
cout<<coverPoints(A,B);
return 0;
}<file_sep>/Java/Simplecal/src/simplecal/Simplecal.java
package simplecal;
import java.util.Scanner;
public class Simplecal{
public static void main(String[] args) {
double n1;
double n2;
double result;
char options;
Scanner reader = new Scanner(System.in);
System.out.print("Enter First numbers: ");
n1 = reader.nextDouble();
System.out.print("Enter Second numbers: ");
n2 = reader.nextDouble();
System.out.print("\nEnter an operator (+, -, *, /): ");
options = reader.next().charAt(0);
switch(options) {
case '+': result = n1 + n2;
break;
case '-': result = n1 - n2;
break;
case '*': result = n1 * n2;
break;
case '/': result = n1 / n2;
break;
default: System.out.printf("Error! You Enter incorrect operator");
return;
}
System.out.print("\nYour Result is:\n");
System.out.printf(n1 + " " + options + " " + n2 + " = " + result);
}
}
<file_sep>/CONTRIBUTERS.md
| Name | Github | Starred the repo |
| -------------------- | ------------------------------------------------------------- | ---------------- |
| <NAME> | [@notmarshmllow](https://github.com/notmarshmllow) | 26 |
| <NAME> | [hansajith98](https://github.com/hansajith98) | 1 |
| <NAME> | [nilupulmanodya](https://github.com/nilupulmanodya/) | 2 |
| <NAME> |[yashshah2002](https://github.com/yashshah2002)| 3 |
| Searath | [deshitha98](https://github.com/deshitha98) | 4 |
| <NAME> | [Thimira97](https://github.com/Thimira97) | 5 |
| <NAME> | [dnadawa](https://github.com/dnadawa) | 6 |
| <NAME>j | [liamsj0605](https://github.com/Liam0605) | 7 |
| <NAME> | [SamGanYX](https://github.com/SamGanYX) | 8 |
| <NAME> | [shayan-cyber](https://github.com/shayan-cyber) | 9 |
| <NAME> | [avyay jain](https://github.com/avyayjain) | 10 |
| <NAME> | [Subho-codegeek](https://github.com/Subho-codegeek) | 11 |
| <NAME> | [Anthony-Citizen](https://github.com/Anthony-Citizen) | 12 |
| NMORTHA | [nmortha](https://github.com/nmortha)|13|
| <NAME> | [msameerfarooq](https://github.com/msameerfarooq | 14 |
| <NAME> | [bagasahmad](https://github.com/bagasahmad) | 15 |
| <NAME> | [MuShaf-NMS](https://github.com/MuShaf-NMS) | 16 |
| liam sj | [liamsj0605](https://github.com/Liam0605) | 17 |
| <NAME> | [shayan-cyber](https://github.com/shayan-cyber) | 18 |
| <NAME> | [Aaryan0424](https://github.com/Aaryan0424) | 19 |
| <NAME> | [0xSebin](https://github.com/0xSebin/) | 20 |
| <NAME> | [v1nc1d4](https://github.com/v1nc1d4/) | 21 |
| <NAME> | [justnunuz](https://github.com/JustNunuz) | 22 |
| <NAME> | [Nishant3007](https://github.com/Nishant3007) | 23 |
| <NAME> | [<NAME>](https://github.com/danieledelgiudice) |
| <NAME> | [Mammoth](https://github.com/mammothneck) | 25 |
| <NAME> | [MaheshaKandambi](https://github.com/MaheshaKandambi) |
| <NAME> | [SachiniKarunarathne](https://github.com/SachiniKarunarathne) |
| <NAME> | [sd78912](https://github.com/sd78912) | 27 |
| <NAME> | [HiruniSenevirathne](https://github.com/HiruniSenevirathne) |
| gitlogin97 | [gitlogin97](https://github.com/gitlogin97) |
| <NAME> | [Critical07](https://github.com/Critical07) |
| <NAME> | [jilloestreicher](https://github.com/jilloestreicher) | 23 |=
| <NAME> | [burhannn](https://github.com/burhannn) |
| <NAME> | [ts4475](https://github.com/ts4475) |
| <NAME> | [Think-JIn99](https://github.com/Think-JIn99) |
| <NAME> | [keshavrkaranth](https://github.com/keshavrkaranth) | 1 |
| <NAME> | [triipaathii](https://github.com/triipaathii) | 26 |
| <NAME> | [abhishekdey4444](https://github.com/abhishekdey4444) |
| <NAME> | [styxOO7](https://github.com/styxOO7) |
| <NAME> | [praneet1001](https://github.com/praneet1001) | 24 |
| <NAME> | [varshajose123](https://github.com/varshajose123) |
| <NAME> | [ramadh-an](https://github.com/ramadh-an) | 1 |
|<NAME>|[Soumya111v](https://github.com/Soumya111v)|40|
| B<NAME> | [bharath-acchu](https://github.com/bharath-acchu) | 27 |
| <NAME>| [varous7](https://github.com/varous7) |
| Shravya| [ShravyaMallya](https://github.com/ShravyaMallya) |
| <NAME> | [react-ions](https://github.com/react-ions) | |
<file_sep>/CPP/binaryTreeTemplate.cpp
#include <bits/stdc++.h>
using namespace std;
struct TreeNode{
int data;
struct TreeNode* left;
struct TreeNode* right;
TreeNode(int val){
data = val;
left = right = NULL;
}
};
TreeNode* makeTree(vector<int> arr, int i){
if(i >= arr.size()) return NULL;
TreeNode* root = new TreeNode(arr[i]);
root->left = makeTree(arr, 2*i+1);
root->right = makeTree(arr, 2*i+2);
return root;
}
void printTree_PRE(TreeNode* root){
if(root == NULL) return;
// preorder: root, left, right
cout << root->data << " ";
printTree_PRE(root->left);
printTree_PRE(root->right);
}
void printTree_IN(TreeNode* root){
if(root == NULL) return;
// preorder: left, root, right
printTree_IN(root->left);
cout << root->data << " ";
printTree_IN(root->right);
}
void printTree_POST(TreeNode* root){
if(root == NULL) return;
// preorder: left, right, root
printTree_POST(root->left);
printTree_POST(root->right);
cout << root->data << " ";
}
int main(){
// makeTree() use number of elements = 1 3 7 15 (2**h - 1)
// driver code
TreeNode* root = makeTree({1,2,3,4,5,6,7}, 0);
printTree_PRE(root);
return 0;
}
<file_sep>/JavaScript/react-calculator/script.js
// ~ Calculator logic ~
const MAX_PROMPT_LENGTH = 10;
const MAX_HISTORY_LENGTH = 18;
const isPoint = key => key === '.';
const isZero = key => key === '0';
const isDigit = key => '0123456789'.indexOf(key) >= 0;
const isOp = key => '+-×÷'.indexOf(key) >= 0;
const isEqual = key => key === '=';
const isAC = key => key === 'AC';
const calcResult = ({ prompt, history }) => {
let expr = `${history}${prompt}`;
expr = expr.replace('÷', '/');
expr = expr.replace('×', '*');
const result = eval(expr);
return result.toString().substr(0, 10);
};
const nextMode = (state, key) => {
if (isAC(key)) return 'START';
const { mode } = state;
switch (mode) {
case 'RESULT':
if (isZero(key))
return 'START';
if (isDigit(key) || isPoint(key))
return 'ACC';
if (isOp(key))
return 'OP';
break;
case 'START':
if ((!isZero(key) && isDigit(key)) ||
isPoint(key))
return 'ACC';
if (isOp(key))
return 'OP';
break;
case 'ACC':
if (isOp(key))
return 'OP';
if (isEqual(key))
return 'RESULT';
break;
case 'OP':
if ((!isZero(key) && isDigit(key)) ||
isPoint(key))
return 'ACC';
break;
}
return mode;
};
const nextPrompt = (state, key) => {
if (isAC(key)) return '0';
const { mode, prompt, history } = state;
switch (mode) {
case 'RESULT':
if (isDigit(key) || isOp(key))
return key;
if (isPoint(key))
return '0.';
break;
case 'START':
case 'OP':
if ((!isZero(key) && isDigit(key)) ||
isOp(key))
return key;
if (isPoint(key))
return '0.';
break;
case 'ACC':
if (isDigit(key) ||
(isPoint(key) && prompt.indexOf('.') < 0))
return `${prompt}${key}`.substr(0, MAX_PROMPT_LENGTH);
if (isOp(key))
return key;
if (isEqual(key))
return calcResult(state).substr(0, MAX_PROMPT_LENGTH);
break;
}
return prompt;
};
const nextHistory = (state, key) => {
if (isAC(key)) return '';
const { mode, prompt, history } = state;
switch (mode) {
case 'RESULT':
if (isDigit(key) || isPoint(key))
return '';
if (isOp(key))
return prompt;
break;
case 'START':
if (isPoint(key))
return '';
if (isOp(key))
return `${history}${prompt}`;
break;
case 'OP':
if ((!isZero(key) && isDigit(key)) ||
isPoint(key))
return `${history}${prompt}`;
break;
case 'ACC':
if (isOp(key))
return `${history}${prompt}`;
if (isEqual(key))
return `${history}${prompt}=`;
break;
}
return history;
};
const digitsNames = ['one', 'two', 'three', 'four', 'five',
'six', 'seven', 'eight', 'nine'];
// ~ Components ~
const CalculatorKey = ({ onKeyPress, keyName, id }) => {
return (
<div
className="key"
onClick={() => onKeyPress(keyName)}
>
<span id={id}>
{keyName}
</span>
</div>
);
}
const CalculatorKeys = ({ onKeyPress }) => {
return (
<div id="keys">
{digitsNames.map((name, i) => (
<div key={name} style={{
gridRow: 4 - Math.floor(i / 3),
gridColumn: 1 + i % 3
}}>
<CalculatorKey keyName={(i + 1).toString()}
id={name} onKeyPress={onKeyPress} />
</div>
))}
<div style={{ gridRow: 5, gridColumn: "1 / span 2" }}>
<CalculatorKey keyName="0" id="zero"
onKeyPress={onKeyPress} />
</div>
<div style={{ gridRow: 5, gridColumn: 3 }}>
<CalculatorKey keyName="." id="decimal"
onKeyPress={onKeyPress} />
</div>
<div style={{ gridRow: "4 / span 2", gridColumn: 4 }}>
<CalculatorKey keyName="=" id="equals"
onKeyPress={onKeyPress} />
</div>
<div style={{ gridRow: 3, gridColumn: 4 }}>
<CalculatorKey keyName="+" id="add"
onKeyPress={onKeyPress} />
</div>
<div style={{ gridRow: 2, gridColumn: 4 }}>
<CalculatorKey keyName="-" id="subtract"
onKeyPress={onKeyPress} />
</div>
<div style={{ gridRow: 1, gridColumn: 4 }}>
<CalculatorKey keyName="×" id="multiply"
onKeyPress={onKeyPress} />
</div>
<div style={{ gridRow: 1, gridColumn: 3 }}>
<CalculatorKey keyName="÷" id="divide"
onKeyPress={onKeyPress} />
</div>
<div style={{ gridRow: 1, gridColumn: "1 / span 2" }}>
<CalculatorKey keyName="AC" id="clear"
onKeyPress={onKeyPress} />
</div>
</div>
);
}
const CalculatorDisplay = ({ history, prompt }) => {
let displayHistory = `${history}${prompt}`;
if (displayHistory.length > MAX_HISTORY_LENGTH)
displayHistory =
'...' +
displayHistory.substr(
displayHistory.length - MAX_HISTORY_LENGTH,
displayHistory.length
);
return (
<div id="screen">
<span id="display">{prompt}</span>
<span id="history">{displayHistory}</span>
</div>
);
};
class Calculator extends React.Component {
state = {
mode: 'START', // START, ACC, OP, RESULT
prompt: '0',
history: '',
}
handleKeyPress = (key) => {
const mode = nextMode(this.state, key);
const prompt = nextPrompt(this.state, key);
const history = nextHistory(this.state, key);
this.setState({ mode, prompt, history });
}
render() {
return (
<div id="calculator">
<CalculatorDisplay
prompt={this.state.prompt}
history={this.state.history}
/>
<CalculatorKeys onKeyPress={this.handleKeyPress} />
</div>
);
}
}
const App = () => <Calculator />
ReactDOM.render(<App />, document.getElementById('app'));<file_sep>/Python/reddit_extract.py
import praw
# Create your access keys in https://www.reddit.com/prefs/apps for python reddit data extraction
# Enter your client id, client secret, user agent details
reddit = praw.Reddit(
# Client ID
client_id="",
# Client Secret Key
client_secret="",
# User Agent
user_agent="",
check_for_async=False
)
# Search by subreddits only
def subreddit_extraction(subreddit):
for submission in reddit.subreddit(subreddit).hot(limit=None):
print(submission.title)
print("\n")
print("The data from the given subreddit has been extracted successfully.\n")
if __name__ == "__main__":
sub_reddit = "all" # Enter the subreddit you want to extract
subreddit_extraction(subreddit_extraction(sub_reddit))
<file_sep>/C/Circular_queue.c
#include <stdio.h>
#include <stdlib.h>
#define N 10
int F=-1,R=-1;
void enqueue(int q[],int val)
{
if((R+1)%N==F)
{
printf("\n Queue is full %d is not inserted",val);
}
else
{
R=(R+1)%N;
q[R]=val;
if(F==-1)
{
F=0;
}
}
}
int dequeue(int q[])
{
int item;
if(F==-1)
{
printf("\n Queue is empty");
return 0;
}
item=q[F];
if(F==R)
{
F=R=-1;
}
else
{
F=(F+1)%N;
}
return item;
}
void display(int q[])
{
int i;
for(i=F;i<=R;i++)
{
printf("\n The element is %d\n",q[i]);
}
if(F==-1)
{
printf("\n There is no element");
}
}
int main(int argc, char *argv[]) {
int q[N];
int val,n,item;
printf("\n 1.Insert \t\n 2.Delete \t\n 3.Display \t\n 4.EXIT \t\n");
do
{
printf("\nEnter choice = ");
scanf("%d",&n);
switch(n)
{
case 1:
printf("\nEnter the value of an element = ");
scanf("%d",&val);
enqueue(q,val);
break;
case 2:
item = dequeue(q);
if(item!=0) printf("\n%d is deleted",item);
break;
case 3:
display(q);
break;
case 4:
printf("EXIT");
}
}while(n!=4);
return 0;
}
/* ""OUTPUT""
1.Insert
2.Delete
3.Display
4.EXIT
Enter choice = 1
Enter the value of an element = 10
Enter choice = 1
Enter the value of an element = 20
Enter choice = 1
Enter the value of an element = 30
Enter choice = 3
The element is 10
The element is 20
The element is 30
Enter choice = 2
10 is deleted
Enter choice = 2
20 is deleted
Enter choice = 3
The element is 30
Enter choice = 4
EXIT
*/
<file_sep>/Java/Ticket_booking.java
/* Driver Code:
import java.util.Scanner;
public class TicketBooking {
public static void main(String[] args) {
Scanner tk = new Scanner(System.in);
int availTickets = tk.nextInt();
int reqJohn = tk.nextInt();
int reqMike = tk.nextInt();
AvailableTicket avlTic = new AvailableTicket(availTickets,reqJohn,reqMike);
Thread t = new Thread(avlTic);
Thread tt = new Thread(avlTic);
t.setName("John");
tt.setName("Mike");
t.setPriority(10);
t.start();
tt.start();
}
}
*/
class AvailableTicket extends Thread{
// Write your code here
int available;
int wantedMike;
int wantedJohn;
public AvailableTicket(int avail, int reqJohn, int reqMike) {
available = avail;
wantedMike = reqMike;
wantedJohn = reqJohn;
}
public void run() {
synchronized (this) {
int wanted;
String threadName = Thread.currentThread().getName();
if(threadName=="John") {
wanted = wantedJohn;
}
else {
wanted = wantedMike;
}
if(available >= wanted) {
System.out.print(Thread.currentThread().getName());
System.out.println(": tickets booked: " + wanted);
available = available - wanted;
}
else {
System.out.println(Thread.currentThread().getName() + ": not booked");
}
}
}
}
<file_sep>/Python/reverse-linked-list-in-groups-of-size-k.py
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if k==1:
return head
dummy = ListNode()
dummy.next=head
count = 0
prev = curr = nex = dummy
# count the nodes in LL
while curr.next:
curr=curr.next
count+=1
# until non-reversed nodes in LL >= k
while count>=k:
curr = prev.next
nex = curr.next
# reverse k-nodes in place
for i in range(1,k):
# memorise/understand/create logic
curr.next = nex.next
nex.next = prev.next
prev.next=nex
nex=curr.next
prev=curr
# reduce count by k times - for exit condition
count-=k
return dummy.next
<file_sep>/Wiki/RandomWikipedia.py
import requests
from bs4 import BeautifulSoup
import random
import wikipedia
# $********IMPORTING MODULES*********$
import tkinter
from tkinter import *
# $********CREATING WINDOW***********$
wind = tkinter.Tk()
wind.title("WIKI SCRAPER")
wind.geometry("800x600")
wind.resizable(width=False, height=False)
wind.config(bg="grey")
global linkToScrape
linkToScrape = "https://en.wikipedia.org/wiki/Programming_language"
def randomWikipediaPages(urlToScrape):
req = requests.get(url=urlToScrape, )
# print(req.status_code) ITS WORKING OR NOT
# print(req.content) TO ACCESS THE RESPONSE BODY AS BYTES, TYPE OF HTML DOC
beautifulSoupObj = BeautifulSoup(req.content, "html.parser")# CONVERTS TO UNICODE AND THEN PARSES IT (ALSO XML
# PARSER)
# print(beautifulSoupObj.prettify())
titleObj = beautifulSoupObj.find(id="firstHeading") # FIND TAG USING ID
# print(title)
print(titleObj.string) # A STRING = BIT OF TEXT WITHIN A TAG.
a_Title.config(text=titleObj.text)
# print("\n"+beautifulSoupObj.getText())
print(wikipedia.summary(title=titleObj.string))
wikiSummary.config(text=wikipedia.summary(title=titleObj.text))
# print(beautifulSoupObj)
links = beautifulSoupObj.find(id="bodyContent").find_all("a")
random.shuffle(links)
# print(type(links[4])) ITS A TAG
maxSize = len(links)
point = random.randint(1, maxSize)
for link in links[point:]:
if link["href"].find("/wiki/") == -1:
continue
if not link["href"].startswith("/wiki/"):
continue
if link["href"].find("/wiki/Category") != -1:
continue
if link["href"].find("/wiki/Help") != -1 or link["href"].find("/wiki/Wikipedia") != -1:
continue
if link["href"].find("/wiki/File") != -1:
continue
if link["href"].find("/wiki/Category") != -1:
continue
print(link)
global linkToScrape
linkToScrape = link
linkToScrape = "https://en.wikipedia.org" + linkToScrape["href"]
# print(linkToScrape)
break
def start():
# randomWikipediaPages("https://en.wikipedia.org" + linkToScrape["href"])
randomWikipediaPages(linkToScrape)
wikiTitle = Label(wind, text="WIKIPEDIA SCRAPER", font=("Fixedsys", 24,), bg="grey", fg="black", relief=RIDGE, bd=5)
wikiTitle.place(x=220, y=15, width=360, height=40)
articleTitle = Label(wind, text="Title : ", font=("Fixedsys", 15,), bg="grey", fg="black", bd=5)
articleTitle.place(x=5, y=100)
a_Title = Label(wind, text=" ", font=("Fixedsys", 15,), bg="grey", fg="black", bd=5)
a_Title.place(x=90, y=100)
convert = Button(wind, text="Change", command=start, font=("Courier", 16, "bold"), bg="black", fg="green",
relief=RAISED, bd=6)
convert.place(x=550, y=80)
wikiSummary = Label(wind, text=" ", font=("Fixedsys", 5,), bg="grey", fg="white", relief=RIDGE, bd=5, wraplength=600)
wikiSummary.place(x=0, y=150, width=800, height=450)
wind.mainloop()
<file_sep>/Python/left_rotate_array.py
def main():
n = int(input())
a = list(map(int,input().split()))
d = int(input())
b = [0]*n
if d%n==0:
for i in a:
print(i,end=" ")
else:
d = d%n
for i in range(n):
x = i-d
if x<0:
x = n+x
b[x] = a[i]
for i in b:
print(i,end=" ")
if __name__=="__main__":
main()<file_sep>/Python/ReplaceDuplicateOccurance.py
# Python3 code to demonstrate working of
# Replace duplicate Occurrence in String
# Using split() + enumerate() + loop
# initializing string
test_str = 'Gfg is best . Gfg also has Classes now. \
Classes help understand better . '
# printing original string
print("The original string is : " + str(test_str))
# initializing replace mapping
repl_dict = {'Gfg' : 'It', 'Classes' : 'They' }
# Replace duplicate Occurrence in String
# Using split() + enumerate() + loop
test_list = test_str.split(' ')
res = set()
for idx, ele in enumerate(test_list):
if ele in repl_dict:
if ele in res:
test_list[idx] = repl_dict[ele]
else:
res.add(ele)
res = ' '.join(test_list)
# printing result
print("The string after replacing : " + str(res))
<file_sep>/Python/json_to_xlsx/main.py
import json
import pandas as pd
import openpyxl
def json_to_xlsx(filename):
"""
This function will export the converted .xlsx file in same folder
:param filename : Pass the string filename as parameter (Example: if your file name is "myFile.json" then pass
"myFile" as parameter):
:return : this function does not return anything:
"""
with open(f'./{filename}.json') as json_file:
data = json.load(json_file)
df = pd.DataFrame(data)
df.to_excel(f'./{filename}.xlsx', index=False)
if __name__ == "__main__":
json_to_xlsx(filename="example")
<file_sep>/Python/Face verification/face verification.py
import numpy as np
from PIL import Image
from mtcnn.mtcnn import MTCNN
from keras_vggface.vggface import VGGFace
from keras_vggface.utils import preprocess_inputinput
import tensorflow as tf
tf.__version__
D = MTCNN()
model = VGGFace(model='resnet50',include_top=False,input_shape=(224,224,3),pooling='avg')
P1 = Image.open(r'C:\Users\lenovo\Desktop\ML\CNN\Data\FaceVerification\pos_1.jpg')
P2 = Image.open(r'C:\Users\lenovo\Desktop\ML\CNN\Data\FaceVerification\pos_2.jpg')
N1 = Image.open(r'C:\Users\lenovo\Desktop\ML\CNN\Data\FaceVerification\neg_1.jpg')
P1
P2
N1
P1 = np.asarray(P1)
P2 = np.asarray(P2)
N1 = np.asarray(N1)
def f_getFace(I):
r = D.detect_faces(I)
x1,y1,w,h = r[0]['box']
x2,y2 = x1+w,y1+h
face = I[y1:y2,x1:x2]
return Image.fromarray(face)
f1 = f_getFace(P1)
f2 = f_getFace(P2)
f3 = f_getFace(N1)
f1 = f1.resize((224,224))
f2 = f2.resize((224,224))
f3 = f3.resize((224,224))
f1
f1 = np.asarray(f1,'float32')
f2 = np.asarray(f2,'float32')
f3 = np.asarray(f3,'float32')
f1.shape
PE1 = model.predict(f1[np.newaxis,...])
PE2 = model.predict(f2[np.newaxis,...])
NE3 = model.predict(f3[np.newaxis,...])
PE1.shape
distance_pos = np.sum((PE1-PE2)**2)**0.5
distance_neg = np.sum((PE1-NE3)**2)**0.5
print(distance_pos,distance_neg)<file_sep>/CPP/Partitions.cpp
#include <bits/stdc++.h>
using namespace std;
int Partitions(int A,vector<int> &B){
int ans=0;
int total=0;
std::vector<int> suffx(A,0);
for (int i = 0; i <A; ++i)
{
total+=B[i];
}
if(total%3!=0){
return ans;
}
long long part=total/3;
long long local =0;
for (int i = A-1; i >=0; i--)
{
local+=B[i];
if(local==part){
suffx[i]=1;
}
}
for (int i = A-2; i >=0; i--)
{
suffx[i]+=suffx[i+1];
}
local=0;
for (int i = 0; i+2 < A; ++i)
{
local+=B[i];
if(local==part){
ans+=suffx[i+2];
}
}
return ans;
}
int main(){
std::vector<int> B={1, 2, 3, 0, 3};
int A=5;
cout<<Partitions(A,B)<<endl;
return 0;
}<file_sep>/Python/Design_Circular_Queue.py
"""Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer".
One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values.
Implementation the MyCircularQueue class:
MyCircularQueue(k) Initializes the object with the size of the queue to be k.
int Front() Gets the front item from the queue. If the queue is empty, return -1.
int Rear() Gets the last item from the queue. If the queue is empty, return -1.
boolean enQueue(int value) Inserts an element into the circular queue. Return true if the operation is successful.
boolean deQueue() Deletes an element from the circular queue. Return true if the operation is successful.
boolean isEmpty() Checks whether the circular queue is empty or not.
boolean isFull() Checks whether the circular queue is full or not."""
class MyCircularQueue:
def __init__(self, k: int):
self.data = [None] * k
self.head = self.tail = self.num_entries = 0
def enQueue(self, value: int) -> bool:
if self.isFull(): return False
self.data[self.tail] = value
self.tail = (self.tail + 1) % len(self.data)
self.num_entries += 1
return True
def deQueue(self) -> bool:
if self.isEmpty(): return False
self.num_entries -= 1
self.head = (self.head + 1) % len(self.data)
return True
def Front(self) -> int:
return -1 if self.isEmpty() else self.data[self.head]
def Rear(self) -> int:
return -1 if self.isEmpty() else self.data[(self.tail - 1) % len(self.data)]
def isEmpty(self) -> bool:
return self.num_entries == 0
def isFull(self) -> bool:
return self.num_entries == len(self.data)
# Your MyCircularQueue object will be instantiated and called as such:
# obj = MyCircularQueue(k)
# param_1 = obj.enQueue(value)
# param_2 = obj.deQueue()
# param_3 = obj.Front()
# param_4 = obj.Rear()
# param_5 = obj.isEmpty()
# param_6 = obj.isFull()
<file_sep>/Java/LongestIncreasingSubsequence.java
"""
Given an integer array nums, return the length of the longest strictly increasing subsequence.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
Example 1:
Input: nums = [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Example 2:
Input: nums = [0,1,0,3,2,3]
Output: 4
Example 3:
Input: nums = [7,7,7,7,7,7,7]
Output: 1
"""
import java.util.*;
class Solution {
public static int lengthOfLIS(int[] a) {
int dp[]=new int[a.length+1];
Arrays.fill(dp,1);
for(int i=1;i<=a.length;i++){
int max=0;
for(int j=1;j<i;j++){
if(a[j-1]<a[i-1]){
max=Math.max(max,dp[j]);
}
}
dp[i]=max+1;
}
int ans=0;
for(int i:dp)
ans=Math.max(ans,i);
return ans;
}
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter the size of array :- ");
int a=sc.nextInt();
int arr[]=new int[a];
System.out.println("Enter the elements of array :- ");
for(int i=0;i<a;i++){
arr[i]=sc.nextInt();
}
System.out.println("The maximum array size with increasing subsequence is :- "+lengthOfLIS(arr));
}
}<file_sep>/CPP/Add_One _to_Number.cpp
#include <iostream>
#include<vector>
using namespace std;
vector<int> plusOne(vector<int> &A){
int n=A.size();
int carry=0;
vector<int> res;
res.push_back(1+A[n-1]%10);
carry=(1+A[n-1])/10;
for (int i = n-2; i >=0; i--)
{
res.push_back((carry+A[i])%10);
carry=(carry+A[i])/10;
}
if(carry){
res.push_back(carry);
}
int x=res.size();
for(int i=0;i<=x/2;i++){
swap(res[i],res[x-i-1]);
}
while(res[0]==0){
res.erase(res.begin());
}
for (int i = 0; i < res.size(); ++i)
{
cout<<res[i]<<" ";
}
cout<<endl;
return res;
}
int main(){
vector<int> A={1, 2, 3};
plusOne(A);
}
<file_sep>/Python/Language Translator/Readme.md
# Project name: Language Translator
Programming Languagw used:
- [X] Python 3.X
### Libraries Used:
- Tkinter
- Textblob
### How to install this libraries:
Tkinter
```
pip install tk
```
Textblob
```
pip install -U textblob
python -m textblob.download_corpora
```
<hr>
About Project and how to use it:
This project is used to translate one languages to another languages.
To used this app, just copy your text it automatically detect's the language of your text and you have to select in which language you have to convert your text<b>(click on choose output language )</b>.
<br>After that click on <b>Click</b> button.
#### Output of the code-

---
Contributed by- [<NAME>](https://github.com/Satyam-bajpai007)
<file_sep>/Python/ClassificationBreastCanser.py
import numpy as np
from sklearn import preprocessing, neighbors, model_selection
import pandas as pd
df = pd.read_csv('breast-cancer-wisconsin.data')
df.replace('?', -99999, inplace=True)
df.drop(['id'], 1, inplace=True)
#print(df.head())
x = np.array(df.drop(['class'], 1))
y = np.array(df['class'])
xTrain, xTest, yTrain, yTest = model_selection.train_test_split(x, y, test_size = 0.8)
classifier = neighbors.KNeighborsClassifier()
classifier.fit(xTrain, yTrain)
accuracy = classifier.score(xTest, yTest)
print('Accuracy ', accuracy)
example_data = np.array([2,1,2,1,2,1,3,1,2])
example_data = example_data.reshape(len(example_data), -1)
prediction = classifier.predict(example_data)
print(prediction)
<file_sep>/Java/sorting algo/Merge_Sort.java
import java.util.*;
import java.io.*;
public class Merge_Sort {
static void merge(int a[], int l, int r, int m){
int n1 = m - l + 1;
int n2= r - m;
int b[] = new int[n1];
int c[] = new int[n2];
int k = 0;
for(int i = l; i <= m; i++){
b[k] = a[i];
k++;
}
k = 0;
for(int i = m + 1; i <= r; i++){
c[k] = a[i];
k++;
}
int f = 0, s = 0;
int j = l;
while(f < n1 && s < n2){
if(b[f] > c[s]){
a[j] = c[s];
s++;
}
else{
a[j] = b[f];
f++;
}
j++;
}
while(f < n1){
a[j] = b[f];
f++;
j++;
}
while(s < n2){
a[j] = c[s];
s++;
j++;
}
}
static void sort(int a[], int l, int r){
if(l < r){
int m = (l + r) / 2;
sort(a, l, m);
sort(a, m + 1, r);
merge(a, l, r, m);
}
}
static void display_array(int a[], int l, int r){
for(int i = l; i <= r; i++)
System.out.print(a[i] + " ");
System.out.println();
}
public static void main(String[] args) throws Exception {
Reader.init(System.in);
int n = Reader.nextint();
int a[] = new int[n];
for(int i = 0; i< n; i++)
a[i] = Reader.nextint();
sort(a, 0, n - 1);
for(int i = 0; i < n; i++)
System.out.print(a[i] + " ");
}
}
class Reader {
static BufferedReader reader;
static StringTokenizer tokenizer;
static void init(InputStream input) {
reader = new BufferedReader(new InputStreamReader(input) );
tokenizer = new StringTokenizer("");
}
static String next() throws IOException {
while ( ! tokenizer.hasMoreTokens() ) {
//TODO add check for eof if necessary
tokenizer = new StringTokenizer(
reader.readLine() );
}
return tokenizer.nextToken();
}
static int nextint() throws IOException {
return Integer.parseInt( next() );
}
static long nextlong() throws IOException {
return Long.parseLong( next() );
}
static double nextdouble() throws IOException {
return Double.parseDouble( next() );
}
}<file_sep>/C/pallindrome
#include <stdio.h>
int main() {
int n, reversed = 0, remainder, original;
printf("Enter an integer: ");
scanf("%d", &n);
original = n;
// reversed integer is stored in reversed variable
while (n != 0) {
remainder = n % 10;
reversed = reversed * 10 + remainder;
n /= 10;
}
// palindrome if orignal and reversed are equal
if (original == reversed)
printf("%d is a palindrome.", original);
else
printf("%d is not a palindrome.", original);
return 0;
}
<file_sep>/Euclid's Series.py
# Python program to demonstrate working of extended
# Euclidean Algorithm
# function for extended Euclidean Algorithm
def gcdExtended(a, b):
# Base Case
if a == 0:
return b,0,1
else:
gcd, x, y = gcdExtended(b % a, a)
return gcd, y - (b // a) * x, x
# from here execution starts
# Driver code
if __name__ == '__main__':
print("ax + by = gcd(a, b)") # this is what we have to do
# taking input from the user
m = int(input("Enter the first number: "))
n = int(input("Enter the second number: "))
# invoking the function
gcd, x, y = gcdExtended(m, n)
print("The gcd or hcf is: ", gcd)
# using fstring
print(f"x = {x}, y = {y}")
<file_sep>/Python/Profit_or_Loss_Calculator.py
# Python Program to Calculate Profit or Loss
actual_cost = float(input(" Please Enter the Actual Product Price: "))
sale_amount = float(input(" Please Enter the Sales Amount: "))
if(actual_cost > sale_amount):
amount = actual_cost - sale_amount
print("Total Loss Amount = {0}".format(amount))
elif(sale_amount > actual_cost):
amount = sale_amount - actual_cost
print("Total Profit = {0}".format(amount))
else:
print("No Profit No Loss!!!")
<file_sep>/Java/reversestr.java
import java.lang.*;
import java.io.*;
import java.util.*;
public class RS{
public static void main(String[] args)
{
String input = "JAVACOMPILER";
byte[] BA = input.getBytes();
byte[] res = new byte[BA.length];
for (int i = 0; i < BA.length; i++)
res[i] = BA[BA.length - i - 1];
System.out.println(new String(res));
}
}
<file_sep>/Python/json_to_xlsx/requirements.md
# Json to xlsx Converter
### This scripts libraries like
- pandas
- openpyxl
- json
### How it works
- Keep the file you want to convert and the script in same folder
- Pass the file name as parameter
- Example: if filename is `example.json` then pass `example` as parameter in function<file_sep>/Python/chatbot.py
import speech_recognition as sr
import datetime
import webbrowser as wb
import os
import pyttsx3
import wikipedia
import pywhatkit
import pyjokes as pj
import smtplib
import requests
from bs4 import BeautifulSoup
import winsound
import operator
engine = pyttsx3.init()
def sendmail():
recivers = ['<EMAIL>','<EMAIL>','<EMAIL>']
a = smtplib.SMTP('smtp.gmail.com',587)
a.starttls()
a.login('<EMAIL>','PintooAvyay_72')
a.sendmail('<EMAIL>',recivers,'test message')
a.quit()
def search():
speech("enter the topic you want to search on wikipedia ")
query= takeCommand().lower()
wresult = str(wikipedia.search(query, results = 1))
results = wikipedia.summary(wresult, sentences=2)
speech("According to Wikipedia")
print(results)
speech(results)
def wishMe():
hour = int(datetime.datetime.now().hour)
if(hour >= 0 and hour <12 ):
wish = 'good morning'
#speech('good morning')
#print('good morning')
elif(hour >=12 and hour<= 18):
wish = 'good afternoon'
#speech('good afternoon')
#print('good afternoon')
else:
wish = 'good evening'
#speech('good evening')
# print('good evening')
return wish
def Whatsapp():
speech('opening whatsApp')
os.startfile('C:\\Users\\avyay\\AppData\\Local\\WhatsApp\\WhatsApp.exe')
def chrome():
speech('opening chrome')
os.startfile('C:\Program Files\Google\Chrome\Application\chrome.exe')
def speech(audio):
engine.setProperty('rate', 200)
voices = engine.getProperty('voices') #getting details of current voice
#engine.setProperty('voice', voices[1].id) #changing index, changes voices. o for male
engine.setProperty('voice', voices[0].id)
engine.say(audio)
engine.runAndWait()
def dateAndTime():
time = datetime.datetime.now().strftime("%Y\n %B\n %A\n %I %M %S %Z")
print(time)
speech(time)
def google():
wb.open('google.com')
speech("opening google")
def takeCommand():
#It takes microphone input from the user and returns string output
r = sr.Recognizer()
with sr.Microphone() as source:
r.adjust_for_ambient_noise(source,duration=1)
print()
print("Listening...")
print()
#r.pause_threshold = 1
audio = r.listen(source)
try:
print("Recognizing...")
print()
query = r.recognize_google(audio, language='en-in')
print(f"you said: {query}\n")
except Exception as e:
print("Say that again please...")
print()
return "None"
return query
def playmusic():
speech("what would you like to play ")
song = takeCommand()
speech('playing '+song)
pywhatkit.playonyt(song)
def joke():
speech('telling a joke')
a = pj.get_joke(language='en',category='neutral')
speech(a)
print(a)
def searchOnGoogle():
speech('what would you like to search on google')
print('what would you like to search on google')
a= takeCommand()
pywhatkit.search(a)
def weather():
speech("please tell city name ")
city = takeCommand().lower()
print(city)
url = "https://google.com/search?q="+"weather"+city
html = requests.get(url).content
soup = BeautifulSoup(html,'html.parser')
temp = soup.find('div',attrs={'class': 'BNeawe iBp4i AP7Wnd'}).text
time_skyDescription = soup.find('div',attrs={'class': 'BNeawe tAd8D AP7Wnd'}).text
data = time_skyDescription.split('\n')
time = data[0]
sky = data[1]
listdiv = soup.findAll('div',attrs={'class': 'BNeawe s3v9rd AP7Wnd'})
strd = listdiv[5].text
pos = strd.find('wind')
otherData= strd[pos:]
print("Temperature is ",temp)
speech("Temperature is "+temp)
print("time is ",time)
speech("time is "+time)
print("sky description: ",sky)
speech("sky description: "+sky)
print(otherData)
def alarm(Timing):
altime = str(datetime.datetime.now().strptime(Timing,"%I:%M %p"))
altime = altime[11:-3]
print(altime)
Horeal = altime[:2]
Horeal = int(Horeal)
Mireal = altime[3:5]
Mireal = int(Mireal)
print(f"Done, alarm is set for {Timing}")
while True:
if Horeal == datetime.datetime.now().hour and Mireal == datetime.datetime.now().minute:
print("alarm is running")
winsound.PlaySound('abc',winsound.SND_LOOP)
elif Mireal<datetime.datetime.now().minute:
break
def calculate():
r = sr.Recognizer()
with sr.Microphone( )as source:
speech("say what you want to calculate, example 3 plus 3")
print("Listening...")
r.adjust_for_ambient_noise(source)
audio = r.listen(source)
my_string = r.recognize_google(audio)
print(my_string)
def get_operator_fn(op):
return{
'+':operator.add,
'-':operator.sub,
'*':operator.mul,
'divided':operator.__truediv__,
}[op]
def evel_binary(op1,oper,op2):
op1,op2 = int(op1),int(op2)
return get_operator_fn(oper)(op1,op2)
speech("your result is ")
speech(evel_binary(*(my_string.split())))
wish = wishMe()
print(wish)
speech(f"{wish} sir, i am jarvis what would you like to do")
while True:
speechinput= takeCommand().lower()
#print(speechinput)
if 'time' in speechinput :
dateAndTime()
elif 'google' in speechinput:
google()
elif 'play music' in speechinput:
playmusic()
elif 'open whatsapp' in speechinput:
Whatsapp()
elif 'open chrome' in speechinput:
chrome()
elif 'search' in speechinput:#wikipedia
search()
elif 'tell me a joke' in speechinput:
joke()
elif 'send mail' in speechinput:
sendmail()
elif 'exit' in speechinput:
speech("goodbye sir going off duty")
print("goodbye sir going off duty")
exit()
elif 'search on web' in speechinput:
searchOnGoogle()
elif 'what is the weather' in speechinput:
weather()
elif 'what is your name' in speechinput:
speech('my name is jarvis your personal voice assistant')
elif'who made you' in speechinput:
speech('i was made by <NAME>')
elif 'alarm' in speechinput:
speech("say set alarm for 5:30 am ")
print("say set alarm for 5:30 am")
tt = takeCommand()
tt = tt.replace("set alarm to ","")
tt = tt.replace(".","")
tt = tt.upper()
alarm(tt)
elif'calculate' in speechinput:
calculate()
<file_sep>/CPP/binary number to decimal number system.cpp
//C++ program to convert a binary number to decimal number system
#include <bits/stdc++.h>
using namespace std;
// Function to convert a binary number to decimal number system
int convertBinaryToDecimal(int n)
{
int decimalNumber=0,i=0,remainder;
while (n!=0)
{
remainder = n%10;
n /= 10;
decimalNumber += remainder*pow(2,i);
i++;
}
return decimalNumber;
}
// Driven Program to check above
int main()
{
int n;
cout <<"Enter a binary number: ";
cin >> n;
cout << n << " in binary = " << convertBinaryToDecimal(n) <<" in decimal";
return 0;
}
<file_sep>/CPP/Maximum_Absolute_Difference.cpp
#include <bits/stdc++.h>
using namespace std;
int maxArr(vector<int> &a){
int max1=INT_MIN,min1=INT_MAX,max2=INT_MIN,min2=INT_MAX;
for (int i = 0; i <a.size(); ++i)
{
max1=max(max1,a[i]+i);
min1=min(min1,a[i]+i);
max2=max(max2,a[i]-i);
min2=min(min2,a[i]-i);
}
int ans=INT_MIN;
for (int i = 0; i <a.size(); ++i)
{
ans=max(ans,abs(a[i]+i));
ans=max(ans,abs(a[i]+i));
ans=max(ans,abs(a[i]-i));
ans=max(ans,abs(a[i]-i));
}
return ans;
}
int main(){
vector<int> a={1, 3, -1};
cout<<maxArr(a)<<endl;
}<file_sep>/Java/SudokuSolver.java
//sudoku solver
class Solution {
public void solveSudoku(char[][] board) {
solve(board);
}
boolean solve(char[][] board){
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if(board[i][j]=='.'){
for(char c='1';c<='9';c++){
if(isvalid(board,i,j,c)){
board[i][j]=c;
if(solve(board)==true){return true;}
else{board[i][j]='.';}
}
}
return false;
}
}
}
return true;
}
boolean isvalid(char[][]board, int row,int col, char c){
for(int i=0;i<9;i++){
if( board[row][i]==c){return false;}
if( board[i][col]==c){return false;}
if(board[3*(row/3) +i/3][3*(col/3)+i%3]==c){return false;}
}
return true;
}
}
<file_sep>/Python/permutaition.py
"""You can check all permutaion start with 1 to n
just like
1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1
"""
import copy
def permutaition(num_list,removed_nums):
if len(num_list) == 1:
print(removed_nums + num_list)
return
for i in num_list:
list_copy = copy.deepcopy(num_list)
permutaition(list_copy.replace(i,''), removed_nums + i + " ")
#input the number of n
num_list = [str(i) for i in range(1 , int(input("input n: ")) + 1)]
num_list = ''.join(num_list)
permutaition(num_list,"")
<file_sep>/Python/Scraping/Top-100-movies-by-Genre---Rotten-Tomato/README.md
<h1 align=center>Top 100 Movies by Genre - Rotten Tomatoes Scraper</h1>
Takes A Movie Genre As A Command-Line Argument, scrapes the top 100 movies of a particular genre and stores rank,rating, title of the movie and total no of reviews in the desired csv file.
## *Author Name*
[<NAME>](https://github.com/Anshul275)
## Pre-Requisites
Run The Command `pip install -r requirements.txt`
## To Run the File
For Windows - `python top100_scrapy.py 'movie-genre name'`
For Ubuntu/Linux - ` ./top100_scrapy.py 'movie-genre name'`
## Screenshots -
### Generated CSV File

### If movie related to the entered genre is not found

<file_sep>/Letter_Counter_GUI_App.py
import tkinter as tk
root = tk.Tk()
root.geometry("400x260+50+50")
root.title("Welcome to Letter Counter App")
message1 = tk.StringVar()
Letter1 = tk.StringVar()
def printt():
message=message1.get()
letter=Letter1.get()
message = message.lower()
letter = letter.lower()
# Get the count and display results.
letter_count = message.count(letter)
a = "your message has " + str(letter_count) + " " + letter + "'s in it."
labl = tk.Label(root,text=a,font=('arial',15),fg='black').place(x=10,y=220)
lbl = tk.Label(root,text="Enter the Message--",font=('Ubuntu',15),fg='black').place(x=10,y=10)
lbl1 = tk.Label(root,text="Enter the Letter you want to count--",font=('Ubuntu',15),fg='black').place(x=10,y=80)
E1= tk.Entry(root,font=("arial",15),textvariable=message1,bg="white",fg="black").place(x=10,y=40,height=40,width=340)
E2= tk.Entry(root,font=("arial",15),textvariable=Letter1,bg="white",fg="black").place(x=10,y=120,height=40,width=340)
but = tk.Button(root,text="Check",command=printt,cursor="hand2",font=("Times new roman",30),fg="white",bg="black").place(x=10,y=170,height=40,width=380)
# print("In this app, I will count the number of times that a specific letter occurs in a message.")
# message = input("\nPlease enter a message: ")
# letter = input("Which letter would you like to count the occurrences of?: ")
root.mainloop()
<file_sep>/Python/palindrome with recursion.py
def palindrome(s):
if len(s)==0 or len(s)==1:
return True
else:
if s[0]==s[-1]:
return palindrome(s[1:-1])
else:
return False
s=input("Enter a String")
if palindrome(s):
print("It is a Palindrome")
else:
print("It is not a Palindrome")
<file_sep>/PHP/min_max_in_array.php
<?php
// Returns maximum in array
function getMax($array)
{
$n = count($array);
$max = $array[0];
for ($i = 1; $i < $n; $i++)
if ($max < $array[$i])
$max = $array[$i];
return $max;
}
// Returns maximum in array
function getMin($array)
{
$n = count($array);
$min = $array[0];
for ($i = 1; $i < $n; $i++)
if ($min > $array[$i])
$min = $array[$i];
return $min;
}
// Driver code
$array = array(1, 2, 3, 4, 5);
echo(getMax($array));
echo("\n");
echo(getMin($array));
?>
<file_sep>/C/heapsort.c
#include<stdlib.h>
#include<stdio.h>
void swap(int *first, int *second){
int temp = *first;
*first = *second;
*second = temp;
}
void min_heapify(int heap[], int sub_root, int length){
int max = sub_root;
while(max <= length){
int here = max;
int left = here * 2;
int right = here * 2 + 1;
if(left <= length && heap[left] > heap[max]) max = left;
if(right <= length && heap[right] > heap[max]) max = right;
if (max != here) swap(&heap[max],&heap[here]);
else break;
}
}
void build_heap(int heap[], int length){
for(int i = length / 2; i >= 1; i--){
min_heapify(heap, i, length);
}
}
void heap_sort(int heap[], int heap_size){
for (int i = heap_size; i >= 1; i--){
swap(&heap[1],&heap[i]);
min_heapify(heap,1,i-1);
}
}
int main(){
int heap[9] = {-1,12, 30, 21, 55, 25, 72, 45, 50};
int length = sizeof(heap) / sizeof(int) - 1;
build_heap(heap,length);
heap_sort(heap,length);
for (int i = 0; i < 9; i++){
printf("%d\t",heap[i]);
}
}<file_sep>/Python/Blackjack/blackjack_main.py
# To know basic idea of this game:
# Checkout => https://games.washingtonpost.com/games/blackjack
################ Our Blackjack House Rules ####################
## The deck is unlimited in size.
## There are no jokers.
## The Jack/Queen/King all count as 10.
## The the Ace can count as 11 or 1.
## Use the following list as the deck of cards:
## cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
## The cards in the list have equal probability of being drawn.
## Cards are not removed from the deck as they are drawn.
## The computer is the dealer.
###############################################################
import blackjack_art
import random
import os
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
#Initial amount in both players' acoount
dealer_cash = 1000
player_cash = 1000
player_win = 1
def add_card(total):
card_provided = random.choice(cards)
#this condition will decide whether to use 'ACE' card as 1 or 11
if card_provided == 11:
if total+card_provided > 21:
card_provided = 1
return card_provided
#To print result of each game
def result (a,b,a_cards,b_cards):
global player_win
if a>21:
player_win = 0
return "You went over. You lose 😭"
elif b>a and b<=21:
player_win = 0
#to check whether dealer got a blackjack
if b==21 and len(b_cards)==2:
return "Dealer got a blackjack. You lost 😥"
return "You lose 😤"
elif a>b and a<=21:
player_win = 1
#to check whether player got a blackjack
if a==21 and len(a_cards)==2:
return "You got a blackjack. You win 😄"
return "You win 🙃"
elif b>21 and a<=21:
player_win = 1
return "Dealer went over. You win 😀"
else:
player_win = -1
return "It's a draw 😬 "
if input("Do you want to play a game of Blackjack? Type 'y' or 'n': ") == 'y':
game_continue = True
else:
game_continue = False
while game_continue:
os.system('clear')
dealer_cards = []
player_cards = []
dealer_total = 0
player_total = 0
player_continue = True
print (blackjack_art.logo)
print("\nBalance:")
print(f" Dealer: {dealer_cash}")
print(f" Player: {player_cash}")
cash_deal = int(input("Make a deal($1, $5, $25, $50, $100, $500, $1000): $"))
for i in range(2):
dealer_cards.append(add_card(dealer_total))
player_cards.append(add_card(player_total))
dealer_total+=dealer_cards[i]
player_total+=player_cards[i]
while dealer_total < 16:
dealer_cards.append(add_card(dealer_total))
dealer_total+=dealer_cards[len(dealer_cards)-1]
print(f" Your cards: {player_cards}, current score: {player_total}")
print(f" Computer's first card: {dealer_cards[0]}")
while player_total < 21 and player_continue:
player_choice = input("Type 'y' to get another card, type 'n' to pass: ")
if player_choice == 'y':
player_cards.append(add_card(player_total ))
player_total+=player_cards[len(player_cards)-1]
print(f" Your cards: {player_cards}, current score: {player_total}")
else:
player_continue = False
print(f" Your final hand: {player_cards}, final score: {player_total}")
print(f" Computer's final hand: {dealer_cards}, final score: {dealer_total}")
print(result(player_total, dealer_total,player_cards,dealer_cards))
if player_win == 1:
player_cash += cash_deal
dealer_cash -= cash_deal
if player_win == 0:
player_cash -= cash_deal
dealer_cash += cash_deal
if player_cash <=0 or dealer_cash <=0:
game_continue = False
if player_cash <=0:
print(blackjack_art.you_lost)
else:
print(blackjack_art.you_won)
else:
if input("Do you want to play again a game of Blackjack? Type 'y' or 'n': ") == 'y':
game_continue = True
else:
game_continue = False<file_sep>/Python/DiscordAnimeBot/animebot.py
import asyncio
import discord
from discord import channel
from discord import colour
from discord.embeds import Embed
import requests
import json
import random
client = discord.Client()
# get random anime facts
def get_fax():
url = "https://airi1.p.rapidapi.com/fact"
headers = {
'auth': "182720a05a3766ca59d00c5ec46e8a3cd793d0aee852",
'x-rapidapi-key': "4fdebbade4msh8568e7f28f6d9acp1d7b97jsn66f10976032e",
'x-rapidapi-host': "airi1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers)
print(response.json())
return response.json()
# get random anime cute characters
def get_waifu():
url = "https://airi1.p.rapidapi.com/waifu"
headers = {
'auth': "182720a05a3766ca59d00c5ec46e8a3cd793d0aee852",
'x-rapidapi-key': "4fdebbade4msh8568e7f28f6d9acp1d7b97jsn66f10976032e",
'x-rapidapi-host': "airi1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers)
return response.json()
#get random anime quotes
def get_quote():
url = "https://airi1.p.rapidapi.com/quote"
headers = {
'auth': "182720a05a3766ca59d00c5ec46e8a3cd793d0aee852",
'x-rapidapi-key': "4fdebbade4msh8568e7f28f6d9acp1d7b97jsn66f10976032e",
'x-rapidapi-host': "airi1.p.rapidapi.com"
}
response = requests.request("GET", url, headers=headers)
print(response.json())
return response.json()
#get naruto chracter details
def nrt_character(name):
_name = name
print(str(_name))
query = '''
{
characters(filter: {name:" ''' +str(_name) +'''"}) {
info {
count
pages
next
prev
}
results {
_id
name
avatarSrc
description
rank
village
}
}
}
'''
print(query)
url = 'http://narutoql.com/graphql?query='+ query
# print(query)
r = requests.get(url)
print(r.status_code)
print(r.text)
resp = r.json()
if resp["data"]["characters"]["info"]["count"] == 0:
return False
else:
return resp
#get naruto village details
def nrt_village(name):
_name = name
print(str(_name))
query = '''
{
characters(filter: {village:"''' +str(_name) + '''"}) {
info {
count
pages
next
prev
}
results {
_id
name
avatarSrc
description
rank
village
}
}
}
'''
print(query)
url = 'http://narutoql.com/graphql?query='+ query
# print(query)
r = requests.get(url)
print(r.status_code)
print(r.text)
resp = r.json()
if resp["data"]["characters"]["info"]["count"] == 0:
return False
else:
return resp
#get naruto rank details
def nrt_rank(rank, village):
print(str(rank))
query = '''
{
characters(filter: {village:"''' +str(village)+ '''",''' +'''rank:"''' + str(rank) +'''"}) {
info {
count
pages
next
prev
}
results {
_id
name
avatarSrc
description
rank
village
}
}
}
'''
print(query)
url = 'http://narutoql.com/graphql?query='+ query
# print(query)
r = requests.get(url)
print(r.status_code)
print(r.text)
resp = r.json()
if resp["data"]["characters"]["info"]["count"] == 0:
return False
else:
return resp
@client.event
async def on_message(message):
if message.author == client.user :
return
if message.content.startswith('$waifu'):
rsp = get_waifu()
print(rsp)
embed = discord.Embed(
title = rsp["names"]["en"],
colour= discord.Colour.blue()
)
embed.set_footer(text ="from Animo")
embed.set_thumbnail(url =rsp["images"][0])
embed.set_image(url = rsp["images"][-1])
embed.add_field(name="From", value=rsp["from"]["name"])
embed.add_field(name="Type", value=rsp["from"]["type"])
await message.channel.send(embed = embed)
elif message.content.startswith('$fax'):
rsp = get_fax()
await message.channel.send( "❗Fact ahead❗\n" +"**" + rsp['fact'] + "**")
elif message.content.startswith("$quote"):
rsp = get_quote()
embed = discord.Embed(
title= rsp["said"] + ":",
description= rsp["quote"],
colour = discord.Colour.orange()
)
embed.add_field(name="Anime",value=rsp["anime"])
embed.set_footer(text="from Animo")
await message.channel.send(embed=embed)
elif message.content.startswith("$nrt character"):
await message.channel.send("**" +"Please Enter Character's name :" + "**")
def check(m):
return m.author == message.author
try:
guess = await client.wait_for('message', check=check, timeout=10.0)
except asyncio.TimeoutError:
return await message.channel.send("Sorry, You Took Too Long")
rsp = nrt_character(guess.content)
if rsp== False:
return await message.channel.send("Sorry No Character Found")
else:
embed = discord.Embed(
title = rsp["data"]["characters"]['results'][0]["name"],
description = rsp["data"]["characters"]['results'][0]["description"],
colour = discord.Colour.blue()
)
embed.set_footer(text ="from Animo")
embed.set_thumbnail(url =rsp["data"]["characters"]['results'][0]['avatarSrc'])
embed.set_image(url = rsp["data"]["characters"]['results'][0]['avatarSrc'])
embed.add_field(name="Rank", value=rsp["data"]["characters"]['results'][0]["rank"])
embed.add_field(name="Village", value=rsp["data"]["characters"]['results'][0]["village"])
await message.channel.send(embed=embed)
elif message.content.startswith("$nrt village"):
await message.channel.send("**" +"Please Enter Village's name :" + "**")
def check(m):
return m.author == message.author
try:
guess = await client.wait_for('message', check=check, timeout=10.0)
except asyncio.TimeoutError:
return await message.channel.send("Sorry, You Took Too Long")
rsp = nrt_village(guess.content)
if rsp== False:
return await message.channel.send("Sorry No Clan Found")
else:
d = rsp["data"]["characters"]['results']
random.shuffle(d)
for item in d[:5]:
embed = discord.Embed(
title = item["name"],
description = item["description"],
colour = discord.Colour.blue()
)
embed.set_footer(text ="from Animo")
embed.set_thumbnail(url =item['avatarSrc'])
embed.set_image(url = item['avatarSrc'])
await message.channel.send(embed=embed)
elif message.content.startswith("$nrt rank"):
await message.channel.send("**" +"Please Enter Rank's name :" + "**")
def check(m):
return m.author == message.author
try:
rank = await client.wait_for('message', check=check, timeout=10.0)
except asyncio.TimeoutError:
return await message.channel.send("Sorry, You Took Too Long")
await message.channel.send("**" +"Please Enter Village's name :" + "**")
try:
village = await client.wait_for('message', check=check, timeout=10.0)
except asyncio.TimeoutError:
return await message.channel.send("Sorry, You Took Too Long")
rsp = nrt_rank(rank.content ,village.content)
if rsp== False:
return await message.channel.send("Sorry No Clan Found")
else:
d = rsp["data"]["characters"]['results']
random.shuffle(d)
for item in d:
embed = discord.Embed(
title = item["name"],
description = item["description"],
colour = discord.Colour.blue()
)
embed.set_footer(text ="from Animo")
embed.set_thumbnail(url =item['avatarSrc'])
embed.set_image(url = item['avatarSrc'])
await message.channel.send(embed=embed)
# get discord bot token from developer portal of discord
client.run('YOUR BOT TOKEN')<file_sep>/Python/N-queens.py
import random
def stochastic_hillclimbing(state):
expand = 0
generate = 0
while 1:
steep = []
neighbors = []
next_state = state.copy()
current = attacking_queens(next_state)
if current == 0:
print("No of nodes generated:")
print(generate)
print("No of nodes expanded:")
print(expand)
return state
for i in range(0, 8):
next_state[random.randint(0, 7)] = random.randint(0, 7)
next = attacking_queens(next_state)
if current == next:
next_state = state.copy()
continue
else:
if next < current:
steep.append(current - next)
neighbors.append(next_state)
next_state = state.copy()
if len(neighbors) == 0:
continue
generate += len(neighbors)
# if len(neighbors)==1:
# state = neighbors[0].copy()
# expand += 1
# continue
j = random.randrange(0, len(neighbors))
state = neighbors[j].copy()
expand += 1
print("Next state:")
print(state)
def attacking_queens(state):
attack = 0
for i in range(0, len(state)):
for j in range(0, len(state)):
if i != j:
if state[i] == state[j]:
attack += 1
offset = j - i
if abs(state[i] - state[j]) == offset:
attack += 1
return attack
def initial_state():
state = []
for i in range(0, 8):
state.append(random.randint(0, 7))
return state
def main():
s = initial_state()
print("Initial state:")
print(s)
sol = stochastic_hillclimbing(s)
print("\n\nSolution:")
print(sol)
for i in range(8):
for i2 in range(8):
if sol[i2] == i:
print("Q", end=" ")
else:
print("*", end=" ")
print()
if __name__ == "__main__":
main()
<file_sep>/gif-creater.py
from moviepy.editor import *
from moviepy.editor import *
clip = (VideoFileClip("Gif-Creator/video.webm").subclip((2.25),(6.25))
.resize(0.3))
clip.write_gif("output.gif")
<file_sep>/Python/Blinding Auction/blindAuction.py
# This program is designed so that we can organize blind auction at a small platform
import os
logo = '''
___________
\ /
)_______(
|"""""""|_.-._,.---------.,_.-._
| | | | | | ''-.
| |_| |_ _| |_..-'
|_______| '-' `'---------'` '-'
)"""""""(
/_________\\
.-------------.
/_______________\\
'''
bid_details = {}
bid_continue = True
max_bid = 0
winner = ""
print(logo)
print("Welcome to the secret auction program.")
while bid_continue:
name = input("What is your name?: ")
bid_price = float(input("What's your bid?: $"))
bid_details[name] = bid_price
if bid_price > max_bid:
max_bid = bid_price
winner = name
continue_bid = input("Are there any other bidders? Type 'yes' or 'no'.\n").lower()
if continue_bid == 'yes':
os.system('clear')
else:
bid_continue = False
print(f"Hence, the highest bid is ${max_bid} made by {winner}.")
<file_sep>/Python/SelectinSort.py
#It Doesn't Comes Under Selection Sort
import time as t
print(" Brought To You by ")
t.sleep(0.5)
print("*"*40)
t.sleep(0.5)
print(" ____ _ _ ")
print(" | _ \ ___ _ __ ___ (_) ___| |")
print(" | |_) / _ \ '_ ` _ \| |/ _ \ |")
print(" | _ < __/ | | | | | | __/ |")
print(" |_| \_\___|_| |_| |_|_|\___|_|")
print(" Insta:@jrxag_official ")
t.sleep(0.5)
print("*"*40)
t.sleep(0.5)
print("\n --------SELECTION SORT--------")
#----------------------------------------------
#Main Definiton Of The Selection Sort
def sort(nums):
for i in range(len(nums)-1):
min=i
for j in range(i,len(nums)):
if nums[j]<nums[min]:
min=j
temp=nums[i]
nums[i]=nums[min]
nums[min]=temp
return nums
#__main__
nums=[]
n=int(input("Enter the No.Of Elements"))
for i in range(0,n):
ele=int(input())
nums.append(ele)
isort=sort(nums)
print("The Correct Order Is")
t.sleep(0.5)
print(isort)
t.sleep(0.5)
#appreciation
print("*"*40)
print("Thanks, Checkout My Profile For More")
t.sleep(2)
print("Leave A Star, That Motivates Me A Lot")
t.sleep(1)
print(" _______ __ __ _______ ")
print(" | _ || | | || |")
print(" | |_| || |_| || ___|")
print(" | || || |___ ")
print(" | _ | |_ _|| ___|")
print(" | |_| | | | | |___ ")
print(" |_______| |___| |_______|")
<file_sep>/CPP/Circular Queue - Array Implementation.cpp
#include<iostream>
using namespace std;
#define MAX_SIZE 10
class MyQueue {
private:
int front;
int rear;
int queue[MAX_SIZE];
public:
MyQueue() {
front = -1;
rear = -1;
}
bool isEmpty() {
if (front == -1 && rear == -1) return true;
else return false;
}
int enQueue(int x) {
if (isEmpty()) {//checking for empty queue
front = rear = 0;
}
else if ((rear + 1) % MAX_SIZE == front) {//checking if the queue is full
cout << "Error: Queue is Full" << endl;
return 0;
}
else {
rear = (rear + 1) % MAX_SIZE;
}
//placing the value at rear.
queue[rear] = x;
}
int frontOfQueue() {
if (isEmpty()) return 0;
return queue[front];
}
int rearOfQueue() {
if (isEmpty()) return 0;
return queue[rear];
}
int deQueue() {
if (isEmpty()) {
cout << "Queue is Empty. Nothing to DeQueue" << endl;
return 0;
}
else if (front == rear) {
int data = queue[front];
front = rear = -1;
return data;
}
int data = queue[front];
front = (front + 1) % MAX_SIZE;
return data;
}
void show() {
if (!isEmpty()) {
cout << "QUEUE is: ";
for (int i = front; i <= rear; i++) {
cout << queue[i] << " ";
}
cout << endl;
}
else {
cout << "Queue is Empty.!" << endl;
}
}
};
int main() {
MyQueue q;
q.isEmpty();
q.show();
q.enQueue(4);
q.show();
cout << "front of queue is : " << q.frontOfQueue() << endl;
cout << "rear of queue is : " << q.rearOfQueue() << endl;
q.enQueue(5);
q.show();
cout << "front of queue is : " << q.frontOfQueue() << endl;
cout << "rear of queue is : " << q.rearOfQueue() << endl;
q.enQueue(10);
q.show();
cout << "front of queue is : " << q.frontOfQueue() << endl;
cout << "rear of queue is : " << q.rearOfQueue() << endl;
q.enQueue(9);
q.show();
cout << "front of queue is : " << q.frontOfQueue() << endl;
cout << "rear of queue is : " << q.rearOfQueue() << endl;
q.enQueue(4);
q.enQueue(9);
q.enQueue(22);
q.enQueue(5);
q.enQueue(0);
q.enQueue(99);
q.show();
q.enQueue(100);
q.show();
cout << q.deQueue() << " DeQueue" << endl;
q.show();
cout << q.deQueue() << " DeQueue" << endl;
q.show();
cout << q.deQueue() << " DeQueue" << endl;
q.show();
cout << q.deQueue() << " DeQueue" << endl;
q.show();
return 0;
}<file_sep>/C/Pattern.cpp
// C++ code to demonstrate star pattern
#include <iostream>
using namespace std;
int main()
{
int n = 5;
// Outer loop to handle number of rows
for (int i = 0; i < n; i++) {
// Inner loop to handle number of columns
for (int j = 0; j <= i; j++) {
cout << "* ";
}
cout << endl;
}
return 0;
}<file_sep>/CPP/Queue - Linked List Implementation.cpp
//Queue Linked List Implementation
#include<iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int data, Node* next = NULL) {
this->data = data;
this->next = next;
}
};
class MyQueue {
private:
Node* front;
Node* rear;
public:
MyQueue() {
front = rear = NULL;
}
bool isEmpty() {
if (front == NULL) return true;
else return false;
}
//this method is same as add to tail method of singly linked list.
void enQueue(int i) {
if (isEmpty()) {
front = rear = new Node(i);
}
else {
rear->next = new Node(i);
rear = rear->next;
}
}
//this method is same as remove from head method of sinlgy linked list.
int deQueue() {
if (isEmpty()) return 0;
else if (front == rear) {
int data = front->data;
front = rear = NULL;
return data;
}
Node* temp = front;
int data = temp->data;
front = front->next;
temp->next = NULL;
delete temp;
return data;
}
int frontOfQueue() {
if (isEmpty()) return 0;
return front->data;
}
void display() {
if (isEmpty()) cout << "Empty List.!" << endl;
else {
Node* temp = front;
cout << "Queue is: ";
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
}
};
int main() {
MyQueue q;
if (q.isEmpty()) cout << "Queue is Empty!" << endl;
q.enQueue(3);
q.display();
q.enQueue(4);
q.display();
q.enQueue(5);
q.display();
cout << "Front : " << q.frontOfQueue() << endl;
q.enQueue(23);
q.display();
int dq;
for (int i = 0; i < 4; i++) {
dq = q.deQueue();
if (dq == 0) {
cout << "Empty Queue!" << endl;
}
else {
cout << dq << " DeQueue" << endl;
}
}
return 0;
}<file_sep>/Python/pattern_heart.py
print("\n".join(" ".join(*zip(*row)) for row in ([[
"*" if row == 0 and col % 3 != 0 or row == 1 and col % 3 == 0 or row -
col == 2 or row + col == 8 else " " for col in range(7)
] for row in range(6)])))<file_sep>/Python/MinJumps.py
def minJumps(arr, n):
i=0
jump=0
while(i<n):
if arr[i]==0:
return -1
val=arr[i] #maximum number of steps that can be taken currently
curr_max=0 #initializing the next maxm step
#If we reached to the final step
if i+arr[i]>=n-1:
jump+=1
return jump
flag=1
#Finding the next maximum step
for j in range(i+1,i+val+1):
if arr[j]+j>curr_max:
curr_max=arr[j]+j
i=j
flag=0
if flag:
return -1
jump+=1
return jump
print("Enter array elements with space")
arr=list(map(int,input().split()))
jump=minJumps(arr,len(arr))
print("Minimum Jumps to reach to end of array :",jump)<file_sep>/C/LibMgmt.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct library {
char book_name[20];
char author[20];
int pages;
float price;
};
int main()
{
struct library lib[100];
char ar_nm[30], bk_nm[30];
int i, input, count;
i = input = count = 0;
while (input != 5) {
printf("\n\n1. Add book information\n2. Display book information\n 3. List all books of given author\n 4. List the count of books in the library\n 5. Exit");
printf("\n\nEnter one of the above: ");
scanf("%d", &input);
switch (input) {
case 1:
printf("Enter book name = ");
scanf("%s", lib[i].book_name);
printf("Enter author name = ");
scanf("%s", lib[i].author);
printf("Enter pages = ");
scanf("%d", &lib[i].pages);
printf("Enter price = ");
scanf("%f", &lib[i].price);
count++;
break;
case 2:
for (i = 0; i < count; i++) {
printf("book name = %s", lib[i].book_name);
printf("\t author name = %s", lib[i].author);
printf("\t pages = %d", lib[i].pages);
printf("\t price = %f", lib[i].price);
}
break;
case 3:
printf("Enter author name : ");
scanf("%s", ar_nm);
for (i = 0; i < count; i++) {
if (strcmp(ar_nm, lib[i].author)== 0)
printf("%s %s %d %f", lib[i].book_name, lib[i].author, lib[i].pages, lib[i].price);
}
break;
case 4:
printf("\n No of books in library : %d", count);
break;
case 5:
exit(0);
}
}
return 0;
}<file_sep>/Python/BFS.py
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def setEdge(self, u, v):
self.graph[u].append(v)
def bfs(self, s):
visited = set()
queue = []
queue.append(s)
visited.add(s)
while queue:
u = queue.pop(0)
print(u, end=" ")
for v in self.graph[u]:
if v not in visited:
queue.append(v)
visited.add(v)
g = Graph()
g.setEdge(2, 1)
g.setEdge(2, 5)
g.setEdge(5, 6)
g.setEdge(5, 8)
g.setEdge(6, 9)
g.bfs(2)<file_sep>/C/calculate_pow.c
/* Given two integers x and n, write a function to compute xn.
We may assume that x and n are small and overflow doesn’t happen.*/
#include<stdio.h>
float powerOfX(float x, int y) {
float tempVar;
if(y == 0) return 1;
tempVar = powerOfX(x, y/2);
if(y%2 == 0) return tempVar*tempVar;
else {
if(y > 0) return x*tempVar*tempVar;
else return (tempVar*tempVar)/x;
}
}
int main() {
float x;
scanf("%f",&x);
int n ;
scanf("%d",&n);
printf("%.2f", powerOfX(x, n));
return 0;
}<file_sep>/Python/rotate_matrix_90_degree.py
'''
Rotate matrix 90 degree
123 741
456 ==>852
789 963
'''
import numpy
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# method 1
myArray = numpy.array(matrix)
print(numpy.rot90(myArray, len(myArray)))
# method 2
def rotate_matrix(matrix):
n = len(matrix)
for layer in range(n // 2):
first, last = layer, n - layer - 1
for i in range(first, last):
top = matrix[layer][i]
matrix[layer][i] = matrix[-i - 1][layer]
matrix[-i - 1][layer] = matrix[-layer - 1][-i - 1]
matrix[-layer - 1][-i - 1] = matrix[i][- layer - 1]
matrix[i][- layer - 1] = top
return matrix
print(rotate_matrix(myArray))
<file_sep>/Python/Convert Celsius to Fahrenheit.py
# Celsius to Fahrenheit
celsius = float(input("Please Enter the Temperature in Celsius = "))
fahrenheit = (1.8 * celsius) + 32
//fahrenheit = ((celsius * 9)/5) + 32
print("%.2f Celsius Temperature = %.2f Fahrenheit" %(celsius, fahrenheit))
<file_sep>/Python/Cumulative_Sum_in_List.py
def Cumulative(lists):
cu_list = []
length = len(lists)
cu_list = [sum(lists[0:x:1]) for x in range(0, length+1)]
return cu_list[1:]
# Driver Code
lists = [10, 20, 30, 40, 50]
print (Cumulative(lists))
<file_sep>/Python/Caesar cipher.py
def encrypt(letter, s):
if (letter.isupper()):
return chr((ord(letter) + s - 65) % 26 + 65)
elif (letter.islower()):
return chr((ord(letter) + s - 97) % 26 + 97)
else:
return letter
text = input("Enter the word: ")
s = int(input("Enter the shift: "))
shift = [s] * len(text)
result = list(map(encrypt, text, shift))
print("Encrypted text: ", end="")
for i in result:
print(i, end="")
<file_sep>/Python/pascals-triangle.py
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
# initializing triangle's 1st level
res=[[1]]
for i in range(1,numRows):
n=len(res)
# initializing array at level n to have length n
row=[0]*(i+1)
# iterating over array at level n
for j in range(len(row)):
# 1st ele = ele to top-left to this ele in the triangle
a=res[n-1][j-1] if j>0 else 0
# 2nd ele = ele to top-right to this ele in the triangle
b=res[n-1][j] if j<n else 0
# 1st+2nd to get the current ele
row[j]=a+b
# add the row to the triangle
res.append(row)
return res
<file_sep>/C/coincounter.c
#include <stdio.h>
int calc_coins(int coin, int amount);
int main(){
int amount;
int coins[] = {50, 20, 5, 2, 1};
printf("Type in your amount of money in cent : ");
scanf("%d", &amount);
for(int i = 0; i < 5; i++){
amount = calc_coins(coins[i], amount);
}
return 0;
}
int calc_coins(int coin, int amount){
int n = amount/coin;
printf("Amount of %2i-cent Coins: %3i\n", coin, n);
amount = amount - n*coin;
return amount;
}
<file_sep>/Python/countwords.py
from bs4 import BeautifulSoup as bsoup
import pandas as pd
import numpy as np
import humanfriendly
# Read in email data file
df = pd.read_csv('../bodytext.csv', header = 0)
# Filter out sent mail
emails = df.query('FromEmail != "[my email address]"').copy()
def wordCount(row):
if(row['Format'] == 'Html'):
return htmlWordCount(row['Body'])
return textWordCount(row['Body'])
def textWordCount(text):
if not(isinstance(text, str)):
return 0
return len(text.split(None))
def htmlWordCount(text):
if not(isinstance(text, str)):
return 0
soup = bsoup(text, 'html.parser')
if soup is None:
return 0
stripped = soup.get_text(" ", strip=True)
[s.extract() for s in soup(['style', 'script', 'head', 'title'])]
stripped = soup.get_text(" ", strip=True)
return textWordCount(stripped)
averageWordsPerMinute = 350
# Count the words in each message body
emails['WordCount'] = emails.apply(wordCount, axis=1)
emails['MinutesToRead'] = emails['WordCount'] / averageWordsPerMinute
# Get total number of minutes required to read all these emails
totalMinutes = emails['MinutesToRead'].sum()
# And convert that to a more human-readable timespan
timeToRead = humanfriendly.format_timespan(totalMinutes * 60)
<file_sep>/JavaScript/quote-generator/README.md
# Random Quote Generator (React)

## What is it
A simple React project, that shows how you can use public APIs to improve your project.
## How it works
We're using the API provided by [https://api.quotable.io/](https://api.quotable.io/) to show a random quote.<file_sep>/JavaScript/alert.js
<html>
<head>
<meta charset="UTF-8" />
<script>
function main() {
alert('You clicked me!');
}
</script>
</head>
<body>
<button onclick="main()">Click Me</button>
</body>
</html>
<file_sep>/Python/VerticalConcatination.py
#Python3 code to demonstrate working of
# Vertical Concatenation in Matrix
# Using loop
# initializing lists
test_list = [["Gfg", "good"], ["is", "for"], ["Best"]]
# printing original list
print("The original list : " + str(test_list))
# using loop for iteration
res = []
N = 0
while N != len(test_list):
temp = ''
for idx in test_list:
# checking for valid index / column
try: temp = temp + idx[N]
except IndexError: pass
res.append(temp)
N = N + 1
res = [ele for ele in res if ele]
# printing result
print("List after column Concatenation : " + str(res))
<file_sep>/Python/DFS.py
from collections import defaultdict
class Graph:
def __init__(self):
self.graph = defaultdict(list)
def insertEdge(self, v1, v2):
self.graph[v1].append(v2)
def DFS(self, startNode):
visited = set()
st = []
st.append(startNode)
while(len(st)):
cur = st[-1]
st.pop()
if(cur not in visited):
print(cur, end=" ")
visited.add(cur)
for vertex in self.graph[cur]:
if(vertex not in visited):
st.append(vertex)
g = Graph()
g.insertEdge(2, 1)
g.insertEdge(2, 5)
g.insertEdge(5, 6)
g.insertEdge(5, 8)
g.insertEdge(6, 9)
g.DFS(2)<file_sep>/JavaScript/promiseAllSettled.js
let p1 = new Promise((resolve, reject) => {
setTimeout(() => resolve("one"), 200);
});
let p2 = new Promise((resolve, reject) => {
setTimeout(() => resolve("two"), 300);
});
let p3 = new Promise((resolve, reject) => {
setTimeout(() => resolve("three"), 100);
});
let p4 = new Promise((resolve, reject) => {
setTimeout(() => reject("four"), 500);
});
let p5 = new Promise((resolve, reject) => {
setTimeout(() => reject("five"), 100);
});
let p6 = 20;
function settleAllPromise(promiseArray) {
let resultArray = [];
let promiseExecuted = 0
return new Promise((resolve, reject) => {
promiseArray.forEach(async(promise, index) => {
try {
const response = await promise;
resultArray[index] = {
status: 'fulfilled',
value: response
}
}
catch(err){
resultArray[index] = {status:'rejected',reason:err}
}
finally{
promiseExecuted++;
if(promiseExecuted === promiseArray.length){
resolve(resultArray);
}
}
})
})
}
settleAllPromise([p1, p2, p3, p4, p5, p6]).then((res) => console.log(res));
/* Output:
[
{ status: 'fulfilled', value: 'one' },
{ status: 'fulfilled', value: 'two' },
{ status: 'fulfilled', value: 'three' },
{ status: 'rejected', reason: 'four' },
{ status: 'rejected', reason: 'five' },
{ status: 'fulfilled', value: 20 }
]
*/
<file_sep>/Python/DiscordAnimeBot/README.md
# Animo
Discord bot to share random anime facts, quotes, and details about anime characters, clans, villages etc using Discord.py .
Just a fun project to dive into the world of chatbots.
## Screenshots

## commands
- $fax : for random anime facts
- $quotes : for random quotes
- $nrt character : for details of Naruto characters
- $nrt rank : for details of many Naruto characters with certain ranks
- $nrt village : for details of many Naruto characters of certain villages
- $waifu : If you know you know :-)
## How to Invite Animo
[Click The Link](https://discord.com/api/oauth2/authorize?client_id=869574479347585104&permissions=259846044736&scope=bot)
## Run Locally
- Clone the project
```bash
git clone https://github.com/shayan-cyber/Animo.git
```
- Make virtualenv
```bash
python -m virtualenv [env name]
```
- Activate virtualenv
```bash
. [env name]/Scripts/activate
```
- Install dependencies
```bash
pip install -r requirements.txt
```
- visit and make application(bot)
```bash
https://discord.com/developers/applications
```
- Obtain Bot token from there
## Invite the bot to your server while executing the python file
## Tech Stack
**Stacks:** Python, Discord.py

<file_sep>/CPP/longestIncreasingSubsequence.cpp
#include <iostream>
using namespace std;
int _lis(int arr[], int n, int* max_ref)
{
/* Base case */
if (n == 1)
return 1;
int res, max_ending_here = 1;
for (int i = 1; i < n; i++) {
res = _lis(arr, i, max_ref);
if (arr[i - 1] < arr[n - 1]
&& res + 1 > max_ending_here)
max_ending_here = res + 1;
}
if (*max_ref < max_ending_here)
*max_ref = max_ending_here;
return max_ending_here;
}
int lis(int arr[], int n)
{
int max = 1;
_lis(arr, n, &max);
return max;
}
int main()
{
int arr[] = { 10, 22, 9, 33, 21, 50, 41, 60 };
int n = sizeof(arr) / sizeof(arr[0]);
cout <<"Length of lis is "<< lis(arr, n);
return 0;
}
<file_sep>/Python/swap_case.py
def swap_case(s): #Defining a function called swap_case
res=''
for letter in s:
if(letter.islower()): #Returns true if the characters in the string are in lowercase
res=res+letter.upper() #Converting the lowercase characters to uppercase characters
else:
res=res+letter.lower() #Converting the uppercase characters to lowercase characters
print(res)
s=input("Enter a string:")
swap_case(s) #Calling the function
<file_sep>/CPP/Memory Partition and Fragmentation.cpp
#include<bits/stdc++.h>
using namespace std;
void bestFit(int blockSize[], int m, int processSize[], int n)
{
int allocation[n];
memset(allocation, -1, sizeof(allocation));
for (int i=0; i<n; i++)
{
int bestIdx = -1;
for (int j=0; j<m; j++)
{
if (blockSize[j] >= processSize[i])
{
if (bestIdx == -1)
bestIdx = j;
else if (blockSize[bestIdx] > blockSize[j])
bestIdx = j;
}
}
if (bestIdx != -1)
{
allocation[i] = bestIdx;
blockSize[bestIdx] -= processSize[i];
}
}
cout << "\nProcess No.\tProcess Size\tBlock no.\n";
for (int i = 0; i < n; i++)
{
cout << " " << i+1 << "\t\t" << processSize[i] << "\t\t";
if (allocation[i] != -1)
cout << allocation[i] + 1;
else
cout << "Not Allocated";
cout << endl;
}
}
int main()
{
int blockSize[] = {100, 500, 200, 300, 600};
int processSize[] = {212, 417, 112, 426};
int m = sizeof(blockSize)/sizeof(blockSize[0]);
int n = sizeof(processSize)/sizeof(processSize[0]);
bestFit(blockSize, m, processSize, n);
return 0 ;
}<file_sep>/Python/mathematical calculator.py
# take two input numbers
number1 = input("Insert first number : ")
number2 = input("Insert second number : ")
operator = input("Insert operator (+ or - or * or /)")
if operator == '+':
total = number1 + number2
elif operator == '-':
total = number1 - number2
elif operator == '*':
total = number2 * number1
elif operator == '/':
total = number1 / number2
else:
total = "invalid operator"
# printing output
print(total)<file_sep>/CPP/ATM.cpp
#include<iostream>
#include<stdio.h>
using namespace std;
void showMenu()
{
cout<<"***********Menu***********"<<endl;
cout<<"1.Check Balance"<<endl;
cout<<"2.Deposit"<<endl;
cout<<"3.Withdrawl"<<endl;
cout<<"4.Exit";
cout<<"**************************"<<endl;
}
int main()
{
int number, balance = 500;
do
{
showMenu();
cout<<"Select Option : ";
cin>>number;
switch (number)
{
case 1: cout<<"Balance is "<<balance<<" rupees"<<endl;break;
case 2: cout<<"Deposit Amout : ";
double deposit;
cin>> deposit;
balance += deposit;
break;
case 3: cout<<"Withdraw Amout : ";
double withdraw;
cin>>withdraw;
if(withdraw <=balance)
balance -= withdraw;
else
cout<<"Insufficient balance"<<endl;
break;
}
}
while(number!=4);
return 0;
}<file_sep>/C/MatrixDnC.c
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int **add(int **a, int **b, int n);
void matrix_print( int **a, int n);
int **matrix_allocate(int n)
{
int **matrix = malloc(n * sizeof(*matrix));
for (int i = 0; i < n; i++)
{
matrix[i] = calloc(n, sizeof(*matrix[i]));
}
return matrix;
}
int** multiply(int** a,int** b,int n)
{
int **result=matrix_allocate(n);
if (n == 1) {
result[0][0] = a[0][0] * b[0][0];
}
else
{
int n2=n/2;
int **a11 = matrix_allocate(n2);
int **a12 = matrix_allocate(n2);
int **a21 = matrix_allocate(n2);
int **a22 = matrix_allocate(n2);
int **b11 = matrix_allocate(n2);
int **b12 = matrix_allocate(n2);
int **b21 = matrix_allocate(n2);
int **b22 = matrix_allocate(n2);
for (int i = 0; i < n2; i++)
{
for (int j = 0; j < n2; j++)
{
a11[i][j] = a[i][j];
a12[i][j] = a[i][j + n2];
a21[i][j] = a[i + n2][j];
a22[i][j] = a[i + n2][j + n2];
b11[i][j] = b[i][j];
b12[i][j] = b[i][j + n2];
b21[i][j] = b[i + n2][j];
b22[i][j] = b[i + n2][j + n2];
}
}
int **c11 = add(multiply(a11, b11, n2),multiply(a12, b21, n2), n2);
int **c12 = add(multiply(a11, b12, n2),multiply(a12, b22, n2), n2);
int **c21 = add(multiply(a21, b11, n2),multiply(a22, b21, n2), n2);
int **c22 = add(multiply(a21, b12, n2),multiply(a22, b22, n2), n2);
for (int i = 0; i < n2; i++)
{
for (int j = 0; j < n2; j++)
{
result[i][j] = c11[i][j];
result[i][j + n2] = c12[i][j];
result[i + n2][j] = c21[i][j];
result[i + n2][j + n2] = c22[i][j];
}
}
}
return result;
}
int **add(int **a, int **b, int n) {
int **c = matrix_allocate(n);
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
return c;
}
void matrix_print( int **a, int n) {
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
}
int isPowerOfTwo (int x)
{
return x && (!(x&(x-1)));
}
int main () {
printf("Enter the order of matrix:-\n");
int n;
scanf("%d",&n);
if(isPowerOfTwo(n)==0)
{
printf("please give the order of the matrix as a power of 2 only\n");
}
else
{
int **matrix1,**matrix2,**ans;
matrix1=matrix_allocate(n);
matrix2=matrix_allocate(n);
ans=matrix_allocate(n);
printf("Enter the matrix 1:-\n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
scanf("%d",&matrix1[i][j]);
}
}
printf("Enter the matrix 2:-\n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
scanf("%d",&matrix2[i][j]);
}
}
clock_t start=clock();
printf("The multiplication of both the matrices are as follows:-\n");
ans=multiply(matrix1,matrix2,n);
matrix_print(ans,n);
clock_t end=clock();
printf("\nTotal time in ms :-%u",end-start);
}
return 0;
}
<file_sep>/Python/Simple_Chat_Bot_TFIDS/ChatBot.py
import nltk
import warnings
warnings.filterwarnings("ignore")
import numpy as np
import random
import string
f=open('train_txt.txt','r',errors = 'ignore')
raw=f.read()
raw=raw.lower()
sent_tokens = nltk.sent_tokenize(raw)# converts to list of sentences
word_tokens = nltk.word_tokenize(raw)
lemmer = nltk.stem.WordNetLemmatizer()
def LemTokens(tokens):
return [lemmer.lemmatize(token) for token in tokens]
remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)
def LemNormalize(text):
return LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict)))
GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up","hey",)
GREETING_RESPONSES = ["hi", "hello", "I am glad! You are talking to me"]
def greeting(sentence):
for word in sentence.split():
if word.lower() in GREETING_INPUTS:
return random.choice(GREETING_RESPONSES)
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
def response(user_response):
robo_response=''
sent_tokens.append(user_response)
TfidfVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english')
tfidf = TfidfVec.fit_transform(sent_tokens)
vals = cosine_similarity(tfidf[-1], tfidf)
vals = cosine_similarity(tfidf[-1], tfidf)
idx=vals.argsort()[0][-2]
flat = vals.flatten()
flat.sort()
req_tfidf = flat[-2]
if(req_tfidf==0):
robo_response=robo_response+"I don't understand you"
return robo_response
else:
robo_response = robo_response+sent_tokens[idx]
return robo_response
flag=True
print("BOT: My name is Chatty. I will answer your queries about Chatbots. If you want to exit, type Bye!")
while(flag==True):
user_response = input()
user_response=user_response.lower()
if(user_response!='bye'):
if(user_response=='thanks' or user_response=='thank you' ):
flag=False
print("BOT: You are welcome..")
else:
if(greeting(user_response)!=None):
print("BOT: "+greeting(user_response))
else:
print("BOT: ",end="")
print(response(user_response))
sent_tokens.remove(user_response)
else:
flag=False
print("BOT: Bye! take care..")
<file_sep>/CPP/ARRAY_IMPL1.cpp
#include <bits/stdc++.h>
using namespace std;
vector<int> performOps(vector<int> A) {
vector<int> B(2 * A.size(), 0);
for (int i = 0; i < A.size(); i++) {
B[i] = A[i];
B[i + A.size()] = A[(A.size() - i) % A.size()];
}
return B;
}
int main() {
vector<int> A={5, 10, 2, 1};
vector<int> B = performOps(A);
for (int i = 0; i < B.size(); i++) {
cout<<B[i]<<" ";
}
return 0;
}<file_sep>/Python/Matrix Multiplication.py
l = []
print("Enter values for matrix - A")
row1 = int(input("Number of rows, m = "))
col1 = int(input("Number of columns, n = "))
for i in range(row1):
a = []
for j in range(col1):
print("Entry in row:",i+1,"column:",j+1)
x = int(input())
a.append(x)
l.append(a)
print("Enter values for matrix - B")
p = []
row2 = int(input("Number of rows, m = "))
col2 = int(input("Number of columns, n = "))
for k in range(row2):
b = []
for t in range(col2):
print("Entry in row:", k+1,"column:", t+1)
z = int(input())
b.append(z)
p.append(b)
ans = []
for k in range(row1):
l1 = []
for i in range(col2):
s = 0
for j in range(col1):
s += l[k][j]*p[j][i]
l1.append(s)
ans.append(l1)
print("Matrix - A =", l)
print("Matrix - B =", p)
print("Matrix - A * Matrix- B =", ans)
<file_sep>/Clock/README.md
# Clock
Minimal Analog Clock made with javascript and CSS

<file_sep>/Python/Dice_Simulator.py
import random
print("This is my Dice simulator")
a = "y"
while a == "y" or a == "Y":
r = random.randint(1, 6)
if r == 1:
print("----------------")
print("| |")
print("| O |")
print("| |")
print("----------------")
elif r == 2:
print("----------------")
print("| |")
print("| O O |")
print("| |")
print("----------------")
elif r == 3:
print("----------------")
print("| O |")
print("| O |")
print("| O |")
print("----------------")
elif r == 4:
print("----------------")
print("| O O |")
print("| |")
print("| O O |")
print("----------------")
elif r == 5:
print("----------------")
print("| O O |")
print("| O |")
print("| O O |")
print("----------------")
elif r == 6:
print("----------------")
print("| O O |")
print("| O O |")
print("| O O |")
print("----------------")
a = input("If you want to roll Dice again then Press 'y' otherwise press any other key to exit")
print("Thanks!! , See You Later")
<file_sep>/CPP/Piglatin.cpp
// C++ program to encode a word to a Pig Latin.
#include <bits/stdc++.h>
using namespace std;
bool isVowel(char c)
{
return (c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' || c == 'a' ||c == 'e' || c == 'i' || c == 'o' || c == 'u');
}
void pigLatin(string s)
{
int len = s.length();string c;
int index = -1;
for (int i = 0; i < len; i++) {
if (isVowel(s[i])) {
index = i;
break;
}
}
if (index == -1)
cout<< "-1";
c=s.substr(index) + s.substr(0, index);
cout<<c<<"ay";
}
int main()
{
string str ;
cout<<"Enter a String:\n";
cin>>str;
pigLatin(str);
if (str == "-1")
cout << "No vowels found. Pig Latin not possible";
}
<file_sep>/Python/Pulse(Voice-Assistance)/voice.py
import pyttsx3
import datetime
import speech_recognition as sr
import wikipedia
import time
import webbrowser
import youtube_dl
from googleapiclient.discovery import build
import os
from selenium import webdriver
from playsound import playsound
#Initializing the object for pttxs3
engine=pyttsx3.init('sapi5')
voices=engine.getProperty('voices')
#voices[0] will give male vocals while voices[1] will give female
engine.setProperty('voice',voices[0].id)
youtube_api=input("Enter your api key for Youtube")
def get_url(url):
api_key=youtube_api
youtube=build('youtube','v3',developerKey=api_key)
print("here")
req=youtube.search().list(q=url,part='snippet',type='video')
req=req.execute()
val=(req['items'][0]['id']['videoId'])
return ('https://youtube.com/watch?v='+val)
def takeCommand():
r=sr.Recognizer()
with sr.Microphone() as source:
print('Listening..')
speak('Listening..')
r.pause_threshold=1
r.adjust_for_ambient_noise(source)
audio=r.listen(source)
try:
query=r.recognize_google(audio)
time.sleep(2)
print('Recognizing...')
print(f"user said {query} \n")
except Exception :
speak('Please Say Again')
return "none"
return query
def speak(audio):
engine.say(audio)
engine.runAndWait()
def wishme():
hour =int(datetime.datetime.now().hour)
if hour >=0 and hour <12 :
speak('Good Morning!')
elif hour >=12 and hour<18 :
speak('Good Afternoon!')
else:
speak('Good evening!')
speak('Hello I am Pulse')
time.sleep(1)
speak('How may I help you?')
if __name__ == "__main__":
wishme()
while True:
query=takeCommand().lower()
if 'wikipedia' in query:
speak("searching wiipedia")
query=query.replace('wikipedia',"")
results=wikipedia.summary(query, sentences=2)
print(results)
speak("according to wikipedia")
speak(results)
elif 'open youtube' in query:
speak('opening')
browser=webdriver.Chrome()
browser.get('https://www.youtube.com/')
elif 'song' in query:
# speak('playing')
# browser=webdriver.Chrome()
query=query.replace('play song',"")
url=get_url(query)
# print('playing')
print(url)
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '720',
}],
}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
song_there = os.path.isfile("song.mp3")
try:
if song_there:
os.remove("song.mp3")
except:
pass
for file in os.listdir("./"):
print(file)
if file.endswith(".mp3"):
os.rename(file, "song.mp3")
playsound('song.mp3')
speak('song finished')
elif 'google search' in query:
speak('searching')
browser=webdriver.Chrome()
query=query.replace('google search',"")
browser.get('https://www.google.com/')
browser.find_element_by_name("q").send_keys(query)
time.sleep(2)
browser.find_element_by_xpath("//*[@id='tsf']/div[2]/div[1]/div[2]/div[2]/ul/li[1]/div/div[2]").click()
elif 'exit' in query:
speak("ok bye")
break
else:
pass
#more to be written<file_sep>/Python/largestofthree.py
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
num3 = int(input('Enter third number: '))
def sort():
if (num1 >= num2) and (num1 >= num3):
print(num1)
elif (num2 >= num1) and (num2 >= num3):
print(num2)
else:
print(num3)
sort()
<file_sep>/Python/bresenham.py
#
import matplotlib.pyplot as plt
def bresenham(x1,y1,x2, y2):
m = 2 * (y2 - y1)
slope_error = m - (x2 - x1)
y=y1
for x in range(x1,x2+1):
print("(",x ,",",y ,")\n")
slope_error =slope_error + m
if (slope_error >= 0):
y=y+1
slope_error =slope_error - 2 * (x2 - x1)
x1= int(input())
x2= int(input())
y1= int(input())
y2= int(input())
point1 = [x1,y1]
point2 = [x2, y2]
x_values = [point1[0], point2[0]]
y_values = [point1[1], point2[1]]
plt.plot(x_values,y_values)
plt.show()
<file_sep>/Color_game.py
import tkinter
import random
class ColorGame:
colors = ["Red", "Yellow", "Orange", "Green", "Blue", "Purple", "Black", "White", "Pink"]
time_left = 30
score = 0
def __init__(self, window):
window.title("Color Game")
window.geometry("400x250")
self.instruction_label = tkinter.Label(window, text="Type the color of the word, not the text!",
font=("Century", 14))
self.instruction_label.pack(pady=10)
self.start_label = tkinter.Label(window, text="Press Enter to Start.", font=("Copperplate Gothic Light", 12))
self.start_label.pack()
self.score_label = tkinter.Label(window, text="Score: 0", font=("Comic Sans MS", 14))
self.time_label = tkinter.Label(window, text="Time Left: " + str(self.time_left),
font=("Arial", 14))
self.color_text_label = tkinter.Label(window, fg=self.colors[0], text="Color", font=("Times", 40))
self.entry = tkinter.Entry(window, font=("Arial", 14))
self.play_again_button = tkinter.Button(window, text="Play Again", font=("Arial", 14), padx=3,
pady=3, background="Green", fg="White", command=self.restart)
window.bind("<Return>", self.play_game)
def play_game(self, event):
self.start_label.pack_forget()
self.score_label.pack()
self.time_label.pack()
self.color_text_label.pack()
self.entry.pack(fill="x", padx=100)
if self.time_left > 0:
self.entry.focus_set()
if self.time_left == 30:
self.countdown()
self.change_color()
else:
self.color_text_label.pack_forget()
self.entry.pack_forget()
self.play_again_button.pack(pady=10)
def change_color(self):
self.check_answer()
random.shuffle(self.colors)
self.color_text_label.config(fg=self.colors[0], text=self.colors[1])
self.color_text_label.pack(pady=13)
def check_answer(self):
if self.entry.get().lower() == self.colors[0].lower():
self.score += 1
self.score_label.config(text="Score: " + str(self.score))
self.entry.delete(0, tkinter.END)
def countdown(self):
if self.time_left > 0:
self.time_left -= 1
self.time_label.config(text="Time Left: " + str(self.time_left))
self.time_label.after(1000, self.countdown)
def restart(self):
self.score = 0
self.time_left = 30
self.score_label.config(text="Score: 0")
self.time_label.config(text="Time Left: " + str(self.time_left))
self.play_again_button.pack_forget()
self.score_label.pack_forget()
self.time_label.pack_forget()
self.start_label.pack()
new_window = tkinter.Tk()
game = ColorGame(new_window)
new_window.mainloop()
<file_sep>/Python/Scraping/Top-100-movies-by-Genre---Rotten-Tomato/top100_scrapy.py
import csv
import requests
from bs4 import BeautifulSoup
# Method for Scrapping the RottenTomatoes site and storing the list of top 100 movies of a particular genre in csv file
def search_with_genre(genre):
# Creating the file name (for CSV file) same as input provided
filename = genre
# Formatting the genre variable for use
genre = genre.replace("&","")
genre = (genre.lower()).replace(" ","_")
url = "https://www.rottentomatoes.com/top/bestofrt/top_100_" + genre + "_movies"
# Requesting and storing the contents of desired webpage in "soup" variable
result = requests.get(url)
soup = BeautifulSoup(result.text, "html.parser")
# Finding all the contents stored in the table format
find_contents = soup.find(attrs={"class": "table"})
if find_contents is None:
print("Can't find the movies of genre you are looking for!")
# If input genre is not found then providing the user with a list of valid genres from which user can choose
print("Try using these GENRES:")
genre_list = [ "Action & Adventure", "Animation", "Art House & International", "Classics",
"Comedy", "Documentary", "Drama", "Horror", "Kids & Family",
"Musical & Performing Arts", "Mystery & Suspense", "Romance", "Science Fiction & Fantasy",
"Special Interest", "Sports & Fitness", "Television", "Western"
]
for i in genre_list:
print(i)
else:
rows = find_contents.find_all("tr")
# Creating a csv file and storing the movie information in it
# If a file already exists the program overwrites its contents
with open(filename+".csv", "w") as csv_file:
writer = csv.writer(csv_file)
# Initializing the first row with the column title
writer.writerow(["Rank" , "Rating" , "Title" , "No of Reviews"])
# Iterating all the rows of the scrapped contents and storing them in desired csv file
for row in range(1,101):
dataset = rows[row].find_all("td")
rank = dataset[0].text.replace(".","")
rating = dataset[1].find(attrs={"class": "tMeterScore"}).text[1:]
title = dataset[2].find("a",attrs={"class": "unstyled articleLink"}).text.replace(" ","")
reviews = dataset[3].text
writer.writerow([rank, rating, title, reviews])
# Taking the input from the user and searching for movies of particular genre
genre = input()
search_with_genre(genre)<file_sep>/JavaScript/script.js
const person = {
firstName:"randika",
lastName:"chathuranga",
get fullName(){
return (`${person.firstName} ${person.lastName}`);
},
set fullName(value){
const parts = value.split(' ');
this.firstName = parts[0];
this.lastName = parts[1];
}
}
person.fullName = "<NAME>";
console.log(person.fullName);
const jobs = [
{id:1 , isActive:true},
{id:2 , isActive:true},
{id:3 , isActive:false}
]
const activeJobs = jobs.filter(function(job){return job.isActive});
console.log(activeJobs);
const colors = ['red','green','yellow'];
const items = colors.map(function(color){
return '<li>' + color + '</li>'
})
console.log(items);
// class
class Man {
constructor(name){
this.name = name;
}
walk(){
console.log("walk");
}
}
const person1 = new Man("randika");
console.log(person1.name);
//inheritance
class Teacher extends Man {
constructor(name,age){
super(name);
this.age = age;
}
walk(){
console.log("walk");
}
}
const teacher = new Teacher('chathuranga',24);
console.log(teacher.age);<file_sep>/README.md
<p align="center">
<a href="https://hacktoberfest.digitalocean.com/">
<img src="https://raw.githubusercontent.com/Hansajith98/hacktoberfest2021/main/Assets/logo-hacktoberfest-full.f42e3b1.svg" width="30%">
</a>
</p>
<h1 align="center"> Hacktoberfest 2021 🎉</h1>
<div align="center">
<img src="https://img.shields.io/badge/hacktoberfest-2021-blueviolet" alt="Hacktober Badge"/>
<img src="https://img.shields.io/static/v1?label=%F0%9F%8C%9F&message=If%20Useful&style=style=flat&color=BC4E99" alt="Star Badge"/>
<a href="https://github.com/Hansajith98" ><img src="https://img.shields.io/badge/Contributions-welcome-violet.svg?style=flat&logo=git" alt="Contributions" /></a>
<a href="https://github.com/Hansajith98/hacktoberfest2021/pulls"><img src="https://img.shields.io/github/issues-pr/hacktoberfest2021/hacktoberfest2021" alt="Pull Requests Badge"/></a>
<a href="https://github.com/Hansajith98/hacktoberfest2021/graphs/contributors"><img alt="GitHub contributors" src="https://img.shields.io/github/contributors/Hansajith98/hacktoberfest2021?color=2b9348"></a>
<a href="https://github.com/Hansajith98/hacktoberfest2021/blob/master/LICENSE"><img src="https://img.shields.io/github/license/Hansajith98/hacktoberfest2021?color=2b9348" alt="License Badge"/></a>
</div>
### 🗣 Hacktoberfest encourages participation in the open source community, which grows bigger every year. Complete the 2021 challenge and earn a limited edition T-shirt.
📢 **Register [here](https://hacktoberfest.digitalocean.com) for Hacktoberfest and make four pull requests (PRs) between October 1st-31st to grab free SWAGS 🔥.**
> Upload your code in this repository to particular section if folder is not present then create folder.
> some more repos for contribution
> Make PR to the dev branch
Make Sure to Star this project.
| Repository | Issues | Pull Requests |
| ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Python](https://github.com/Hansajith98/Python) | [](https://github.com/keshavsingh4522/Hansajith98/issues) | [](https://github.com/keshavsingh4522/Hansajith98/pulls) |
| [C](https://github.com/Hansajith98/c/) | [](https://github.com/Hansajith98/c/issues) | [](https://github.com/Hansajith98/c/pulls) |
| [Javascript](https://github.com/Hansajith98/javascript) | [](https://github.com/Hansajith98/javascript/issues) | [](https://github.com/Hansajith98/javascript/pulls) |
| [PHP](https://github.com/Hansajith98/PHP) | [](https://github.com/Hansajith98/PHP/issues) | [](https://github.com/Hansajith98/PHP/pulls) |
| [Java](https://github.com/Hansajith98/Java/) | [](https://github.com/Hansajith98/Java/issues) | [](https://github.com/Hansajith98/Java/pulls) |
## Rules
- Don't use dirty words and be welcome for beginners and other people in this community.
---
## Github Contribution Rules
- Pull requests can be submitted to any opted-in repository on GitHub or GitLab.
- The pull request must contain commits you made yourself.
- If a maintainer reports your pull request as spam, it will not be counted toward your participation in Hacktoberfest.
- If a maintainer reports behavior that’s not in line with the project’s code of conduct, you will be ineligible to participate.
- To get a shirt, you must make four approved pull requests (PRs) on opted-in projects between October 1-31 in any time zone.
- This year, the first 50,000 participants can earn a T-shirt.
---
Steps for adding your name below
1. Fork this repo
2. Add your Name also link your github profile
3. Make pull request
## License
[](https://creativecommons.org/publicdomain/zero/1.0/)
Keep Connect With Me [<NAME>](https://www.linkedin.com/in/deshitha-hansajith/) LinkedIn
README.md styling motivation credit goes to [<NAME> ](https://github.com/keshavsingh4522/hacktoberfest2021)
<file_sep>/Python/find Area Of Circle.py
# Python Program to find Area Of Circle using Radius
PI = 3.14
radius = float(input(' Please Enter the radius of a circle: '))
area = PI * radius * radius
circumference = 2 * PI * radius
print(" Area Of a Circle = %.2f" %area)
print(" Circumference Of a Circle = %.2f" %circumference
<file_sep>/Python/TowerOfHanoi.py
def TowerOfHanoi(Disks, source, temp, destination):
if(Disks == 1):
print("Move Disk 1 From {} to {}".format(source, destination))
return
TowerOfHanoi(Disks - 1, source, destination, temp)
print("Move Disk {} From {} to {}".format(Disks, source, destination))
TowerOfHanoi(Disks - 1, temp, source, destination)
Disks = int(input("Enter Number of Disks: "))
# Source : A, Intermediate : B, Destination : C
TowerOfHanoi(Disks, 'A', 'B', 'C')
<file_sep>/Python/minimum_in_rotated_sorted_array.py
# Problem Statement
"""
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For example, the array nums = [0,1,2,4,5,6,7] might become:
[4,5,6,7,0,1,2] if it was rotated 4 times.
[0,1,2,4,5,6,7] if it was rotated 7 times.
Notice that rotating an array [a[0], a[1], a[2], ..., a[n-1]] 1 time results in the array [a[n-1], a[0], a[1], a[2], ..., a[n-2]].
Given the sorted rotated array nums of unique elements, return the minimum element of this array.
You must write an algorithm that runs in O(log n) time.
"""
class Solution:
def findMin(self, nums: List[int]) -> int:
low = 0
high = len(nums) - 1
while low <= high:
mid = low + (high - low) // 2
if nums[mid] > nums[high]:
low = mid + 1
elif mid == 0 or nums[mid - 1] > nums[mid]:
return nums[mid]
else:
high = mid - 1<file_sep>/CPP/Arra_bug.cpp
#include <iostream>
#include<vector>
using namespace std;
vector<int> rotateArray(vector<int> &A, int B) {
vector<int> ret;
int j=0;
B=B%(A.size());
for (int i = 0; i < A.size(); ++i)
{
if((i+B)<A.size()){
ret.push_back(A[i+B]);
}
else{
ret.push_back(A[j]);
j++;
}
}
return ret;
}
int main(){
vector<int> A={2,3,5,1,1,5};
int B=2;
rotateArray(A,B);
return 0;
}<file_sep>/Python/filehandling1.py
'''TO ENTER BOOKS OF VARIOUS SUBJECT AND PERFORM MULTIPLE OPERATIONS'''
def write_books():
op="y"
while op=="y":
sub=input("ENTER THE SUBJECT:")
bname=input("ENTER THE BOOK NAME:")
auth=input("ENTER THE AUTHOR:")
price=input("ENTER THE PRICE:")
op=input("WANT TO CONTINUE:")
l=[]
l.append(sub)
l.append(bname)
l.append(auth)
l.append(price)
f=open(fname,"a")
f.write("\n")
f.write(str(l))
f.close()
def read():
l1=[]
sub1=input("ENTER THE SUBJECT:")
f=open(fname,"r")
for i in f:
if sub1 in i:
l1=eval(i)
print("subject:",l1[0])
print("Book:",l1[1])
print("Author:",l1[2])
print("Price:",l1[3])
f.close()
print("HELLO!! ADD AS MUCH BOOKS YOU WANT")
do=input("1.want to add books OR 2.find books:")
fname=input("ENTER THE FILE NAME:")
addbooks=["1","add","add books"]
findbooks=["2","find","find books"]
if do in addbooks:
write_books()
elif do in findbooks:
read()
else:
print("ok ended the program")
print("THANK YOU") <file_sep>/C/Circular linked list.cpp
#include<iostream>
using namespace std;
struct Node
{
int data;
struct Node *next;
};
//insert a new node in an empty list
struct Node *insertInEmpty(struct Node *last, int new_data)
{
// if last is not null then list is not empty, so return
if (last != NULL)
return last;
// allocate memory for node
struct Node *temp = new Node;
// Assign the data.
temp -> data = new_data;
last = temp;
// Create the link.
last->next = last;
return last;
}
//insert new node at the beginning of the list
struct Node *insertAtBegin(struct Node *last, int new_data)
{
//if list is empty then add the node by calling insertInEmpty
if (last == NULL)
return insertInEmpty(last, new_data);
//else create a new node
struct Node *temp = new Node;
//set new data to node
temp -> data = new_data;
temp -> next = last -> next;
last -> next = temp;
return last;
}
//insert new node at the end of the list
struct Node *insertAtEnd(struct Node *last, int new_data)
{
//if list is empty then add the node by calling insertInEmpty
if (last == NULL)
return insertInEmpty(last, new_data);
//else create a new node
struct Node *temp = new Node;
//assign data to new node
temp -> data = new_data;
temp -> next = last -> next;
last -> next = temp;
last = temp;
return last;
}
//insert a new node in between the nodes
struct Node *insertAfter(struct Node *last, int new_data, int after_item)
{
//return null if list is empty
if (last == NULL)
return NULL;
struct Node *temp, *p;
p = last -> next;
do
{
if (p ->data == after_item)
{
temp = new Node;
temp -> data = new_data;
temp -> next = p -> next;
p -> next = temp;
if (p == last)
last = temp;
return last;
}
p = p -> next;
} while(p != last -> next);
cout << "The node with data "<<after_item << " is not present in the list." << endl;
return last;
}
//traverse the circular linked list
void traverseList(struct Node *last) {
struct Node *p;
// If list is empty, return.
if (last == NULL) {
cout << "Circular linked List is empty." << endl;
return;
}
p = last -> next; // Point to the first Node in the list.
// Traverse the list starting from first node until first node is visited again
do {
cout << p -> data << "==>";
p = p -> next;
} while(p != last->next);
if(p == last->next)
cout<<p->data;
cout<<"\n\n";
}
//delete the node from the list
void deleteNode(Node** head, int key)
{
// If linked list is empty retun
if (*head == NULL)
return;
// If the list contains only a single node,delete that node; list is empty
if((*head)->data==key && (*head)->next==*head) {
free(*head);
*head=NULL;
}
Node *last=*head,*d;
// If key is the head
if((*head)->data==key) {
while(last->next!=*head) // Find the last node of the list
last=last->next;
// point last node to next of head or second node of the list
last->next=(*head)->next;
free(*head);
*head=last->next;
}
// end of list is reached or node to be deleted not there in the list
while(last->next!=*head&&last->next->data!=key) {
last=last->next;
}
// node to be deleted is found, so free the memory and display the list
if(last->next->data==key) {
d=last->next;
last->next=d->next;
cout<<"The node with data "<<key<<" deleted from the list"<<endl;
free(d);
cout<<endl;
cout<<"Circular linked list after deleting "<<key<<" is as follows:"<<endl;
traverseList(last);
}
else
cout<<"The node with data "<< key << " not found in the list"<<endl;
}
// main Program
int main()
{
struct Node *last = NULL;
last = insertInEmpty(last, 30);
last = insertAtBegin(last, 20);
last = insertAtBegin(last, 10);
last = insertAtEnd(last, 40);
last = insertAtEnd(last, 60);
last = insertAfter(last, 50,40 );
cout<<"The circular linked list created is as follows:"<<endl;
traverseList(last);
deleteNode(&last,10);
return 0;
}
<file_sep>/CPP/Preorder Traversal.cpp
#include<iostream>
#include<cstdlib>
/*--------------PREORDER TRAVERSAL OF BINARY TREE---------------------*/
using namespace std;
class BinT
{
public:
int data;
BinT *l;
BinT *r;
BinT(int n)
{
this->data=n;
this->l=NULL;
this->r=NULL;
}
void preorder(BinT* root)
{
if(root== NULL)
return;
cout<<root->data<<" ";
preorder(root->l);
preorder(root->r);
}
};
int main()
{
BinT *nr=(BinT*)(calloc(5,sizeof(BinT)));
nr=new BinT(1);
nr->l=new BinT(2);
nr->r=new BinT(3);
nr->l->l=new BinT(4);
nr->l->r=new BinT(5);
nr->preorder(nr);
return 0;
}
<file_sep>/C/linked lit.c
// A simple C program to introduce
// a linked list
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
// Program to create a simple linked
// list with 3 nodes
int main()
{
struct Node* head = NULL;
struct Node* second = NULL;
struct Node* third = NULL;
// allocate 3 nodes in the heap
head = (struct Node*)malloc(sizeof(struct Node));
second = (struct Node*)malloc(sizeof(struct Node));
third = (struct Node*)malloc(sizeof(struct Node));
/* Three blocks have been allocated dynamically.
We have pointers to these three blocks as head,
second and third
head second third
| | |
| | |
+---+-----+ +----+----+ +----+----+
| # | # | | # | # | | # | # |
+---+-----+ +----+----+ +----+----+
# represents any random value.
Data is random because we haven�t assigned
anything yet */
head->data = 1; // assign data in first node
head->next = second; // Link first node with
// the second node
/* data has been assigned to the data part of the first
block (block pointed by the head). And next
pointer of first block points to second.
So they both are linked.
head second third
| | |
| | |
+---+---+ +----+----+ +-----+----+
| 1 | o----->| # | # | | # | # |
+---+---+ +----+----+ +-----+----+
*/
// assign data to second node
second->data = 2;
// Link second node with the third node
second->next = third;
/* data has been assigned to the data part of the second
block (block pointed by second). And next
pointer of the second block points to the third
block. So all three blocks are linked.
head second third
| | |
| | |
+---+---+ +---+---+ +----+----+
| 1 | o----->| 2 | o-----> | # | # |
+---+---+ +---+---+ +----+----+ */
third->data = 3; // assign data to third node
third->next = NULL;
return 0;
}
<file_sep>/Python/sms.py
# Download the helper library from https://www.twilio.com/docs/python/install
import os
from twilio.rest import Client
# Find your Account SID and Auth Token at twilio.com/console
# and set the environment variables. See http://twil.io/secure
account_sid ='<KEY>'
auth_token = '<KEY>'
client = Client(account_sid, auth_token)
text = input("Enter Your Message : ")
message = client.messages \
.create(
body= f"{text}",
from_='twilio number',
to='number'
)
print(message.sid)
<file_sep>/Python/Reverse_a_Number.py
# Python Program to Reverse a Number using While loop
Number = int(input("Please Enter any Number: "))
Reverse = 0
while(Number > 0):
Reminder = Number %10
Reverse = (Reverse *10) + Reminder
Number = Number //10
print("\n Reverse of entered number is = %d" %Reverse)
<file_sep>/Python/maximum_sum_of_sub_array.py
arr = [-2,1,-3,4,-1,2,1,-5,4]
current_sum = 0
maximum_sum = 0
for i in arr:
current_sum = max(current_sum+i,i)
maximum_sum = max(maximum_sum,current_sum)
print(maximum_sum)<file_sep>/CPP/2dVector_reverse.cpp
#include <bits/stdc++.h>
using namespace std;
vector<vector<int> > reverse2d(vector<vector<int> > &A) {
vector<vector<int> > B;
B.resize(A.size());
for (int i = 0; i < A.size(); i++) {
B[i].resize(A[i].size());
for (int j = 0; j < A[i].size(); j++) {
B[i][A[i].size() - 1 - j] = A[i][j];
}
}
return B;
}
int main() {
vector<vector<int>> A
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
vector<vector<int> > B = reverse2d(A);
for (int i = 0; i < B.size(); i++) {
for (int j = 0; j < B[i].size(); j++) cout<<B[i][j]<<" ";
}
return 0;
}<file_sep>/Python/kruskal.py
"""
Make MST by kruskal algorithm
you can calculate minimum weight of MST by this code
"""
def find(node) -> int:
node_ = node
#After iteration, node variable reach to root node.
while node != disjoin_set[node]: # iterate until node reaches to root node
node = disjoin_set[node]
while node_ != disjoin_set[node_]: #compressing the path to end node
p_node = disjoin_set[node_]
disjoin_set[node_] = node # make node_ and every parents of it as a child of root
node_ = p_node
return node
def union(u,v) -> None:
u_root = find(u)
v_root = find(v)
#union by rank
if tree_rank[u_root] > tree_rank[v_root]:
disjoin_set[v_root] = u_root
tree_rank[u_root] += tree_rank[v_root]
else:
disjoin_set[u_root] = v_root
tree_rank[v_root] += tree_rank[u_root]
return
#n is number of nodes m is number of edges
n = 6; m = 9
edges = [
#each element in tuple means start node , end node, weight
(1,2,5),
(1,3,4),
(2,3,2),
(2,4,7),
(3,4,6),
(3,5,11),
(4,5,3),
(4,6,8),
(5,6,8)
]
disjoin_set = [i for i in range(n + 1)] #set for union-find
tree_rank = [1 for _ in range(n + 1)] #the height of each trees
res,edge_count = 0,0
#use kruskal algorithm
for u,v,w in sorted(edges, key = lambda k: k[2]):
#if count of edges in tree exceed n-1 break iteration since we found MST
if edge_count >= n - 1:
break
u_root = find(u); v_root = find(v)
if u_root == v_root: continue #if each nodes has same root two nodes in tree
union(u,v)
res += w; edge_count += 1
#print the minumun weight of MST
print(res)<file_sep>/Python/hamming-distance.py
# Hamming distance
def hammingDist(v1, v2):
i = 0
count = 0
if len(v1) != len(v2):
print("Please provide same length of both strings.")
exit()
while (i < len(v1)):
if (v1[i] != v2[i]):
count += 1
i += 1
return count
# Driver code
v1 = input("enter v1: ")
v2 = input("enter v2: ")
# function call
print(hammingDist(v1, v2))
<file_sep>/Python/Digital_Clock.py
import time
from tkinter import *
root = Tk()
root.title("Digital Clock")
root.geometry("250x100+0+0")
root.resizable(0,0)
label = Label(root, font=("Arial", 30, 'bold'), bg="blue", fg="powder blue", bd =30)
label.grid(row =0, column=1)
def dig_clock():
text_input = time.strftime("%H:%M:%S") # get the current local time from the PC
label.config(text=text_input)
# calls itself every 200 milliseconds
# to update the time display as needed
# could use >200 ms, but display gets jerky
label.after(200, dig_clock)
dig_clock()
root.mainloop()
<file_sep>/CPP/daa_job_sequencing.cpp
#include<bits/stdc++.h>
using namespace std;
void sort_end (int profit[], int deadline[], int job[], int n)
{
for (int i=0; i<n-1; i++)
{
int flag = 0;
for (int j=0; j<n-1-i; j++)
{
if (profit[j] < profit[j+1])
{
swap(profit[j], profit[j+1]);
swap(deadline[j], deadline[j+1]);
swap(job[j], job[j+1]);
flag = 1;
}
}
if (flag == 0)
break;
}
// for (int i=0; i<n; i++)
// cout<<job[i]<<" ";
// cout<<endl;
// for (int i=0; i<n; i++)
// cout<<profit[i]<<" ";
// cout<<endl;
// for (int i=0; i<n; i++)
// cout<<deadline[i]<<" ";
// cout<<endl;
}
void jobsSelected (int job[], int profit[], int deadline[], int n)
{
int maxx = INT_MIN;
int max_profit = 0;
for (int i=0; i<n; i++)
maxx = max(maxx, deadline[i]);
int res[maxx]={0};
for (int i=0; i<n; i++)
{
int x = deadline[i]-1;
while (res[x] != 0 && x>=0)
{
x--;
}
if (x>=0 && x<n)
{
res[x] = job[i];
max_profit += profit[i];
}
}
for (int i=0; i<maxx; i++)
{
if (res[i] != 0)
cout<<res[i]<<" ";
}
cout<<"\nMaximum profit is: "<<max_profit;
}
int main()
{
int n;
cout<<"\nEnter size of array: ";
cin>>n;
int job[n], profit[n], deadline[n];
cout<<"\nEnter profit array: ";
for (int i=0; i<n; i++)
cin>>profit[i];
cout<<"\nEnter deadline array: ";
for (int i=0; i<n; i++)
cin>>deadline[i];
for (int i=0; i<n; i++)
job[i] = i+1;
sort_end(profit, deadline, job, n);
cout<<"\nThe selected jobs are: ";
jobsSelected(job, profit, deadline, n);
}
<file_sep>/CPP/LargestNumber.cpp
#include <bits/stdc++.h>
using namespace std;
bool com(string a,string b){
string ab=a.append(b);
string ba=b.append(a);
return ab.compare(ba)>0?true:false;
}
string largestNumber(vector<int> &A){
vector<string> Ans;
string s="";
int i,c=0;
for (int i = 0; i < A.size(); ++i)
{
Ans.push_back(to_string(A[i]));
if(A[i]==0){
c++;
}
}
if(A.size()==c){
return "0";
}
sort(Ans.begin(),Ans.end(),com);
for (int i = 0; i <Ans.size(); i++)
{
s+=Ans[i];
}
cout<<s<<endl;
return s;
}
int main(){
vector<int> A={3, 30, 34, 5, 9};
largestNumber(A);
} | d9fe08742be57dec4ef87bec4255231a2f852a99 | [
"JavaScript",
"Markdown",
"Java",
"Python",
"PHP",
"C",
"C++"
] | 111 | Python | ethan786/hacktoberfest2021-1 | 7525b01fa1a6466a657663c50da4c41400a4a137 | 69f0f15db3eb6740dc61629e13aa0feb91a6ad87 |
refs/heads/master | <file_sep>/*
* 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 projdiario;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javax.swing.JOptionPane;
import java.io.FileOutputStream;
import java.io.PrintStream;
import javafx.geometry.Pos;
import javafx.print.PrinterJob;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
import javax.swing.JFrame;
/**
* FXML Controller class
*
* @author migue
*/
public class EscolherController implements Initializable {
@FXML DatePicker DataEscrever;
@FXML DatePicker DataQuando;
@FXML TextArea TextEscrever;
@FXML ImageView ImgGuardar;
@FXML ImageView apagar;
@FXML ImageView imprimir;
@FXML ImageView procurar;
@FXML DatePicker DataAte;
@FXML HBox Hbox;
@FXML CheckBox check;
@FXML Label LabelAte;
@FXML Button BConfirmar;
@FXML TextArea TextConsultar;
@FXML Button sair;
@FXML
private void ConfirmarButton() throws ClassNotFoundException, SQLException{
if(DataEscrever.getValue()==null){
JOptionPane.showMessageDialog(null, "Tem de inserir uma data");
return;
}
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DiarioBD;user=admin;password=sqlserver");
String query = "select * from tblDiario where Data = '"+java.sql.Date.valueOf(DataEscrever.getValue())+"'";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
if(rs.next()){
JOptionPane.showMessageDialog(null, "Deve introduzir uma data onde ainda não escreveu!");
}else{JOptionPane.showMessageDialog(null, "Pode escrever nesta data!");}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Erro!");
}
}
@FXML
private void imagePicker(){
Date data;
if(DataEscrever.getValue()==null){
JOptionPane.showMessageDialog(null, "Tem de inserir uma data");
}else{
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DiarioBD;user=sa;password=<PASSWORD>");
String query = "INSERT INTO tblDiario (Data, Texto)" + "values (?, ?);";
PreparedStatement pst = con.prepareStatement(query);
data = java.sql.Date.valueOf(DataEscrever.getValue());
pst.setDate(1, data);
pst.setString(2, TextEscrever.getText());
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Inserido com sucesso");
TextEscrever.clear();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Erro!");
}
}
}
@FXML
private void checkB(){
if(check.isSelected()){
Hbox.setVisible(true);
}else
Hbox.setVisible(false);
}
@FXML
private void BConsultar(){
Date data;
String texto;
Diario diario = null;
String resultado = "";
if(!check.isSelected()){
if(DataQuando.getValue()==null)
JOptionPane.showMessageDialog(null, "Deve introduzir uma data");
else{
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DiarioBD;user=admin;password=<PASSWORD>");
String query = "select * from tblDiario where Data = '"+java.sql.Date.valueOf(DataQuando.getValue())+"'";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()){
data = rs.getDate(1);
texto = rs.getString(2);
System.out.println(data);
System.out.println(texto);
TextConsultar.setText(data.toString() + " : \n" + texto);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Erro!");
}
}
}
if(check.isSelected()){
Date dataQuando, dataAte;
if(DataQuando.getValue()==null || DataAte.getValue()==null){
JOptionPane.showMessageDialog(null, "As datas não são válidas!");
}
dataQuando = java.sql.Date.valueOf(DataQuando.getValue());
dataAte = java.sql.Date.valueOf(DataAte.getValue());
if(dataAte.before(dataQuando) ){
JOptionPane.showMessageDialog(null, "As datas não são válidas!");
}
else{
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DiarioBD;user=admin;password=<PASSWORD>");
String query = "select * from tblDiario where Data >= '"+java.sql.Date.valueOf(DataQuando.getValue())+"' and data <= ' "+ java.sql.Date.valueOf(DataAte.getValue()) + "' " ;
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()){
data = rs.getDate(1);
texto = rs.getString(2);
//System.out.println(data);
//System.out.println(texto);
resultado = ( resultado + data.toString() + " : \n" + texto + "\n\n\n");
System.out.println(resultado);
}
TextConsultar.setText(resultado);
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Erro!");
}
}
}
}
@FXML
private void ApagarConsultar(){
TextConsultar.clear();
}
@FXML
private void GuardarPDF() throws FileNotFoundException, DocumentException{
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("Diario.pdf"));
String conteudo= TextConsultar.getText();
document.open();
Font font = FontFactory.getFont(FontFactory.COURIER, 16, BaseColor.BLACK);
Chunk chunk = new Chunk(conteudo, font);
document.add(new Paragraph(chunk));
document.close();
JOptionPane.showMessageDialog(null, "Exportado com sucesso!");
}
@FXML
private void imprimir(){
Text extractedText = new Text(TextConsultar.getText());
extractedText.setWrappingWidth(450);
// use pane to place the text
StackPane container = new StackPane(extractedText);
container.setAlignment(Pos.TOP_LEFT);
PrinterJob printerJob = PrinterJob.createPrinterJob();
if (printerJob != null ) {
if (printerJob.printPage(container)) {
printerJob.endJob();
} else {
System.out.println("Failed to print");
}
} else {
System.out.println("Canceled");
}
}
@FXML
private void procurar(){
JFrame f;
Date data;
String texto;
String resultado="";
TextConsultar.clear();
f=new JFrame();
String name=JOptionPane.showInputDialog(f,"Insira palavra a procurar");
if(name.isEmpty()){
JOptionPane.showMessageDialog(null, "Deve inserir pelo menos uma palavra!");
}
else{
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=DiarioBD;user=admin;password=<PASSWORD>");
String query = "select * from tblDiario where Texto like '%"+name+"%'";
Statement st = con.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()){
data = rs.getDate(1);
texto = rs.getString(2);
//System.out.println(data);
//System.out.println(texto);
resultado = ( resultado + data.toString() + " : \n" + texto + "\n\n\n");
System.out.println(resultado);
}
TextConsultar.setText(resultado);
}
catch(Exception e){
JOptionPane.showMessageDialog(null, "Erro!");
}
}
}
@FXML
public void sair(){
try{
Parent root = FXMLLoader.load(getClass().getResource("FXMLLogin.fxml"));
Stage stage = (Stage) sair.getScene().getWindow();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
catch (IOException e){
e.printStackTrace();
}
}
@Override
public void initialize(URL url, ResourceBundle rb) {
Hbox.setVisible(false);
TextConsultar.setEditable(false);
TextEscrever.setWrapText(true);
TextConsultar.setWrapText(true);
}
}
| 86f5911aaf4bc5cbb6572f2d80013094f1cac3ad | [
"Java"
] | 1 | Java | migasbruno/DigitalDiary | 1c0541a136b66003d2a4865f71fe379e9d8fcf1c | b33f4b8c29d45af12647b1d9939440c012aec6d1 |
refs/heads/master | <repo_name>dljones79/ASD1307<file_sep>/asdcouch/asdcouch/app/views/schools/map.js
function(doc) {
if (doc._id.substr(0, 7) === "school:"){
emit(doc._id.substr(7), {
"sName": doc.sName,
"contact": doc.contact,
"cNumber": doc.cNumber,
"building": doc.building,
"enrollment": doc.enrollment,
"sports": doc.sports,
"notes": doc.notes
});
}
};<file_sep>/asdcouch/asdcouch2/schooldatabase/app/views/schools/map.js
function(doc) {
if (doc._id.substr(0, 7) === "school:"){
emit(doc._id.substr(7), {
"id" : doc._id,
"rev" : doc._rev,
"sName": doc.sName,
"building": doc.building,
"enrollment": doc.enrollment
});
}
}; | a574d2284b0f44efa8767b29dde34fc009b48790 | [
"JavaScript"
] | 2 | JavaScript | dljones79/ASD1307 | 23fa4e16aaef51c0fd46adc0c954417f61e6025d | 3d70228c1a6bf355057c5827aafb5d360b1b18c5 |
refs/heads/master | <repo_name>tlynch591/tlynch591<file_sep>/main.cpp
//Name: <NAME>
//Student ID: #0587591
//Example 01 - Displays hello world to the console
#include <iostream>
#include <string>
using namespace std;
int main() {
// create a variable to store a message
string message ="Hello C++ World!";
// display a message to the console
cout << "Hello, World! \" Hi" << endl;
return 0;
}
//<NAME>
| 41cd5fcbd6c23a2a7af5bb741c5ec1fad36a2b39 | [
"C++"
] | 1 | C++ | tlynch591/tlynch591 | 93b1f04b00f4917a6cf3efa15e9c82fa58c2e529 | 473bcf411d3edc6324154060c8f3b7f8d07fa10c |
refs/heads/master | <repo_name>vctormb/react-testing-library<file_sep>/typings/index.d.ts
import {getQueriesForElement} from 'dom-testing-library'
export * from 'dom-testing-library'
type GetsAndQueries = ReturnType<typeof getQueriesForElement>
export interface RenderResult extends GetsAndQueries {
container: HTMLElement
baseElement: HTMLElement
debug: (baseElement?: HTMLElement | DocumentFragment) => void
rerender: (ui: React.ReactElement<any>) => void
unmount: () => boolean
asFragment: () => DocumentFragment
}
/**
* Render into a container which is appended to document.body. It should be used with cleanup.
*/
export function render(
ui: React.ReactElement<any>,
options?: {container: HTMLElement; baseElement?: HTMLElement},
): RenderResult
/**
* Unmounts React trees that were mounted with render.
*/
export function cleanup(): void
<file_sep>/src/__tests__/rerender.js
import React from 'react'
import {render, cleanup} from '../'
import 'jest-dom/extend-expect'
afterEach(cleanup)
test('rerender will re-render the element', () => {
const Greeting = props => <div>{props.message}</div>
const {container, rerender} = render(<Greeting message="hi" />)
expect(container.firstChild).toHaveTextContent('hi')
rerender(<Greeting message="hey" />)
expect(container.firstChild).toHaveTextContent('hey')
})
| e6ae8ae3dee6f41e60b34e005f405537183aa942 | [
"JavaScript",
"TypeScript"
] | 2 | TypeScript | vctormb/react-testing-library | 322c53e5c8aa5d21b568929c67f57e0e6c2626a9 | 2d30385ef3849abaf3b0161f5021e9eb99d4635e |
refs/heads/master | <repo_name>jitender336/pug-nodejs<file_sep>/views/call_to.js
function viewPost()(){
alert("No layman");
} | 22903562e00e1d7cb14c1b42e25ce22bf4bb1f1b | [
"JavaScript"
] | 1 | JavaScript | jitender336/pug-nodejs | d8d04ba150c001f24f2f00b10b547ce8ced9ae72 | 10d902676ef14b6f9cf4c111ee2cbf4833724418 |
refs/heads/master | <file_sep>This deploys no-dogma home.
This is a simple landing page to make visible the other apps.
Code:
https://github.com/BradfordMedeiros/nodogma-home
Dockerhub:
https://cloud.docker.com/repository/docker/bradfordmedeiros/nodogma-home
<file_sep>#!/usr/bin/env bash
INGRESS_IP=$(kubectl get ingress | tail -n 1 | awk '{ print $3 }')
if [[ -z "$INGRESS_IP" ]]; then
echo "Not defined"
exit 1
fi
xdg-open "http://$INGRESS_IP"
<file_sep>#!/usr/bin/env bash
xdg-open "https://console.cloud.google.com/home/dashboard?project=api-project-246632137166"
<file_sep>#!/usr/bin/env bash
#kubectl apply -f ./charts/prometheus/prometheus-configmap.yaml
#kubectl apply -f ./charts/prometheus/prometheus-deployment.yaml
#kubectl apply -f ./charts/prometheus/prometheus-service.yaml
kubectl apply -f ./charts/hippo/hippo-deployment.yaml
kubectl apply -f ./charts/hippo/hippo-service.yaml
kubectl apply -f ./charts/home/home-configmap.yaml
kubectl apply -f ./charts/home/home-deployment.yaml
kubectl apply -f ./charts/home/home-service.yaml
#kubectl apply -f ./charts/irc/irc-deployment.yaml
#kubectl apply -f ./charts/irc/irc-service.yaml
kubectl apply -f ./charts/bootstrapper/bootstrapper-deployment.yaml
kubectl apply -f ./charts/bootstrapper/bootstrapper-service.yaml
kubectl apply -f ./charts/main-ingress.yaml
<file_sep>This deploys prometheus.
Prometheus monitors the health of other services.
Dockerhub:
https:i//cloud.docker.com/repository/docker/bradfordmedeiros/hippo
<file_sep>#!/usr/bin/env bash
gcloud container clusters create main --zone us-central1-a --num-nodes 2
<file_sep>#!/usr/bin/env bash
#kubectl delete -f ./charts/prometheus/prometheus-configmap.yaml
#kubectl delete -f ./charts/prometheus/prometheus-deployment.yaml
#kubectl delete -f ./charts/prometheus/prometheus-service.yaml
kubectl delete -f ./charts/hippo/hippo-deployment.yaml
kubectl delete -f ./charts/hippo/hippo-service.yaml
kubectl delete -f ./charts/home/home-configmap.yaml
kubectl delete -f ./charts/home/home-deployment.yaml
kubectl delete -f ./charts/home/home-service.yaml
#kubectl delete -f ./charts/irc/irc-deployment.yaml
#kubectl delete -f ./charts/irc/irc-service.yaml
kubectl delete -f ./charts/bootstrapper/bootstrapper-deployment.yaml
kubectl delete -f ./charts/bootstrapper/bootstrapper-service.yaml
kubectl delete -f ./charts/main-ingress.yaml
<file_sep>This deploys hippo.
Hippo is package manager for automate.
Code:
https://github.com/BradfordMedeiros/hippo
Dockerhub:
https://cloud.docker.com/repository/docker/bradfordmedeiros/hippo
<file_sep>#!/usr/bin/env bash
xdg-open "https://console.cloud.google.com/billing/012470-E705B8-89DA6A?project=api-project-246632137166"
| 486bc35124ed6bd888fe7325849a131484d48940 | [
"Markdown",
"Shell"
] | 9 | Markdown | BradfordMedeiros/central-deployment | 42f5f902d764d27d91a78da53c8a44dd315d1652 | bd3d221206ccfb1c9c41efa621a8377f5bdb6bf2 |
refs/heads/master | <repo_name>paul-ocalla/DevOps-Pipeline-sweng<file_sep>/src/App.js
// eslint-disable-next-line
import logo from './logo.svg';
import React, { useState } from 'react';
import ReactMapGL from 'react-map-gl';
import './App.css';
import './map.jsx';
function App() {
const [viewport, setViewport] = useState({
width: "100vw",
height: "100vh",
latitude: 37.7577,
longitude: -122.4376,
zoom: 10
});
console.log(process.env.REACT_APP_MAPBOX_TOKEN)
return (
<ReactMapGL
{...viewport}
mapboxApiAccessToken = {process.env.REACT_APP_MAPBOX_TOKEN}
onViewportChange={setViewport}
/>
);
}
// eslint-disable-next-line
function startGame(){
console.log("Start game button pressed!")
}
export default App;
<file_sep>/README.md
# DevOps-Pipeline-sweng
A project aimed at implementing a CI/CD pipeline for a simple reactJS application. | 2022da37acf55d372d892ac0d5564a27cf7a1081 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | paul-ocalla/DevOps-Pipeline-sweng | f9c7873db02fca8ae566849de87e7c7878f7a8c2 | fd911d92cbdf0eff635ad941aa7132d4b847d93d |
refs/heads/master | <file_sep>dotfiles
========
Dotfiles, like .vimrc, .bashrc, .inputrc
Current files
-------------
_vimrc for vim
.bashrc for cygwin
.inputrc for cygwin
<file_sep>alias ogrep='grep -ioP --color=auto'
alias ngrep='grep -inP --color=auto'
alias rtouch='find . -exec touch {} \;'
| d97d317c2c53276f60ef9be557c4d74166c582bd | [
"Markdown",
"Shell"
] | 2 | Markdown | Atheuz/dotfiles | a2c1e9e4ac91797de808a3825211de5f65ef95ea | e0402484d6fe68648dba3e86485023354ac7f4b3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.